// Órbita — Analytics (2 variações + estados completos)

const { useState: useStateA, useMemo: useMemoA } = React;

// ── helpers ────────────────────────────────────────────────
const formatNumber = (n) => n >= 1000 ? `${(n/1000).toFixed(1)}k` : String(n);
const sumArr = (arr) => arr.reduce((a, b) => a + b, 0);
const pctChange = (a, b) => b === 0 ? 0 : ((a - b) / b) * 100;

// ── AnalyticsScreen ────────────────────────────────────────
const AnalyticsScreen = ({ onNewSession, onOpenSettings, state = 'data', variant = 'cockpit' }) => {
  const { theme } = useTheme();
  const A = window.ORBITA_DATA.analytics;
  const consulentes = window.ORBITA_DATA.consulentes;

  const [range, setRange] = useStateA('12w');
  const [localState, setLocalState] = useStateA(state);
  React.useEffect(() => { setLocalState(state); }, [state]);
  const retry = () => { setLocalState('loading'); setTimeout(() => setLocalState('data'), 900); };

  const [tagFilter, setTagFilter] = useStateA('all');
  const allTags = useMemoA(() => {
    const set = new Set();
    consulentes.forEach(c => c.tags.forEach(t => set.add(t)));
    return Array.from(set).sort();
  }, [consulentes]);
  const filteredConsulentes = useMemoA(
    () => tagFilter === 'all' ? consulentes : consulentes.filter(c => c.tags.includes(tagFilter)),
    [consulentes, tagFilter]
  );
  const filteredA = useMemoA(() => ({
    ...A,
    recent_events: A.recent_events.filter(ev => filteredConsulentes.some(c => c.id === ev.consulente_id)),
  }), [A, filteredConsulentes]);

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, color: theme.fg, fontFamily: 'Inter, sans-serif' }}>
      <GrainOverlay />
      <ScreenHeader title="Analytics" onOpenSettings={onOpenSettings} />

      <div className="orbita-page" style={{ maxWidth: 1100, margin: '0 auto', padding: '32px 32px 100px', position: 'relative' }}>
        <RadialGlow opacity={0.08} top="-100px" />

        {/* Title row */}
        <div style={{
          marginBottom: 28, position: 'relative', zIndex: 1,
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap',
        }}>
          <div>
            <p style={{ margin: '0 0 4px', fontSize: 11, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Sua prática</p>
            <h1 style={{ margin: 0, fontSize: 36, fontFamily: '"Instrument Serif", serif', fontWeight: 400, letterSpacing: '-0.01em' }}>
              Analytics
            </h1>
          </div>
          {localState === 'data' && (
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <TagFilterMenu value={tagFilter} onChange={setTagFilter} options={allTags} />
              <RangeSelector value={range} onChange={setRange} />
              <ExportReportButton />
            </div>
          )}
        </div>

        {localState === 'loading' && <AnalyticsLoading />}
        {localState === 'error'   && <AnalyticsError onRetry={retry} />}
        {localState === 'empty'   && <AnalyticsEmpty onNewSession={onNewSession} />}

        {localState === 'data' && (
          variant === 'cockpit'
            ? <AnalyticsCockpit A={filteredA} consulentes={filteredConsulentes} />
            : <AnalyticsNarrative A={filteredA} consulentes={filteredConsulentes} />
        )}
      </div>
    </div>
  );
};

// ── Tag filter ──────────────────────────────────────────────
const TagFilterMenu = ({ value, onChange, options }) => {
  const { theme } = useTheme();
  return (
    <select value={value} onChange={e => onChange(e.target.value)} style={{
      padding: '9px 14px', background: theme.inputBg, border: `1px solid ${theme.border}`,
      borderRadius: 999, color: theme.fg, fontSize: 12, fontFamily: 'Inter', outline: 'none', cursor: 'pointer',
    }}>
      <option value="all">Todas as tags</option>
      {options.map(t => <option key={t} value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>)}
    </select>
  );
};

// ── Range selector ─────────────────────────────────────────
const RangeSelector = ({ value, onChange }) => {
  const { theme } = useTheme();
  const opts = [{id:'4w',label:'4 sem'},{id:'12w',label:'12 sem'},{id:'6m',label:'6 m'},{id:'1y',label:'1 ano'}];
  return (
    <div style={{ display: 'inline-flex', gap: 0, padding: 4, background: theme.inputBg, borderRadius: 999, border: `1px solid ${theme.border}` }}>
      {opts.map(o => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          padding: '6px 14px', borderRadius: 999, border: 'none',
          background: value === o.id ? theme.accent : 'transparent',
          color: value === o.id ? (theme.id === 'light' ? '#FDFAF5' : '#100D0A') : theme.fgMuted,
          fontFamily: 'Inter', fontSize: 12, fontWeight: 500, cursor: 'pointer',
        }}>{o.label}</button>
      ))}
    </div>
  );
};

// ── Export report button ───────────────────────────────────
const ExportReportButton = () => {
  const { theme } = useTheme();
  const [open, setOpen] = useStateA(false);
  const [done, setDone] = useStateA(null); // 'PDF' | 'CSV'
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const exportAs = (fmt) => { setOpen(false); setDone(fmt); setTimeout(() => setDone(null), 2200); };
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        padding: '9px 16px', borderRadius: 999, border: `1px solid ${theme.border}`,
        background: theme.inputBg, color: done ? theme.success : theme.fg, fontSize: 12, fontWeight: 500,
        cursor: 'pointer', fontFamily: 'Inter, sans-serif',
      }}>{done ? `✓ ${done} baixado` : 'Exportar relatório ↓'}</button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0, width: 180, zIndex: 50,
          background: theme.surface, border: `1px solid ${theme.border}`, borderRadius: 12, overflow: 'hidden',
          boxShadow: '0 12px 32px rgba(0,0,0,0.35)',
        }}>
          {['PDF', 'CSV'].map(fmt => (
            <button key={fmt} onClick={() => exportAs(fmt)} style={{
              display: 'block', width: '100%', textAlign: 'left', padding: '10px 14px',
              background: 'none', border: 'none', color: theme.fgMuted, fontSize: 12.5,
              cursor: 'pointer', fontFamily: 'Inter, sans-serif',
            }}
            onMouseEnter={e => e.currentTarget.style.background = theme.inputBg}
            onMouseLeave={e => e.currentTarget.style.background = 'none'}
            >Baixar como {fmt}</button>
          ))}
        </div>
      )}
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// Variant 1: Cockpit — KPI grid + charts side-by-side
// ════════════════════════════════════════════════════════════
const AnalyticsCockpit = ({ A, consulentes }) => {
  const { theme } = useTheme();

  const kpis = [
    { label: 'Sessões',         value: A.totals.sessions_total,    delta: 24,   sub: `${A.totals.sessions_published} publicadas` },
    { label: 'Consulentes',     value: A.totals.consulentes_active, delta: 12.5, sub: `${A.totals.consulentes_engaged} engajadas` },
    { label: 'Visitas portal',  value: A.totals.portal_visits_30d, delta: 38,   sub: 'últimos 30 dias' },
    { label: 'Check-ins',       value: A.totals.check_ins_30d,     delta: 19,   sub: 'últimos 30 dias' },
  ];

  return (
    <div style={{ position: 'relative', zIndex: 1 }}>
      {/* KPI strip */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12, marginBottom: 28,
      }}>
        {kpis.map(k => <KPICard key={k.label} {...k} />)}
      </div>

      {/* Two-column charts */}
      <div className="orbita-chart-grid-a" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16, marginBottom: 16 }}>
        <style>{`@media (min-width: 900px){ .orbita-chart-grid-a{ grid-template-columns: 1.6fr 1fr !important; } }`}</style>
        <ChartCard title="Atividade semanal" subtitle="Sessões criadas e publicadas, últimas 12 semanas">
          <DualLineChart labels={A.week_labels} a={A.weekly_sessions} b={A.weekly_publishes} aLabel="Criadas" bLabel="Publicadas" />
        </ChartCard>

        <ChartCard title="Por área de vida" subtitle="Distribuição dos cards revisados">
          <AreaBars data={A.by_area} />
        </ChartCard>
      </div>

      <div className="orbita-chart-grid-b" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16, marginBottom: 16 }}>
        <style>{`@media (min-width: 900px){ .orbita-chart-grid-b{ grid-template-columns: 1fr 1fr !important; } }`}</style>
        <ChartCard title="Engajamento das consulentes" subtitle="Visitas e check-ins, 12 semanas">
          <StackedBars labels={A.week_labels} a={A.weekly_visits} b={A.weekly_checkins} aLabel="Visitas" bLabel="Check-ins" />
        </ChartCard>

        <ChartCard title="Funil de sessão" subtitle="Da gravação ao acesso da consulente">
          <Funnel data={A.funnel} />
        </ChartCard>
      </div>

      {/* Bottom: top consulentes + activity feed */}
      <div className="orbita-chart-grid-c" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16 }}>
        <style>{`@media (min-width: 900px){ .orbita-chart-grid-c{ grid-template-columns: 1fr 1.2fr !important; } }`}</style>
        <ChartCard title="Top consulentes" subtitle="Por engajamento nos últimos 30 dias">
          <TopList ids={A.top_consulentes} consulentes={consulentes} />
        </ChartCard>

        <ChartCard title="Atividade recente" subtitle="O que suas consulentes andaram fazendo">
          <ActivityFeed events={A.recent_events} consulentes={consulentes} />
        </ChartCard>
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// Variant 2: Narrative — single column, story-shaped
// ════════════════════════════════════════════════════════════
const AnalyticsNarrative = ({ A, consulentes }) => {
  const { theme } = useTheme();
  const recentSessions = A.weekly_sessions.slice(-4);
  const prevSessions   = A.weekly_sessions.slice(-8, -4);
  const sessionsDelta  = pctChange(sumArr(recentSessions), sumArr(prevSessions));
  const visitsDelta    = pctChange(sumArr(A.weekly_visits.slice(-4)), sumArr(A.weekly_visits.slice(-8,-4)));

  return (
    <div style={{ position: 'relative', zIndex: 1, maxWidth: 820, margin: '0 auto' }}>
      {/* Hero stat */}
      <div style={{
        background: `linear-gradient(135deg, ${theme.accent}10, ${theme.accent}03)`,
        border: `1px solid ${theme.accent}30`, borderRadius: 24,
        padding: '40px 36px', marginBottom: 24, textAlign: 'center',
      }}>
        <p style={{ margin: '0 0 12px', fontSize: 12, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.12em' }}>
          Você economizou
        </p>
        <div style={{ fontSize: 84, fontFamily: '"Instrument Serif", serif', color: theme.accent, lineHeight: 1, marginBottom: 8 }}>
          {A.totals.hours_saved}h
        </div>
        <p style={{ margin: 0, fontSize: 14, color: theme.fgMuted, fontFamily: '"Instrument Serif", serif', fontStyle: 'italic' }}>
          de pós-trabalho nos últimos 30 dias
        </p>
        <p style={{ margin: '20px auto 0', fontSize: 13, color: theme.fg, lineHeight: 1.7, maxWidth: 480 }}>
          O equivalente a uma semana inteira de devolutivas, transcrições e diagramação. Com o Órbitas, esse tempo virou {A.totals.sessions_published} sessões publicadas e {A.totals.portal_visits_30d} visitas das suas consulentes.
        </p>
      </div>

      {/* Narrative blocks */}
      <NarrativeBlock
        eyebrow="Crescimento"
        title={`Sua prática cresceu ${sessionsDelta > 0 ? '+' : ''}${sessionsDelta.toFixed(0)}% no último mês`}
        body="Você criou mais sessões nas últimas 4 semanas do que nas 4 anteriores. O ritmo é sustentável — mas se quiser desacelerar, abra dois espaços de revolução solar por semana, no máximo."
      >
        <SparkLine values={A.weekly_sessions} accent />
        <p style={{ margin: '14px 0 0', fontSize: 11, color: theme.fgDim, fontFamily: 'DM Mono, monospace', textAlign: 'right' }}>
          {sumArr(A.weekly_sessions)} sessões nas últimas 12 semanas
        </p>
      </NarrativeBlock>

      <NarrativeBlock
        eyebrow="Engajamento"
        title={`As consulentes voltam ${visitsDelta > 0 ? '+' : ''}${visitsDelta.toFixed(0)}% mais aos portais`}
        body="O portal funciona como ponto de retorno: cada consulente ativa volta em média 3,4 vezes por mês. As que não voltam costumam ter check-ins atrasados — pode valer um lembrete pessoal."
      >
        <SparkLine values={A.weekly_visits} accent={false} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14 }}>
          <span style={{ fontSize: 11, color: theme.fgDim, fontFamily: 'DM Mono, monospace' }}>
            {A.totals.portal_visits_30d} visitas · {A.totals.check_ins_30d} check-ins
          </span>
          <span style={{ fontSize: 11, color: theme.success, fontFamily: 'DM Mono, monospace' }}>
            ↑ tendência de alta
          </span>
        </div>
      </NarrativeBlock>

      <NarrativeBlock
        eyebrow="Áreas mais frequentes"
        title="Carreira e relações dominam suas devolutivas"
        body="Mais de metade dos seus cards revisados nos últimos 90 dias falam de carreira ou relações. Faz sentido pelo perfil etário das suas consulentes — mas vale notar que saúde tem aparecido menos do que nas estações anteriores."
      >
        <AreaBars data={A.by_area} compact />
      </NarrativeBlock>

      <NarrativeBlock
        eyebrow="Quem está mais engajada"
        title="Cinco consulentes mantêm sua prática viva"
        body="Estas voltam ao portal com regularidade e usam os check-ins. Considere oferecer encontros mensais para esse grupo — você já tem dados para sustentar a continuidade."
      >
        <TopList ids={A.top_consulentes} consulentes={consulentes} />
      </NarrativeBlock>

      <div style={{
        padding: '24px 28px', marginTop: 8,
        background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 16,
      }}>
        <p style={{ margin: '0 0 6px', fontSize: 11, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Funil de sessão</p>
        <Funnel data={A.funnel} />
      </div>
    </div>
  );
};

const NarrativeBlock = ({ eyebrow, title, body, children }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 16,
      padding: '28px 32px', marginBottom: 16,
    }}>
      <p style={{ margin: '0 0 6px', fontSize: 11, color: theme.accent, textTransform: 'uppercase', letterSpacing: '0.12em' }}>{eyebrow}</p>
      <h3 style={{ margin: '0 0 12px', fontSize: 22, fontFamily: '"Instrument Serif", serif', fontWeight: 400, letterSpacing: '-0.01em', color: theme.fg, lineHeight: 1.3 }}>
        {title}
      </h3>
      <p style={{ margin: '0 0 20px', fontSize: 14, color: theme.fgMuted, lineHeight: 1.65 }}>{body}</p>
      {children}
    </div>
  );
};

// ── KPI Card ───────────────────────────────────────────────
const KPICard = ({ label, value, delta, sub }) => {
  const { theme } = useTheme();
  const positive = delta >= 0;
  return (
    <div style={{
      background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 14,
      padding: '20px 22px',
    }}>
      <div style={{ fontSize: 10, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 12 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 6 }}>
        <span style={{ fontSize: 36, fontFamily: '"Instrument Serif", serif', color: theme.fg, lineHeight: 1 }}>
          {formatNumber(value)}
        </span>
        <span style={{
          fontSize: 11, fontFamily: 'DM Mono, monospace', fontWeight: 500,
          color: positive ? theme.success : theme.hot,
        }}>
          {positive ? '↑' : '↓'} {Math.abs(delta).toFixed(0)}%
        </span>
      </div>
      <div style={{ fontSize: 11, color: theme.fgDim }}>{sub}</div>
    </div>
  );
};

// ── ChartCard wrapper ──────────────────────────────────────
const ChartCard = ({ title, subtitle, children }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 16,
      padding: '22px 24px',
    }}>
      <div style={{ marginBottom: 18 }}>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: theme.fg }}>{title}</h3>
        {subtitle && <p style={{ margin: '3px 0 0', fontSize: 11, color: theme.fgMuted }}>{subtitle}</p>}
      </div>
      {children}
    </div>
  );
};

// ── Charts ─────────────────────────────────────────────────
const DualLineChart = ({ labels, a, b, aLabel, bLabel }) => {
  const { theme } = useTheme();
  const W = 560, H = 180, pad = { l: 28, r: 12, t: 12, b: 22 };
  const max = Math.max(...a, ...b, 4);
  const x = (i) => pad.l + (i / (labels.length - 1)) * (W - pad.l - pad.r);
  const y = (v) => H - pad.b - (v / max) * (H - pad.t - pad.b);
  const path = (arr) => arr.map((v, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');

  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        {/* gridlines */}
        {[0.25, 0.5, 0.75, 1].map((p, i) => (
          <line key={i} x1={pad.l} x2={W - pad.r} y1={pad.t + p * (H - pad.t - pad.b)} y2={pad.t + p * (H - pad.t - pad.b)} stroke={theme.border} strokeDasharray="2 4" />
        ))}
        {/* y-axis ticks */}
        {[0, max].map((v, i) => (
          <text key={i} x={pad.l - 6} y={i === 0 ? H - pad.b + 4 : pad.t + 4} textAnchor="end" fontSize="9" fontFamily="DM Mono, monospace" fill={theme.fgDim}>{v}</text>
        ))}
        {/* x labels (every other) */}
        {labels.map((l, i) => i % 2 === 0 && (
          <text key={i} x={x(i)} y={H - 6} textAnchor="middle" fontSize="9" fontFamily="DM Mono, monospace" fill={theme.fgDim}>{l}</text>
        ))}

        {/* area under line A */}
        <path d={`${path(a)} L${x(a.length-1)},${H-pad.b} L${pad.l},${H-pad.b} Z`} fill={`${theme.accent}18`} />
        <path d={path(a)} fill="none" stroke={theme.accent} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
        <path d={path(b)} fill="none" stroke={theme.info} strokeWidth="1.6" strokeDasharray="4 3" strokeLinecap="round" strokeLinejoin="round" />

        {/* end-point dots */}
        <circle cx={x(a.length-1)} cy={y(a[a.length-1])} r="3.5" fill={theme.accent} />
        <circle cx={x(b.length-1)} cy={y(b[b.length-1])} r="3.5" fill={theme.info} />
      </svg>
      <div style={{ display: 'flex', gap: 18, marginTop: 8, fontSize: 11, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 10, height: 2, background: theme.accent, borderRadius: 1 }} /> {aLabel}
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 10, height: 2, background: theme.info, borderRadius: 1, opacity: 0.7 }} /> {bLabel}
        </span>
      </div>
    </div>
  );
};

const StackedBars = ({ labels, a, b, aLabel, bLabel }) => {
  const { theme } = useTheme();
  const W = 380, H = 180, pad = { l: 24, r: 8, t: 12, b: 22 };
  const max = Math.max(...a.map((v, i) => v + b[i]), 1);
  const bw = (W - pad.l - pad.r) / labels.length * 0.7;
  const xc = (i) => pad.l + (i + 0.5) * (W - pad.l - pad.r) / labels.length;

  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        {labels.map((l, i) => i % 3 === 0 && (
          <text key={i} x={xc(i)} y={H - 6} textAnchor="middle" fontSize="9" fontFamily="DM Mono, monospace" fill={theme.fgDim}>{l}</text>
        ))}
        {a.map((v, i) => {
          const aH = (v / max) * (H - pad.t - pad.b);
          const bH = (b[i] / max) * (H - pad.t - pad.b);
          const x = xc(i) - bw / 2;
          return (
            <g key={i}>
              <rect x={x} y={H - pad.b - aH} width={bw} height={aH} fill={theme.info} opacity="0.65" rx="1.5" />
              <rect x={x} y={H - pad.b - aH - bH} width={bw} height={bH} fill={theme.accent} opacity="0.9" rx="1.5" />
            </g>
          );
        })}
      </svg>
      <div style={{ display: 'flex', gap: 18, marginTop: 8, fontSize: 11, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 8, height: 8, background: theme.accent, borderRadius: 2 }} /> {bLabel}
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 8, height: 8, background: theme.info, borderRadius: 2, opacity: 0.65 }} /> {aLabel}
        </span>
      </div>
    </div>
  );
};

const AreaBars = ({ data, compact }) => {
  const { theme } = useTheme();
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: compact ? 8 : 12 }}>
      {data.map(d => (
        <div key={d.area}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
            <span style={{ fontSize: 12, color: theme.fg, textTransform: 'capitalize' }}>{d.area}</span>
            <span style={{ fontSize: 11, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>{Math.round(d.pct * 100)}%</span>
          </div>
          <div style={{ height: 6, background: theme.inputBg, borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ width: `${d.pct * 100}%`, height: '100%', background: `linear-gradient(90deg, ${theme.accent}, ${theme.accent}aa)`, borderRadius: 3 }} />
          </div>
        </div>
      ))}
    </div>
  );
};

const Funnel = ({ data }) => {
  const { theme } = useTheme();
  const max = data[0].value;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {data.map((d, i) => {
        const pct = (d.value / max) * 100;
        const dropoff = i > 0 ? data[i-1].value - d.value : 0;
        return (
          <div key={d.stage} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ fontSize: 12, color: theme.fgMuted, width: 130, flexShrink: 0 }}>{d.stage}</span>
            <div style={{ flex: 1, height: 26, background: theme.inputBg, borderRadius: 4, position: 'relative' }}>
              <div style={{
                width: `${pct}%`, height: '100%',
                background: `linear-gradient(90deg, ${theme.accent}cc, ${theme.accent}77)`,
                borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 10,
              }}>
                <span style={{ fontSize: 11, color: theme.id === 'light' ? '#FDFAF5' : '#100D0A', fontFamily: 'DM Mono, monospace', fontWeight: 600 }}>
                  {d.value}
                </span>
              </div>
            </div>
            <span style={{ width: 50, fontSize: 10, color: dropoff > 0 ? theme.hot : theme.fgDim, fontFamily: 'DM Mono, monospace', textAlign: 'right' }}>
              {dropoff > 0 ? `−${dropoff}` : ''}
            </span>
          </div>
        );
      })}
    </div>
  );
};

const TopList = ({ ids, consulentes }) => {
  const { theme } = useTheme();
  const list = ids.map(id => consulentes.find(c => c.id === id)).filter(Boolean);
  if (list.length === 0) {
    return <div style={{ fontSize: 12, color: theme.fgDim, padding: '8px 0' }}>Nenhuma consulente com esta tag entre os destaques.</div>;
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {list.map((c, i) => (
        <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 11, color: theme.fgDim, fontFamily: 'DM Mono, monospace', width: 18 }}>{(i+1).toString().padStart(2,'0')}</span>
          <Avatar name={c.name} size={28} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, color: theme.fg, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
            <div style={{ fontSize: 10, color: theme.fgDim, fontFamily: 'DM Mono, monospace' }}>{c.check_ins} check-ins</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 50, height: 4, background: theme.inputBg, borderRadius: 2, overflow: 'hidden' }}>
              <div style={{ width: `${c.engagement * 100}%`, height: '100%', background: theme.accent }} />
            </div>
            <span style={{ fontSize: 10, color: theme.fgMuted, fontFamily: 'DM Mono, monospace', width: 26 }}>{Math.round(c.engagement*100)}%</span>
          </div>
        </div>
      ))}
    </div>
  );
};

const ActivityFeed = ({ events, consulentes }) => {
  const { theme } = useTheme();
  const iconMap = {
    check_in: '◉', visit: '○', publish: '◆', session: '◐',
  };
  const colorMap = {
    check_in: theme.success, visit: theme.info, publish: theme.accent, session: theme.fg,
  };
  if (events.length === 0) {
    return <div style={{ fontSize: 12, color: theme.fgDim, padding: '8px 0' }}>Nenhuma atividade recente com esta tag.</div>;
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {events.map((ev, i) => {
        const c = consulentes.find(c => c.id === ev.consulente_id);
        return (
          <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
            <span style={{ fontSize: 12, color: colorMap[ev.kind], marginTop: 1 }}>{iconMap[ev.kind]}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, color: theme.fg, lineHeight: 1.4 }}>
                <span style={{ fontWeight: 500 }}>{c?.name}</span> · <span style={{ color: theme.fgMuted }}>{ev.label}</span>
              </div>
              <div style={{ fontSize: 10, color: theme.fgDim, fontFamily: 'DM Mono, monospace', marginTop: 2 }}>{ev.when}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

const SparkLine = ({ values, accent = true }) => {
  const { theme } = useTheme();
  const W = 720, H = 80;
  const max = Math.max(...values, 1);
  const min = Math.min(...values, 0);
  const range = max - min || 1;
  const x = (i) => (i / (values.length - 1)) * W;
  const y = (v) => H - ((v - min) / range) * (H - 8) - 4;
  const path = values.map((v, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');
  const color = accent ? theme.accent : theme.info;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 80, display: 'block' }}>
      <defs>
        <linearGradient id={`sg-${accent}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.25" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={`${path} L${W},${H} L0,${H} Z`} fill={`url(#sg-${accent})`} />
      <path d={path} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={x(values.length-1)} cy={y(values[values.length-1])} r="4" fill={color} />
    </svg>
  );
};

// ── States ─────────────────────────────────────────────────
const AnalyticsEmpty = ({ onNewSession }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      padding: '80px 32px', textAlign: 'center', position: 'relative', zIndex: 1,
      background: theme.card, border: `1px dashed ${theme.border}`, borderRadius: 24,
    }}>
      <div style={{ fontSize: 48, color: theme.fgDim, fontFamily: '"Instrument Serif", serif', marginBottom: 16 }}>—</div>
      <h2 style={{ margin: '0 0 8px', fontSize: 24, fontFamily: '"Instrument Serif", serif', fontWeight: 400 }}>
        Sem dados suficientes ainda
      </h2>
      <p style={{ margin: '0 auto 24px', fontSize: 14, color: theme.fgMuted, maxWidth: 420, lineHeight: 1.6 }}>
        Analytics aparecem depois que você publicar pelo menos 3 sessões e suas consulentes começarem a usar os portais. Volte em alguns dias.
      </p>
      <BtnGhost onClick={onNewSession}>Criar primeira sessão</BtnGhost>
    </div>
  );
};

const AnalyticsLoading = () => {
  const { theme } = useTheme();
  return (
    <div style={{ position: 'relative', zIndex: 1 }}>
      <style>{`
        @keyframes pulseA { 0%, 100% { opacity: 0.5; } 50% { opacity: 1; } }
        @media (min-width: 640px){ .orbita-analytics-skel-kpi{ grid-template-columns: repeat(4, 1fr) !important; } }
        @media (min-width: 900px){ .orbita-analytics-skel-charts{ grid-template-columns: 1.6fr 1fr !important; } }
      `}</style>
      <div className="orbita-analytics-skel-kpi" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginBottom: 24 }}>
        {Array.from({ length: 4 }).map((_, i) => (
          <div key={i} style={{ background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 14, padding: 22, height: 112, animation: `pulseA 1.4s ease-in-out ${i*0.1}s infinite` }}>
            <div style={{ height: 9, width: '60%', background: theme.inputBg, borderRadius: 4, marginBottom: 16 }} />
            <div style={{ height: 30, width: '40%', background: theme.inputBg, borderRadius: 6, marginBottom: 8 }} />
            <div style={{ height: 8, width: '70%', background: theme.inputBg, borderRadius: 4 }} />
          </div>
        ))}
      </div>
      <div className="orbita-analytics-skel-charts" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16 }}>
        {[0,1].map(i => (
          <div key={i} style={{ background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 16, padding: 24, height: 240, animation: `pulseA 1.4s ease-in-out ${i*0.15}s infinite` }}>
            <div style={{ height: 12, width: '40%', background: theme.inputBg, borderRadius: 4, marginBottom: 24 }} />
            <div style={{ height: 160, background: theme.inputBg, borderRadius: 8 }} />
          </div>
        ))}
      </div>
    </div>
  );
};

const AnalyticsError = ({ onRetry }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      padding: '60px 32px', textAlign: 'center', position: 'relative', zIndex: 1,
      background: theme.card, border: `1px solid ${theme.hot}40`, borderRadius: 16,
    }}>
      <div style={{ fontSize: 28, color: theme.hot, marginBottom: 16, fontFamily: '"Instrument Serif", serif' }}>⚠</div>
      <h3 style={{ margin: '0 0 8px', fontSize: 18, color: theme.fg }}>Os dados não vieram</h3>
      <p style={{ margin: '0 0 20px', fontSize: 13, color: theme.fgMuted }}>
        Pode ser uma instabilidade momentânea. Tentar de novo geralmente resolve.
      </p>
      <BtnGhost onClick={onRetry}>Tentar novamente</BtnGhost>
    </div>
  );
};

Object.assign(window, { AnalyticsScreen });
