/* ============================================================
   Screen 1 — Bosh sahifa (Executive Overview)
   All dynamic data fetched from the Worker via useApi.
   ============================================================ */

const STATUS_FUNNEL_ORDER = ['new', 'classified', 'routed', 'answered', 'resolved'];
const STATUS_UZ = {
  new: 'Qabul qilindi',
  classified: 'Tasniflandi',
  routed: 'Yoʻnaltirildi',
  answered: 'Javob berildi',
  resolved: 'Tasdiqlandi',
};

function ScreenOverview() {
  const [range, setRange] = useState(30);

  // All the panel data
  const overview = useApi('/api/stats/overview',                     { pollMs: 15000 });
  const ranking  = useApi(`/api/stats/topic-ranking?days=${range}`,  { pollMs: 15000 });
  const byDay    = useApi(`/api/stats/by-day?days=${range}`,         { pollMs: 30000 });
  const byTopic  = useApi('/api/stats/by-topic',                     { pollMs: 30000 });
  const byRegion = useApi('/api/stats/by-region',                    { pollMs: 30000 });
  const funnel   = useApi('/api/stats/funnel',                       { pollMs: 30000 });
  const momentum = useApi('/api/stats/momentum',                     { pollMs: 30000 });
  const sentByT  = useApi('/api/stats/sentiment-by-topic',           { pollMs: 30000 });
  const aiMetric = useApi('/api/stats/ai-metrics',                   { pollMs: 30000 });
  const feed     = useApi('/api/inquiries/feed?limit=15',            { pollMs: 8000 });
  const urgent   = useApi('/api/inquiries/urgent?limit=5',           { pollMs: 15000 });

  // KPIs
  const o = overview.data || {};
  const kpiTiles = [
    { id: 'total',      label: 'Jami murojaat',        value: fmtNum(o.total),                                hint: 'kumulyativ' },
    { id: 'classified', label: 'Tasniflandi (AI)',     value: fmtNum(o.classified),                           hint: 'avto-tasniflangan' },
    { id: 'open',       label: 'Ochiq',                value: fmtNum(o.open),                                 hint: 'hal etilmagan' },
    { id: 'urgent',     label: 'Shoshilinch ochiq',    value: fmtNum(o.urgent_open),                          hint: 'eng yuqori prioritet' },
    { id: 'today',      label: 'Bugun',                value: fmtNum(o.today),                                hint: 'bugun qabul qilingan' },
    { id: 'farmers',    label: 'Fermerlar',            value: fmtNum(o.farmers),                              hint: 'unikal yuboruvchilar' },
    { id: 'latency',    label: 'AI tasniflash',        value: o.avg_classify_sec != null ? (o.avg_classify_sec).toFixed(1) : '—', unit: 's', hint: 'oʻrtacha kechikish' },
    { id: 'conf',       label: 'AI ishonchlilik',      value: o.avg_confidence != null ? (o.avg_confidence * 100).toFixed(1) : '—', unit: '%', hint: 'oʻrtacha' },
  ];

  // Topic-ranking items, with per-topic sparkline pulled from byDay
  const sparkByTopic = useMemo(() => buildSparklines(byDay.data, range), [byDay.data, range]);
  const rankingItems = (ranking.data?.items || []).map((t) => ({
    id: t.id,
    label: t.uz,
    color: t.color,
    value: t.total,
    delta: t.prev_week > 0 ? ((t.this_week - t.prev_week) / t.prev_week) * 100 : t.this_week > 0 ? 100 : 0,
    spark: sparkByTopic[t.id] || [],
  }));

  // Donut data
  const donutData = (byTopic.data?.items || []).map((t) => ({
    id: t.id,
    label: t.uz,
    value: t.total,
    color: t.color,
  }));

  // Map values
  const choroValues = useMemo(() => {
    const out = {};
    (byRegion.data?.items || []).forEach((r) => { out[r.id] = r.total; });
    return out;
  }, [byRegion.data]);

  // Funnel — cumulative top-down
  const funnelSteps = useMemo(() => {
    const counts = Object.fromEntries((funnel.data?.items || []).map((s) => [s.status, s.n]));
    const total = (counts.new || 0) + (counts.classified || 0) + (counts.routed || 0) + (counts.answered || 0) + (counts.resolved || 0);
    const past = (set) => set.reduce((s, k) => s + (counts[k] || 0), 0);
    return [
      { uz: 'Qabul qilindi', value: total },
      { uz: 'Tasniflandi',   value: past(['classified', 'routed', 'answered', 'resolved']) },
      { uz: 'Yoʻnaltirildi', value: past(['routed', 'answered', 'resolved']) },
      { uz: 'Javob berildi', value: past(['answered', 'resolved']) },
      { uz: 'Tasdiqlandi',   value: past(['resolved']) },
    ];
  }, [funnel.data]);

  // Momentum — sort desc by % delta
  const momentumItems = useMemo(() => {
    return (momentum.data?.items || [])
      .map((t) => {
        const tw = t.this_week || 0;
        const pw = t.prev_week || 0;
        const delta = pw > 0 ? ((tw - pw) / pw) * 100 : tw > 0 ? 100 : 0;
        return { id: t.id, label: t.uz, delta };
      })
      .sort((a, b) => b.delta - a.delta);
  }, [momentum.data]);

  // Top 6 topics by total for sentiment gauges
  const sentTop6 = (sentByT.data?.items || []).slice(0, 6);

  const feedItems = feed.data?.items || [];
  const urgentItems = urgent.data?.items || [];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-crumbs">
            <span>Asosiy</span><span>/</span><span style={{ color: 'var(--ink-2)' }}>Bosh sahifa</span>
          </div>
          <h1 className="page-title">Bosh sahifa<span className="ru">Обзор · Executive Overview</span></h1>
        </div>
        <div className="page-actions">
          <div className="seg">
            <button>Bugun</button>
            <button className="on">Bu hafta</button>
            <button>Bu oy</button>
          </div>
          <button className="btn" onClick={() => { overview.refresh(); ranking.refresh(); feed.refresh(); }}>
            <Icon name="refresh" size={12} /> Yangilash
          </button>
          <button className="btn btn-primary"><Icon name="download" size={12} /> Hisobot</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="kpi-strip mb-12">
        {kpiTiles.map((k) => <OverviewKpi key={k.id} {...k} />)}
      </div>

      {/* Row 1: Topic ranking + Donut */}
      <div className="grid-2-1 mb-12">
        <Panel
          title="Mavzular boʻyicha hajm"
          sub={`Reyting · ${range} kun · ${rankingItems.length} mavzu`}
          num="01"
          actions={
            <>
              <Seg
                options={[
                  { value: 7,  label: '7K'  },
                  { value: 14, label: '14K' },
                  { value: 30, label: '30K' },
                  { value: 90, label: '90K' },
                ]}
                value={range}
                onChange={setRange}
              />
              <button className="btn btn-ghost btn-sm"><Icon name="download" size={12} /></button>
              <button className="btn btn-ghost btn-sm"><Icon name="expand" size={12} /></button>
            </>
          }
        >
          <TopicRankingList items={rankingItems} />
        </Panel>

        <Panel
          title="Mavzular ulushi"
          sub={`Hajm boʻyicha · ${donutData.length} mavzu`}
          num="02"
        >
          <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 16px' }}>
            <Donut
              data={donutData}
              size={220}
              label="Jami murojaat"
              sub={`${range} kun`}
            />
          </div>
        </Panel>
      </div>

      {/* Row 2: Map + Funnel */}
      <div className="grid-2-1 mb-12">
        <Panel title="Hududiy zichlik" sub="14 viloyat · choropleth" num="03">
          <UzMap values={choroValues} height={320} layerLabel="Murojaat zichligi" />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-4)' }}>
            <span>kam</span>
            <div style={{ flex: 1, height: 6, margin: '0 10px', background: 'linear-gradient(90deg, #e7f5f8, #a5dae6 50%, #16566c)', borderRadius: 1 }} />
            <span>koʻp</span>
          </div>
        </Panel>

        <Panel title="Tasniflash voronkasi" sub="Qabul → tasdiq" num="04">
          <Funnel steps={funnelSteps} height={300} />
          <div style={{ borderTop: '1px solid var(--line)', marginTop: 10, paddingTop: 10, display: 'flex', justifyContent: 'space-between', fontSize: 11 }}>
            <div>
              <div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Yetib borish %</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14 }}>
                {funnelSteps[0].value > 0
                  ? ((funnelSteps[4].value / funnelSteps[0].value) * 100).toFixed(1) + '%'
                  : '—'}
              </div>
            </div>
            <div>
              <div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Hozir AI ishonchli</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--accent-ink)' }}>
                {o.avg_confidence ? (o.avg_confidence * 100).toFixed(1) + '%' : '—'}
              </div>
            </div>
          </div>
        </Panel>
      </div>

      {/* Row 3: Momentum + Sentiment */}
      <div className="grid-2-1 mb-12">
        <Panel title="Mavzu momentum" sub="Bu hafta vs oʻtgan hafta" num="05">
          <DivergingBar data={momentumItems} height={320} />
        </Panel>

        <Panel title="Sentiment indikatorlari" sub={`Top ${sentTop6.length} mavzu`} num="06">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, padding: '4px 0' }}>
            {sentTop6.map((t) => (
              <SentGauge key={t.id} pos={t.pos || 0} neu={t.neu || 0} neg={t.neg || 0} label={t.uz} />
            ))}
          </div>
        </Panel>
      </div>

      {/* Row 4: Activity feed + Urgent + AI metrics */}
      <div className="grid-2 mb-12">
        <Panel
          title="Jonli faollik"
          sub={`Soʻnggi ${feedItems.length} murojaat · 8s yangilanadi`}
          num="07"
          body={false}
        >
          <div style={{ padding: '6px 0 0', maxHeight: 560, overflowY: 'auto' }}>
            {feedItems.length === 0 && (
              <div style={{ padding: 24, textAlign: 'center', color: 'var(--ink-4)', fontSize: 12 }}>
                Hozircha murojaatlar yoʻq — bot orqali yuborilgach shu yerda paydo boʻladi.
              </div>
            )}
            {feedItems.map((inq) => {
              const t = inq.topic_id ? TOPIC_BY_ID[inq.topic_id] : null;
              const region = inq.region_id ? REGION_BY_ID[inq.region_id] : null;
              const ts = new Date(inq.created_at * 1000);
              return (
                <div key={inq.id} className="feed-item">
                  <span className="topic-mark" style={{ background: t?.color || 'var(--ink-4)' }} />
                  <div style={{ minWidth: 0 }}>
                    <div className="msg" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <strong style={{ fontWeight: 600 }}>{inq.farmer_name}</strong>
                      {t && <span className="chip" style={{ background: 'transparent', border: '1px solid var(--line)' }}>{t.uz}</span>}
                      {inq.priority === 'urgent' && <PriorityChip p="urgent" />}
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-2)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {inq.text}
                    </div>
                    <div className="meta">
                      <span className="mono">{inq.id}</span>
                      {region && <> · {region.uz}</>}
                      {inq.confidence != null && <> · AI {(inq.confidence * 100).toFixed(0)}%</>}
                    </div>
                  </div>
                  <div className="time">{formatRel(ts)}</div>
                </div>
              );
            })}
          </div>
        </Panel>

        <div className="stack">
          <Panel title="Shoshilinch ochiq" sub={`${o.urgent_open ?? 0} ta · eng yuqori prioritet`} num="08" body={false}>
            <div>
              {urgentItems.length === 0 && (
                <div style={{ padding: 24, textAlign: 'center', color: 'var(--ink-4)', fontSize: 12 }}>
                  Shoshilinch murojaatlar yoʻq.
                </div>
              )}
              {urgentItems.map((inq, i) => {
                const t = inq.topic_id ? TOPIC_BY_ID[inq.topic_id] : null;
                const region = inq.region_id ? REGION_BY_ID[inq.region_id] : null;
                const ts = new Date(inq.created_at * 1000);
                return (
                  <div key={inq.id} style={{ display: 'grid', gridTemplateColumns: '26px 1fr auto', gap: 10, padding: '10px 14px', borderBottom: i < urgentItems.length - 1 ? '1px solid var(--line)' : 'none', alignItems: 'start' }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 16, color: 'var(--rose)', fontWeight: 600 }}>0{i + 1}</div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 12, color: 'var(--ink)', display: 'flex', gap: 6, alignItems: 'center' }}>
                        {t && <TopicMark topicId={inq.topic_id} size={14} />}
                        <span style={{ fontWeight: 600 }}>{t?.uz || '—'}</span>
                        {inq.sub_topic && <span style={{ color: 'var(--ink-4)', fontSize: 10.5 }}>· {inq.sub_topic}</span>}
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 3, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                        {inq.text}
                      </div>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-4)', marginTop: 4, display: 'flex', gap: 8 }}>
                        <span>{inq.farmer_name}</span>
                        {region && <><span>·</span><span>{region.code}</span></>}
                      </div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-end' }}>
                      <span className="chip chip-rose">{formatRel(ts)}</span>
                      <button className="btn btn-sm btn-primary" style={{ marginTop: 4 }}>Koʻrish</button>
                    </div>
                  </div>
                );
              })}
            </div>
          </Panel>

          <Panel title="AI tezkor koʻrsatkichlar" sub="jonli" num="09">
            <AiMetricsLiveGrid metrics={aiMetric.data} />
          </Panel>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// Helper components
// ============================================================

function fmtNum(n) {
  if (n == null) return '—';
  return formatNum(n);
}

// Build per-topic daily sparkline arrays from /api/stats/by-day response
function buildSparklines(byDayData, days) {
  if (!byDayData) return {};
  const items = byDayData.items || [];
  // Generate the last N days as ISO date strings
  const dayKeys = [];
  const today = new Date();
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date(today.getTime() - i * 86400000);
    dayKeys.push(d.toISOString().slice(0, 10));
  }
  // Bucket: { topic_id: { day: n } }
  const bucket = {};
  items.forEach((row) => {
    if (!bucket[row.topic_id]) bucket[row.topic_id] = {};
    bucket[row.topic_id][row.day] = row.n;
  });
  // Flatten to arrays in dayKeys order
  const out = {};
  Object.keys(bucket).forEach((tid) => {
    out[tid] = dayKeys.map((d) => bucket[tid][d] || 0);
  });
  return out;
}

function OverviewKpi({ label, value, unit, hint }) {
  return (
    <div className="kpi-tile">
      <div className="kpi-label">{label}</div>
      <div className="kpi-value mono">
        {value}
        {unit && <span className="kpi-unit">{unit}</span>}
      </div>
      <div className="kpi-foot">
        <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>{hint}</span>
      </div>
    </div>
  );
}

function TopicRankingList({ items }) {
  const max = Math.max(1, ...items.map((i) => i.value));
  if (items.length === 0) {
    return (
      <div style={{ padding: '24px 0', textAlign: 'center', color: 'var(--ink-4)', fontSize: 12 }}>
        Mavzu boʻyicha murojaat hali yoʻq.
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '22px 14px 110px 1fr 64px 60px 76px',
        gap: 12,
        padding: '0 0 6px',
        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>Ulush</span>
        <span style={{ textAlign: 'right' }}>Hajm</span>
        <span style={{ textAlign: 'right' }}>Δ</span>
        <span style={{ textAlign: 'right' }}>Trend</span>
      </div>
      {items.map((it, i) => {
        const pct = it.value / max;
        const up = it.delta >= 0;
        return (
          <div key={it.id} style={{
            display: 'grid',
            gridTemplateColumns: '22px 14px 110px 1fr 64px 60px 76px',
            gap: 12,
            alignItems: 'center',
            padding: '8px 0',
            borderBottom: i < items.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: it.color, borderRadius: 1 }} />
            <span style={{ fontSize: 12, color: 'var(--ink)', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {it.label}
            </span>
            <div style={{ position: 'relative', height: 10, 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: it.color,
                opacity: 0.78,
              }} />
            </div>
            <span className="mono" style={{ fontSize: 12, fontWeight: 500, textAlign: 'right', color: 'var(--ink)' }}>
              {formatNum(it.value)}
            </span>
            <span style={{
              fontFamily: 'var(--font-mono)',
              fontSize: 11,
              fontWeight: 600,
              color: up ? 'oklch(0.45 0.10 155)' : 'oklch(0.50 0.14 25)',
              textAlign: 'right',
            }}>
              {up ? '↑' : '↓'} {Math.abs(it.delta).toFixed(1)}%
            </span>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              {it.spark.length > 1 && (
                <Sparkline data={it.spark} width={76} height={20} color={it.color} strokeWidth={1.25} />
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function AiMetricsLiveGrid({ metrics }) {
  const m = metrics || {};
  const tiles = [
    { label: 'Ishonchlilik',  value: m.confidence_avg != null ? (m.confidence_avg * 100).toFixed(1) : '—', unit: '%',  dir: 'up'   },
    { label: 'O‘rt. kechikish', value: m.latency_ms_avg != null ? Math.round(m.latency_ms_avg)        : '—', unit: 'ms', dir: 'down' },
    { label: 'Til aniqlash',  value: m.lang_detect_rate != null ? (m.lang_detect_rate * 100).toFixed(1) : '—', unit: '%', dir: 'up'   },
    { label: 'Xatolar',       value: m.errors != null ? m.errors                                       : '—', unit: '',  dir: 'down' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
      {tiles.map((t, i) => (
        <div key={i}>
          <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{t.label}</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8, marginTop: 2 }}>
            <div className="mono" style={{ fontSize: 20, fontWeight: 500, lineHeight: 1.1 }}>
              {t.value}{t.unit && <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{t.unit}</span>}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

window.ScreenOverview = ScreenOverview;
