/* ============================================================
   Screen 6 — AI tahlil (Model Performance & Explainability)
   ============================================================ */

function ScreenAI() {
  const [threshold, setThreshold] = useState(75);

  // Live API data
  const overview = useApi('/api/stats/overview',              { pollMs: 20000 });
  const aiMetric = useApi('/api/stats/ai-metrics',            { pollMs: 20000 });
  const histApi  = useApi('/api/stats/confidence-histogram',  { pollMs: 30000 });
  const langApi  = useApi('/api/stats/language-breakdown',    { pollMs: 30000 });
  const trendApi = useApi('/api/stats/confidence-trend?days=30', { pollMs: 30000 });

  // Build 20-bin histogram from API (gracefully handle empty)
  const confDist = useMemo(() => {
    const bins = new Array(20).fill(0);
    (histApi.data?.items || []).forEach(({ bin, n }) => {
      const i = Math.min(19, Math.max(0, bin));
      bins[i] = n;
    });
    return bins;
  }, [histApi.data]);

  const belowThreshold = useMemo(() => {
    const bin = Math.floor(threshold / 5);
    return confDist.slice(0, bin).reduce((a, b) => a + b, 0);
  }, [threshold, confDist]);
  const totalClassified = confDist.reduce((a, b) => a + b, 0);
  const belowPct = totalClassified > 0 ? (belowThreshold / totalClassified) * 100 : 0;

  // Accuracy trend → real avg confidence per day (last 30)
  const accuracyTrend = useMemo(() => {
    const items = trendApi.data?.items || [];
    // Pad to last 30 days
    const today = new Date();
    const keys = Array.from({ length: 30 }, (_, i) => {
      const d = new Date(today.getTime() - (29 - i) * 86400000);
      return d.toISOString().slice(0, 10);
    });
    const byDay = Object.fromEntries(items.map(it => [it.day, it.avg_conf]));
    return keys.map(k => byDay[k] != null ? +(byDay[k] * 100).toFixed(2) : null);
  }, [trendApi.data]);

  // Language detection breakdown
  const langItems = langApi.data?.items || [];
  const o = overview.data || {};
  const m = aiMetric.data || {};

  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)' }}>AI tahlil</span>
          </div>
          <h1 className="page-title">AI tahlil<span className="ru">AI-анализ · Model performance & explainability</span></h1>
        </div>
        <div className="page-actions">
          <span className="chip chip-jade"><span className="dot dot-live" /> Model v2.18 faol</span>
          <button className="btn"><Icon name="refresh" size={12} /> Qayta o'rgatish</button>
          <button className="btn"><Icon name="download" size={12} /> Hisobot</button>
        </div>
      </div>

      {/* KPI strip — live */}
      <div className="kpi-strip mb-12" style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}>
        <AiKpi
          label="O‘rt. ishonchlilik"
          value={m.confidence_avg != null ? (m.confidence_avg * 100).toFixed(1) : '—'}
          unit="%"
          hint="tasniflangan murojaatlar"
        />
        <AiKpi
          label="Qayta ishlangan"
          value={formatNum(o.classified || 0)}
          unit=""
          hint={`jami: ${formatNum(o.total || 0)}`}
        />
        <AiKpi
          label="Tasniflash tezligi"
          value={m.classify_rate != null ? (m.classify_rate * 100).toFixed(1) : '—'}
          unit="%"
          hint="muvaffaqiyat darajasi"
        />
        <AiKpi
          label="Til aniqlash"
          value={m.lang_detect_rate != null ? (m.lang_detect_rate * 100).toFixed(1) : '—'}
          unit="%"
          hint={`${langItems.length} til`}
        />
        <AiKpi
          label="O‘rt. kechikish"
          value={m.latency_ms_avg != null ? Math.round(m.latency_ms_avg) : '—'}
          unit="ms"
          hint={`P100: ${m.latency_ms_p100 != null ? Math.round(m.latency_ms_p100) : '—'} ms`}
        />
      </div>

      {/* Row 1: Confidence histogram */}
      <div className="mb-12">
        <Panel
          title="Ishonchlilik taqsimoti"
          sub={`> ${threshold}% chegara · tahlilchi tekshiruvini talab qiladi`}
          num="01"
        >
          <ConfidenceHistogram bins={confDist} threshold={threshold} />
          <div style={{ marginTop: 12, padding: 12, background: 'var(--bg-sunken)', borderRadius: 4 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>Ishonchlilik chegarasi:</span>
              <span className="mono" style={{ fontSize: 14, fontWeight: 500 }}>{threshold}%</span>
            </div>
            <input type="range" min="50" max="95" value={threshold} onChange={e => setThreshold(+e.target.value)} style={{ width: '100%' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11 }}>
              <div>
                <span style={{ color: 'var(--ink-3)' }}>chegaradan past: </span>
                <span className="mono" style={{ color: 'var(--rose)', fontWeight: 500 }}>{formatNum(belowThreshold)} ({belowPct.toFixed(1)}%)</span>
                <span style={{ marginLeft: 12, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>jami: {formatNum(totalClassified)}</span>
              </div>
              <div style={{ fontSize: 10, color: 'var(--ink-4)' }}>chegaradan yuqori avtomatik tasdiqlanadi</div>
            </div>
          </div>
        </Panel>
      </div>

      {/* Row 2: Accuracy over time + language detection */}
      <div className="grid-2-1 mb-12">
        <Panel title="Aniqlik dinamikasi" sub="haftalik qayta o‘rgatish nuqtalari" num="02">
          <AccuracyTrendChart data={accuracyTrend} />
          <div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', fontSize: 11 }}>
            <span style={{ color: 'var(--ink-3)' }}>Oxirgi 16 hafta · har dushanba qayta o'rgatiladi</span>
            <span className="mono" style={{ color: 'var(--jade)' }}>oxirgi qayta o'rgatish: +2.3 ball</span>
          </div>
        </Panel>

        <Panel title="Til aniqlash" sub={`${langItems.length || 0} til · oʻrtacha ishonch`} num="03">
          {langItems.length === 0 && (
            <div style={{ padding: 16, fontSize: 11, color: 'var(--ink-4)' }}>Hali tasniflangan murojaat yoʻq.</div>
          )}
          {langItems.map((row) => {
            const labels = { 'uz-latn': "O'zbek (Lotin)", 'uz-cyrl': "O'zbek (Kirill)", 'ru': 'Rus', 'mixed': 'Aralash' };
            const acc = row.avg_conf != null ? row.avg_conf * 100 : 0;
            const maxN = Math.max(...langItems.map(r => r.n));
            const pctN = maxN > 0 ? (row.n / maxN) * 100 : 0;
            return (
              <div key={row.language} style={{ marginBottom: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, fontSize: 11.5 }}>
                  <span style={{ fontWeight: 500 }}>{labels[row.language] || row.language}</span>
                  <span className="mono" style={{ color: acc >= 90 ? 'var(--jade)' : acc >= 75 ? 'var(--amber)' : 'var(--rose)' }}>{acc.toFixed(1)}%</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ flex: 1, height: 4, background: 'var(--bg-sunken)', borderRadius: 1, overflow: 'hidden' }}>
                    <div style={{ width: `${pctN}%`, height: '100%', background: acc >= 90 ? 'var(--jade)' : acc >= 75 ? 'var(--amber)' : 'var(--rose)' }} />
                  </div>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-4)', width: 70, textAlign: 'right' }}>{formatNum(row.n)} xab.</span>
                </div>
              </div>
            );
          })}
        </Panel>
      </div>

      {/* Row 3: Model card */}
      <Panel title="Model kartasi" sub="ishlab chiqarish versiyasi" num="04" className="mb-12">
        <ModelCard />
      </Panel>
    </div>
  );
}

// ============================================================
// Confusion matrix
// ============================================================
function ConfusionMatrix({ matrix, max, hover, onHover }) {
  const cell = 30;
  const padL = 80, padT = 80;
  const w = padL + cell * 12 + 10;
  const h = padT + cell * 12 + 10;

  return (
    <svg width="100%" viewBox={`0 0 ${w} ${h}`} style={{ display: 'block' }}>
      {/* axis labels */}
      <text x={padL / 2} y={20} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-3)" textAnchor="middle" fontWeight="600" letterSpacing="0.04em">BASHORAT →</text>
      <text x={6} y={padT + cell * 6} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-3)" fontWeight="600" letterSpacing="0.04em" transform={`rotate(-90 6 ${padT + cell * 6})`}>HAQIQIY ↑</text>

      {/* column labels */}
      {TOPICS.map((t, i) => (
        <g key={i} transform={`translate(${padL + i * cell + cell / 2}, ${padT - 6}) rotate(-45)`}>
          <text fontSize="9" fontFamily="var(--font-sans)" fill="var(--ink-2)" textAnchor="start">{t.uz}</text>
        </g>
      ))}
      {/* row labels */}
      {TOPICS.map((t, i) => (
        <text key={i} x={padL - 6} y={padT + i * cell + cell / 2 + 3} fontSize="9.5" fontFamily="var(--font-sans)" fill="var(--ink-2)" textAnchor="end">{t.uz}</text>
      ))}
      {/* cells */}
      {matrix.map((row, r) =>
        row.map((v, c) => {
          const isDiag = r === c;
          const t = v / (isDiag ? max : max * 0.3);
          const fill = isDiag
            ? `oklch(${(0.95 - Math.min(1, t) * 0.40).toFixed(3)} ${(0.02 + Math.min(1, t) * 0.10).toFixed(3)} 155)`
            : v === 0 ? 'var(--bg-sunken)' : `oklch(${(0.95 - Math.min(1, t) * 0.35).toFixed(3)} ${(0.02 + Math.min(1, t) * 0.12).toFixed(3)} 25)`;
          const isHov = hover && hover.r === r && hover.c === c;
          return (
            <g key={`${r}-${c}`}>
              <rect
                x={padL + c * cell + 1} y={padT + r * cell + 1}
                width={cell - 2} height={cell - 2}
                fill={fill}
                stroke={isHov ? 'var(--ink)' : 'transparent'}
                strokeWidth="1.5"
                rx="1"
                onMouseEnter={() => onHover({ r, c })}
                onMouseLeave={() => onHover(null)}
                style={{ cursor: 'pointer' }}
              />
              {v > 0 && (
                <text
                  x={padL + c * cell + cell / 2}
                  y={padT + r * cell + cell / 2 + 3}
                  fontSize={v > 99 ? 8 : 9.5}
                  fontFamily="var(--font-mono)"
                  textAnchor="middle"
                  fill={t > 0.5 ? 'oklch(0.22 0.05 155)' : 'var(--ink-3)'}
                  fontWeight={isDiag ? 600 : 400}
                  pointerEvents="none"
                >{v < 1000 ? v : (v / 1000).toFixed(1) + 'k'}</text>
              )}
            </g>
          );
        })
      )}
    </svg>
  );
}

// ============================================================
// Confidence histogram with threshold marker
// ============================================================
function ConfidenceHistogram({ bins, threshold }) {
  const [ref, size] = useSize();
  const w = size.w || 600;
  const h = 200;
  const padL = 40, padR = 8, padT = 12, padB = 24;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const max = Math.max(...bins);
  const barW = innerW / bins.length;
  const tx = padL + (threshold / 100) * innerW;

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {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)">{formatNum(Math.round(max * t))}</text>
            </g>
          ))}
          {/* below-threshold shaded region */}
          <rect x={padL} y={padT} width={tx - padL} height={innerH} fill="var(--rose)" opacity="0.06" />
          {/* bars */}
          {bins.map((v, i) => {
            const barH = (v / max) * innerH;
            const isLow = i * 5 < threshold;
            return (
              <rect
                key={i}
                x={padL + i * barW + 1.5}
                y={padT + innerH - barH}
                width={barW - 3}
                height={barH}
                fill={isLow ? 'var(--rose)' : 'var(--jade)'}
                opacity={isLow ? 0.65 : 0.78}
                rx="1"
              />
            );
          })}
          {/* threshold line */}
          <line x1={tx} x2={tx} y1={padT - 4} y2={padT + innerH} stroke="var(--ink)" strokeWidth="1.5" strokeDasharray="3 2" />
          <text x={tx} y={padT - 6} fontSize="9.5" fontFamily="var(--font-mono)" fontWeight="600" textAnchor="middle" fill="var(--ink)">{threshold}%</text>
          {/* x labels */}
          {[0, 25, 50, 75, 100].map(p => (
            <text key={p} x={padL + (p / 100) * innerW} y={h - 8} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">{p}%</text>
          ))}
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Accuracy over time
// ============================================================
function AccuracyTrendChart({ data }) {
  const [ref, size] = useSize();
  const w = size.w || 600;
  const h = 200;
  const padL = 40, padR = 8, padT = 14, padB = 26;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const min = Math.min(...data) - 1;
  const max = Math.max(...data) + 1;
  const range = max - min;
  const xs = data.map((_, i) => padL + (i / (data.length - 1)) * innerW);
  const y = (v) => padT + innerH - ((v - min) / range) * innerH;
  const path = data.map((v, i) => (i === 0 ? `M ${xs[i]} ${y(v)}` : `L ${xs[i]} ${y(v)}`)).join(' ');
  const areaPath = path + ` L ${xs[xs.length - 1]} ${y(min)} L ${xs[0]} ${y(min)} Z`;
  const targetY = y(90);

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {/* grid */}
          {[min, (min + max) / 2, max].map((v, i) => (
            <g key={i}>
              <line x1={padL} x2={w - padR} y1={y(v)} y2={y(v)} stroke="var(--line)" strokeWidth="0.5" strokeDasharray={i === 1 ? '2 3' : '0'} />
              <text x={padL - 6} y={y(v) + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-4)">{v.toFixed(1)}%</text>
            </g>
          ))}
          {/* target line at 90 */}
          <line x1={padL} x2={w - padR} y1={targetY} y2={targetY} stroke="var(--jade)" strokeWidth="1" strokeDasharray="4 2" />
          <text x={w - padR - 4} y={targetY - 4} fontSize="9" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--jade)">maqsad 90%</text>
          {/* area + line */}
          <path d={areaPath} fill="var(--accent)" opacity="0.12" />
          <path d={path} stroke="var(--accent)" strokeWidth="1.8" fill="none" strokeLinejoin="round" />
          {/* retrain markers */}
          {data.map((v, i) => (
            <g key={i}>
              <line x1={xs[i]} x2={xs[i]} y1={y(v) + 5} y2={padT + innerH} stroke="var(--ink-5)" strokeWidth="0.5" />
              <circle cx={xs[i]} cy={y(v)} r="3" fill="var(--panel)" stroke="var(--accent-ink)" strokeWidth="1.5" />
            </g>
          ))}
          {/* x labels: week numbers */}
          {[0, 4, 8, 12, 15].map(i => (
            <text key={i} x={xs[i]} y={h - 10} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">H{16 - i}</text>
          ))}
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Precision / Recall grouped bar
// ============================================================
function PrecisionRecallChart({ data }) {
  const [ref, size] = useSize();
  const w = size.w || 800;
  const h = 260;
  const padL = 40, padR = 8, padT = 14, padB = 60;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const groupW = innerW / data.length;
  const barW = (groupW - 8) / 2;

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {[0, 25, 50, 75, 100].map((v, i) => (
            <g key={i}>
              <line x1={padL} x2={w - padR} y1={padT + (1 - v / 100) * innerH} y2={padT + (1 - v / 100) * innerH} stroke="var(--line)" strokeWidth="0.5" strokeDasharray={v === 0 ? '0' : '2 3'} />
              <text x={padL - 6} y={padT + (1 - v / 100) * innerH + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-4)">{v}%</text>
            </g>
          ))}
          {data.map((d, i) => {
            const x = padL + i * groupW + 4;
            const pH = (d.precision / 100) * innerH;
            const rH = (d.recall / 100) * innerH;
            return (
              <g key={d.id}>
                <rect x={x} y={padT + innerH - pH} width={barW} height={pH} fill={d.color} opacity="0.9" rx="1" />
                <rect x={x + barW + 4} y={padT + innerH - rH} width={barW} height={rH} fill={d.color} opacity="0.45" rx="1" />
                <text x={x + barW + 2} y={padT + innerH - Math.max(pH, rH) - 4} fontSize="9" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-3)">{d.precision.toFixed(0)}/{d.recall.toFixed(0)}</text>
                <g transform={`translate(${x + barW + 2}, ${padT + innerH + 8}) rotate(-30)`}>
                  <text fontSize="9.5" fontFamily="var(--font-sans)" fill="var(--ink-2)" textAnchor="end">{d.label}</text>
                </g>
              </g>
            );
          })}
          {/* legend */}
          <g transform={`translate(${padL}, 0)`}>
            <rect x={0} y={2} width={10} height={10} fill="var(--ink-2)" />
            <text x={14} y={11} fontSize="10" fontFamily="var(--font-mono)" fill="var(--ink-2)">precision</text>
            <rect x={80} y={2} width={10} height={10} fill="var(--ink-2)" opacity="0.45" />
            <text x={94} y={11} fontSize="10" fontFamily="var(--font-mono)" fill="var(--ink-2)">recall</text>
          </g>
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Model card
// ============================================================
function ModelCard() {
  const fields = [
    ['Versiya', 'v2.18.4', 'mono'],
    ['Arxitektura', 'XLM-RoBERTa + LoRA', ''],
    ['Til', 'UZ-Lotin · UZ-Kirill · RU', ''],
    ['O‘rgatish to‘plami', '142 384 yorliqlangan', 'mono'],
    ['Tasdiq to‘plami', '18 460 yorliqlangan', 'mono'],
    ['Oxirgi o‘rgatish', '07.05.2026 · 03:14', 'mono'],
    ['Keyingi rejalashtirilgan', '14.05.2026 · 03:00 (2 soat)', 'mono'],
    ['F1 (vzvešennaya)', '0.917', 'mono'],
    ['Mas’ul', 'AI nazorat boʻlimi', ''],
  ];
  const changelog = [
    { v: 'v2.18.4', d: '14.05.26', notes: 'Naslchilik aniqligi +3.2%, kirill normalizatsiyasi yaxshilandi' },
    { v: 'v2.17.2', d: '07.05.26', notes: 'Yangi 4 200 yorliqlangan namuna qo‘shildi' },
    { v: 'v2.16.0', d: '30.04.26', notes: 'Sentiment modeli alohida fine-tune' },
    { v: 'v2.15.1', d: '23.04.26', notes: 'Aralash til detektorida bug tuzatildi' },
  ];

  return (
    <>
      <div style={{ display: 'grid', gap: 6 }}>
        {fields.map(([k, v, cls]) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '4px 0', borderBottom: '1px dotted var(--line)', fontSize: 11.5 }}>
            <span style={{ color: 'var(--ink-3)' }}>{k}</span>
            <span className={cls} style={{ color: 'var(--ink)', fontWeight: 500 }}>{v}</span>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 14 }}>
        <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>O'zgartirishlar</div>
        <div style={{ position: 'relative', paddingLeft: 14 }}>
          <div style={{ position: 'absolute', left: 4, top: 6, bottom: 6, width: 1, background: 'var(--line-strong)' }} />
          {changelog.map((c, i) => (
            <div key={c.v} style={{ position: 'relative', paddingBottom: 10 }}>
              <span style={{ position: 'absolute', left: -10, top: 4, width: 8, height: 8, background: i === 0 ? 'var(--accent)' : 'var(--ink-4)', borderRadius: '50%', border: '2px solid var(--panel)' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span className="mono" style={{ fontSize: 11.5, fontWeight: 600 }}>{c.v}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>{c.d}</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-2)', marginTop: 2, lineHeight: 1.4 }}>{c.notes}</div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ============================================================
// AI KPI tile (variant — bigger value, no sparkline)
// ============================================================
function AiKpi({ label, value, unit, trend, delta, hint, inverse }) {
  const positive = inverse ? trend === 'down' : trend === 'up';
  return (
    <div className="kpi">
      <div className="kpi-label">{label}</div>
      <div className="kpi-value">{value}<span className="unit">{unit}</span></div>
      <div style={{ fontSize: 10, color: 'var(--ink-4)' }}>{hint}</div>
      {trend && (
        <div className={`kpi-delta ${positive ? 'delta-up' : 'delta-down'}`} style={{ marginTop: 'auto' }}>
          {trend === 'up' ? '↑' : '↓'} {delta}
        </div>
      )}
    </div>
  );
}

function ConfusionTopPairs({ matrix, limit = 10 }) {
  const pairs = useMemo(() => {
    const out = [];
    matrix.forEach((row, i) => {
      row.forEach((v, j) => {
        if (i !== j && v > 0) out.push({ i, j, count: v });
      });
    });
    return out.sort((a, b) => b.count - a.count).slice(0, limit);
  }, [matrix, limit]);
  const max = pairs[0]?.count || 1;
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '22px 1fr 16px 1fr 1fr 52px',
        gap: 10,
        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>Haqiqiy</span>
        <span></span>
        <span>Bashorat</span>
        <span>Hajm</span>
        <span style={{ textAlign: 'right' }}>Soni</span>
      </div>
      {pairs.map((p, idx) => {
        const tA = TOPICS[p.i];
        const tB = TOPICS[p.j];
        const pct = p.count / max;
        return (
          <div key={`${p.i}-${p.j}`} style={{
            display: 'grid',
            gridTemplateColumns: '22px 1fr 16px 1fr 1fr 52px',
            gap: 10,
            alignItems: 'center',
            padding: '9px 0',
            borderBottom: idx < pairs.length - 1 ? '1px solid var(--line)' : 'none',
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-4)' }}>
              {String(idx + 1).padStart(2, '0')}
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
              <span style={{ width: 8, height: 8, background: tA.color, borderRadius: 1, flex: '0 0 8px' }} />
              <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tA.uz}</span>
            </span>
            <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink-4)', fontSize: 12, textAlign: 'center' }}>→</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
              <span style={{ width: 8, height: 8, background: tB.color, borderRadius: 1, flex: '0 0 8px' }} />
              <span style={{ fontSize: 12, color: 'var(--ink-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tB.uz}</span>
            </span>
            <div style={{ position: 'relative', height: 8, background: 'oklch(0.96 0.004 90)', borderRadius: 1, overflow: 'hidden' }}>
              <div style={{
                position: 'absolute', left: 0, top: 0, bottom: 0,
                width: `${pct * 100}%`,
                background: 'oklch(0.55 0.14 25)',
                opacity: 0.7,
              }} />
            </div>
            <span className="mono" style={{ fontSize: 12, fontWeight: 500, textAlign: 'right', color: 'var(--ink)' }}>
              {p.count}
            </span>
          </div>
        );
      })}
    </div>
  );
}

window.ScreenAI = ScreenAI;
