/* ============================================================
   Screen 3 — Mavzular (Topic Deep Dives)
   ============================================================ */

function ScreenTopics() {
  const [selected, setSelected] = useState(null);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-crumbs">
            <span>Asosiy</span><span>/</span><span style={{ color: 'var(--ink-2)' }}>Mavzular</span>
            {selected && <><span>/</span><span style={{ color: 'var(--ink-2)' }}>{TOPIC_BY_ID[selected]?.uz}</span></>}
          </div>
          <h1 className="page-title">
            {selected ? TOPIC_BY_ID[selected]?.uz : 'Mavzular'}
            <span className="ru">{selected ? TOPIC_BY_ID[selected]?.ru : 'Темы · 12 категорий'}</span>
          </h1>
        </div>
        <div className="page-actions">
          {selected && <button className="btn" onClick={() => setSelected(null)}>← Barcha mavzular</button>}
          <button className="btn"><Icon name="download" size={12} /> Eksport</button>
        </div>
      </div>

      {selected ? <TopicDetail topicId={selected} /> : <TopicGrid onSelect={setSelected} />}
    </div>
  );
}

// ============================================================
// Topic grid — 12 cards
// ============================================================
function TopicGrid({ onSelect }) {
  const ranking  = useApi('/api/stats/topic-ranking?days=30', { pollMs: 30000 });
  const sentByT  = useApi('/api/stats/sentiment-by-topic',    { pollMs: 30000 });
  const byDay    = useApi('/api/stats/by-day?days=7',         { pollMs: 30000 });
  const overview = useApi('/api/stats/overview',              { pollMs: 30000 });

  // Map per-topic stats together
  const stats = useMemo(() => {
    const out = {};
    (ranking.data?.items || []).forEach(t => {
      out[t.id] = { ...out[t.id], total: t.total, this_week: t.this_week, prev_week: t.prev_week, uz: t.uz, color: t.color };
    });
    (sentByT.data?.items || []).forEach(t => {
      out[t.id] = { ...out[t.id], pos: t.pos || 0, neu: t.neu || 0, neg: t.neg || 0 };
    });
    return out;
  }, [ranking.data, sentByT.data]);

  // Per-topic 7-day sparkline arrays
  const sparkByTopic = useMemo(() => {
    const items = byDay.data?.items || [];
    const today = new Date();
    const keys = Array.from({ length: 7 }, (_, i) => {
      const d = new Date(today.getTime() - (6 - i) * 86400000);
      return d.toISOString().slice(0, 10);
    });
    const bucket = {};
    items.forEach(r => {
      if (!bucket[r.topic_id]) bucket[r.topic_id] = {};
      bucket[r.topic_id][r.day] = r.n;
    });
    const out = {};
    Object.keys(bucket).forEach(tid => { out[tid] = keys.map(k => bucket[tid][k] || 0); });
    return out;
  }, [byDay.data]);

  const totalAll = overview.data?.total || 0;

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
        {TOPICS.map(t => {
          const b = stats[t.id] || {};
          const total = b.total || 0;
          const tw = b.this_week || 0;
          const pw = b.prev_week || 0;
          const trend = pw > 0 ? ((tw - pw) / pw) * 100 : tw > 0 ? 100 : 0;
          const trendUp = trend >= 0;
          const sentTotal = (b.pos || 0) + (b.neu || 0) + (b.neg || 0);
          const sentScore = sentTotal > 0 ? ((b.pos - b.neg) / sentTotal) : 0;
          const share = totalAll > 0 ? (total / totalAll) * 100 : 0;
          const spark = sparkByTopic[t.id] || [];

          return (
            <div
              key={t.id}
              className="panel interactive"
              style={{ padding: 0, cursor: 'pointer', overflow: 'hidden' }}
              onClick={() => onSelect(t.id)}
            >
              <div style={{ height: 4, background: t.color }} />
              <div style={{ padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <TopicMark topicId={t.id} size={28} />
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13.5 }}>{t.uz}</div>
                      <div style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.02em' }}>{t.ru}</div>
                    </div>
                  </div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: trendUp ? 'var(--jade)' : 'var(--rose)', fontWeight: 600 }}>
                    {trendUp ? '↑' : '↓'} {Math.abs(trend).toFixed(1)}%
                  </div>
                </div>

                <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
                  <div>
                    <div className="mono" style={{ fontSize: 20, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>{formatNum(total)}</div>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>jami</div>
                  </div>
                  <div>
                    <div className="mono" style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1 }}>{formatNum(tw)}</div>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>haftalik</div>
                  </div>
                  <div style={{ marginLeft: 'auto' }}>
                    <div className="mono" style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1 }}>{share.toFixed(1)}%</div>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>ulush</div>
                  </div>
                </div>

                {spark.length > 0 && (
                  <div style={{ marginTop: 8 }}>
                    <Sparkline data={spark} width={200} height={28} color={t.color} fill strokeWidth={1.5} dot />
                  </div>
                )}

                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--line)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: sentScore > 0.1 ? 'var(--jade)' : sentScore < -0.1 ? 'var(--rose)' : 'var(--ink-4)' }} />
                    <span style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>
                      {sentScore > 0.1 ? 'Ijobiy' : sentScore < -0.1 ? 'Salbiy' : 'Neytral'}
                    </span>
                  </div>
                  <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-4)' }}>
                    {sentTotal} sent.
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Summary donut */}
      <Panel title="Mavzular boʻyicha umumiy" sub="hajm taqsimoti" num="—" className="mb-12">
        <div style={{ display: 'flex', justifyContent: 'center', padding: '12px 0' }}>
          <Donut
            size={220}
            data={TOPICS.map(t => ({ id: t.id, label: t.uz, value: stats[t.id]?.total || 0, color: t.color }))}
            label={`${totalAll}`}
            sub="jami"
          />
        </div>
      </Panel>
    </>
  );
}

// ============================================================
// Topic detail
// ============================================================
function TopicDetail({ topicId }) {
  const { data, loading } = useApi(`/api/topics/${topicId}`, { pollMs: 20000 });
  const t = TOPIC_BY_ID[topicId];

  // Build a 60-day series from daily{ day, n } even before data lands
  const series = useMemo(() => {
    const daily = data?.daily || [];
    const today = new Date();
    const keys = Array.from({ length: 60 }, (_, i) => {
      const d = new Date(today.getTime() - (59 - i) * 86400000);
      return d.toISOString().slice(0, 10);
    });
    const byDay = Object.fromEntries(daily.map(d => [d.day, d.n]));
    return keys.map(k => byDay[k] || 0);
  }, [data]);

  // Anomaly detection over 60-day series
  const anomalies = useMemo(() => {
    const out = [];
    for (let i = 6; i < series.length; i++) {
      const window = series.slice(Math.max(0, i - 7), i);
      const avg = window.reduce((a, b) => a + b, 0) / window.length;
      if (series[i] > avg * 1.55 && series[i] > 2) out.push(i);
    }
    return out.slice(0, 5);
  }, [series]);

  const xLabels = useMemo(() => {
    const today = new Date();
    return [0, 1, 2, 3, 4].map(i => {
      const idx = Math.round((i / 4) * 59);
      const d = new Date(today.getTime() - (59 - idx) * 86400000);
      return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}`;
    });
  }, []);

  if (!data) {
    return <div className="panel" style={{ padding: 32, textAlign: 'center', color: 'var(--ink-4)' }}>{loading ? 'Yuklanmoqda…' : 'Maʼlumot yoʻq.'}</div>;
  }

  const stats = data.stats || {};
  const total = stats.total || 0;
  const tw = stats.this_week || 0;
  const pw = stats.prev_week || 0;
  const trend = pw > 0 ? ((tw - pw) / pw) * 100 : tw > 0 ? 100 : 0;

  // Sub-topic breakdown from API
  const subBreakdown = (data.sub_topics || []).map(s => ({
    label: s.name, value: s.n, color: t.color,
  }));
  // Fallback: if backend has no sub_topic data, use topic.subs as labels with zero values
  const subData = subBreakdown.length > 0
    ? subBreakdown
    : t.subs.map(s => ({ label: s, value: 0, color: t.color }));

  // Regional values
  const regionalValues = useMemo(() => {
    const out = {};
    (data.by_region || []).forEach(r => { out[r.id] = r.n; });
    return out;
  }, [data]);

  // Top farmers
  const topFarmers = data.top_farmers || [];

  return (
    <>
      {/* Hero */}
      <div className="panel mb-12" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ height: 6, background: t.color }} />
        <div style={{ padding: 20, display: 'grid', gridTemplateColumns: 'auto 1fr auto auto auto', alignItems: 'center', gap: 24 }}>
          <TopicMark topicId={topicId} size={56} />
          <div>
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em' }}>{t.uz}</div>
            <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>{t.ru} · {t.en}</div>
            <div style={{ display: 'flex', gap: 4, marginTop: 6 }}>
              {t.subs.map(s => <span key={s} className="chip">{s}</span>)}
            </div>
          </div>
          <KpiCell label="Jami" value={formatNum(total)} />
          <KpiCell label="Bu hafta" value={formatNum(tw)} />
          <KpiCell label="Trend (haftalik)" value={`${trend >= 0 ? '+' : ''}${trend.toFixed(1)}%`} color={trend >= 0 ? 'var(--jade)' : 'var(--rose)'} />
        </div>
      </div>

      {/* Row 1: time series + sub-topics */}
      <div className="grid-2-1 mb-12">
        <Panel title="Vaqt seriyasi · anomaliyalar bilan" sub="60 kun · avtomatik tepalar" num="01">
          <LineChart data={series} height={220} color={t.color} anomalies={anomalies} xLabels={xLabels} fill />
          {anomalies.length > 0 && (
            <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--line)', display: 'flex', gap: 14, fontSize: 11 }}>
              <span style={{ color: 'var(--ink-3)' }}>Anomaliyalar:</span>
              {anomalies.slice(0, 3).map((a, i) => {
                const today = new Date();
                const d = new Date(today.getTime() - (59 - a) * 86400000);
                return (
                  <span key={i} style={{ fontFamily: 'var(--font-mono)', color: 'var(--rose)' }}>
                    ⚠ {String(d.getDate()).padStart(2, '0')}.{String(d.getMonth() + 1).padStart(2, '0')} · {series[a]} ta
                  </span>
                );
              })}
            </div>
          )}
        </Panel>

        <Panel title="Pastki kategoriyalar" sub="treemap" num="02">
          <TreemapResp data={subData} height={220} />
        </Panel>
      </div>

      {/* Row 2: map */}
      <div className="grid-2 mb-12">
        <Panel title={`${t.uz} hududiy taqsimot`} sub="14 viloyat" num="03">
          <UzMap values={regionalValues} height={240} layerLabel={t.uz.toUpperCase()} />
        </Panel>

        <Panel title="Sentiment" sub="murojaatlar tahlili" num="04">
          <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <SentRow color="var(--jade)" label="Ijobiy" value={stats.pos || 0} max={total} />
            <SentRow color="var(--ink-4)" label="Neytral" value={stats.neu || 0} max={total} />
            <SentRow color="var(--rose)" label="Salbiy" value={stats.neg || 0} max={total} />
          </div>
          <div style={{ padding: '12px 20px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', fontSize: 11 }}>
            <div>
              <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Net sentiment</div>
              <div className="mono" style={{ fontSize: 16, fontWeight: 500, color: total > 0 && stats.pos > stats.neg ? 'var(--jade)' : total > 0 && stats.neg > stats.pos ? 'var(--rose)' : 'var(--ink)' }}>
                {total > 0 ? (((stats.pos - stats.neg) / total) * 100).toFixed(1) : '0'}%
              </div>
            </div>
            <div>
              <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Savol</div>
              <div className="mono" style={{ fontSize: 16, fontWeight: 500 }}>{stats.q || 0}</div>
            </div>
            <div>
              <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Shoshilinch</div>
              <div className="mono" style={{ fontSize: 16, fontWeight: 500, color: 'var(--rose)' }}>{stats.urgent || 0}</div>
            </div>
          </div>
        </Panel>
      </div>

      {/* Row 3: top farmers */}
      <Panel title="Eng faol fermerlar" sub="bu mavzuda" num="05" className="mb-12">
        {topFarmers.length === 0 ? (
          <div style={{ padding: 16, color: 'var(--ink-4)', fontSize: 11 }}>Hali fermer yoʻq.</div>
        ) : (
          <table style={{ width: '100%', fontSize: 11.5 }}>
            <thead>
              <tr>
                <th style={{ textAlign: 'left', padding: '4px 6px', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>#</th>
                <th style={{ textAlign: 'left', padding: '4px 6px', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>Fermer</th>
                <th style={{ textAlign: 'right', padding: '4px 6px', fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>Murojaat</th>
              </tr>
            </thead>
            <tbody>
              {topFarmers.map((tf, i) => {
                const max = topFarmers[0]?.n || 1;
                return (
                  <tr key={tf.id} style={{ borderTop: '1px solid var(--line)' }}>
                    <td style={{ padding: '6px 6px', fontFamily: 'var(--font-mono)', color: 'var(--ink-4)', fontSize: 10 }}>{String(i + 1).padStart(2, '0')}</td>
                    <td style={{ padding: '6px 6px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <Avatar name={tf.name} size={20} />
                        <div>
                          <div style={{ fontSize: 11.5 }}>{tf.name}</div>
                          <div style={{ fontSize: 9.5, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>{tf.id}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '6px 6px', textAlign: 'right' }}>
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                        <div style={{ width: 60 }}><MiniBar value={tf.n} max={max} color={t.color} height={4} /></div>
                        <span className="mono" style={{ fontSize: 11.5, fontWeight: 500 }}>{tf.n}</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </Panel>
    </>
  );
}

function KpiCell({ label, value, color }) {
  return (
    <div style={{ borderLeft: '1px solid var(--line)', paddingLeft: 18 }}>
      <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', color: color || 'var(--ink)' }}>{value}</div>
    </div>
  );
}

function SentRow({ color, label, value, max }) {
  const pct = max > 0 ? (value / max) * 100 : 0;
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, fontSize: 11.5 }}>
        <span>{label}</span>
        <span className="mono" style={{ color: 'var(--ink-3)' }}>{value} · {pct.toFixed(0)}%</span>
      </div>
      <div style={{ height: 6, background: 'var(--bg-sunken)', borderRadius: 1, overflow: 'hidden' }}>
        <div style={{ width: `${pct}%`, height: '100%', background: color }} />
      </div>
    </div>
  );
}

window.ScreenTopics = ScreenTopics;
