/* ============================================================
   Screen 10 — Trendlar (Trends & Forecasting)
   ============================================================ */

function ScreenTrends() {
  const [period, setPeriod] = useState('24h');
  const [forecastTopic, setForecastTopic] = useState('onion');

  // Trending keywords — multi-period
  const KEYWORD_PERIODS = useMemo(() => {
    return {
      '24h': KEYWORDS.slice(),
      '7d': KEYWORDS.map(k => ({ ...k, count: Math.round(k.count * 6.3), prev: Math.round(k.prev * 6.1) })),
      '30d': KEYWORDS.map(k => ({ ...k, count: Math.round(k.count * 24), prev: Math.round(k.prev * 22) })),
    };
  }, []);

  const sortedKw = useMemo(() => {
    return [...KEYWORD_PERIODS[period]].map(k => ({ ...k, growth: ((k.count - k.prev) / Math.max(1, k.prev)) * 100 }))
      .sort((a, b) => b.growth - a.growth);
  }, [period]);

  // Topic forecast
  const FORECAST = useMemo(() => {
    const out = {};
    TOPICS.forEach(t => {
      const hist = BY_DAY.slice(-30).map(d => d.byTopic[t.id]);
      // simple forecast: last week avg + slope + noise
      const lastWeek = hist.slice(-7).reduce((a, b) => a + b, 0) / 7;
      const prevWeek = hist.slice(-14, -7).reduce((a, b) => a + b, 0) / 7;
      const slope = (lastWeek - prevWeek) / 7;
      const fc = [];
      for (let i = 1; i <= 7; i++) {
        const base = lastWeek + slope * i;
        const noise = base * 0.08;
        fc.push({
          mean: Math.max(0, Math.round(base)),
          lower: Math.max(0, Math.round(base - noise * 2)),
          upper: Math.round(base + noise * 2),
        });
      }
      out[t.id] = { hist, forecast: fc };
    });
    return out;
  }, []);

  // Anomaly log
  const ANOMALIES = [
    { id: 'AN-2026-014', when: '14.05 · 13:42', topic: 'onion',    region: 'sam', mag: 4.2, val: '−38% narx', cause: 'Saudiya import siyosati o\'zgardi', status: 'investigating' },
    { id: 'AN-2026-013', when: '14.05 · 11:18', topic: 'logistic', region: 'qsh', mag: 3.1, val: '+47% murojaat', cause: 'M39 yoʻlining qisman yopilishi', status: 'investigating' },
    { id: 'AN-2026-012', when: '13.05 · 22:04', topic: 'beef',     region: 'fer', mag: 2.8, val: '+12% narx', cause: 'Veterinariya cheklovi (Andijon)', status: 'resolved' },
    { id: 'AN-2026-011', when: '12.05 · 09:30', topic: 'flour',    region: null,  mag: 2.4, val: '+28% salbiy sentiment', cause: 'Davlat zaxirasi tarqatish kechikishi', status: 'investigating' },
    { id: 'AN-2026-010', when: '10.05 · 16:55', topic: 'rice',     region: 'xor', mag: 3.5, val: '+52% eksport so\'rov', cause: 'Yangi Qozogʻiston shartnomasi', status: 'resolved' },
    { id: 'AN-2026-009', when: '07.05 · 08:12', topic: 'oil',      region: null,  mag: 2.1, val: '−15% narx', cause: 'Paxta hosili kutilgandan yaxshi', status: 'resolved' },
    { id: 'AN-2026-008', when: '03.05 · 14:20', topic: 'poultry',  region: 'tas', mag: 2.6, val: '−18% narx', cause: 'Brendlar oʻrtasidagi raqobat', status: 'monitoring' },
    { id: 'AN-2026-007', when: '28.04 · 11:00', topic: 'potato',   region: 'jiz', mag: 3.0, val: 'kasallik tarqalishi', cause: 'Late blight (Phytophthora) hisoblari', status: 'resolved' },
  ];

  // Seasonal pattern: year-over-year for selected topic
  const SEASONAL = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 52; i++) {
      const seasonal = 1 + Math.sin((i / 52) * Math.PI * 2 + 1) * 0.35;
      const baseT = 120 * seasonal;
      arr.push({
        week: i + 1,
        thisYear: Math.round(baseT * (1.1 + (rand() - 0.5) * 0.2)),
        lastYear: Math.round(baseT * (0.95 + (rand() - 0.5) * 0.2)),
        prevYear: Math.round(baseT * (0.85 + (rand() - 0.5) * 0.2)),
      });
    }
    return arr;
  }, [forecastTopic]);

  return (
    <div className="page" style={{ maxWidth: '100%' }}>
      <div className="page-head">
        <div>
          <div className="page-crumbs">
            <span>Asosiy</span><span>/</span><span style={{ color: 'var(--ink-2)' }}>Trendlar</span>
          </div>
          <h1 className="page-title">Trendlar va prognozlar<span className="ru">Тренды и прогнозирование</span></h1>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="refresh" size={12} /> Modelni yangilash</button>
          <button className="btn btn-primary"><Icon name="download" size={12} /> Prognoz hisoboti</button>
        </div>
      </div>

      {/* KPI summary */}
      <div className="kpi-strip mb-12" style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}>
        <SimpleKpi label="Aniqlangan trendlar" value="14" hint="oxirgi 24 soat" trend="up" delta="+4" />
        <SimpleKpi label="Anomaliyalar" value="7" hint="3 ta tekshirilmoqda" trend="up" delta="+2" inverse />
        <SimpleKpi label="Prognoz aniqligi" value="87.4" hint="% · 7 kunlik MAPE" trend="up" delta="+1.2" />
        <SimpleKpi label="Kuchayayotgan kalit so'z" value="22" hint={`+30% dan ortiq · ${period}`} trend="up" delta="+5" />
        <SimpleKpi label="Sezgir mavzu" value={TOPICS.find(t => t.id === 'logistic').uz} hint="eng katta o'zgarish" mono={false} />
      </div>

      {/* Trending keywords */}
      <Panel
        title="Yuksalayotgan kalit soʻzlar"
        sub={`${sortedKw.length} ta soʻz · oʻsish bo‘yicha`}
        num="01"
        className="mb-12"
        actions={
          <>
            <Seg value={period} onChange={setPeriod} options={[
              { value: '24h', label: '24 soat' },
              { value: '7d',  label: '7 kun' },
              { value: '30d', label: '30 kun' },
            ]} />
            <button className="btn btn-ghost btn-sm"><Icon name="download" size={12} /></button>
          </>
        }
      >
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1, background: 'var(--line)', border: '1px solid var(--line)', borderRadius: 4 }}>
          {sortedKw.slice(0, 20).map((kw, i) => {
            const t = TOPIC_BY_ID[kw.topic];
            return (
              <div key={kw.w} style={{ background: 'var(--panel)', padding: '10px 14px', display: 'grid', gridTemplateColumns: '24px 18px 1fr 120px 90px', gap: 10, alignItems: 'center' }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-4)' }}>{String(i + 1).padStart(2, '0')}</span>
                <TopicMark topicId={kw.topic} size={14} />
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, letterSpacing: '-0.01em', fontWeight: 500 }}>{kw.w}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Sparkline data={[kw.prev * 0.7, kw.prev * 0.85, kw.prev, kw.prev * 1.05, kw.count * 0.92, kw.count]} width={70} height={20} color={kw.growth > 0 ? 'var(--jade)' : 'var(--rose)'} fill strokeWidth={1.2} />
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-2)', width: 40 }}>{kw.count}</span>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <span className="mono" style={{
                    fontSize: 12,
                    fontWeight: 600,
                    color: kw.growth > 30 ? 'var(--jade)' : kw.growth > 0 ? 'var(--ink-2)' : 'var(--rose)',
                  }}>
                    {kw.growth > 0 ? '↑' : '↓'} {Math.abs(kw.growth).toFixed(0)}%
                  </span>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>oldingi: {kw.prev}</div>
                </div>
              </div>
            );
          })}
        </div>
      </Panel>

      {/* 12-week history small multiples */}
      <Panel
        title="Mavzular bo‘yicha 12 haftalik tarix"
        sub="haftalik hajm · barcha 12 mavzu · faqat tarixiy maʼlumot"
        num="02"
        className="mb-12"
      >
        <TopicHistoryGrid />
      </Panel>

      {/* Anomaly log + Seasonal */}
      <div className="grid-2-1 mb-12">
        <Panel title="Anomaliyalar jurnali" sub={`${ANOMALIES.length} ta · 6 ko'rinmoqda`} num="03" body={false}>
         <div style={{ maxHeight: 280, overflowY: 'auto' }}>
          <table className="tbl">
            <thead style={{ position: 'sticky', top: 0, background: 'var(--panel)', zIndex: 1 }}>
              <tr>
                <th>ID</th>
                <th>Vaqt</th>
                <th>Mavzu / hudud</th>
                <th>Anomaliya</th>
                <th>Magnituda</th>
                <th>Taxminiy sabab</th>
                <th>Holat</th>
              </tr>
            </thead>
            <tbody>
              {ANOMALIES.map(a => {
                const t = TOPIC_BY_ID[a.topic];
                return (
                  <tr key={a.id}>
                    <td className="mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>{a.id}</td>
                    <td className="mono" style={{ fontSize: 11 }}>{a.when}</td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                        <TopicMark topicId={a.topic} size={14} />
                        <span style={{ fontSize: 11.5 }}>{t.uz}</span>
                        {a.region && <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>· {REGION_BY_ID[a.region].code}</span>}
                      </div>
                    </td>
                    <td style={{ fontSize: 11.5, color: 'var(--ink)', fontWeight: 500 }}>{a.val}</td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <div style={{ width: 80 }}><MiniBar value={a.mag} max={5} color={a.mag > 3 ? 'var(--rose)' : 'var(--amber)'} height={6} /></div>
                        <span className="mono" style={{ fontSize: 11, fontWeight: 600 }}>σ{a.mag.toFixed(1)}</span>
                      </div>
                    </td>
                    <td style={{ fontSize: 11.5, color: 'var(--ink-2)', maxWidth: 280 }}>{a.cause}</td>
                    <td>
                      <span className={`chip chip-${a.status === 'investigating' ? 'amber' : a.status === 'resolved' ? 'jade' : 'accent'}`} style={{ fontSize: 9.5 }}>
                        {a.status === 'investigating' ? 'tekshiruv' : a.status === 'resolved' ? 'hal etilgan' : 'kuzatuv'}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
         </div>
        </Panel>

        <Panel title="Mavsumiy naqsh" sub="yillik solishtirish · joriy / o'tgan / undan oldingi" num="04">
          <SeasonalChart data={SEASONAL} color={TOPIC_BY_ID[forecastTopic].color} />
          <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', fontSize: 11 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 14, height: 2, background: 'var(--ink)' }} /> 2026
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 14, height: 2, background: 'var(--ink-3)', borderBottom: '1px dashed' }} /> 2025
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 14, height: 2, background: 'var(--ink-4)', borderBottom: '1px dashed' }} /> 2024
            </span>
            <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink-4)' }}>52 hafta</span>
          </div>
        </Panel>
      </div>

      {/* Topic momentum slope */}
      <Panel title="Mavzu momentum" sub="oʻtgan hafta → bu hafta · barcha 12 mavzu" num="05">
        <TopicMomentumSlope />
      </Panel>
    </div>
  );
}

// ============================================================
// Forecast chart with confidence band
// ============================================================
function ForecastChart({ history, forecast, color }) {
  const [ref, size] = useSize();
  const w = size.w || 700;
  const h = 280;
  const padL = 40, padR = 24, padT = 14, padB = 30;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const total = history.length + forecast.length;
  const all = [...history, ...forecast.map(f => f.upper)];
  const max = Math.max(...all) * 1.1;
  const xs = (i) => padL + (i / (total - 1)) * innerW;
  const y = (v) => padT + innerH - (v / max) * innerH;

  const histPath = history.map((v, i) => (i === 0 ? `M ${xs(i)} ${y(v)}` : `L ${xs(i)} ${y(v)}`)).join(' ');
  const histArea = histPath + ` L ${xs(history.length - 1)} ${y(0)} L ${xs(0)} ${y(0)} Z`;
  const fcStart = history.length - 1;
  // confidence band
  const upperPath = [`M ${xs(fcStart)} ${y(history[history.length - 1])}`, ...forecast.map((f, i) => `L ${xs(fcStart + 1 + i)} ${y(f.upper)}`)].join(' ');
  const lowerPath = forecast.slice().reverse().map((f, i) => `L ${xs(total - 1 - i)} ${y(f.lower)}`).join(' ');
  const bandPath = `${upperPath} ${lowerPath} L ${xs(fcStart)} ${y(history[history.length - 1])} Z`;
  const fcLinePath = [`M ${xs(fcStart)} ${y(history[history.length - 1])}`, ...forecast.map((f, i) => `L ${xs(fcStart + 1 + i)} ${y(f.mean)}`)].join(' ');

  return (
    <div ref={ref} style={{ width: '100%', position: 'relative' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {/* grid */}
          {[0, 0.25, 0.5, 0.75, 1].map((t, i) => (
            <g key={i}>
              <line x1={padL} x2={w - padR} y1={padT + (1 - t) * innerH} y2={padT + (1 - t) * innerH} stroke="var(--line)" strokeWidth="0.5" strokeDasharray={t === 0 ? '0' : '2 3'} />
              <text x={padL - 6} y={padT + (1 - t) * innerH + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-4)">{Math.round(max * t)}</text>
            </g>
          ))}
          {/* "today" divider */}
          <line x1={xs(fcStart)} x2={xs(fcStart)} y1={padT} y2={padT + innerH} stroke="var(--ink-3)" strokeWidth="1" strokeDasharray="3 3" />
          <text x={xs(fcStart) - 4} y={padT + 12} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-3)" fontWeight="600">bugun</text>
          <text x={xs(fcStart) + 4} y={padT + 12} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--accent-ink)" fontWeight="600">prognoz →</text>
          {/* historical */}
          <path d={histArea} fill={color} opacity="0.12" />
          <path d={histPath} stroke={color} strokeWidth="1.5" fill="none" strokeLinejoin="round" />
          {/* confidence band */}
          <path d={bandPath} fill={color} opacity="0.18" />
          {/* forecast mean line */}
          <path d={fcLinePath} stroke={color} strokeWidth="1.8" fill="none" strokeDasharray="4 2" strokeLinejoin="round" />
          {/* forecast points */}
          {forecast.map((f, i) => (
            <circle key={i} cx={xs(fcStart + 1 + i)} cy={y(f.mean)} r="3" fill="var(--panel)" stroke={color} strokeWidth="1.5" />
          ))}
          {/* axis labels */}
          {[0, 7, 14, 21, 29].map(i => (
            <text key={i} x={xs(i)} y={h - 14} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">{29 - i}k</text>
          ))}
          {forecast.map((_, i) => (
            <text key={i} x={xs(fcStart + 1 + i)} y={h - 14} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--accent-ink)">+{i + 1}</text>
          ))}
          <text x={padL + innerW / 2} y={h - 2} fontSize="10" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-3)">
            kunlar · oxirgi 30 + kelgusi 7
          </text>
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Seasonal year-over-year overlay
// ============================================================
function SeasonalChart({ data, color }) {
  const [ref, size] = useSize();
  const w = size.w || 500;
  const h = 240;
  const padL = 36, padR = 8, padT = 14, padB = 22;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const max = Math.max(...data.flatMap(d => [d.thisYear, d.lastYear, d.prevYear])) * 1.1;
  const xs = (i) => padL + (i / (data.length - 1)) * innerW;
  const y = (v) => padT + innerH - (v / max) * innerH;

  const seriesPath = (key, prev) => data.map((d, i) => (i === 0 ? `M ${xs(i)} ${y(d[key])}` : `L ${xs(i)} ${y(d[key])}`)).join(' ');

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {[0, 0.5, 1].map(t => (
            <g key={t}>
              <line x1={padL} x2={w - padR} y1={padT + (1 - t) * innerH} y2={padT + (1 - t) * innerH} stroke="var(--line)" strokeWidth="0.5" strokeDasharray={t === 0 ? '0' : '2 3'} />
              <text x={padL - 6} y={padT + (1 - t) * innerH + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-4)">{Math.round(max * t)}</text>
            </g>
          ))}
          {/* season shading: winter peak around weeks 50-2 */}
          <rect x={padL} y={padT} width={(2 / 52) * innerW} height={innerH} fill="var(--accent-soft)" opacity="0.3" />
          <rect x={padL + (50 / 52) * innerW} y={padT} width={(2 / 52) * innerW} height={innerH} fill="var(--accent-soft)" opacity="0.3" />
          {/* lines */}
          <path d={seriesPath('prevYear')} stroke="var(--ink-4)" strokeWidth="1" fill="none" strokeDasharray="3 3" />
          <path d={seriesPath('lastYear')} stroke="var(--ink-3)" strokeWidth="1.2" fill="none" strokeDasharray="4 2" />
          <path d={seriesPath('thisYear')} stroke="var(--ink)" strokeWidth="1.8" fill="none" />
          {/* current marker */}
          <circle cx={xs(19)} cy={y(data[19].thisYear)} r="4" fill="var(--accent)" />
          <text x={xs(19)} y={y(data[19].thisYear) - 8} fontSize="9" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--accent-ink)" fontWeight="600">joriy</text>
          {/* x labels */}
          {[1, 13, 26, 39, 52].map(w => (
            <text key={w} x={padL + ((w - 1) / 51) * innerW} y={h - 6} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">H{w}</text>
          ))}
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Topic momentum 2D grid: x = volume, y = growth%
// ============================================================
function TopicMomentumGrid() {
  const data = TOPICS.map(t => {
    const b = BY_TOPIC[t.id];
    const growth = ((b.thisWeek - b.prevWeek) / Math.max(1, b.prevWeek)) * 100;
    return {
      label: t.uz,
      color: t.color,
      x: b.total,
      y: growth,
      r: b.urgent + 4,
      topicId: t.id,
    };
  });

  const [ref, size] = useSize();
  const w = size.w || 800;
  const h = 320;
  const padL = 70, padR = 16, padT = 14, padB = 42;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const xMax = Math.max(...data.map(d => d.x)) * 1.1;
  const yMax = Math.max(...data.map(d => Math.abs(d.y))) * 1.2;
  const x = (v) => padL + (v / xMax) * innerW;
  const y = (v) => padT + innerH / 2 - (v / yMax) * (innerH / 2);

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {/* quadrant shading */}
          <rect x={padL + innerW / 2} y={padT} width={innerW / 2} height={innerH / 2} fill="var(--jade-soft)" opacity="0.3" />
          <rect x={padL} y={padT + innerH / 2} width={innerW / 2} height={innerH / 2} fill="var(--rose-soft)" opacity="0.3" />
          {/* axes */}
          <line x1={padL} x2={w - padR} y1={padT + innerH / 2} y2={padT + innerH / 2} stroke="var(--ink-3)" strokeWidth="1" />
          <line x1={padL + innerW / 2} x2={padL + innerW / 2} y1={padT} y2={padT + innerH} stroke="var(--line-strong)" strokeWidth="0.5" strokeDasharray="3 3" />
          {/* y ticks */}
          {[-yMax, -yMax / 2, 0, yMax / 2, yMax].map((v, i) => (
            <g key={i}>
              {v !== 0 && <line x1={padL} x2={w - padR} y1={y(v)} y2={y(v)} stroke="var(--line)" strokeWidth="0.5" strokeDasharray="2 3" />}
              <text x={padL - 6} y={y(v) + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-4)">{v.toFixed(0)}%</text>
            </g>
          ))}
          {/* quadrant labels */}
          <text x={padL + innerW * 0.75} y={padT + 16} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--jade)" fontWeight="600" letterSpacing="0.04em">★ YULDUZLAR</text>
          <text x={padL + innerW * 0.25} y={padT + 16} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)" letterSpacing="0.04em">YORDAMCHILAR</text>
          <text x={padL + innerW * 0.25} y={padT + innerH - 4} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)" letterSpacing="0.04em">PASAYAYOTGAN</text>
          <text x={padL + innerW * 0.75} y={padT + innerH - 4} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--rose)" fontWeight="600" letterSpacing="0.04em">DIQQAT</text>
          {/* bubbles */}
          {data.map((d, i) => (
            <g key={i}>
              <circle cx={x(d.x)} cy={y(d.y)} r={6 + d.r * 0.4} fill={d.color} fillOpacity="0.5" stroke={d.color} strokeWidth="1.5" />
              <text x={x(d.x)} y={y(d.y) - 6 - d.r * 0.4} fontSize="10" fontFamily="var(--font-sans)" textAnchor="middle" fontWeight="600" fill="var(--ink)">{d.label}</text>
            </g>
          ))}
          {/* axis labels */}
          <text x={padL + innerW / 2} y={h - 6} fontSize="10" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-3)">Hajm (jami murojaat) →</text>
          <text x={14} y={padT + innerH / 2} fontSize="10" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-3)" transform={`rotate(-90 14 ${padT + innerH / 2})`}>↑ Haftalik o'sish (%)</text>
        </svg>
      )}
    </div>
  );
}

function TopicHistoryGrid() {
  const { data: api } = useApi('/api/stats/by-day?days=84', { pollMs: 60000 });
  // Bucket API rows (topic_id, day, n) into 12-week buckets per topic
  const cells = useMemo(() => {
    const items = api?.items || [];
    const today = new Date();
    // 12 weeks × 7 days = 84 days; weeks[0] = oldest, weeks[11] = current
    const weekKeys = []; // for each week, list of day-string keys
    for (let w = 0; w < 12; w++) {
      const wk = [];
      for (let d = 0; d < 7; d++) {
        const idx = (11 - w) * 7 + (6 - d); // days back from today
        const dt = new Date(today.getTime() - idx * 86400000);
        wk.push(dt.toISOString().slice(0, 10));
      }
      weekKeys.push(wk);
    }
    // Bucket: topic -> { day -> n }
    const byTopicDay = {};
    items.forEach((r) => {
      if (!byTopicDay[r.topic_id]) byTopicDay[r.topic_id] = {};
      byTopicDay[r.topic_id][r.day] = r.n;
    });
    return TOPICS.map((t) => {
      const dayMap = byTopicDay[t.id] || {};
      const weekly = weekKeys.map((days) => days.reduce((a, k) => a + (dayMap[k] || 0), 0));
      const curr = weekly[weekly.length - 1];
      const prev = weekly[weekly.length - 2] || 0;
      const growth = prev > 0 ? ((curr - prev) / prev) * 100 : curr > 0 ? 100 : 0;
      const max = Math.max(...weekly);
      const peakIdx = weekly.indexOf(max);
      const peakWeeksAgo = max === 0 ? -1 : (11 - peakIdx);
      return { id: t.id, label: t.uz, color: t.color, weekly, curr, growth, peakWeeksAgo };
    });
  }, [api]);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
      {cells.map(c => {
        const up = c.growth >= 0;
        return (
          <div key={c.id} style={{
            border: '1px solid var(--line)',
            borderRadius: 4,
            padding: '12px 14px',
            background: 'var(--panel)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
              <span style={{ width: 10, height: 10, background: c.color, borderRadius: 1 }} />
              <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)' }}>{c.label}</span>
            </div>
            <div style={{ marginBottom: 8 }}>
              <Sparkline data={c.weekly} width={180} height={32} color={c.color} fill strokeWidth={1.4} dot />
            </div>
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'baseline',
              borderTop: '1px solid var(--line)',
              paddingTop: 6,
            }}>
              <div>
                <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Bu hafta</div>
                <div className="mono" style={{ fontSize: 14, fontWeight: 500 }}>{formatNum(c.curr)}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="mono" style={{
                  fontSize: 11, fontWeight: 600,
                  color: up ? 'oklch(0.50 0.10 155)' : 'oklch(0.55 0.14 25)',
                }}>
                  {up ? '↑' : '↓'} {Math.abs(c.growth).toFixed(0)}%
                </div>
                <div style={{ fontSize: 9, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)', marginTop: 1 }}>
                  pik: {c.peakWeeksAgo < 0 ? '—' : c.peakWeeksAgo === 0 ? 'bu hafta' : `${c.peakWeeksAgo} hafta oldin`}
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function TopicMomentumSlope() {
  const { data: api } = useApi('/api/stats/momentum', { pollMs: 30000 });
  const data = useMemo(() => {
    const items = api?.items || [];
    return items.map((t) => {
      const prev = t.prev_week || 0;
      const curr = t.this_week || 0;
      const growth = prev > 0 ? ((curr - prev) / prev) * 100 : curr > 0 ? 100 : 0;
      return { id: t.id, label: t.uz, color: t.color, prev, curr, growth };
    }).sort((a, b) => b.growth - a.growth);
  }, [api]);
  const max = Math.max(1, ...data.flatMap(d => [d.prev, d.curr]));

  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '22px 14px 130px 70px 1fr 70px 70px',
        gap: 12,
        padding: '0 0 8px',
        fontSize: 9.5,
        fontFamily: 'var(--font-mono)',
        color: 'var(--ink-4)',
        textTransform: 'uppercase',
        letterSpacing: '0.06em',
        borderBottom: '1px solid var(--line)',
      }}>
        <span>№</span>
        <span></span>
        <span>Mavzu</span>
        <span style={{ textAlign: 'right' }}>O‘tgan</span>
        <span style={{ textAlign: 'center' }}>O‘zgarish</span>
        <span style={{ textAlign: 'right' }}>Bu hafta</span>
        <span style={{ textAlign: 'right' }}>Δ</span>
      </div>
      {data.map((d, i) => {
        const up = d.growth >= 0;
        const trackColor = up ? 'oklch(0.55 0.10 155)' : 'oklch(0.55 0.14 25)';
        const trackBg = up ? 'oklch(0.96 0.018 155)' : 'oklch(0.97 0.018 25)';
        const xPrev = (d.prev / max) * 100;
        const xCurr = (d.curr / max) * 100;
        const lineLeft = Math.min(xPrev, xCurr);
        const lineRight = Math.max(xPrev, xCurr);
        return (
          <div key={d.id} style={{
            display: 'grid',
            gridTemplateColumns: '22px 14px 130px 70px 1fr 70px 70px',
            gap: 12,
            alignItems: 'center',
            padding: '10px 0',
            borderBottom: i < data.length - 1 ? '1px solid var(--line)' : 'none',
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-4)' }}>
              {String(i + 1).padStart(2, '0')}
            </span>
            <span style={{ width: 10, height: 10, background: d.color, borderRadius: 1 }} />
            <span style={{ fontSize: 12, color: 'var(--ink)', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {d.label}
            </span>
            <span className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)', textAlign: 'right' }}>
              {formatNum(d.prev)}
            </span>
            <div style={{ position: 'relative', height: 16, background: trackBg, borderRadius: 2 }}>
              <div style={{
                position: 'absolute',
                left: `${lineLeft}%`,
                right: `${100 - lineRight}%`,
                top: 6, height: 4,
                background: trackColor,
                opacity: 0.5,
              }} />
              <div title={`o‘tgan: ${formatNum(d.prev)}`} style={{
                position: 'absolute',
                left: `calc(${xPrev}% - 5px)`,
                top: 3, width: 10, height: 10,
                background: 'var(--panel)',
                border: `1.5px solid ${trackColor}`,
                borderRadius: '50%',
              }} />
              <div title={`bu hafta: ${formatNum(d.curr)}`} style={{
                position: 'absolute',
                left: `calc(${xCurr}% - 5px)`,
                top: 3, width: 10, height: 10,
                background: trackColor,
                borderRadius: '50%',
                boxShadow: '0 0 0 2px var(--panel)',
              }} />
              {/* Arrow indicating direction at midpoint */}
              <span style={{
                position: 'absolute',
                left: `${(lineLeft + lineRight) / 2}%`,
                top: -2,
                transform: 'translateX(-50%)',
                fontSize: 9,
                color: trackColor,
                fontFamily: 'var(--font-mono)',
                fontWeight: 700,
              }}>
                {up ? '→' : '←'}
              </span>
            </div>
            <span className="mono" style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)', textAlign: 'right' }}>
              {formatNum(d.curr)}
            </span>
            <span style={{
              fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
              color: trackColor, textAlign: 'right',
            }}>
              {up ? '↑' : '↓'} {Math.abs(d.growth).toFixed(1)}%
            </span>
          </div>
        );
      })}
    </div>
  );
}

window.ScreenTrends = ScreenTrends;
