// SQSEO per-query drill-down (slide-over drawer). Opens from the Performance
// queries table. Everything shown is already loaded (the query row + its
// siblings) plus the cached insight bundle (GET /api/insights) for the site's
// own CTR curve — so the opportunity math ("~N more clicks if this reached the
// top 3") uses the same calibrated numbers as the Insights screen. Ends in a
// cross-link into the content-brief drawer for the query.
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.DrawerShell || !window.LTQ.Sparkline){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Icon, Badge } = DS;
const { DrawerShell, Sparkline, api, fmtCompact } = window.LTQ;
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

const fmtPct = (v) => window.LTQ.fmtPct1(v);
const pathOf = (u) => { try { return decodeURIComponent(new URL(u, "https://x").pathname) || u; } catch (e) { return u; } };
const posColor = (p) => (p <= 3 ? "var(--viz-green)" : p <= 10 ? "var(--text-strong)" : "var(--viz-amber)");

// Expected CTR (fraction) at a fractional position on the bundle's curve.
const expAt = (p, curve) => {
  const c = curve && curve.curve;
  if (!c || !c.length) return null;
  const cl = Math.max(1, Math.min(20, Number(p) || 20));
  const lo = Math.floor(cl), hi = Math.ceil(cl), f = cl - lo;
  return c[lo - 1] * (1 - f) + c[Math.min(19, hi - 1)] * f;
};

function Tile({ label, value, tone }) {
  return (
    <div style={{ border: "1px solid var(--border-subtle)", borderRadius: 10, padding: "9px 12px" }}>
      <div style={{ fontSize: 10.5, color: "var(--text-faint)", marginBottom: 2 }}>{label}</div>
      <div className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 15, fontWeight: 700, color: tone || "var(--text-strong)" }}>{value}</div>
    </div>
  );
}

const Eyebrow = ({ children }) => (
  <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", marginBottom: 8 }}>{children}</div>
);

// The top-3 opportunity block: real arithmetic on the site's own curve.
function Opportunity({ q, curve }) {
  const e3 = expAt(3, curve);
  if (e3 == null || !(q.pos > 3) || !(q.impressions > 0)) return null;
  const gain = Math.round(q.impressions * Math.max(0, e3 * 100 - (Number(q.ctr) || 0)) / 100);
  if (gain <= 0) return null;
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "13px 14px", background: "var(--ink-50)", borderRadius: 10, fontSize: 13, color: "var(--text-body)", lineHeight: 1.55 }}>
      <Icon name="target" size={15} style={{ color: "var(--accent-500)", marginTop: 2, flex: "none" }} />
      <span>
        <b className="lt-num" style={{ fontFamily: "var(--font-mono)", color: "var(--accent-600)" }}>+{fmtCompact(gain)}</b>{" "}
        {t("qdrawer.opportunity", { pos: q.pos, ctr: fmtPct(q.ctr), expected: fmtPct(e3 * 100) })}
      </span>
    </div>
  );
}

function QueryDrawer({ q, siblings, onClose }) {
  const [bundle, setBundle] = React.useState(null);
  const [briefFor, setBriefFor] = React.useState(null);
  React.useEffect(() => {
    let alive = true;
    api.get("/api/insights").then((r) => { if (alive && r.ok) setBundle(r.data.insights); });
    return () => { alive = false; };
  }, []);
  const curve = bundle && bundle.ctrCurve;
  const striking = bundle && bundle.striking && bundle.striking.some((s) => s.query === q.query);
  const gap = bundle && bundle.ctrGaps && bundle.ctrGaps.find((g) => g.query === q.query);
  const related = (siblings || []).filter((s) => s.page && s.page === q.page && s.query !== q.query).slice(0, 6);

  return (
    <DrawerShell eyebrow={t("qdrawer.eyebrow")} icon="search" onClose={onClose}
      footer={window.LTQ.BriefDrawer ? (
        <button onClick={() => setBriefFor(q.query)} style={{ height: 38, padding: "0 14px", borderRadius: 9, border: "none", background: "var(--ink-900)", color: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 7 }}>
          <Icon name="file-pen-line" size={14} /> {t("qdrawer.create_brief")}
        </button>
      ) : null}>
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginBottom: 8 }}>
            {q.intent && <Badge tone="neutral">{q.intent}</Badge>}
            {striking && <Badge tone="green">{t("qdrawer.tag_striking")}</Badge>}
            {gap && <Badge tone="amber">{t("qdrawer.tag_gap")}</Badge>}
          </div>
          <h2 style={{ fontFamily: "var(--font-display)", fontSize: 21, fontWeight: 600, letterSpacing: "-0.02em", color: "var(--text-strong)", lineHeight: 1.3 }}>{q.query}</h2>
        </div>

        <div className="lt-keep-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8 }}>
          <Tile label={t("dash.metric.clicks")} value={fmtCompact(q.clicks)} />
          <Tile label={t("perf.col_impr")} value={fmtCompact(q.impressions)} />
          <Tile label={t("insights.col_ctr")} value={fmtPct(q.ctr)} />
          <Tile label={t("perf.col_pos")} value={q.pos} tone={posColor(q.pos)} />
        </div>

        {Array.isArray(q.trend) && q.trend.length > 1 && (
          <div>
            <Eyebrow>{t("qdrawer.trend")}</Eyebrow>
            <Sparkline points={q.trend} color="var(--viz-blue)" width={200} height={44} />
          </div>
        )}

        <Opportunity q={q} curve={curve} />

        {gap && (
          <div style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "13px 14px", background: "var(--amber-50)", borderRadius: 10, fontSize: 13, color: "var(--text-body)", lineHeight: 1.55 }}>
            <Icon name="pen-line" size={15} style={{ color: "var(--viz-amber)", marginTop: 2, flex: "none" }} />
            <span>{t("qdrawer.gap_note", { ctr: fmtPct(gap.ctr), expected: fmtPct(gap.expected), lost: fmtCompact(gap.lostClicks) })}</span>
          </div>
        )}

        {q.page && (
          <div>
            <Eyebrow>{t("qdrawer.lands_on")}</Eyebrow>
            <a href={q.page} target="_blank" rel="noopener noreferrer" style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 12px", borderRadius: 10, border: "1px solid var(--border-subtle)", textDecoration: "none", color: "var(--text-strong)", fontSize: 13, fontWeight: 600 }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "var(--ink-50)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
              <Icon name="file-text" size={15} style={{ color: "var(--text-faint)", flex: "none" }} />
              <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{pathOf(q.page)}</span>
              <Icon name="external-link" size={13} style={{ color: "var(--text-faint)", flex: "none" }} />
            </a>
          </div>
        )}

        {related.length > 0 && (
          <div>
            <Eyebrow>{t("qdrawer.related", { n: related.length })}</Eyebrow>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {related.map((s, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 2px", borderBottom: i < related.length - 1 ? "1px solid var(--border-subtle)" : "none" }}>
                  <span style={{ flex: 1, minWidth: 0, fontSize: 13, color: "var(--text-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.query}</span>
                  <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", flex: "none" }}>#{s.pos}</span>
                  <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 700, color: "var(--text-strong)", flex: "none", minWidth: 38, textAlign: "right" }}>{fmtCompact(s.clicks)}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      {briefFor && window.LTQ.BriefDrawer && <window.LTQ.BriefDrawer keyword={briefFor} onClose={() => setBriefFor(null)} />}
    </DrawerShell>
  );
}

window.LTQ = window.LTQ || {};
window.LTQ.QueryDrawer = QueryDrawer;
})();
