// SQSEO app, AI Search Queries screen (live: GET /api/ai-queries).
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.useApi){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Card, Icon, Badge, Button, Select } = DS;
const { PlatformBadge, SectionTitle, useApi, api, toast } = window.LTQ;
const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

// Real questions people ask Google (and AI answer engines) around the site's
// topics — mined from Google Autocomplete (Phase 20). Refresh re-mines live.
function RealQuestions({ questions, onReload }) {
  const [busy, setBusy] = React.useState(false);
  const refresh = async () => {
    setBusy(true);
    const r = await api.post("/api/questions/refresh");
    setBusy(false);
    if (r.ok) { onReload(); toast(t("aiq.q_refreshed", { n: r.data.count }), { tone: "success" }); }
    else toast(r.error || t("aiq.q_failed"), { tone: "error" });
  };
  return (
    <Card pad={0} style={{ overflow: "hidden" }}>
      <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
        <Icon name="messages-square" size={17} style={{ color: "var(--accent-500)" }} />
        <span style={{ fontSize: 14, fontWeight: 700, color: "var(--text-strong)" }}>{t("aiq.q_title")}</span>
        <Badge tone="accent" variant="soft">{t("aiq.q_hint")}</Badge>
        <Button variant="secondary" size="sm" leadingIcon={busy ? undefined : "refresh-cw"} onClick={refresh} disabled={busy} style={{ marginLeft: "auto" }}>{busy ? t("aiq.q_mining") : t("aiq.q_refresh")}</Button>
      </div>
      {questions.length === 0 ? (
        <div style={{ padding: "26px 18px", textAlign: "center", color: "var(--text-faint)", fontSize: 13.5 }}>{t("aiq.q_empty")}</div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(320px,1fr))", gap: 0 }}>
          {questions.slice(0, 30).map((q, i) => (
            <div key={q.id || i} style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "12px 16px", borderBottom: "1px solid var(--border-subtle)", borderRight: "1px solid var(--border-subtle)" }}>
              <Icon name="help-circle" size={15} style={{ color: "var(--text-faint)", flex: "none", marginTop: 1 }} />
              <span style={{ flex: 1, minWidth: 0 }}>
                <span style={{ display: "block", fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)", lineHeight: 1.4 }}>{q.phrase}</span>
                {q.seed && <span style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{t("aiq.q_from", { seed: q.seed })}</span>}
              </span>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}

function MiniStat({ label, value, icon, tone }) {
  return (
    <Card pad={16} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <span style={{ width: 30, height: 30, borderRadius: 9, display: "grid", placeItems: "center", background: tone || "var(--violet-50)", color: tone ? "#fff" : "var(--violet-600)" }}>
        <Icon name={icon} size={16} />
      </span>
      <div>
        {(() => {
          const Odometer = window.LTQ.Odometer;
          const ns = { fontFamily: "var(--font-mono)", fontSize: 24, fontWeight: 600, color: "var(--text-strong)", letterSpacing: "-0.02em" };
          return Odometer && typeof value === "number"
            ? <Odometer value={value} className="lt-num" style={ns} />
            : <div className="lt-num" style={ns}>{value}</div>;
        })()}
        <div style={{ fontSize: 12.5, color: "var(--text-muted)", fontWeight: 600 }}>{label}</div>
      </div>
    </Card>
  );
}
function MentionBar({ value }) {
  const c = value >= 70 ? "var(--green-500)" : value >= 50 ? "var(--accent-500)" : "var(--amber-500)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
      <span style={{ position: "relative", width: 54, height: 6, background: "var(--ink-100)", borderRadius: 999, overflow: "hidden" }}>
        <span style={{ position: "absolute", inset: 0, width: value + "%", background: c, borderRadius: 999 }} />
      </span>
      <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)" }}>{value}%</span>
    </span>
  );
}
const Skel = ({ h = 16, w = "100%" }) => <span className="lt-shimmer" style={{ display: "block", height: h, width: w, borderRadius: 6, background: "var(--ink-100)" }} />;

function MobileQueryCard({ r, last }) {
  return (
    <div style={{ padding: "14px 16px", borderBottom: last ? "none" : "1px solid var(--border-subtle)" }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 9 }}>
        <Icon name="sparkle" size={15} style={{ color: "var(--violet-500)", marginTop: 3, flex: "none" }} />
        <span style={{ flex: 1, minWidth: 0, fontSize: 14, fontWeight: 600, color: "var(--text-strong)", lineHeight: 1.4 }}>{r.query}</span>
        <span style={{ flex: "none" }}><Badge tone={r.priority === "High" ? "accent" : "neutral"} variant={r.priority === "High" ? "solid" : "soft"}>{t("level." + String(r.priority).toLowerCase())}</Badge></span>
      </div>
      <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: "6px 14px", margin: "9px 0 0 24px" }}>
        <PlatformBadge value={r.engine} />
        <span style={{ fontSize: 12.5, color: "var(--text-muted)", fontWeight: 600 }}>{window.LTQ.dataLabel("intent", r.intent)}</span>
        <Badge tone={r.citation === "High" ? "green" : r.citation === "Medium" ? "amber" : "neutral"} dot>{t("level." + String(r.citation).toLowerCase())}</Badge>
      </div>
      <div style={{ margin: "9px 0 0 24px", maxWidth: 260 }}><MentionBar value={r.mention} /></div>
      <div style={{ margin: "7px 0 0 24px", fontSize: 12, color: "var(--text-muted)" }}>{t("aiq.col_rec")}: <b style={{ color: "var(--text-body)" }}>{window.LTQ.dataLabel("type", r.rec)}</b></div>
    </div>
  );
}

function AISearchQueries() {
  const { loading, data, reload } = useApi("/api/ai-queries");
  const phone = window.LTQ.usePhone ? window.LTQ.usePhone() : false;
  const ALL = t("aiq.all_engines");
  const [engine, setEngine] = React.useState(ALL); // real filter over the table
  const allRows = (data && data.queries) || [];
  const rows = engine === ALL ? allRows : allRows.filter((r) => r.engine === engine);
  const questions = (data && data.questions) || [];
  const cols = ["query", "intent", "engine", "format", "mention", "citation", "rec", "priority"].map((k) => t("aiq.col_" + k));
  const high = rows.filter((r) => r.citation === "High").length;
  const recs = new Set(rows.map((r) => r.rec)).size;
  const ops = rows.filter((r) => r.mention >= 50).length;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <SectionTitle eyebrow={t("aiq.eyebrow")} title={t("nav.ai")}
        sub={t("aiq.sub")}
        right={<div style={{ display: "flex", gap: 10 }}><Select size="sm" label={t("aiq.engine")} value={engine} onChange={(e) => setEngine(e.target.value)} options={[ALL, "ChatGPT", "Perplexity", "Google AI Overview"]} /></div>} />

      <div className="lt-keep-grid lt-metric-strip" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
        <MiniStat label={t("aiq.prompts_discovered")} value={rows.length} icon="message-square-text" tone="var(--violet-500)" />
        <MiniStat label={t("aiq.brand_mention_ops")} value={ops} icon="at-sign" />
        <MiniStat label={t("aiq.high_citation_ops")} value={high} icon="quote" />
        <MiniStat label={t("aiq.pages_recommended")} value={recs} icon="file-stack" />
      </div>

      {!loading && <RealQuestions questions={questions} onReload={reload} />}

      <Card pad={0} style={{ overflow: "hidden" }}>
        {phone ? (
          <div>
            {loading && <div style={{ padding: 18 }}>{[0,1,2,3].map((i) => <div key={i} style={{ marginBottom: 10 }}><Skel h={56} /></div>)}</div>}
            {!loading && rows.length === 0 && <div style={{ padding: "40px 16px", textAlign: "center", color: "var(--text-faint)", fontSize: 13.5 }}>{t("aiq.empty")}</div>}
            {!loading && rows.map((r, i) => <MobileQueryCard key={r.id || i} r={r} last={i === rows.length - 1} />)}
          </div>
        ) : (
        <div className="lt-scroll" style={{ overflowX: "auto" }}>
          <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 1100 }}>
            <thead><tr>
              {cols.map((c, i) => <th key={i} style={{ textAlign: "left", padding: "0 16px", height: 46, 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" }}>{c}</th>)}
            </tr></thead>
            <tbody>
              {loading && [0, 1, 2, 3, 4].map((i) => <tr key={i}><td colSpan={8} style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-subtle)" }}><Skel /></td></tr>)}
              {!loading && rows.length === 0 && <tr><td colSpan={8} style={{ padding: "40px 16px", textAlign: "center", color: "var(--text-faint)", fontSize: 13.5 }}>{t("aiq.empty")}</td></tr>}
              {!loading && rows.map((r, i) => {
                const bd = { padding: 16, borderBottom: i < rows.length - 1 ? "1px solid var(--border-subtle)" : "none" };
                return (
                  <tr key={r.id || i} onMouseEnter={e => e.currentTarget.style.background = "var(--ink-50)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <td style={{ ...bd, maxWidth: 340 }}><span style={{ display: "inline-flex", alignItems: "flex-start", gap: 9 }}><Icon name="sparkle" size={15} style={{ color: "var(--violet-500)", marginTop: 2 }} /><span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)", lineHeight: 1.4 }}>{r.query}</span></span></td>
                    <td style={bd}><span style={{ fontSize: 12.5, color: "var(--text-muted)", fontWeight: 600 }}>{window.LTQ.dataLabel("intent", r.intent)}</span></td>
                    <td style={bd}><PlatformBadge value={r.engine} /></td>
                    <td style={bd}><span style={{ fontSize: 12.5, color: "var(--text-body)" }}>{window.LTQ.dataLabel("format", r.format)}</span></td>
                    <td style={bd}><MentionBar value={r.mention} /></td>
                    <td style={bd}><Badge tone={r.citation === "High" ? "green" : r.citation === "Medium" ? "amber" : "neutral"} dot>{t("level." + String(r.citation).toLowerCase()) }</Badge></td>
                    <td style={bd}><span style={{ fontSize: 12.5, color: "var(--text-body)", fontWeight: 600 }}>{window.LTQ.dataLabel("type", r.rec)}</span></td>
                    <td style={bd}><Badge tone={r.priority === "High" ? "accent" : "neutral"} variant={r.priority === "High" ? "solid" : "soft"}>{t("level." + String(r.priority).toLowerCase())}</Badge></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        )}
      </Card>
    </div>
  );
}
window.LTQ.AISearchQueries = AISearchQueries;
})();
