/* screen-campaign.jsx — Campaign detail + auto-narrative report */
/* global React, Sidebar, Topbar, Counter, Sparkline, BarChart, LineChart, Donut, Avatar, Pill, MatchCircle, Icon, useInView */

function ScreenCampaignReport() {
  return (
    <div className="app-shell">
      <AppSidebar portal="brand" active="brand-campaigns" />
      <main className="main">
        <AppTopbar />

        {/* Breadcrumb + title */}
        <div className="mb-6">
          <div className="row items-center gap-6 muted" style={{ fontSize: 12, marginBottom: 8 }}>
            <span>Campaigns</span>
            <span>·</span>
            <span className="bold" style={{ color: 'var(--ink)' }}>Vitamin C Skin Glow · Q2 Launch</span>
          </div>
          <div className="row items-end justify-between">
            <div>
              <div className="row items-center gap-12">
                <h1 className="page-title">Vitamin C Skin Glow</h1>
                <Pill variant="mint" icon={<span style={{ width: 6, height: 6, background: 'currentColor', borderRadius: 999, display: 'inline-block', animation: 'pulse 1.5s ease-out infinite' }} />}>LIVE · DAY 14 / 28</Pill>
              </div>
              <div className="page-subtitle">Campaign C-1182 · Brief #B-2419 · 3 KOLs · TikTok &amp; Instagram</div>
            </div>
            <div className="row gap-8">
              <button className="btn btn-ghost btn-sm">{Icon.external} Share report</button>
              <button className="btn btn-ghost btn-sm">Export PDF</button>
              <button className="btn btn-primary btn-sm">{Icon.spark} Re-book best</button>
            </div>
          </div>
        </div>

        {/* AI Narrative banner — the showpiece */}
        <NarrativeBanner />

        {/* Tabs */}
        <div className="row gap-4 mt-6" style={{ borderBottom: '1px solid var(--line)', paddingBottom: 0 }}>
          {['Overview', 'Creators', 'Content', 'Timeline', 'Budget', 'Settings'].map((t, i) => (
            <button key={t} style={{
              background: 'transparent', border: 0,
              padding: '10px 14px', fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
              color: i === 0 ? 'var(--ink)' : 'var(--ink-soft)',
              borderBottom: '2px solid ' + (i === 0 ? 'var(--ink)' : 'transparent'),
              marginBottom: -1,
              cursor: 'pointer'
            }}>{t}</button>
          ))}
        </div>

        {/* KPI row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginTop: 18 }}>
          {[
            { l: 'Total reach', v: 4.8, suf: 'M', d: 38, c: 'var(--cyan)' },
            { l: 'Impressions', v: 12.4, suf: 'M', d: 24, c: 'var(--indigo)' },
            { l: 'Engagements', v: 296, suf: 'K', d: 42, c: 'var(--pink-hot)' },
            { l: 'Avg. ER', v: 6.2, suf: '%', d: 28, dec: 1, c: 'var(--mint-deep)' },
            { l: 'CPM', v: 8.4, pre: '$', d: -18, dec: 1, c: 'var(--yellow-deep)' },
          ].map((k, i) => <BigKpi key={i} {...k} index={i} />)}
        </div>

        {/* Chart + per-creator */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 14, marginTop: 18 }}>
          <div className="card-elevated">
            <div className="row items-center justify-between mb-3">
              <div>
                <div className="title-md">Reach trajectory</div>
                <div className="muted" style={{ fontSize: 12 }}>Day 1 → Day 14 · plan vs actual</div>
              </div>
              <div className="row gap-12">
                <div className="row items-center gap-6"><span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--cyan)' }} /><span style={{ fontSize: 12 }}>Actual</span></div>
                <div className="row items-center gap-6"><span style={{ width: 10, height: 2, background: 'var(--ink-soft)' }} /><span style={{ fontSize: 12 }}>Plan</span></div>
              </div>
            </div>
            <LineChart
              series={[
                { name: 'Plan', color: '#738A9E', data: [0.1, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.0, 2.3, 2.6, 2.9, 3.1, 3.3, 3.5] },
                { name: 'Actual', color: '#009CFF', data: [0.1, 0.4, 0.9, 1.3, 1.7, 2.1, 2.5, 2.9, 3.3, 3.7, 4.0, 4.3, 4.6, 4.8] },
              ]}
              xLabels={['D1','D2','D3','D4','D5','D6','D7','D8','D9','D10','D11','D12','D13','D14']}
              height={260}
            />
          </div>
          <PerCreatorPanel />
        </div>

        {/* Content gallery + funnel */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14, marginTop: 18 }}>
          <ContentGallery />
          <FunnelChart />
        </div>

        {/* Audience + Budget */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 18 }}>
          <AudienceCard />
          <BudgetCard />
        </div>

      </main>
    </div>
  );
}

function NarrativeBanner() {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setShown(true), 200);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="card-elevated" style={{
      padding: 24,
      background: 'linear-gradient(135deg, #002B50 0%, #1C1CC9 100%)',
      color: 'white',
      position: 'relative', overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', top: -60, right: -60,
        width: 240, height: 240, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(121,254,231,0.45), transparent 60%)',
        filter: 'blur(20px)'
      }} />
      <div style={{
        position: 'absolute', bottom: -80, left: 100,
        width: 240, height: 240, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,111,163,0.4), transparent 60%)',
        filter: 'blur(30px)'
      }} />
      <div className="row items-start gap-16" style={{ position: 'relative', zIndex: 1 }}>
        <div className="orb" style={{ flexShrink: 0 }} />
        <div className="flex-1">
          <Pill variant="dark"><span style={{ color: 'var(--mint)' }}>●</span> AI summary · auto-generated 2m ago</Pill>
          <div className="font-display" style={{ fontSize: 22, fontWeight: 700, lineHeight: 1.35, marginTop: 14, letterSpacing: '-0.015em', maxWidth: 880 }}>
            <NarrativeText shown={shown} />
          </div>
          <div className="row gap-6 mt-4">
            <Pill variant="dark">+38% vs plan</Pill>
            <Pill variant="dark">CPM down 18%</Pill>
            <Pill variant="dark">3/3 deliverables on time</Pill>
            <Pill variant="dark"><span style={{ color: 'var(--mint)' }}>Verdict:</span> over-performing</Pill>
          </div>
        </div>
      </div>
    </div>
  );
}

function NarrativeText({ shown }) {
  // Text "reveals" word-by-word
  const text = "Vitamin C launch beat plan by 38% with mid-tier KOLs driving 68% of reach. Linh Châu over-performed at CPM $6.12 vs band $9–12 — strong re-book signal for Q3. Audience saturation 62% across top 3 creators suggests adding nano-tier diversification.";
  const words = text.split(' ');
  return (
    <div>
      {words.map((w, i) => {
        // highlight key parts
        const isHighlight = ['38%', '68%', '$6.12', '62%'].includes(w) || ['Linh', 'Châu'].includes(w);
        return (
          <span key={i} style={{
            opacity: shown ? 1 : 0,
            transform: shown ? 'translateY(0)' : 'translateY(4px)',
            transition: `opacity .35s ${i * 22}ms, transform .35s ${i * 22}ms`,
            display: 'inline-block',
            marginRight: '0.28em',
            color: isHighlight ? 'var(--mint)' : 'white',
            fontWeight: isHighlight ? 800 : 500
          }}>{w}</span>
        );
      })}
    </div>
  );
}

function BigKpi({ l, v, pre = '', suf = '', d, dec = 0, c, index }) {
  const [ref, inView] = useInView();
  return (
    <div ref={ref} className="card-elevated" style={{
      padding: 18,
      opacity: inView ? 1 : 0,
      transform: inView ? 'translateY(0)' : 'translateY(20px)',
      transition: `opacity .8s ${index * 80}ms, transform .8s ${index * 80}ms`
    }}>
      <div className="cap-label">{l}</div>
      <div className="font-display tabular" style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 8, color: c }}>
        {inView && <Counter to={v} prefix={pre} suffix={suf} decimals={dec} duration={1800} />}
      </div>
      <div className="row items-center justify-between mt-2">
        <Pill variant={d >= 0 ? 'mint' : 'pink'} icon={d >= 0 ? Icon.trend : Icon.trendDown}>
          {d >= 0 ? '+' : ''}{d}%
        </Pill>
        <span className="muted" style={{ fontSize: 10 }}>vs plan</span>
      </div>
    </div>
  );
}

function PerCreatorPanel() {
  const list = [
    { n: 'Linh Châu', cat: 'Skincare', reach: 2.4, er: 6.8, m: 94, perf: 'over' },
    { n: 'Mai Vy', cat: 'Lifestyle', reach: 1.6, er: 5.4, m: 88, perf: 'on' },
    { n: 'Hà Giang', cat: 'Beauty', reach: 0.8, er: 7.1, m: 81, perf: 'on' },
  ];
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Creator scoreboard</div>
          <div className="muted" style={{ fontSize: 12 }}>Performance vs predicted match</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {list.map((c, i) => (
          <div key={i} className="row items-center gap-12" style={{
            padding: '14px 4px',
            borderBottom: i < list.length - 1 ? '1px solid var(--line)' : 'none'
          }}>
            <Avatar name={c.n} size={38} />
            <div className="flex-1">
              <div className="row items-center gap-6">
                <div className="bold" style={{ fontSize: 13 }}>{c.n}</div>
                {c.perf === 'over' && <span style={{
                  background: 'var(--mint)', color: 'var(--ink)',
                  fontSize: 9, fontWeight: 800, letterSpacing: '0.08em',
                  padding: '2px 6px', borderRadius: 4
                }}>+38%</span>}
              </div>
              <div className="muted" style={{ fontSize: 11 }}>{c.cat} · {c.reach}M · {c.er}% ER</div>
              {/* mini bar */}
              <div style={{ height: 4, background: 'var(--bg-soft)', borderRadius: 999, marginTop: 6, overflow: 'hidden' }}>
                <div style={{
                  height: '100%', width: ((c.reach / 4.8) * 100) + '%',
                  background: c.perf === 'over' ? 'var(--mint-deep)' : 'var(--cyan)',
                  borderRadius: 999, transformOrigin: 'left',
                  animation: `grow-w 1.1s ${0.3 + i * 0.15}s cubic-bezier(.4,0,.2,1) both`, transform: 'scaleX(0)'
                }} />
              </div>
            </div>
            <MatchCircle score={c.m} size={42} />
          </div>
        ))}
      </div>
      <style>{`@keyframes grow-w { to { transform: scaleX(1); } }`}</style>
    </div>
  );
}

function ContentGallery() {
  const posts = [
    { creator: 'Linh Châu', platform: 'tiktok', reach: '1.2M', er: '7.4%', color: ['#79FEE7', '#009CFF'] },
    { creator: 'Linh Châu', platform: 'tiktok', reach: '820K', er: '6.8%', color: ['#FFC3D6', '#FF6FA3'] },
    { creator: 'Mai Vy', platform: 'instagram', reach: '720K', er: '5.6%', color: ['#EAC2FB', '#1C1CC9'] },
    { creator: 'Mai Vy', platform: 'instagram', reach: '480K', er: '5.2%', color: ['#FEE960', '#FF7A59'] },
    { creator: 'Hà Giang', platform: 'tiktok', reach: '380K', er: '7.6%', color: ['#79FEE7', '#1FD6B4'] },
    { creator: 'Hà Giang', platform: 'tiktok', reach: '320K', er: '6.8%', color: ['#FFC3D6', '#EAC2FB'] },
  ];
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Top posts</div>
          <div className="muted" style={{ fontSize: 12 }}>Sorted by reach · 6 of 14</div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
        {posts.map((p, i) => (
          <div key={i} style={{
            position: 'relative',
            borderRadius: 12,
            overflow: 'hidden',
            aspectRatio: '9 / 14',
            background: `linear-gradient(135deg, ${p.color[0]}, ${p.color[1]})`,
            cursor: 'pointer',
            animation: `cardIn .5s ${i * 60}ms backwards cubic-bezier(.4,0,.2,1)`,
            transition: 'transform .25s'
          }}>
            {/* decorative shape */}
            <div style={{
              position: 'absolute', inset: 0,
              backgroundImage: 'radial-gradient(circle at 30% 70%, rgba(255,255,255,0.4), transparent 50%)',
              mixBlendMode: 'overlay'
            }} />
            {/* play icon */}
            <div style={{
              position: 'absolute', top: '50%', left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 40, height: 40, borderRadius: 999,
              background: 'rgba(255,255,255,0.25)',
              backdropFilter: 'blur(8px)',
              display: 'grid', placeItems: 'center',
              color: 'white', fontSize: 14
            }}>▶</div>
            {/* badges */}
            <div className="row items-center gap-4" style={{ position: 'absolute', top: 8, left: 8, color: 'white' }}>
              {p.platform === 'tiktok' ? Icon.tiktok : Icon.instagram}
            </div>
            <div style={{
              position: 'absolute', bottom: 0, left: 0, right: 0,
              padding: '20px 10px 10px',
              background: 'linear-gradient(transparent, rgba(0,0,0,0.5))',
              color: 'white'
            }}>
              <div className="bold" style={{ fontSize: 11 }}>{p.creator}</div>
              <div className="row items-center justify-between mt-2">
                <div className="font-display bold tabular" style={{ fontSize: 14 }}>{p.reach}</div>
                <div className="bold" style={{ fontSize: 10, background: 'rgba(255,255,255,0.25)', padding: '2px 6px', borderRadius: 4 }}>{p.er}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
      <style>{`@keyframes cardIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </div>
  );
}

function FunnelChart() {
  const steps = [
    { l: 'Impressions', v: 12400000, w: 100, c: 'var(--cyan)' },
    { l: 'Reach', v: 4800000, w: 78, c: 'var(--indigo)' },
    { l: 'Engagements', v: 296000, w: 52, c: 'var(--pink-hot)' },
    { l: 'Profile visits', v: 41200, w: 32, c: 'var(--yellow-deep)' },
    { l: 'Link clicks', v: 8420, w: 16, c: 'var(--mint-deep)' },
    { l: 'Purchases', v: 1180, w: 7, c: 'var(--ink)' },
  ];
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Conversion funnel</div>
          <div className="muted" style={{ fontSize: 12 }}>From view to purchase</div>
        </div>
        <Pill variant="mint">9.5% CTR</Pill>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {steps.map((s, i) => (
          <div key={i} className="row items-center gap-12" style={{ position: 'relative' }}>
            <div style={{ width: 110 }}>
              <div className="cap-label" style={{ fontSize: 9 }}>{s.l}</div>
              <div className="font-display bold tabular" style={{ fontSize: 14 }}>
                <Counter to={s.v} duration={1800} format={(v) => v >= 1e6 ? (v/1e6).toFixed(1) + 'M' : v >= 1e3 ? (v/1e3).toFixed(1) + 'K' : Math.round(v)} />
              </div>
            </div>
            <div style={{ flex: 1, height: 32 }}>
              <div style={{
                height: '100%', width: s.w + '%',
                background: s.c, borderRadius: 6,
                transformOrigin: 'left',
                animation: `grow-w 1s ${i * 100}ms cubic-bezier(.4,0,.2,1) both`,
                transform: 'scaleX(0)'
              }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AudienceCard() {
  return (
    <div className="card-elevated">
      <div className="title-md">Audience reached</div>
      <div className="muted mb-3" style={{ fontSize: 12 }}>Demographics across 4.8M unique users</div>

      <div className="row gap-24">
        {/* Gender */}
        <div style={{ flex: '0 0 auto' }}>
          <div className="cap-label mb-2">Gender</div>
          <Donut
            data={[
              { label: 'Female', value: 72, color: '#FF6FA3' },
              { label: 'Male', value: 24, color: '#009CFF' },
              { label: 'Other', value: 4, color: '#FEE960' },
            ]}
            size={140}
            thickness={18}
            centerLabel="Female"
            centerValue="72%"
          />
        </div>

        {/* Age */}
        <div className="flex-1">
          <div className="cap-label mb-2">Age</div>
          <BarChart
            data={[
              { label: '13–17', value: 8, color: 'var(--lavender)' },
              { label: '18–24', value: 42, color: 'var(--indigo)' },
              { label: '25–34', value: 32, color: 'var(--cyan)' },
              { label: '35–44', value: 14, color: 'var(--mint)' },
              { label: '45+', value: 4, color: 'var(--yellow)' },
            ]}
            height={110}
            labelFmt={(v) => v + '%'}
          />
        </div>
      </div>

      {/* Geo */}
      <div className="mt-4">
        <div className="cap-label mb-2">Top cities</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            ['Ho Chi Minh', 42, 'var(--cyan)'],
            ['Hanoi', 28, 'var(--indigo)'],
            ['Da Nang', 11, 'var(--pink-hot)'],
            ['Can Tho', 6, 'var(--mint-deep)'],
            ['Others', 13, 'var(--ink-soft)'],
          ].map(([l, v, c], i) => (
            <div key={i} className="row items-center gap-12">
              <span style={{ fontSize: 12, width: 100, fontWeight: 600 }}>{l}</span>
              <div style={{ flex: 1, height: 6, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: v + '%', background: c, borderRadius: 999, transformOrigin: 'left',
                  animation: `grow-w 1s ${0.3 + i * 0.1}s cubic-bezier(.4,0,.2,1) both`, transform: 'scaleX(0)' }} />
              </div>
              <span className="tabular bold" style={{ fontSize: 12, width: 40, textAlign: 'right' }}>{v}%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function BudgetCard() {
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Budget &amp; pacing</div>
          <div className="muted" style={{ fontSize: 12 }}>Day 14 of 28 · 50% time elapsed</div>
        </div>
      </div>

      <div className="row items-end justify-between mb-3">
        <div>
          <div className="cap-label">Spent</div>
          <div className="font-display tabular" style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.025em' }}>
            <Counter to={32} prefix="$" duration={1800} />K
          </div>
        </div>
        <div className="text-right">
          <div className="cap-label">Budget</div>
          <div className="font-display tabular muted" style={{ fontSize: 22, fontWeight: 600 }}>$45K</div>
        </div>
      </div>

      {/* Stacked budget bar */}
      <div style={{ position: 'relative', height: 18, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
        <div style={{
          position: 'absolute', left: 0, top: 0, bottom: 0,
          width: '71%',
          background: 'linear-gradient(90deg, var(--cyan), var(--indigo))',
          borderRadius: 999,
          transformOrigin: 'left',
          animation: 'grow-w 1.2s .4s cubic-bezier(.4,0,.2,1) both', transform: 'scaleX(0)'
        }} />
        {/* "now" marker at 50% time elapsed */}
        <div style={{
          position: 'absolute', left: '50%', top: -4, bottom: -4,
          width: 2, background: 'var(--coral)', borderRadius: 999
        }}>
          <div style={{
            position: 'absolute', top: -22, left: -22, fontSize: 9,
            color: 'var(--coral)', fontWeight: 800,
            letterSpacing: '0.08em', whiteSpace: 'nowrap'
          }}>50% TIME</div>
        </div>
      </div>

      <div className="row items-center justify-between" style={{ marginTop: 14, fontSize: 12 }}>
        <Pill variant="yellow">Pacing 21% ahead of plan</Pill>
        <span className="muted">$13K remaining · 14 days left</span>
      </div>

      <div className="cap-label mt-6 mb-2">Breakdown by creator</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {[
          ['Linh Châu', 14, 18, 'var(--cyan)'],
          ['Mai Vy', 12, 16, 'var(--indigo)'],
          ['Hà Giang', 6, 11, 'var(--mint-deep)']
        ].map(([n, s, b, c], i) => (
          <div key={i} className="row items-center gap-12">
            <Avatar name={n} size={26} />
            <span style={{ fontSize: 12, fontWeight: 600, flex: 1 }}>{n}</span>
            <div style={{ flex: 2, height: 6, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: ((s/b)*100) + '%', background: c, borderRadius: 999, transformOrigin: 'left',
                animation: `grow-w .9s ${0.5 + i * 0.12}s cubic-bezier(.4,0,.2,1) both`, transform: 'scaleX(0)' }} />
            </div>
            <span className="tabular bold" style={{ fontSize: 12 }}>${s}K / ${b}K</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenCampaignReport });
