// ============ Per-term details modal ============
const TermDetails = ({ term, onClose, t }) => {
  const [period, setPeriod] = React.useState("30d");
  const { loading, data, error } = useApi(
    term ? `/api/term?term=${encodeURIComponent(term)}&period=${period}` : null,
    [term, period]
  );

  React.useEffect(() => {
    if (!term) return;
    const onKey = (e) => e.key === "Escape" && onClose && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [term, onClose]);

  if (!term) return null;

  const k = data?.kpis || {};
  const series = data?.series || [];
  const totals = series.map(r => r.c);
  const zeros  = series.map(r => r.z);
  const labels = series.map(r => r.d.slice(5));
  const hasAny = (k.total || 0) + (k.zero_total || 0) > 0;
  const primarySeries = (k.total || 0) >= (k.zero_total || 0) ? totals : zeros;
  const primaryColor  = (k.total || 0) >= (k.zero_total || 0) ? "var(--accent)" : "var(--danger)";
  const primaryLabel  = (k.total || 0) >= (k.zero_total || 0) ? t("daily_volume") : t("daily_zero");

  return (
    <div className="scrim" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="modal" role="dialog" style={{ width: "min(960px, 94vw)" }}>
        <div className="modal-hd">
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 10, letterSpacing: 1.5, textTransform: "uppercase", color: "var(--text-faint)", display: "inline-flex", alignItems: "center", gap: 6 }}>
              <Icon name="search" size={11}/> {t("term_details")} <InfoTip text={t("tip_term_details")}/>
            </div>
            <h3 style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 600 }}>
              "{term}"
            </h3>
          </div>
          <div style={{ flex: 1 }}/>
          <Segment options={TOKENS.period.map(p => ({ value: p.value, label: t(p.labelKey)}))} value={period} onChange={setPeriod}/>
          <Button variant="ghost" icon="x" onClick={onClose}/>
        </div>
        <div className="modal-bd" style={{ maxHeight: "72vh", overflowY: "auto" }}>
          {error && <ApiError t={t} message={error}/>}
          {loading && !data
            ? <LoadingBlock t={t}/>
            : !hasAny
              ? <EmptyBlock t={t}/>
              : (
                <>
                  {/* KPIs */}
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0,1fr))", gap: 10, marginBottom: 16 }}>
                    <TermKpi label={t("searches")}  value={(k.total || 0).toLocaleString()} color="var(--accent)"/>
                    <TermKpi label={t("kpi_zero")}  value={(k.zero_total || 0).toLocaleString()} color="var(--danger)"/>
                    <TermKpi label={t("zero_rate")} value={`${((k.zero_ratio || 0) * 100).toFixed(1)}%`} color="var(--warn)"/>
                    <TermKpi label={t("days")}      value={(k.days_active || 0).toLocaleString()} color="var(--success)"/>
                  </div>

                  {/* Primary chart */}
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 11, letterSpacing: 1.2, textTransform: "uppercase", color: "var(--text-dim)", marginBottom: 8 }}>
                      {primaryLabel}
                    </div>
                    {series.length > 0 && primarySeries.some(v => v > 0)
                      ? <LineChart data={primarySeries} labels={labels} color={primaryColor} />
                      : <EmptyBlock t={t}/>}
                  </div>

                  {/* Optional zero overlay if both have data */}
                  {(k.total || 0) > 0 && (k.zero_total || 0) > 0 && zeros.some(v => v > 0) && (
                    <div style={{ marginBottom: 16 }}>
                      <div style={{ fontSize: 11, letterSpacing: 1.2, textTransform: "uppercase", color: "var(--text-dim)", marginBottom: 8 }}>
                        {t("daily_zero")}
                      </div>
                      <LineChart data={zeros} labels={labels} color="var(--danger)" height={160}/>
                    </div>
                  )}

                  {/* First/last seen */}
                  <div style={{ display: "flex", gap: 24, marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)", fontSize: 12, color: "var(--text-faint)", flexWrap: "wrap" }}>
                    <span>{t("first_seen")}: <span className="mono" style={{ color: "var(--text-dim)" }}>{k.first_day || "—"}</span></span>
                    <span>{t("last_seen")}: <span className="mono" style={{ color: "var(--text-dim)" }}>{k.last_day || "—"}</span></span>
                  </div>
                </>
              )
          }
        </div>
      </div>
    </div>
  );
};

const TermKpi = ({ label, value, color }) => (
  <div style={{ padding: 12, borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--line)" }}>
    <div style={{ fontSize: 10, letterSpacing: 1, textTransform: "uppercase", color: "var(--text-faint)" }}>{label}</div>
    <div className="num-mono" style={{ fontSize: 22, fontWeight: 700, color, marginTop: 4, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
      {value}
    </div>
  </div>
);

Object.assign(window, { TermDetails, TermKpi });
