// ============ Analytics view ============
const ViewAnalytics = ({ t }) => {
  const [period, setPeriod] = React.useState("30d");
  const { loading, data, error } = useStats(period);

  const series = (data?.series || []).map(x => x.c);
  const labels = (data?.series || []).map(x => x.d.slice(5));
  const terms = data?.top_terms || [];
  const zeroTerms = data?.top_zero_terms || [];
  const totalSearches = data?.kpis.total || 0;
  const zeroTotal = data?.kpis.zero_total || 0;

  // sorting + pagination (client-side on the top-50 slice we already have)
  const [sort, setSort] = React.useState({ key: "searches", dir: "desc" });
  const sorted = React.useMemo(() => {
    const arr = [...terms];
    arr.sort((a, b) => {
      const dir = sort.dir === "asc" ? 1 : -1;
      if (a[sort.key] < b[sort.key]) return -1 * dir;
      if (a[sort.key] > b[sort.key]) return 1 * dir;
      return 0;
    });
    return arr;
  }, [terms, sort]);

  const [page, setPage] = React.useState(1);
  React.useEffect(() => { setPage(1); }, [period]);
  const perPage = 10;
  const pages = Math.max(1, Math.ceil(sorted.length / perPage));
  const rows = sorted.slice((page - 1) * perPage, page * perPage);
  const max = sorted[0]?.searches || 1;

  const head = (key, label, num) => (
    <th className={num ? "num" : ""} onClick={() => setSort(s => ({ key, dir: s.key === key ? (s.dir === "asc" ? "desc" : "asc") : "desc" }))}>
      {label} {sort.key === key && <span style={{ color: "var(--accent)" }}>{sort.dir === "asc" ? "↑" : "↓"}</span>}
    </th>
  );

  return (
    <div className="view">
      {error && <ApiError t={t} message={error}/>}

      <Card title={<SectionTitle icon="analytics" tip={t("tip_volume")}>{t("trend_searches")}</SectionTitle>}
        right={<Segment options={TOKENS.period.map(p => ({ value: p.value, label: t(p.labelKey)}))} value={period} onChange={setPeriod}/>}
        style={{ marginBottom: 16 }}>
        {loading && !data
          ? <LoadingBlock t={t}/>
          : series.length === 0
            ? <EmptyBlock t={t}/>
            : <LineChart data={series} labels={labels} />
        }
      </Card>

      <Card title={<SectionTitle icon="x" color="var(--danger)" tip={t("tip_zero_list")}>{t("zero_list")}</SectionTitle>}
        right={<Chip tone="danger" dot>{zeroTotal.toLocaleString()}</Chip>}
        style={{ marginBottom: 16 }}>
        <div style={{ padding: "4px 0", display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", columnGap: 16 }}>
          {loading && !data && <LoadingBlock t={t}/>}
          {zeroTerms.map((r) => (
            <div key={r.term} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 4px", borderBottom: "1px solid var(--line)" }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.term}</div>
                <div style={{ fontSize: 11, color: "var(--text-faint)" }}>
                  {zeroTotal ? ((r.count / zeroTotal) * 100).toFixed(2) : "0"}% · {r.days} {t("days")}
                </div>
              </div>
              <div className="num-mono" style={{ fontSize: 13, color: "var(--danger)", fontWeight: 600 }}>
                {r.count.toLocaleString()}
              </div>
            </div>
          ))}
          {!loading && zeroTerms.length === 0 && <EmptyBlock t={t}/>}
        </div>
      </Card>

      <Card title={<SectionTitle icon="trending" tip={t("tip_terms_full")}>{t("terms_full")}</SectionTitle>}
        right={
          <div style={{ display: "flex", gap: 8 }}>
            <Button size="sm" variant="ghost" icon="download" onClick={() => exportCsv(sorted)}>{t("export")}</Button>
          </div>
        }>
        {loading && !data
          ? <LoadingBlock t={t}/>
          : rows.length === 0
            ? <EmptyBlock t={t}/>
            : (
              <>
                <table className="table">
                  <thead>
                    <tr>
                      <th>#</th>
                      {head("term", t("term"))}
                      {head("searches", t("searches"), true)}
                      <th className="num">{t("pct_of_total")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map((r, i) => {
                      const rank = (page - 1) * perPage + i + 1;
                      const pct = (r.searches / max) * 100;
                      const shareOfTotal = totalSearches ? (r.searches / totalSearches) * 100 : 0;
                      return (
                        <tr key={r.term}>
                          <td style={{ color: "var(--text-faint)", fontFamily: "JetBrains Mono", fontSize: 12, width: 40 }}>{rank}</td>
                          <td className="bar-cell">
                            <div className="bar" style={{ width: pct + "%" }}/>
                            <span className="label">{r.term}</span>
                          </td>
                          <td className="num">{r.searches.toLocaleString()}</td>
                          <td className="num" style={{ color: "var(--text-dim)" }}>{shareOfTotal.toFixed(2)}%</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
                <div className="pager">
                  <div style={{ flex: 1, fontSize: 12, color: "var(--text-faint)" }}>
                    {(page - 1) * perPage + 1}–{Math.min(page * perPage, sorted.length)} {t("of")} {sorted.length}
                  </div>
                  <button className="pg-btn" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}>‹</button>
                  {Array.from({ length: pages }, (_, i) => (
                    <button key={i} className={"pg-btn" + (page === i + 1 ? " active" : "")} onClick={() => setPage(i + 1)}>{i + 1}</button>
                  ))}
                  <button className="pg-btn" onClick={() => setPage(p => Math.min(pages, p + 1))} disabled={page === pages}>›</button>
                </div>
              </>
            )
        }
      </Card>
    </div>
  );
};

function exportCsv(rows) {
  const lines = ["term,searches"];
  rows.forEach(r => lines.push(`"${r.term.replace(/"/g, '""')}",${r.searches}`));
  const blob = new Blob([lines.join("\n")], { type: "text/csv" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url; a.download = "top_terms.csv"; a.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

Object.assign(window, { ViewAnalytics });
