// SQSEO Performance screen (Phase 7): surfaces the Search Console data the sync
// writes — top pages, queries, topics, and device/country/appearance breakdowns.
// Live: GET /api/performance. Sync now + CSV export wired.
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.useApi || !window.LTQ.TrendChart){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Card, Icon, Badge, Button } = DS;
const { useApi, api, toast, reloadBoot, TrendChart, fmtCompact, SectionTitle, EmptyState, Popover, MenuItem } = window.LTQ;
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

const STATUS = {
  "Top performer": "var(--viz-green)", Rising: "var(--viz-blue)", Steady: "var(--text-faint)",
  "Needs attention": "var(--viz-amber)", New: "var(--viz-violet)",
};
const STATUS_KEY = { "Top performer": "top", Rising: "rising", Steady: "steady", "Needs attention": "attention", New: "new" };
const fmtPct = (v) => window.LTQ.fmtPct1(v);
const StatusPill = ({ s }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: "var(--text-body)", whiteSpace: "nowrap" }}>
    <span style={{ width: 7, height: 7, borderRadius: 999, background: STATUS[s] || "var(--text-faint)", flex: "none" }} />{STATUS_KEY[s] ? t("perf.status_" + STATUS_KEY[s]) : s}
  </span>
);
const Skel = ({ h = 16, w = "100%" }) => <span className="lt-shimmer" style={{ display: "block", height: h, width: w, borderRadius: 6, background: "var(--ink-100)" }} />;
// AI-interception risk for a page (impression-weighted, from the GEO model).
const AiRisk = ({ v }) => {
  if (!v) return <span style={{ color: "var(--text-faint)" }}>—</span>;
  const tone = v >= 60 ? "var(--viz-red)" : v >= 35 ? "var(--viz-amber)" : "var(--text-faint)";
  return <span title={t("perf.ai_risk_title", { v })} className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: tone }}>{v}</span>;
};

function StatCard({ label, value, sub, icon, tone }) {
  return (
    <Card pad={16}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
        <span style={{ fontSize: 12.5, color: "var(--text-muted)", fontWeight: 600 }}>{label}</span>
        <Icon name={icon} size={15} style={{ color: tone || "var(--text-faint)" }} />
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
        <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 24, fontWeight: 600, color: "var(--text-strong)", letterSpacing: "-0.02em" }}>{value}</span>
        {sub && <span style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{sub}</span>}
      </div>
    </Card>
  );
}

function MiniBars({ rows, label }) {
  const max = Math.max(1, ...rows.map((r) => r.clicks));
  return (
    <div>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 10 }}>{label}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {rows.length === 0 ? <span style={{ fontSize: 12.5, color: "var(--text-faint)" }}>{t("perf.no_data")}</span> : rows.map((r, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "110px 1fr 48px", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 12.5, color: "var(--text-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.name}</span>
            <span style={{ height: 7, background: "var(--ink-100)", borderRadius: 999, overflow: "hidden" }}><span style={{ display: "block", height: "100%", width: (r.clicks / max) * 100 + "%", background: "var(--viz-blue)", borderRadius: 999 }} /></span>
            <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-strong)", textAlign: "right" }}>{fmtCompact(r.clicks)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ExportMenu() {
  const dl = (path) => { const a = document.createElement("a"); a.href = path; document.body.appendChild(a); a.click(); a.remove(); toast(t("chrome.export_started"), { tone: "success" }); };
  return (
    <Popover align="right" width={220}
      trigger={(open, toggle) => (
        <button onClick={toggle} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 32, padding: "0 12px", border: "1px solid var(--border-subtle)", background: open ? "var(--ink-50)" : "var(--paper)", borderRadius: 8, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>
          <Icon name="download" size={14} /> {t("chrome.export")} <Icon name="chevron-down" size={13} style={{ color: "var(--text-faint)" }} />
        </button>
      )}>
      {(close) => (<>
        <MenuItem icon="file-text" label={t("perf.pages_csv")} onClick={() => { close(); dl("/api/export/pages.csv"); }} />
        <MenuItem icon="search" label={t("perf.queries_csv")} onClick={() => { close(); dl("/api/export/queries.csv"); }} />
      </>)}
    </Popover>
  );
}

function Th({ children, right }) {
  return <th style={{ textAlign: right ? "right" : "left", padding: "0 14px", height: 42, background: "var(--ink-50)", borderBottom: "1px solid var(--border-strong)", fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", whiteSpace: "nowrap" }}>{children}</th>;
}

function Performance({ onNavigate }) {
  const { loading, data, reload } = useApi("/api/performance");
  const [syncing, setSyncing] = React.useState(false);
  const [drillQ, setDrillQ] = React.useState(null); // query row → drill-down drawer
  const d = data || {};
  const sum = d.summary;
  const sample = d.lastSync && d.lastSync.source === "sample";

  const syncNow = async () => {
    setSyncing(true);
    const r = await api.post("/api/sync");
    setSyncing(false);
    const o = r.data || {};
    if (r.ok && o.ok) { await reloadBoot(); reload(); toast(t("wizard.search.pages_queries", { pages: o.pages, queries: o.queries }), { tone: "success" }); }
    else if (o.error === "not_connected") toast(t("wizard.search.title"), { tone: "warning" });
    else toast(r.error || t("wizard.search.sync_failed"), { tone: "error" });
  };

  const SyncBtn = <Button variant="secondary" size="sm" leadingIcon="refresh-cw" onClick={syncNow} disabled={syncing}>{syncing ? t("perf.syncing") : t("perf.sync_now")}</Button>;
  const empty = !sum || sum.pages === 0;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <SectionTitle eyebrow={t("perf.eyebrow")} title={t("nav.performance")}
        sub={t("perf.sub")}
        right={(!loading && empty) ? null : <div style={{ display: "flex", gap: 8 }}><ExportMenu />{SyncBtn}</div>} />

      {!loading && (!sum || sum.pages === 0) ? (
        <Card pad={0}><EmptyState icon="line-chart" sq="idle" title={t("perf.empty_title")}
          body={t("perf.empty_body")}
          action={<Button variant="primary" leadingIcon="plug" onClick={() => { window.location.href = "/oauth/google/authorize"; }}>{t("wizard.search.connect_title")}</Button>} /></Card>
      ) : (
        <>
          {sample && (
            <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("perf.sample_1")} <b style={{ color: "var(--text-strong)" }}>{t("dash.sample_bold")}</b> {t("perf.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>
          )}

          {/* summary */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
            {loading || !sum ? [0,1,2,3].map((i)=><Card key={i} pad={16}><Skel h={48} /></Card>) : <>
              <StatCard label={t("dash.metric.clicks")} value={fmtCompact(sum.clicks)} sub={t("perf.28_days")} icon="mouse-pointer-click" tone="var(--accent-500)" />
              <StatCard label={t("perf.impressions")} value={fmtCompact(sum.impressions)} sub={t("perf.28_days")} icon="eye" tone="var(--viz-blue)" />
              <StatCard label={t("perf.avg_ctr")} value={fmtPct(sum.ctr)} icon="percent" tone="var(--viz-green)" />
              <StatCard label={t("dash.metric.position")} value={sum.avg_position} sub={t("perf.n_pages", { n: sum.pages })} icon="target" tone="var(--viz-amber)" />
            </>}
          </div>

          {/* pages table */}
          <Card pad={0} style={{ overflow: "hidden" }}>
            <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", fontSize: 14, fontWeight: 700, color: "var(--text-strong)" }}>{t("perf.top_pages")}</div>
            <div className="lt-scroll" style={{ overflowX: "auto" }}>
              <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 980 }}>
                <thead><tr><Th>{t("perf.col_page")}</Th><Th>{t("perf.col_status")}</Th><Th right>{t("dash.metric.clicks")}</Th><Th right>{t("perf.col_impr")}</Th><Th right>CTR</Th><Th right>{t("perf.col_pos")}</Th><Th right>{t("perf.col_ai_risk")}</Th><Th>{t("perf.col_trend")}</Th></tr></thead>
                <tbody>
                  {loading ? [0,1,2,3,4].map((i)=><tr key={i}><td colSpan={8} style={{ padding: "12px 18px", borderBottom: "1px solid var(--border-subtle)" }}><Skel /></td></tr>)
                    : d.pages.slice(0, 25).map((p, i) => {
                      const bd = { padding: "12px 14px", borderBottom: i < Math.min(25, d.pages.length) - 1 ? "1px solid var(--border-subtle)" : "none" };
                      return (
                        <tr key={i} onMouseEnter={(e)=>e.currentTarget.style.background="var(--ink-50)"} onMouseLeave={(e)=>e.currentTarget.style.background="transparent"}>
                          <td style={{ ...bd, maxWidth: 360 }}>
                            <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.title}</div>
                            <div style={{ fontSize: 11.5, color: "var(--text-faint)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.url}</div>
                          </td>
                          <td style={bd}><StatusPill s={p.status} /></td>
                          <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-strong)", fontWeight: 600 }}>{fmtCompact(p.clicks)}</td>
                          <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{fmtCompact(p.impressions)}</td>
                          <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{fmtPct(p.ctr)}</td>
                          <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{p.pos}</td>
                          <td style={{ ...bd, textAlign: "right" }}><AiRisk v={p.aio_risk} /></td>
                          <td style={{ ...bd, width: 120 }}>{p.trend && p.trend.length > 1 ? <div style={{ width: 110 }}><TrendChart id={"pf" + i} points={p.trend} height={32} color={STATUS[p.status] || "var(--viz-blue)"} fill={false} /></div> : <span style={{ color: "var(--text-faint)" }}>—</span>}</td>
                        </tr>
                      );
                    })}
                </tbody>
              </table>
            </div>
          </Card>

          {/* queries + side column */}
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }} className="lt-ov-grid">
            <Card pad={0} style={{ overflow: "hidden" }}>
              <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", fontSize: 14, fontWeight: 700, color: "var(--text-strong)" }}>{t("perf.top_queries")}</div>
              <div className="lt-scroll" style={{ overflowX: "auto" }}>
                <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 520 }}>
                  <thead><tr><Th>{t("gaps.col_query")}</Th><Th right>{t("dash.metric.clicks")}</Th><Th right>{t("perf.col_impr")}</Th><Th right>CTR</Th><Th right>{t("perf.col_pos")}</Th></tr></thead>
                  <tbody>
                    {loading ? [0,1,2,3,4].map((i)=><tr key={i}><td colSpan={5} style={{ padding: "12px 18px", borderBottom: "1px solid var(--border-subtle)" }}><Skel /></td></tr>)
                      : d.queries.slice(0, 18).map((q, i) => {
                        const bd = { padding: "11px 14px", borderBottom: i < Math.min(18, d.queries.length) - 1 ? "1px solid var(--border-subtle)" : "none" };
                        return (
                          <tr key={i} onClick={() => window.LTQ.QueryDrawer && setDrillQ(q)} style={{ cursor: window.LTQ.QueryDrawer ? "pointer" : "default" }}
                            onMouseEnter={(e)=>e.currentTarget.style.background="var(--ink-50)"} onMouseLeave={(e)=>e.currentTarget.style.background="transparent"}>
                            <td style={{ ...bd, maxWidth: 280 }}><span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", display: "block" }}>{q.query}</span></td>
                            <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-strong)", fontWeight: 600 }}>{fmtCompact(q.clicks)}</td>
                            <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{fmtCompact(q.impressions)}</td>
                            <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{fmtPct(q.ctr)}</td>
                            <td style={{ ...bd, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-body)" }}>{q.pos}</td>
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
              </div>
            </Card>
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Card pad={18}><MiniBars label={t("perf.topics")} rows={(d.topics || []).map((t) => ({ name: t.name, clicks: t.clicks }))} /></Card>
              <Card pad={18}><MiniBars label={t("perf.devices")} rows={d.breakdowns ? d.breakdowns.devices : []} /></Card>
              <Card pad={18}><MiniBars label={t("perf.countries")} rows={(d.breakdowns ? d.breakdowns.countries : []).slice(0, 6)} /></Card>
            </div>
          </div>
        </>
      )}
      {drillQ && window.LTQ.QueryDrawer && (
        <window.LTQ.QueryDrawer q={drillQ} siblings={d.queries || []} onClose={() => setDrillQ(null)} />
      )}
    </div>
  );
}
window.LTQ.Performance = Performance;
})();
