﻿// SCREEN: Organic Performance
// Nav ID: organic
// Purpose: Track organic post performance across channels, creator attribution, content ROI.

// ---------------------------------------------------------------------------
// MOCK data — used as fallback if API is unavailable
// ---------------------------------------------------------------------------
const ORGANIC_MOCK = {
  kpis: {
    totalImpressions:   2840000,
    totalClicks:         142000,
    avgEngagementRate:      5.2,
    bestPlatform:    'Instagram',
  },
  platforms: {
    instagram: {
      name: 'Instagram', color: '#E1306C', initial: 'IG',
      impressions: 1240000, clicks: 68000, ctr: 5.5, engagement: 6.8,
      topPost: 'New feature drop: Journey Analytics is now real-time',
      spark: [140, 165, 158, 182, 174, 198, 210],
    },
    linkedin: {
      name: 'LinkedIn', color: '#0077B5', initial: 'LI',
      impressions:  940000, clicks: 48000, ctr: 5.1, engagement: 4.9,
      topPost: 'How we replaced our CDP with an agentic marketing OS',
      spark: [90, 100, 112, 108, 118, 130, 140],
    },
    twitter: {
      name: 'Twitter / X', color: '#1DA1F2', initial: 'X',
      impressions:  660000, clicks: 26000, ctr: 3.9, engagement: 3.8,
      topPost: 'AstraReach now detects anomalies before your team notices',
      spark: [65, 70, 68, 78, 74, 82, 88],
    },
  },
  posts: [
    { id: 'p1',  platform: 'instagram', content: 'New feature drop: Journey Analytics is now real-time ✨',                      impressions: 284000, clicks: 15600, ctr: 5.5, engagement: 7.2, date: '2024-01-28' },
    { id: 'p2',  platform: 'linkedin',  content: 'How we replaced our CDP with an agentic marketing OS — a thread',              impressions: 218000, clicks: 11100, ctr: 5.1, engagement: 5.8, date: '2024-01-25' },
    { id: 'p3',  platform: 'instagram', content: 'Behind the scenes: building Markov chain attribution for offline events',       impressions: 196000, clicks:  9800, ctr: 5.0, engagement: 6.1, date: '2024-01-22' },
    { id: 'p4',  platform: 'twitter',   content: 'AstraReach now detects anomalies before your team even notices. Demo ↓',       impressions: 174000, clicks:  6700, ctr: 3.9, engagement: 4.2, date: '2024-01-20' },
    { id: 'p5',  platform: 'linkedin',  content: 'We cut our attribution guesswork by 40% in week one. Here is what we learned', impressions: 162000, clicks:  8300, ctr: 5.1, engagement: 5.2, date: '2024-01-18' },
    { id: 'p6',  platform: 'instagram', content: 'pgvector + temporal decay = memory that actually forgets the right things',     impressions: 148000, clicks:  7400, ctr: 5.0, engagement: 5.9, date: '2024-01-15' },
    { id: 'p7',  platform: 'twitter',   content: 'Hot take: most CDPs are just expensive ETL pipes. Change my mind.',             impressions: 122000, clicks:  4900, ctr: 4.0, engagement: 3.6, date: '2024-01-12' },
    { id: 'p8',  platform: 'linkedin',  content: 'Introducing multi-tenant org isolation — enterprise-ready from day one',        impressions:  98000, clicks:  5000, ctr: 5.1, engagement: 4.4, date: '2024-01-10' },
  ],
  contentTypes: [
    { type: 'Video',  pct: 28, engagement: 6.8, color: '#8B5CF6' },
    { type: 'Image',  pct: 42, engagement: 4.2, color: '#22D3EE' },
    { type: 'Text',   pct: 18, engagement: 2.1, color: '#F59E0B' },
    { type: 'Link',   pct: 12, engagement: 1.8, color: '#6B7489' },
  ],
  creators: [
    { id: 'c1', initials: 'AK', name: 'Aryan Kumar',    platform: 'linkedin',  posts: 12, impressions: 410000 },
    { id: 'c2', initials: 'MS', name: 'Mei Suzuki',     platform: 'instagram', posts:  9, impressions: 380000 },
    { id: 'c3', initials: 'TR', name: 'Tobias Reinholt',platform: 'twitter',   posts: 18, impressions: 290000 },
    { id: 'c4', initials: 'LP', name: 'Léa Perrin',     platform: 'linkedin',  posts:  7, impressions: 220000 },
  ],
};

// ---------------------------------------------------------------------------
// Platform badge
// ---------------------------------------------------------------------------
const PlatformBadge = ({ platform, size = 16 }) => {
  const cfg = {
    instagram: { label: 'IG', color: '#E1306C' },
    linkedin:  { label: 'LI', color: '#0077B5' },
    twitter:   { label: 'X',  color: '#1DA1F2' },
  };
  const c = cfg[platform] || { label: '?', color: 'var(--bg-3)' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: size, height: size, borderRadius: 3,
      background: c.color, color: '#fff',
      fontSize: size * 0.6, fontWeight: 700, flexShrink: 0,
      fontFamily: 'var(--mono)',
    }}>{c.label}</span>
  );
};

// ---------------------------------------------------------------------------
// Format large numbers: 2840000 → 2.84M, 142000 → 142K
// ---------------------------------------------------------------------------
const fmt = n => {
  if (n >= 1e6) return (n / 1e6).toFixed(2) + 'M';
  if (n >= 1e3) return (n / 1e3).toFixed(n >= 100000 ? 0 : 1) + 'K';
  return String(n);
};

// ---------------------------------------------------------------------------
// Inline donut-style bar for content type breakdown
// ---------------------------------------------------------------------------
const ContentTypeBar = ({ types }) => {
  const total = types.reduce((s, t) => s + t.pct, 0) || 1;
  return (
    <div style={{ height: 12, borderRadius: 6, overflow: 'hidden', display: 'flex' }}>
      {types.map(t => (
        <div key={t.type} style={{
          width: `${(t.pct / total) * 100}%`, background: t.color,
          transition: 'width 0.5s ease',
        }} title={`${t.type}: ${t.pct}%`} />
      ))}
    </div>
  );
};

// ---------------------------------------------------------------------------
// Main screen component
// ---------------------------------------------------------------------------
const OrganicScreen = () => {
  // State initialised from MOCK — API replaces on success
  const [kpis, setKpis]           = React.useState(ORGANIC_MOCK.kpis);
  const [platforms, setPlatforms] = React.useState(ORGANIC_MOCK.platforms);
  const [posts, setPosts]         = React.useState(ORGANIC_MOCK.posts);
  const [creators]                = React.useState(ORGANIC_MOCK.creators);
  const [contentTypes]            = React.useState(ORGANIC_MOCK.contentTypes);

  const [range, setRange]         = React.useState('30d');
  const [expanded, setExpanded]   = React.useState(null); // post id
  const activeRangeRef = React.useRef(range);

  // -------------------------------------------------------------------------
  // Compute date range bounds from segmented control
  // -------------------------------------------------------------------------
  const getDateRange = r => {
    const end   = new Date();
    const start = new Date();
    if (r === '7d')  start.setDate(end.getDate() - 7);
    if (r === '30d') start.setDate(end.getDate() - 30);
    if (r === '90d') start.setDate(end.getDate() - 90);
    return {
      start: start.toISOString().slice(0, 10),
      end:   end.toISOString().slice(0, 10),
    };
  };

  // -------------------------------------------------------------------------
  // Load organic performance data
  // -------------------------------------------------------------------------
  const loadData = r => {
    const { start, end } = getDateRange(r);
    arFetch(`/v1/organic/performance?start_date=${start}&end_date=${end}`)
      .then(data => {
        if (!data || data.error) return;

        // Update KPIs from API response
        if (data.total_impressions || data.total_clicks || data.avg_engagement_rate) {
          if (activeRangeRef.current !== r) return;
          setKpis(prev => ({
            totalImpressions:   data.total_impressions   || prev.totalImpressions,
            totalClicks:        data.total_clicks        || prev.totalClicks,
            avgEngagementRate:  data.avg_engagement_rate != null
                                  ? Math.round(data.avg_engagement_rate * 10) / 10
                                  : prev.avgEngagementRate,
            bestPlatform:       prev.bestPlatform, // derive below
          }));
        }

        // Map posts
        if (data.posts && data.posts.length > 0) {
          if (activeRangeRef.current !== r) return;
          const mapped = data.posts.map(p => ({
            id:          p.post_id,
            platform:    p.platform || 'instagram',
            content:     p.content || p.title || '',
            impressions: p.impressions || 0,
            clicks:      p.clicks || 0,
            ctr:         p.ctr != null ? Math.round(p.ctr * 10) / 10 : 0,
            engagement:  p.engagement_rate != null ? Math.round(p.engagement_rate * 10) / 10 : 0,
            date:        (p.created_at || '').slice(0, 10),
          }));
          // Sort by impressions desc
          mapped.sort((a, b) => b.impressions - a.impressions);
          setPosts(mapped);

          // Derive best platform
          const byPlatform = {};
          mapped.forEach(p => {
            if (!byPlatform[p.platform]) byPlatform[p.platform] = 0;
            byPlatform[p.platform] += p.impressions;
          });
          const best = Object.entries(byPlatform).sort((a, b) => b[1] - a[1])[0];
          if (best) {
            const name = best[0].charAt(0).toUpperCase() + best[0].slice(1);
            setKpis(prev => ({ ...prev, bestPlatform: name === 'Twitter' ? 'Twitter/X' : name }));
          }

          // Update platform stats from post data
          setPlatforms(prev => {
            const next = { ...prev };
            Object.keys(next).forEach(pk => {
              const plPosts = mapped.filter(p => p.platform === pk || p.platform === 'twitter' && pk === 'twitter');
              if (plPosts.length > 0) {
                const totalImp = plPosts.reduce((s, p) => s + p.impressions, 0);
                const totalClk = plPosts.reduce((s, p) => s + p.clicks, 0);
                const avgEng   = plPosts.reduce((s, p) => s + p.engagement, 0) / plPosts.length;
                next[pk] = {
                  ...next[pk],
                  impressions: totalImp,
                  clicks:      totalClk,
                  ctr:         totalImp > 0 ? Math.round((totalClk / totalImp) * 1000) / 10 : 0,
                  engagement:  Math.round(avgEng * 10) / 10,
                  topPost:     plPosts[0].content || next[pk].topPost,
                };
              }
            });
            return next;
          });
        }
      })
      .catch(() => {}); // silently keep MOCK on error
  };

  React.useEffect(() => { loadData(range); }, []);

  const handleRangeChange = r => {
    setRange(r);
    activeRangeRef.current = r;
    loadData(r);
  };

  return (
    <div>
      {/* ------------------------------------------------------------------ */}
      {/* Date range selector + KPI row                                       */}
      {/* ------------------------------------------------------------------ */}
      <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 14, flexWrap: 'wrap' }}>
        {/* Segmented control */}
        <div className="seg">
          {['7d', '30d', '90d'].map(r => (
            <button key={r} className={range === r ? 'active' : ''} onClick={() => handleRangeChange(r)}>
              {r}
            </button>
          ))}
        </div>

        {/* KPI chips */}
        <div style={{ display: 'flex', gap: 10, marginLeft: 'auto', flexWrap: 'wrap' }}>
          {[
            { label: 'Impressions',   value: fmt(kpis.totalImpressions),       color: 'var(--cyan)'    },
            { label: 'Clicks',        value: fmt(kpis.totalClicks),             color: 'var(--accent)'  },
            { label: 'Avg Engagement',value: kpis.avgEngagementRate + '%',      color: 'var(--emerald)' },
            { label: 'Best Platform', value: kpis.bestPlatform,                color: 'var(--amber)'   },
          ].map(k => (
            <div key={k.label} style={{
              background: 'var(--bg-2)', border: '1px solid var(--border)',
              borderRadius: 8, padding: '6px 14px',
              display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 96,
            }}>
              <span style={{ fontSize: 18, fontWeight: 700, color: k.color, fontFamily: 'var(--mono)', whiteSpace: 'nowrap' }}>
                {k.value}
              </span>
              <span style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 1, whiteSpace: 'nowrap' }}>
                {k.label}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* ------------------------------------------------------------------ */}
      {/* Platform performance cards (3-col grid)                             */}
      {/* ------------------------------------------------------------------ */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 14 }}>
        {Object.values(platforms).map(pl => (
          <div key={pl.name} className="card" style={{ padding: '14px 16px' }}>
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 28, height: 28, borderRadius: 6, background: pl.color,
                color: '#fff', fontSize: 12, fontWeight: 800, fontFamily: 'var(--mono)',
              }}>{pl.initial}</span>
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-1)' }}>{pl.name}</span>
            </div>

            {/* Stats grid */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 10 }}>
              {[
                { label: 'Impressions', value: fmt(pl.impressions) },
                { label: 'Clicks',      value: fmt(pl.clicks)      },
                { label: 'CTR',         value: pl.ctr + '%'        },
                { label: 'Engagement',  value: pl.engagement + '%' },
              ].map(s => (
                <div key={s.label} style={{
                  background: 'var(--bg-3)', borderRadius: 6, padding: '7px 10px',
                }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-1)', fontFamily: 'var(--mono)' }}>
                    {s.value}
                  </div>
                  <div style={{ fontSize: 10, color: 'var(--text-3)', marginTop: 1 }}>{s.label}</div>
                </div>
              ))}
            </div>

            {/* 7-day sparkline */}
            <div style={{ marginBottom: 10 }}>
              <Spark data={pl.spark} color={pl.color} h={32} />
            </div>

            {/* Top post preview */}
            <div style={{
              fontSize: 10, color: 'var(--text-3)', lineHeight: 1.45,
              borderTop: '1px solid var(--border)', paddingTop: 8, fontStyle: 'italic',
              overflow: 'hidden', display: '-webkit-box',
              WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
            }}>
              "{pl.topPost}"
            </div>
          </div>
        ))}
      </div>

      {/* ------------------------------------------------------------------ */}
      {/* Top posts table + Content type breakdown                            */}
      {/* ------------------------------------------------------------------ */}
      <div style={{ display: 'grid', gridTemplateColumns: '3fr 2fr', gap: 12, marginBottom: 14 }}>

        {/* Left: Top posts table */}
        <div className="card" style={{ padding: '14px 16px' }}>
          <div className="card-header" style={{ marginBottom: 12 }}>
            <div className="card-title">Top Posts</div>
            <span className="badge">by impressions</span>
          </div>

          {/* Table header */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '18px 1fr 72px 56px 48px 60px 72px',
            gap: 8, padding: '0 6px 8px', marginBottom: 4,
            borderBottom: '1px solid var(--border)',
          }}>
            {['', 'Content', 'Impressions', 'Clicks', 'CTR', 'Eng.', 'Date'].map((h, i) => (
              <span key={i} style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', textAlign: i > 1 ? 'right' : 'left' }}>
                {h}
              </span>
            ))}
          </div>

          {/* Rows */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {posts.map(p => (
              <div key={p.id}
                style={{
                  display: 'grid',
                  gridTemplateColumns: '18px 1fr 72px 56px 48px 60px 72px',
                  gap: 8, padding: '8px 6px',
                  borderRadius: 6, cursor: 'pointer',
                  background: expanded === p.id ? 'var(--bg-3)' : 'transparent',
                  transition: 'background 0.12s',
                }}
                onClick={() => setExpanded(expanded === p.id ? null : p.id)}
              >
                <PlatformBadge platform={p.platform} size={16} />

                {/* Content snippet */}
                <span style={{
                  fontSize: 12, color: 'var(--text-2)', lineHeight: 1.45,
                  overflow: 'hidden', display: '-webkit-box',
                  WebkitLineClamp: expanded === p.id ? 'unset' : 1,
                  WebkitBoxOrient: 'vertical',
                  maxWidth: '100%',
                }}>
                  {expanded === p.id ? p.content : (p.content.length > 60 ? p.content.slice(0, 60) + '…' : p.content)}
                </span>

                <span style={{ fontSize: 12, color: 'var(--text-1)', textAlign: 'right', fontFamily: 'var(--mono)' }}>
                  {fmt(p.impressions)}
                </span>
                <span style={{ fontSize: 12, color: 'var(--text-2)', textAlign: 'right', fontFamily: 'var(--mono)' }}>
                  {fmt(p.clicks)}
                </span>
                <span style={{ fontSize: 12, color: 'var(--cyan)', textAlign: 'right', fontFamily: 'var(--mono)' }}>
                  {p.ctr}%
                </span>
                <span style={{ fontSize: 12, color: 'var(--emerald)', textAlign: 'right', fontFamily: 'var(--mono)' }}>
                  {p.engagement}%
                </span>
                <span style={{ fontSize: 11, color: 'var(--text-3)', textAlign: 'right', fontFamily: 'var(--mono)' }}>
                  {p.date}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* Right: Content type breakdown */}
        <div className="card" style={{ padding: '14px 16px' }}>
          <div className="card-header" style={{ marginBottom: 14 }}>
            <div className="card-title">Content Type Breakdown</div>
            <span className="badge">by engagement</span>
          </div>

          {/* Stacked bar */}
          <ContentTypeBar types={contentTypes} />

          {/* Legend + performance rows */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
            {contentTypes.map(ct => (
              <div key={ct.type} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                {/* Color swatch */}
                <span style={{
                  width: 10, height: 10, borderRadius: 2,
                  background: ct.color, flexShrink: 0, display: 'inline-block',
                }} />
                {/* Type name + share */}
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 3 }}>
                    <span style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 500 }}>{ct.type}</span>
                    <span style={{ fontSize: 11, color: 'var(--text-3)', fontFamily: 'var(--mono)' }}>
                      {ct.pct}% of posts
                    </span>
                  </div>
                  {/* Engagement bar */}
                  <div style={{ height: 6, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
                    <div style={{
                      height: '100%',
                      width: `${(ct.engagement / 8) * 100}%`,
                      background: ct.color,
                      borderRadius: 3,
                      transition: 'width 0.5s ease',
                    }} />
                  </div>
                </div>
                {/* Engagement value */}
                <span style={{
                  fontSize: 13, fontWeight: 700, color: ct.color,
                  fontFamily: 'var(--mono)', width: 38, textAlign: 'right',
                }}>
                  {ct.engagement}%
                </span>
              </div>
            ))}
          </div>

          {/* Summary callout */}
          <div style={{
            marginTop: 16, background: 'rgba(139,92,246,0.08)',
            border: '1px solid rgba(139,92,246,0.2)',
            borderRadius: 8, padding: '10px 12px',
          }}>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Key insight</div>
            <div style={{ fontSize: 12, color: 'var(--text-2)', lineHeight: 1.5 }}>
              Video content drives <strong style={{ color: 'var(--emerald)' }}>3.2x</strong> higher engagement than text posts,
              despite making up only <strong style={{ color: 'var(--text-1)' }}>28%</strong> of your content mix.
            </div>
          </div>
        </div>
      </div>

      {/* ------------------------------------------------------------------ */}
      {/* Creator attribution row (bottom)                                    */}
      {/* ------------------------------------------------------------------ */}
      <div className="card" style={{ padding: '14px 18px' }}>
        <div className="card-header" style={{ marginBottom: 14 }}>
          <div className="card-title">Creator Attribution</div>
          <a
            href="#"
            onClick={e => {
              e.preventDefault();
              if (window.AR_NAVIGATE) {
                window.AR_NAVIGATE('creator');
              } else {
                window.location.href = 'AstraReach.html';
              }
            }}
            style={{ fontSize: 11, color: 'var(--accent)', textDecoration: 'none' }}
          >
            View all creators →
          </a>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
          {creators.map(cr => {
            const pl = ORGANIC_MOCK.platforms[cr.platform] || {};
            const platformColor = pl.color || '#6B7489';
            return (
              <div key={cr.id} style={{
                background: 'var(--bg-3)', border: '1px solid var(--border)',
                borderRadius: 10, padding: '14px 14px',
                display: 'flex', flexDirection: 'column', gap: 8,
              }}>
                {/* Avatar + name */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{
                    width: 36, height: 36, borderRadius: '50%',
                    background: `linear-gradient(135deg, ${platformColor}88, ${platformColor})`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 13, fontWeight: 700, color: '#fff', flexShrink: 0,
                  }}>{cr.initials}</span>
                  <div style={{ overflow: 'hidden' }}>
                    <div style={{
                      fontSize: 12, fontWeight: 600, color: 'var(--text-1)',
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>{cr.name}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
                      <PlatformBadge platform={cr.platform} size={12} />
                      <span style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'capitalize' }}>
                        {cr.platform === 'twitter' ? 'Twitter/X' : cr.platform}
                      </span>
                    </div>
                  </div>
                </div>

                {/* Stats */}
                <div style={{
                  display: 'flex', justifyContent: 'space-between',
                  borderTop: '1px solid var(--border)', paddingTop: 8,
                }}>
                  <div>
                    <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-1)', fontFamily: 'var(--mono)' }}>
                      {cr.posts}
                    </div>
                    <div style={{ fontSize: 10, color: 'var(--text-3)' }}>posts</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--cyan)', fontFamily: 'var(--mono)' }}>
                      {fmt(cr.impressions)}
                    </div>
                    <div style={{ fontSize: 10, color: 'var(--text-3)' }}>impressions</div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

window.OrganicScreen = OrganicScreen;
