// SQSEO Overview: live opportunity metrics + an interactive trend chart with a
// date-window control. Data comes from GET /api/dashboard (window-independent
// metrics + clusters) and GET /api/history?days=N (the trend series + windowed
// summary with prev-window deltas). Refetches when the active project changes.
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.InteractiveArea || !window.LTQ.api || !window.LTQ.useApi){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Icon } = DS;
const { InteractiveArea, useCountUp, fmtCompact, api, useApi } = window.LTQ;
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

const WINDOWS = [{ d: 7, k: "dash.window_7d" }, { d: 28, k: "dash.window_28d" }, { d: 90, k: "dash.window_90d" }, { d: 365, k: "dash.window_12mo" }];
const METRICS = [
  { id: "impressions", labelKey: "dash.metric.impressions", icon: "trending-up", color: "var(--viz-blue)", source: "history", yKey: "impressions", fmt: fmtCompact, sumKey: "impressions", deltaKey: "impressions" },
  { id: "clicks", labelKey: "dash.metric.clicks", icon: "mouse-pointer-click", color: "var(--accent-500)", source: "history", yKey: "clicks", fmt: fmtCompact, sumKey: "clicks", deltaKey: "clicks" },
  { id: "ctr", labelKey: "dash.metric.ctr", icon: "percent", color: "var(--viz-green)", source: "history", yKey: "ctr", fmt: (v)=>window.LTQ.fmtPct1(v), sumKey: "ctr", deltaKey: "ctr" },
  { id: "position", labelKey: "dash.metric.position", icon: "target", color: "var(--viz-amber)", source: "history", yKey: "avg_position", fmt: (v)=>window.LTQ.fmtDec1(v), sumKey: "avg_position", deltaKey: "avg_position", lowerBetter: true },
];
const KIND_COLOR = {
  question: "var(--viz-blue)", buyer: "var(--accent-500)", comparison: "var(--viz-violet)",
  ai: "var(--viz-cyan)", reddit: "var(--viz-amber)", local: "var(--viz-green)",
  product: "var(--ink-400)", longtail: "var(--ink-300)",
};
const kindMeta = (k) => (KIND_COLOR[k] ? [t("kind." + k), KIND_COLOR[k]] : [k.charAt(0).toUpperCase() + k.slice(1), "var(--ink-300)"]);

function Counter({ label, value, suffix }) {
  const v = useCountUp(value || 0, 800, [value]);
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
      <span style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{label}</span>
      <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, color: "var(--text-strong)" }}>{Math.round(v)}{suffix || ""}</span>
    </span>
  );
}

function Delta({ value, lowerBetter }) {
  // No prior period to compare against yet: show nothing rather than a "new"
  // badge on every metric — the absence of a delta already reads as "new".
  if (value == null) return null;
  const up = value >= 0;
  const good = lowerBetter ? value < 0 : value > 0;
  const color = value === 0 ? "var(--text-faint)" : good ? "var(--viz-green)" : "var(--viz-red)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 3, fontSize: 12.5, fontWeight: 600, color, fontFamily: "var(--font-mono)" }}>
      <Icon name={up ? "trending-up" : "trending-down"} size={14} strokeWidth={2.2} />{Math.abs(value)}%
    </span>
  );
}

function MetricTab({ m, active, onClick }) {
  return (
    <button onClick={onClick} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 30, padding: "0 11px",
      borderRadius: 8, border: "1px solid " + (active ? "var(--border-strong)" : "transparent"),
      background: active ? "var(--paper)" : "transparent", boxShadow: active ? "var(--shadow-xs)" : "none",
      cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: active ? 600 : 500,
      color: active ? "var(--text-strong)" : "var(--text-muted)", transition: "all var(--dur-fast)" }}>
      <Icon name={m.icon} size={14} style={{ color: active ? m.color : "var(--text-faint)" }} />{t(m.labelKey)}
    </button>
  );
}

function Segmented({ value, onChange }) {
  return (
    <div style={{ display: "inline-flex", gap: 2, padding: 2, borderRadius: 9, background: "var(--ink-50)", border: "1px solid var(--border-subtle)" }}>
      {WINDOWS.map((w) => (
        <button key={w.d} onClick={() => onChange(w.d)} style={{ height: 26, padding: "0 10px", borderRadius: 7, border: "none", cursor: "pointer",
          background: value === w.d ? "var(--paper)" : "transparent", boxShadow: value === w.d ? "var(--shadow-xs)" : "none",
          fontFamily: "var(--font-mono)", fontSize: 11.5, fontWeight: 600, color: value === w.d ? "var(--text-strong)" : "var(--text-faint)", transition: "all var(--dur-fast)" }}>{t(w.k)}</button>
      ))}
    </div>
  );
}

const Card = ({ children, style, className }) => (
  <div className={className} style={{ border: "1px solid var(--border-subtle)", borderRadius: "var(--r-lg)", background: "var(--paper)", ...style }}>{children}</div>
);
const Skeleton = ({ h = 16, w = "100%", r = 6 }) => (
  <span className="lt-shimmer" style={{ display: "block", height: h, width: w, borderRadius: r, background: "var(--ink-100)" }} />
);

function ClusterRow({ rank, c, last }) {
  const [hover, setHover] = React.useState(false);
  const td = { padding: "11px 8px", borderBottom: last ? "none" : "1px solid var(--border-subtle)" };
  return (
    <tr onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)} style={{ background: hover ? "var(--ink-50)" : "transparent" }}>
      <td style={{ ...td, padding: "11px 8px 11px 14px", color: "var(--text-faint)", fontFamily: "var(--font-mono)", fontSize: 12, width: 28 }}>{rank}</td>
      <td style={td}>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)" }}>{c.name}</span>
        <span style={{ fontSize: 11.5, color: "var(--text-faint)", marginLeft: 8 }}>{t("dash.n_kw", { n: c.count })}</span>
      </td>
      <td style={{ ...td, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{fmtCompact(c.demand)}</td>
      <td style={{ ...td, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{c.difficulty}</td>
      <td style={{ ...td, padding: "11px 14px 11px 8px", textAlign: "right" }}>
        <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: c.opp >= 80 ? "var(--viz-green)" : "var(--text-strong)" }}>{c.opp}</span>
      </td>
    </tr>
  );
}

// First-run "Getting started" checklist (real state from GET /api/onboarding).
// Hides itself once every step is done, or when the user dismisses it.
function OnboardingCard({ onNavigate }) {
  const { loading, data } = useApi("/api/onboarding");
  const [dismissed, setDismissed] = React.useState(() => {
    try { return localStorage.getItem("sqseo_onboarding_done") === "1"; } catch (e) { return false; }
  });
  if (loading || !data || data.complete || dismissed) return null;
  // "Share a live report" dropped from first-run setup: it is a power feature,
  // not an essential onboarding step. Keeps the checklist to the 3 core actions.
  const steps = (data.steps || []).filter((s) => s.id !== "report");
  const done = steps.filter((s) => s.done).length;
  const dismiss = () => { try { localStorage.setItem("sqseo_onboarding_done", "1"); } catch (e) {} setDismissed(true); };
  return (
    <div className="lt-reveal in" data-tour="getting-started" style={{ border: "1px solid var(--border-subtle)", borderRadius: "var(--r-lg)", background: "var(--paper)", overflow: "hidden", boxShadow: "var(--shadow-sm)" }}>
      <div style={{ height: 3, background: "var(--ink-100)" }}><div style={{ height: "100%", width: (done / steps.length) * 100 + "%", background: "linear-gradient(90deg,var(--accent-500),var(--viz-cyan))", transition: "width var(--dur-slow) var(--ease-out)" }} /></div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
          <span style={{ width: 34, height: 34, borderRadius: 10, flex: "none", display: "grid", placeItems: "center", background: "var(--ink-900)", color: "#fff" }}><Icon name="rocket" size={17} /></span>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text-strong)" }}>{t("dash.getting_started")}</div>
            <div style={{ fontSize: 12, color: "var(--text-faint)" }}>{t("dash.steps_done", { done, total: steps.length })}</div>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flex: "none" }}>
          {/* "Open setup" is gone: the guided setup is a standalone first-run
              screen (onboarding revamp Phase 12), not re-enterable in-shell. */}
          <button onClick={dismiss} aria-label={t("chrome.dismiss")} style={{ width: 28, height: 28, display: "grid", placeItems: "center", border: "none", background: "transparent", cursor: "pointer", color: "var(--text-faint)", borderRadius: 8 }}><Icon name="x" size={16} /></button>
        </div>
      </div>
      <div>
        {steps.map((s, i) => (
          <button key={s.id} onClick={() => (!s.done && onNavigate ? onNavigate(s.route) : null)} disabled={s.done}
            style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "left", padding: "13px 18px", border: "none", borderBottom: i < steps.length - 1 ? "1px solid var(--border-subtle)" : "none", background: "transparent", cursor: s.done ? "default" : "pointer", transition: "background var(--dur-fast)" }}
            onMouseEnter={(e) => { if (!s.done) e.currentTarget.style.background = "var(--ink-50)"; }} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
            <span style={{ width: 24, height: 24, flex: "none", borderRadius: 999, display: "grid", placeItems: "center", background: s.done ? "var(--viz-green)" : "var(--ink-50)", border: "1px solid " + (s.done ? "var(--viz-green)" : "var(--border-strong)"), color: s.done ? "#fff" : "var(--text-faint)" }}>
              {s.done ? <Icon name="check" size={14} /> : <Icon name={s.icon} size={13} />}
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 13.5, fontWeight: 600, color: s.done ? "var(--text-faint)" : "var(--text-strong)", textDecoration: s.done ? "line-through" : "none" }}>{["site","performance","keywords","report"].includes(s.id) ? t("dash.step." + s.id + ".title") : s.title}</span>
                {s.hint && <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--viz-green)", background: "var(--accent-50, #ecfdf5)", border: "1px solid var(--accent-100)", borderRadius: 999, padding: "1px 7px" }}>{s.hint === "Connected" ? t("dash.hint_connected") : s.hint === "Sample data" ? t("dash.hint_sample") : s.hint}</span>}
              </div>
              <div style={{ fontSize: 12, color: "var(--text-faint)", marginTop: 1 }}>{["site","performance","keywords","report"].includes(s.id) ? t("dash.step." + s.id + ".body") : s.body}</div>
            </div>
            {!s.done && <Icon name="arrow-right" size={15} style={{ color: "var(--text-faint)", flex: "none" }} />}
          </button>
        ))}
      </div>
    </div>
  );
}

function Dashboard({ onNavigate }) {
  const boot = window.LTQ.boot || {};
  const projectId = boot.project && boot.project.id;
  const projectName = (boot.project && boot.project.name) || t("dash.your_project");
  const [metricId, setMetricId] = React.useState("impressions");
  const [days, setDays] = React.useState(() => { const v = Number((typeof localStorage !== "undefined" && localStorage.getItem("sqseo_days")) || 28); return [7, 28, 90, 365].includes(v) ? v : 28; });
  const [compareOn, setCompareOn] = React.useState(false);
  const [dash, setDash] = React.useState(null);
  const [hist, setHist] = React.useState(null);
  const [loadErr, setLoadErr] = React.useState(false); // failed fetch -> honest retry, not eternal skeletons
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => { try { localStorage.setItem("sqseo_days", String(days)); } catch (e) {} }, [days]);

  const gsc = useApi("/api/gsc/status");
  const gscConnected = gsc.data && gsc.data.connected;
  React.useEffect(() => { let live = true; setDash(null); setLoadErr(false); api.get("/api/dashboard").then((r) => { if (!live) return; if (r.ok) setDash(r.data); else setLoadErr(true); }); return () => { live = false; }; }, [projectId, tick]);
  React.useEffect(() => { let live = true; setHist(null); api.get("/api/history?days=" + days).then((r) => { if (!live) return; if (r.ok) setHist(r.data); else setLoadErr(true); }); return () => { live = false; }; }, [projectId, days, tick]);

  const metric = METRICS.find((m) => m.id === metricId);
  const metrics = dash && dash.metrics;
  const summary = hist && hist.summary;
  const series = hist ? (metric.source === "ai" ? hist.aiHistory : hist.history) : [];
  const canCompare = metric.source === "history";
  const compareSeries = compareOn && canCompare && hist ? hist.compare : null;
  const sumValue = summary ? summary[metric.sumKey] : 0;
  const delta = summary && metric.deltaKey ? summary.delta[metric.deltaKey] : null;

  const strip = metrics ? [
    { l: t("dash.total_longtails"), v: metrics.total, icon: "list", sub: t("dash.n_clusters", { n: dash.clusters.length || 0 }) },
    { l: t("kind.buyer"), v: metrics.buyer, icon: "shopping-bag", sub: metrics.total ? t("dash.pct_of_total", { pct: Math.round((metrics.buyer / metrics.total) * 100) }) : "—" },
    { l: t("dash.low_competition"), v: metrics.lowDifficulty, icon: "trending-down", sub: t("dash.low_competition_sub") },
    { l: t("dash.briefs_ready"), v: metrics.briefs, icon: "file-pen-line", sub: t("dash.briefs_ready_sub") },
  ] : [];

  const SQ = window.LTQ.SQ;
  const hour = new Date().getHours();
  const greetWord = hour < 12 ? t("dash.greet_morning") : hour < 18 ? t("dash.greet_afternoon") : t("dash.greet_evening");
  const firstName = (((window.LTQ.boot || {}).user || {}).name || "").trim().split(/\s+/)[0];
  const greeting = firstName ? t("dash.greet_named", { greet: greetWord, name: firstName }) : greetWord;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* A warm hello from SQ — waves on load, tracks the cursor. Additive; the
          dashboard below is unchanged. */}
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        {SQ && window.SQRobot &&
          <div style={{ flex: "none", marginTop: -6, marginBottom: -14 }}><SQ state="idle" width={72} track="window" hoverWave interactive bubble={false} /></div>}
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)", lineHeight: 1.15 }}>{greeting}</div>
          <div style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 2 }}>{t("dash.greet_sub")}</div>
        </div>
      </div>
      <OnboardingCard onNavigate={onNavigate} />
      {loadErr && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderRadius: "var(--r-lg)", border: "1px solid var(--border-subtle)", background: "var(--red-50)" }}>
          <Icon name="alert-circle" size={16} style={{ color: "var(--viz-red)", flex: "none" }} />
          <span style={{ flex: 1, fontSize: 13, color: "var(--text-body)" }}>{t("chrome.load_failed")}</span>
          <button onClick={() => setTick((n) => n + 1)} style={{ height: 30, padding: "0 12px", borderRadius: 8, border: "none", background: "var(--ink-900)", color: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, flex: "none" }}>{t("chrome.retry")}</button>
        </div>
      )}
      {gsc.data && gsc.data.needs_reconnect ? (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderRadius: "var(--r-lg)", border: "1px solid var(--border-subtle)", background: "var(--red-50)" }}>
          <Icon name="alert-circle" size={16} style={{ color: "var(--viz-red)", flex: "none" }} />
          <span style={{ flex: 1, fontSize: 13, color: "var(--text-body)" }}>{t("dash.revoked_1")} <b style={{ color: "var(--text-strong)" }}>{t("dash.revoked_bold")}</b>{t("dash.revoked_2")}</span>
          <a href="/oauth/google/authorize" style={{ height: 30, padding: "0 12px", borderRadius: 8, background: "var(--ink-900)", color: "#fff", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, flex: "none", display: "inline-flex", alignItems: "center", textDecoration: "none" }}>{t("dash.reconnect")}</a>
        </div>
      ) : gsc.data && !gscConnected ? (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderRadius: "var(--r-lg)", border: "1px solid var(--border-subtle)", background: "var(--amber-50)" }}>
          <Icon name="info" size={16} style={{ color: "var(--viz-amber)", flex: "none" }} />
          <span style={{ flex: 1, fontSize: 13, color: "var(--text-body)" }}>{t("dash.sample_1")} <b style={{ color: "var(--text-strong)" }}>{t("dash.sample_bold")}</b> {t("dash.sample_2")}</span>
          <button onClick={() => onNavigate && onNavigate("settings")} style={{ height: 30, padding: "0 12px", borderRadius: 8, border: "none", background: "var(--ink-900)", color: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, flex: "none" }}>{t("wizard.search.connect_btn")}</button>
        </div>
      ) : null}
      {/* Header row */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap" }}>
          <Icon name="layout-grid" size={16} style={{ color: "var(--text-faint)" }} />
          <span style={{ fontSize: 14.5, fontWeight: 600, color: "var(--text-strong)" }}>{t("nav.dashboard")}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <Counter label={t("dash.opportunity")} value={metrics ? metrics.avgScore : 0} suffix="/100" />
          <Counter label={t("kind.question")} value={metrics ? metrics.questions : 0} />
          <Counter label={t("dash.ai_ops")} value={metrics ? metrics.aiOps : 0} />
        </div>
      </div>

      {/* Chart + clusters */}
      <div style={{ display: "grid", gridTemplateColumns: "1.45fr 1fr", gap: 14, alignItems: "stretch" }} className="lt-ov-grid">
        <Card style={{ padding: 18, display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6, gap: 8, flexWrap: "wrap" }}>
            <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
              {METRICS.map((m) => <MetricTab key={m.id} m={m} active={metricId === m.id} onClick={() => setMetricId(m.id)} />)}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <button onClick={() => setCompareOn((v) => !v)} disabled={!canCompare} title={canCompare ? t("dash.compare_hint") : t("dash.compare_na")}
                style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 28, padding: "0 9px", borderRadius: 8, cursor: canCompare ? "pointer" : "default",
                  border: "1px solid " + (compareOn && canCompare ? "var(--border-strong)" : "var(--border-subtle)"),
                  background: compareOn && canCompare ? "var(--paper)" : "transparent", opacity: canCompare ? 1 : 0.45,
                  fontFamily: "var(--font-sans)", fontSize: 11.5, fontWeight: 600, color: compareOn && canCompare ? "var(--text-strong)" : "var(--text-faint)" }}>
                <Icon name={compareOn && canCompare ? "check" : "git-compare"} size={13} />{t("dash.compare")}
              </button>
              <Segmented value={days} onChange={setDays} />
            </div>
          </div>
          {/* big current value */}
          <div style={{ display: "flex", alignItems: "baseline", gap: 10, margin: "6px 2px 10px" }}>
            <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)" }}>
              {summary ? metric.fmt(sumValue) : "—"}
            </span>
            <span style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{metric.id === "position" ? t("dash.avg_over") + " " : t("dash.total") + " · "}{days >= 365 ? t("dash.12_months") : t("dash.n_days", { n: days })}</span>
            {summary && <Delta value={delta} lowerBetter={metric.lowerBetter} />}
          </div>
          {hist ? <InteractiveArea data={series} yKey={metric.yKey} color={metric.color} format={metric.fmt} lowerIsBetter={metric.lowerBetter} compare={compareSeries} height={236} />
            : <div style={{ height: 236, display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 10, padding: "0 2px 24px" }}>
                <Skeleton h={150} r={10} /><Skeleton h={12} w="40%" />
              </div>}
        </Card>

        {/* Top clusters */}
        <Card style={{ display: "flex", flexDirection: "column" }}>
          <div style={{ padding: "16px 18px 10px" }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-strong)" }}>{t("dash.top_clusters")}</div>
            <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2 }}>{t("dash.top_clusters_sub")}</div>
          </div>
          {!dash ? (
            <div style={{ padding: "8px 18px 18px", display: "flex", flexDirection: "column", gap: 12 }}>
              {[0,1,2,3,4].map((i)=><Skeleton key={i} h={16} />)}
            </div>
          ) : dash.clusters.length === 0 ? (
            <div style={{ padding: "28px 18px", textAlign: "center", color: "var(--text-faint)", fontSize: 13 }}>{t("dash.run_to_build")}</div>
          ) : (
            <table style={{ borderCollapse: "collapse", width: "100%" }}>
              <thead><tr>
                {[["#","left"],[t("chrome.cluster"),"left"],[t("dash.metric.impressions"),"right"],[t("dash.diff_abbr"),"right"],[t("dash.opp_abbr"),"right"]].map((c,i)=>(
                  <th key={i} style={{ textAlign: c[1], padding: i===0?"0 8px 8px 14px":i===4?"0 14px 8px 8px":"0 8px 8px", fontSize: 11, fontWeight: 600, color: "var(--text-faint)", borderBottom: "1px solid var(--border-subtle)" }}>{c[0]}</th>
                ))}
              </tr></thead>
              <tbody>{dash.clusters.map((c,i)=><ClusterRow key={c.name} rank={i+1} c={c} last={i===dash.clusters.length-1} />)}</tbody>
            </table>
          )}
        </Card>
      </div>

      {/* secondary metric strip: 4-up desktop, 2×2 on phones (.lt-keep-grid
          opts out of the shell's mobile 1fr fallback) */}
      <div className="lt-keep-grid lt-metric-strip" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
        {(metrics ? strip : [0,1,2,3]).map((m, i) => (
          <Card key={i} className="fx-enter lt-card-3d" style={{ padding: 16, "--enter-delay": i * 70 + "ms" }}>
            {metrics ? <>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                <span style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{m.l}</span>
                <Icon name={m.icon} size={15} style={{ color: "var(--text-faint)" }} />
              </div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 26, fontWeight: 600, color: "var(--text-strong)", letterSpacing: "-0.02em" }}>{m.v}</span>
                <span style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{m.sub}</span>
              </div>
            </> : <div style={{ display: "flex", flexDirection: "column", gap: 12 }}><Skeleton h={12} w="50%" /><Skeleton h={24} w="40%" /></div>}
          </Card>
        ))}
      </div>

      {/* intent mix + top opportunities */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="lt-ov-grid">
        <Card style={{ padding: 18 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-strong)" }}>{t("dash.intent_mix")}</div>
          <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2, marginBottom: 14 }}>{t("dash.intent_mix_sub")}</div>
          {!dash ? <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>{[0,1,2,3].map((i)=><Skeleton key={i} h={16} />)}</div>
            : dash.intentMix.length === 0 ? <div style={{ color: "var(--text-faint)", fontSize: 13 }}>{t("dash.no_keywords")}</div>
            : (() => {
                const maxN = Math.max(1, ...dash.intentMix.map((m) => m.n));
                return (
                  <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
                    {dash.intentMix.map((m) => {
                      const [label, c] = kindMeta(m.kind);
                      return (
                        <div key={m.kind} style={{ display: "grid", gridTemplateColumns: "118px 1fr 34px", alignItems: "center", gap: 12 }}>
                          <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>
                            <span style={{ width: 8, height: 8, borderRadius: 999, background: c, flex: "none" }} />{label}
                          </span>
                          <span style={{ height: 8, background: "var(--ink-100)", borderRadius: 999, overflow: "hidden" }}>
                            <span style={{ display: "block", height: "100%", width: (m.n / maxN) * 100 + "%", background: c, borderRadius: 999, transition: "width var(--dur-slow) var(--ease-out)" }} />
                          </span>
                          <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)", textAlign: "right" }}>{m.n}</span>
                        </div>
                      );
                    })}
                  </div>
                );
              })()}
        </Card>

        <Card style={{ padding: 18, display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-strong)" }}>{t("dash.top_opportunities")}</div>
              <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2 }}>{t("dash.top_opportunities_sub")}</div>
            </div>
            <button onClick={() => onNavigate && onNavigate("research")} style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 28, padding: "0 9px", border: "1px solid var(--border-subtle)", borderRadius: 8, background: "var(--paper)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 11.5, fontWeight: 600, color: "var(--text-body)" }}>
              {t("dash.view_all")} <Icon name="arrow-right" size={13} />
            </button>
          </div>
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 2 }}>
            {!dash ? [0,1,2,3,4].map((i)=><div key={i} style={{ padding: "6px 0" }}><Skeleton h={16} /></div>)
              : dash.topKeywords.length === 0 ? <div style={{ color: "var(--text-faint)", fontSize: 13 }}>{t("dash.run_to_surface")}</div>
              : dash.topKeywords.map((k, i) => {
                  const [label, c] = kindMeta(k.kind);
                  return (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "8px 0", borderBottom: i === dash.topKeywords.length - 1 ? "none" : "1px solid var(--border-subtle)" }}>
                      <span style={{ width: 18, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", flex: "none" }}>{i + 1}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{k.keyword}</div>
                        <div style={{ fontSize: 11.5, color: "var(--text-faint)", display: "inline-flex", alignItems: "center", gap: 6 }}>
                          <span style={{ width: 6, height: 6, borderRadius: 999, background: c, flex: "none" }} />{label} · {t("dash.n_demand", { n: fmtCompact(k.demand) })}
                        </div>
                      </div>
                      <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 700, color: k.score >= 80 ? "var(--viz-green)" : "var(--text-strong)", flex: "none" }}>{k.score}</span>
                    </div>
                  );
                })}
          </div>
        </Card>
      </div>
    </div>
  );
}
window.LTQ = window.LTQ || {};
window.LTQ.Dashboard = Dashboard;
})();
