// Analytics page
const { useMemo: useMemoAn } = React;

function Sparkline({ data, color = 'var(--blue)', w = 200, h = 36 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / range) * h;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: h }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
      <circle cx={w} cy={h - ((data[data.length - 1] - min) / range) * h} r="2.5" fill={color} />
    </svg>
  );
}

function Analytics() {
  const { TREND, VOLUME, AGENT_STATS, TOPICS, AGENTS } = window.VI_DATA;

  // Trend chart dimensions
  const cW = 760, cH = 220, cPadL = 36, cPadR = 16, cPadT = 16, cPadB = 28;
  const innerW = cW - cPadL - cPadR;
  const innerH = cH - cPadT - cPadB;

  const xAt = (i) => cPadL + (i / (TREND.length - 1)) * innerW;
  const yAt = (v) => cPadT + innerH - (v / 100) * innerH;

  const buildArea = (key, bottomKey) => {
    const top = TREND.map((d, i) => `${xAt(i)},${yAt(d[key])}`).join(' ');
    const bot = [...TREND].reverse().map((d, i) => {
      const origIdx = TREND.length - 1 - i;
      const bottom = bottomKey ? TREND[origIdx][bottomKey] : 0;
      return `${xAt(origIdx)},${yAt(bottom)}`;
    }).join(' ');
    return `${top} ${bot}`;
  };

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Analytics</h1>
          <div className="sub">
            <span className="mono">3,281 calls</span> · Last 12 weeks · All teams · Updated 4 min ago
          </div>
        </div>
        <div className="page-actions">
          <button className="btn">Date range: Last 12w <Icon name="chevdown" /></button>
          <button className="btn">All teams <Icon name="chevdown" /></button>
          <button className="btn"><Icon name="download" /> Export</button>
        </div>
      </div>

      <section className="analytics">

        <div className="sec">Overview</div>

        <div className="kpi-row">
          <div className="kpi">
            <div className="lbl">Positive sentiment</div>
            <div className="v">71<span className="unit">%</span></div>
            <div className="delta up"><span className="arr">▲ 4.2pp</span><span className="txt">vs prev 12w</span></div>
            <div className="spark"><Sparkline data={TREND.map(t => t.pos)} /></div>
          </div>
          <div className="kpi">
            <div className="lbl">Avg QA score</div>
            <div className="v">82.4</div>
            <div className="delta up"><span className="arr">▲ 1.8</span><span className="txt">vs prev 12w</span></div>
            <div className="spark"><Sparkline data={[78,79,80,79,80,81,82,81,82,83,82,82.4]} color="var(--pos)" /></div>
          </div>
          <div className="kpi">
            <div className="lbl">Avg handle time</div>
            <div className="v">11:42</div>
            <div className="delta down"><span className="arr">▲ 0:34</span><span className="txt">vs prev 12w</span></div>
            <div className="spark"><Sparkline data={[11.1,10.9,11.2,11.3,11.5,11.4,11.7,11.6,11.8,11.9,11.7,11.7]} color="var(--neu)" /></div>
          </div>
          <div className="kpi">
            <div className="lbl">Calls analyzed</div>
            <div className="v">3,281</div>
            <div className="delta up"><span className="arr">▲ 12%</span><span className="txt">vs prev 12w</span></div>
            <div className="spark"><Sparkline data={VOLUME} color="var(--blue)" /></div>
          </div>
        </div>

        <div className="sec">Sentiment & Volume Trends</div>

        <div className="grid-2">
          {/* Big trend chart */}
          <div className="panel">
            <div className="ph">
              <div>
                <h3>Sentiment over time</h3>
                <div className="sub">Stacked share of calls per week · last 12 weeks</div>
              </div>
              <div className="ctrl">
                <button className="on">Stack</button>
                <button>Lines</button>
                <button>Ratio</button>
              </div>
            </div>

            <div className="chart">
              <svg viewBox={`0 0 ${cW} ${cH}`} style={{ width: '100%', height: cH }}>
                {/* gridlines */}
                {[0, 25, 50, 75, 100].map(v => (
                  <g key={v}>
                    <line x1={cPadL} x2={cW - cPadR} y1={yAt(v)} y2={yAt(v)} stroke="var(--hair)" strokeWidth="1" strokeDasharray={v === 0 || v === 100 ? '' : '2,3'} />
                    <text x={cPadL - 8} y={yAt(v) + 3} textAnchor="end" fontSize="10" fill="var(--muted)" fontFamily="JetBrains Mono">{v}%</text>
                  </g>
                ))}

                {/* stacked areas: neg (bottom), neu (mid), pos (top) */}
                <polygon
                  points={TREND.map((d, i) => `${xAt(i)},${yAt(d.neg)}`).join(' ') + ' ' +
                    [...TREND].reverse().map((d, i) => `${xAt(TREND.length-1-i)},${yAt(0)}`).join(' ')}
                  fill="var(--neg)" opacity="0.85" />

                <polygon
                  points={TREND.map((d, i) => `${xAt(i)},${yAt(d.neg + d.neu)}`).join(' ') + ' ' +
                    [...TREND].reverse().map((d, i) => `${xAt(TREND.length-1-i)},${yAt(TREND[TREND.length-1-i].neg)}`).join(' ')}
                  fill="var(--neu)" opacity="0.85" />

                <polygon
                  points={TREND.map((d, i) => `${xAt(i)},${yAt(100)}`).join(' ') + ' ' +
                    [...TREND].reverse().map((d, i) => `${xAt(TREND.length-1-i)},${yAt(TREND[TREND.length-1-i].neg + TREND[TREND.length-1-i].neu)}`).join(' ')}
                  fill="var(--pos)" opacity="0.85" />

                {/* x axis labels */}
                {TREND.map((d, i) => (
                  <text key={i} x={xAt(i)} y={cH - 10} textAnchor="middle" fontSize="10" fill="var(--muted)" fontFamily="JetBrains Mono">{d.w}</text>
                ))}

                {/* hover point on last */}
                <line x1={xAt(TREND.length - 1)} x2={xAt(TREND.length - 1)} y1={cPadT} y2={cH - cPadB} stroke="var(--ink)" strokeWidth="1" strokeDasharray="2,3" opacity="0.4" />
              </svg>

              <div style={{ display: 'flex', gap: 18, marginTop: 8, fontSize: 11, color: 'var(--muted)' }}>
                <div className="row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--pos)', borderRadius: 2 }}></span> Positive</div>
                <div className="row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--neu)', borderRadius: 2 }}></span> Neutral</div>
                <div className="row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--neg)', borderRadius: 2 }}></span> Negative</div>
                <div style={{ marginLeft: 'auto' }} className="mono">Latest (W12): 72% · 22% · 6%</div>
              </div>
            </div>
          </div>

          {/* Volume */}
          <div className="panel">
            <div className="ph">
              <div>
                <h3>Call volume</h3>
                <div className="sub">Weekly calls analyzed</div>
              </div>
            </div>

            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 190, padding: '0 4px' }}>
              {VOLUME.map((v, i) => {
                const max = Math.max(...VOLUME);
                return (
                  <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                    <div style={{
                      width: '100%',
                      height: (v / max) * 160 + 'px',
                      background: i === VOLUME.length - 1 ? 'var(--blue)' : 'var(--blue-50)',
                      borderTop: i === VOLUME.length - 1 ? 'none' : '2px solid var(--blue)',
                      borderRadius: '2px 2px 0 0'
                    }}></div>
                    <div style={{ fontSize: 10, color: 'var(--muted)', fontFamily: 'JetBrains Mono' }}>W{i + 1}</div>
                  </div>
                );
              })}
            </div>
            <div className="hairline"></div>
            <div className="row sp-b" style={{ fontSize: 12, color: 'var(--ink-2)' }}>
              <span>Peak: <b className="mono">W12 · 489</b></span>
              <span>Avg: <b className="mono">389</b></span>
              <span style={{ color: 'var(--pos)' }}>+12% vs prior</span>
            </div>
          </div>
        </div>

        <div className="sec">Agent Comparison</div>

        <div className="panel">
          <div className="ph">
            <div>
              <h3>Agent performance · last 30 days</h3>
              <div className="sub">Ranked by QA score · click an agent to drill in</div>
            </div>
            <div className="ctrl">
              <button className="on">QA score</button>
              <button>Sentiment</button>
              <button>AHT</button>
              <button>CSAT</button>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr 80px 70px', gap: 18, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', paddingBottom: 10, borderBottom: '1px solid var(--hair)' }}>
            <div>Agent</div>
            <div>Sentiment mix</div>
            <div style={{ textAlign: 'right' }}>Calls</div>
            <div style={{ textAlign: 'right' }}>QA</div>
          </div>

          {AGENT_STATS.map(a => {
            const ag = AGENTS.find(x => x.id === a.id);
            const [p, n, g] = a.senti;
            return (
              <div key={a.id} className="agent-row">
                <div className="who">
                  <div className="av" style={{ background: ag.avatar }}>{ag.id}</div>
                  <div>
                    <div className="name">{ag.name}</div>
                    <div className="role">{ag.team}</div>
                  </div>
                </div>
                <div>
                  <div className="senti-stack">
                    <div className="p" style={{ width: p + '%' }}></div>
                    <div className="n" style={{ width: n + '%' }}></div>
                    <div className="g" style={{ width: g + '%' }}></div>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'JetBrains Mono', fontSize: 10, color: 'var(--muted)', marginTop: 4 }}>
                    <span>{p}%</span><span>{n}%</span><span>{g}%</span>
                  </div>
                </div>
                <div className="calls">{a.calls}</div>
                <div className={'score ' + (a.score >= 85 ? 'hi' : a.score < 75 ? 'lo' : '')}>{a.score}</div>
              </div>
            );
          })}
        </div>

        <div className="sec" style={{ marginTop: 32 }}>Topic Intelligence</div>

        <div className="grid-2">
          <div className="panel">
            <div className="ph">
              <div>
                <h3>Topic landscape</h3>
                <div className="sub">Auto-extracted topics · last 12 weeks · sized by mention volume</div>
              </div>
              <button className="btn ghost" style={{ fontSize: 12, color: 'var(--blue)' }}>View all 142 <Icon name="chevright" style={{ width: 12, height: 12 }} /></button>
            </div>
            <div className="topic-heat">
              {TOPICS.map(t => (
                <span key={t.t} className={'t l' + t.l}>
                  {t.t} <span className="n">{t.n.toLocaleString()}</span>
                </span>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="ph">
              <div>
                <h3>Rising topics</h3>
                <div className="sub">Largest 4-week deltas</div>
              </div>
            </div>
            {[
              { t: 'Weather delay',       d: '+84%',  n: 389, cls: 'up' },
              { t: 'Auto-pay disputes',   d: '+47%',  n: 214, cls: 'up' },
              { t: 'Competitor mention',  d: '+31%',  n:  98, cls: 'up' },
              { t: 'Damage claim',        d: '+22%',  n: 121, cls: 'up' },
              { t: 'Scheduling flexibility', d: '−18%', n: 156, cls: 'down' },
              { t: 'Part availability',   d: '−24%',  n:  88, cls: 'down' },
            ].map(r => (
              <div key={r.t} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--hair)' }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{r.t}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted)', fontFamily: 'JetBrains Mono' }}>{r.n} mentions</div>
                </div>
                <div className="mono" style={{ fontSize: 14, fontWeight: 600, color: r.cls === 'up' ? 'var(--pos)' : 'var(--neg)' }}>{r.d}</div>
              </div>
            ))}
          </div>
        </div>

      </section>
    </>
  );
}

window.Analytics = Analytics;
