/* screen-brand-dashboard.jsx — KPIs, charts, AI nudges */
/* global React, Counter, Sparkline, BarChart, LineChart, Donut, MatchCircle, Avatar, Pill, Icon, formatCompact, formatMoney,
   DateRangePopover, DATE_RANGE_LABELS, ExportModal, RebookDrawer, TopCreatorsDrawer, ActivityDrawer, Toast,
   useRouter */

// ── KPI tile with sparkline ──
function KpiTile({ label, value, delta, sparkData, color = 'var(--cyan)', icon, decorColor, format }) {
  const [ref, inView] = useInView();
  return (
    <div ref={ref} className="kpi reveal" style={{
      opacity: inView ? 1 : 0,
      transform: inView ? 'translateY(0)' : 'translateY(20px)',
      transition: 'opacity .8s, transform .8s, box-shadow .25s'
    }}>
      {decorColor && <div className="kpi-decor" style={{ background: decorColor }} />}
      <div className="row items-center justify-between" style={{ position: 'relative', zIndex: 1 }}>
        <div className="kpi-label">{label}</div>
        {icon && <div style={{
          width: 40, height: 40, borderRadius: 12,
          background: `color-mix(in srgb, ${color} 14%, white)`,
          border: `1px solid color-mix(in srgb, ${color} 24%, white)`,
          display: 'grid', placeItems: 'center',
          color: color, flexShrink: 0
        }}>{icon}</div>}
      </div>
      <div className="kpi-value" style={{ position: 'relative', zIndex: 1 }}>
        {inView && <Counter to={value} format={format} duration={1600} />}
      </div>
      <div className="kpi-foot" style={{ position: 'relative', zIndex: 1 }}>
        {delta !== undefined && (
          <span className={`kpi-delta ${delta >= 0 ? 'up' : 'down'}`}>
            {delta >= 0 ? Icon.trend : Icon.trendDown}
            {delta >= 0 ? '+' : ''}{delta}%
          </span>
        )}
        {sparkData && <div style={{ flex: 1, marginLeft: 12, maxWidth: 110 }}>
          <Sparkline data={sparkData} color={color} fillId={`kpi-${label}`} height={32} delay={0.3} />
        </div>}
      </div>
    </div>
  );
}

// ── Activity feed (animated entries) ──
function ActivityFeed({ onSelect }) {
  const events = [
    { who: 'Linh Châu', what: 'posted', detail: 'Vitamin C reveal · TikTok', t: '2m ago', color: 'mint' },
    { who: 'AI', what: 'refreshed shortlist for', detail: 'Brief #B-2419', t: '8m ago', color: 'cyan', ai: true },
    { who: 'Mai Vy', what: 'accepted', detail: 'Campaign C-1182 deliverable', t: '24m ago', color: 'lavender' },
    { who: 'Crawler', what: 'updated 412 stats from', detail: 'TikTok · public web', t: '1h ago', color: 'yellow', ai: true },
    { who: 'Hà Giang', what: 'submitted draft', detail: '2 of 3 videos', t: '2h ago', color: 'pink' },
  ];
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-4">
        <div>
          <div className="title-md">Live activity</div>
          <div className="muted" style={{ fontSize: 12 }}>What&rsquo;s happening across your network right now</div>
        </div>
        <Pill variant="mint" icon={<span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--mint-deep)', display: 'inline-block', animation: 'pulse 1.5s ease-out infinite' }} />}>
          Live
        </Pill>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {events.map((e, i) => (
          <div key={i} className="row items-center gap-12"
            onClick={() => onSelect?.(e)}
            style={{
              padding: '12px 4px',
              borderBottom: i < events.length - 1 ? '1px solid var(--line)' : 'none',
              cursor: onSelect ? 'pointer' : 'default',
              animation: `slideIn .6s ${i * 80}ms backwards cubic-bezier(.4,0,.2,1)` }}>
            {e.ai
              ? <div className="orb orb-sm" />
              : <Avatar name={e.who} size={32} />}
            <div className="flex-1">
              <div style={{ fontSize: 13 }}>
                <span className="bold">{e.who}</span>
                <span className="muted"> {e.what} </span>
                <span className="bold">{e.detail}</span>
              </div>
              <div className="muted" style={{ fontSize: 11 }}>{e.t}</div>
            </div>
            <Pill variant={e.color}>•</Pill>
          </div>
        ))}
      </div>
      <style>{`@keyframes slideIn { from { transform: translateX(-12px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }`}</style>
    </div>
  );
}

// ── Campaign cards (mini) ──
function CampaignMini({ name, status, reach, er, spend, budget, color }) {
  const pct = (spend / budget) * 100;
  return (
    <div className="card-elevated" style={{ padding: 18 }}>
      <div className="row items-center justify-between mb-2">
        <div>
          <div className="title-md" style={{ fontSize: 15 }}>{name}</div>
          <Pill variant={status === 'live' ? 'mint' : status === 'review' ? 'yellow' : 'lav'}>
            {status === 'live' ? '● LIVE' : status === 'review' ? 'IN REVIEW' : 'COMPLETED'}
          </Pill>
        </div>
        <div className="orb orb-sm" style={{ background: color }} />
      </div>
      <div className="row gap-16 mt-3">
        <div>
          <div className="cap-label" style={{ fontSize: 9 }}>Reach</div>
          <div className="font-display bold tabular" style={{ fontSize: 18 }}>{reach}</div>
        </div>
        <div>
          <div className="cap-label" style={{ fontSize: 9 }}>ER</div>
          <div className="font-display bold tabular" style={{ fontSize: 18 }}>{er}%</div>
        </div>
        <div>
          <div className="cap-label" style={{ fontSize: 9 }}>Spend / Budget</div>
          <div className="font-display bold tabular" style={{ fontSize: 18 }}>${spend}K / ${budget}K</div>
        </div>
      </div>
      <div style={{ height: 6, background: 'var(--bg-soft)', borderRadius: 999, marginTop: 10, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: pct + '%', background: color, borderRadius: 999, animation: 'grow-w .9s .3s cubic-bezier(.4,0,.2,1) both', transformOrigin: 'left', transform: 'scaleX(0)' }} />
      </div>
    </div>
  );
}

// ── Network heatmap ──
function NetworkHeatmap() {
  // 7x14 grid of activity density
  const rows = 7;
  const cols = 14;
  const palette = [
    'rgba(0,156,255,0.06)',
    'rgba(0,156,255,0.18)',
    'rgba(0,156,255,0.35)',
    'rgba(0,156,255,0.55)',
    'rgba(0,156,255,0.78)',
  ];
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-4">
        <div>
          <div className="title-md">Creator activity heatmap</div>
          <div className="muted" style={{ fontSize: 12 }}>Posts per day · last 2 weeks</div>
        </div>
        <div className="row items-center gap-6">
          <span className="cap-label" style={{ fontSize: 9 }}>Less</span>
          {palette.map((c, i) => <div key={i} style={{ width: 14, height: 14, background: c, borderRadius: 3 }} />)}
          <span className="cap-label" style={{ fontSize: 9 }}>More</span>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 8 }}>
        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-around', fontSize: 10, color: 'var(--ink-soft)', paddingRight: 4 }}>
          {['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map(d => <div key={d}>{d}</div>)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 4 }}>
          {Array.from({ length: rows * cols }).map((_, i) => {
            // pseudo-random seeded
            const v = Math.floor((Math.sin(i * 1.7) + 1) * 2.5);
            return (
              <div key={i} style={{
                aspectRatio: '1/1',
                background: palette[v],
                borderRadius: 4,
                animation: `cellIn .4s ${i * 8}ms backwards cubic-bezier(.4,0,.2,1)`,
                transform: 'scale(0)'
              }} />
            );
          })}
        </div>
      </div>
      <div className="row items-center justify-between" style={{ marginTop: 12, fontSize: 11, color: 'var(--ink-soft)' }}>
        <span>14 days ago</span>
        <span>Today</span>
      </div>
      <style>{`@keyframes cellIn { from { transform: scale(0); } to { transform: scale(1); } }`}</style>
    </div>
  );
}

// ── Top creators leaderboard ──
function TopCreators({ onViewAll, onSelect }) {
  const list = [
    { n: 'Linh Châu', cat: 'Skincare', r: 4.8, er: 6.2, m: 94 },
    { n: 'Mai Vy', cat: 'Lifestyle', r: 3.2, er: 5.8, m: 88 },
    { n: 'Hà Giang', cat: 'Beauty', r: 2.4, er: 7.1, m: 81 },
    { n: 'Phương Anh', cat: 'Fashion', r: 1.9, er: 4.4, m: 78 },
  ];
  return (
    <div className="card-elevated">
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Top creators this week</div>
          <div className="muted" style={{ fontSize: 12 }}>Ranked by AI match × reach</div>
        </div>
        <a className="row items-center gap-6" onClick={onViewAll} style={{ fontSize: 12, color: 'var(--cyan-dark)', fontWeight: 700, cursor: 'pointer' }}>
          View all {Icon.arrow}
        </a>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {list.map((c, i) => (
          <div key={i} className="row items-center gap-12"
            onClick={() => onSelect?.(c)}
            style={{
              padding: '12px 4px',
              borderBottom: i < list.length - 1 ? '1px solid var(--line)' : 'none',
              cursor: onSelect ? 'pointer' : 'default'
            }}>
            <div className="font-display bold tabular" style={{ fontSize: 18, width: 24, color: 'var(--ink-soft)' }}>{i + 1}</div>
            <Avatar name={c.n} size={36} />
            <div className="flex-1">
              <div className="bold" style={{ fontSize: 13 }}>{c.n}</div>
              <div className="muted" style={{ fontSize: 11 }}>{c.cat} · {c.r}M reach · {c.er}% ER</div>
            </div>
            <MatchCircle score={c.m} size={42} />
          </div>
        ))}
      </div>
    </div>
  );
}

function ScreenBrandDashboard() {
  const { go } = useRouter();
  const filterBtnRef = React.useRef(null);
  const [dateRange, setDateRange] = React.useState('7d');
  const [filterOpen, setFilterOpen] = React.useState(false);
  const [exportOpen, setExportOpen] = React.useState(false);
  const [rebookOpen, setRebookOpen] = React.useState(false);
  const [topOpen, setTopOpen] = React.useState(false);
  const [activeEvent, setActiveEvent] = React.useState(null);
  const [toast, setToast] = React.useState(null);

  return (
    <div className="app-shell">
      <AppSidebar portal="brand" active="brand-dashboard" />
      <main className="main">
        <AppTopbar />

        <div className="row items-end justify-between mb-6">
          <div>
            <h1 className="page-title">Good morning, <span style={{
              background: 'linear-gradient(90deg, #009CFF, #1C1CC9)',
              WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent'
            }}>Coolmate</span>.</h1>
            <div className="page-subtitle">Wednesday, 13 May 2026 · 3 campaigns live · 1 brief awaiting approval</div>
          </div>
          <div className="row gap-8">
            <button ref={filterBtnRef} className="btn btn-ghost btn-sm" onClick={() => setFilterOpen(true)}>
              {Icon.filter} {DATE_RANGE_LABELS[dateRange]}
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 2 }}><path d="m6 9 6 6 6-6" /></svg>
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => setExportOpen(true)}>{Icon.external} Export</button>
          </div>
        </div>

        {/* KPI row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
          <KpiTile
            label="Reach (7d)"
            value={4.8}
            format={(v) => v.toFixed(1) + 'M'}
            delta={28}
            color="var(--cyan)"
            decorColor="var(--cyan)"
            icon={Icon.globe}
            sparkData={[2.2, 2.8, 3.0, 3.4, 3.9, 4.3, 4.8]}
          />
          <KpiTile
            label="Engagement rate"
            value={6.2}
            format={(v) => v.toFixed(1) + '%'}
            delta={12}
            color="var(--mint-deep)"
            decorColor="var(--mint)"
            icon={Icon.flame}
            sparkData={[3.2, 3.8, 4.4, 4.9, 5.5, 5.9, 6.2]}
          />
          <KpiTile
            label="Active KOLs"
            value={42}
            delta={9}
            color="var(--indigo)"
            decorColor="var(--lavender)"
            icon={Icon.users}
            sparkData={[28, 32, 35, 36, 38, 40, 42]}
          />
          <KpiTile
            label="Spend / Budget"
            value={72}
            format={(v) => '$' + Math.round(v) + 'K'}
            delta={-4}
            color="var(--coral)"
            decorColor="var(--pink)"
            icon={Icon.dollar}
            sparkData={[12, 24, 36, 44, 56, 64, 72]}
          />
        </div>

        {/* AI Brief recommendation banner */}
        <div className="card-elevated mt-6" style={{
          padding: 24,
          background: 'linear-gradient(120deg, #002B50 0%, #1C1CC9 100%)',
          color: 'white',
          position: 'relative',
          overflow: 'hidden'
        }}>
          <div style={{
            position: 'absolute', top: -40, right: -40,
            width: 220, height: 220, borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(255,111,163,0.45), transparent 60%)',
            filter: 'blur(20px)'
          }} />
          <div className="row items-center gap-16" style={{ position: 'relative', zIndex: 1 }}>
            <div className="orb" />
            <div className="flex-1">
              <Pill variant="dark"><span style={{ color: 'var(--mint)' }}>●</span> AI suggestion</Pill>
              <h3 className="font-display" style={{ fontSize: 24, fontWeight: 700, marginTop: 6, marginBottom: 4, letterSpacing: '-0.02em' }}>
                Re-book <span style={{ color: 'var(--mint)' }}>Linh Châu</span> for Vitamin C Q3 — she over-performed by <Counter to={38} duration={1500} />%.
              </h3>
              <p style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', margin: 0 }}>
                Based on her CPM of $6.12 (band: $9–12), 6.2% ER, and high audience overlap with the new SPF brief.
              </p>
            </div>
            <button className="btn btn-yellow" onClick={() => setRebookOpen(true)}>Review re-book</button>
          </div>
        </div>

        {/* Main grid: chart + activity */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, marginTop: 24 }}>
          <div className="card-elevated">
            <div className="row items-center justify-between mb-3">
              <div>
                <div className="title-md">Reach &amp; engagement over time</div>
                <div className="muted" style={{ fontSize: 12 }}>Last 12 weeks · all campaigns</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 }}>Reach (M)</span></div>
                <div className="row items-center gap-6"><span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--pink-hot)' }} /><span style={{ fontSize: 12 }}>ER (%)</span></div>
              </div>
            </div>
            <LineChart
              series={[
                { name: 'Reach', color: '#009CFF', data: [0.8, 1.2, 1.6, 1.9, 2.4, 2.6, 3.1, 3.4, 3.8, 4.2, 4.4, 4.8] },
                { name: 'ER', color: '#FF6FA3', data: [0.4, 0.5, 0.6, 0.7, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.55] },
              ]}
              xLabels={['W1','W2','W3','W4','W5','W6','W7','W8','W9','W10','W11','W12']}
              height={260}
            />
          </div>
          <ActivityFeed onSelect={(e) => setActiveEvent(e)} />
        </div>

        {/* Campaigns + Donut row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14, marginTop: 18 }}>
          <CampaignMini name="Vitamin C Launch" status="live" reach="4.8M" er="6.2" spend={32} budget={45} color="var(--cyan)" />
          <CampaignMini name="SPF Glow Tour" status="live" reach="2.1M" er="5.4" spend={18} budget={28} color="var(--mint-deep)" />
          <CampaignMini name="Tet Cleanup '26" status="review" reach="—" er="—" spend={4} budget={20} color="var(--indigo)" />
        </div>

        {/* Bottom: heatmap + leaderboard + donut */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18, marginTop: 18 }}>
          <NetworkHeatmap />
          <div className="card-elevated">
            <div className="row items-center justify-between mb-3">
              <div>
                <div className="title-md">Where the budget went</div>
                <div className="muted" style={{ fontSize: 12 }}>By platform · Q2 to date</div>
              </div>
            </div>
            <div className="row items-center gap-24" style={{ paddingTop: 8 }}>
              <Donut
                data={[
                  { label: 'TikTok', value: 42, color: '#002B50' },
                  { label: 'Instagram', value: 28, color: '#FF6FA3' },
                  { label: 'YouTube', value: 18, color: '#FF4444' },
                  { label: 'Shopee', value: 12, color: '#FEE960' },
                ]}
                size={170}
                thickness={22}
                centerLabel="Total"
                centerValue="$72K"
              />
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[
                  { l: 'TikTok', c: '#002B50', v: 42, amt: '$30.2K' },
                  { l: 'Instagram', c: '#FF6FA3', v: 28, amt: '$20.2K' },
                  { l: 'YouTube', c: '#FF4444', v: 18, amt: '$13.0K' },
                  { l: 'Shopee', c: '#FEE960', v: 12, amt: '$8.6K' },
                ].map((d, i) => (
                  <div key={i} className="row items-center gap-12">
                    <span style={{ width: 12, height: 12, borderRadius: 4, background: d.c }} />
                    <span className="bold" style={{ fontSize: 13, flex: 1 }}>{d.l}</span>
                    <span className="tabular muted" style={{ fontSize: 12 }}>{d.v}%</span>
                    <span className="tabular bold" style={{ fontSize: 12 }}>{d.amt}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 18 }}>
          <TopCreators
            onViewAll={() => setTopOpen(true)}
            onSelect={() => go('brand-influencer-detail')}
          />
        </div>

        {/* Overlays */}
        <DateRangePopover
          open={filterOpen}
          onClose={() => setFilterOpen(false)}
          anchorRef={filterBtnRef}
          value={dateRange}
          onChange={(v) => { setDateRange(v); setToast({ msg: `Filtered to ${DATE_RANGE_LABELS[v]}.` }); }}
        />
        <ExportModal
          open={exportOpen}
          onClose={() => setExportOpen(false)}
          onDone={({ format }) => setToast({ msg: `${format.toUpperCase()} export ready. Download started.`, kind: 'success' })}
        />
        <RebookDrawer
          open={rebookOpen}
          onClose={() => setRebookOpen(false)}
          onBook={() => setToast({ msg: 'Linh Châu re-booked for SPF Glow Tour. Contract sent.', kind: 'success' })}
        />
        <TopCreatorsDrawer
          open={topOpen}
          onClose={() => setTopOpen(false)}
          onOpenCreator={() => { setTopOpen(false); go('brand-influencer-detail'); }}
        />
        <ActivityDrawer
          event={activeEvent}
          open={!!activeEvent}
          onClose={() => setActiveEvent(null)}
        />
        <Toast
          open={!!toast}
          onClose={() => setToast(null)}
          kind={toast?.kind || 'info'}
          message={toast?.msg}
        />
      </main>
    </div>
  );
}

Object.assign(window, { ScreenBrandDashboard });
