// SQSEO Research Lab — the longtail question pipeline (keyword-supremacy P9).
// Seeds (chips, typed or imported from Search Console) → one-click research
// batches blending GSC + Google Autocomplete (+ grounded LLM when configured)
// → deterministic clusters with anti-thin-content verdicts → the engine's
// recommended article batch, operator-editable. Registered on
// window.LTQ.ResearchLab.
(function init() {
  if (!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.useApi || !window.LTQ.SectionTitle) { return setTimeout(init, 30); }
  const React = window.React;
  const DS = window.LongtailIQDesignSystem_ae8f12;
  const { Card, Icon, Badge, Button } = DS;
  const { SectionTitle, useApi, api, toast, EmptyState, IntentBadge } = window.LTQ;
  const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

  const SOURCE_TONE = { gsc: "success", autocomplete: "default", llm: "info", competitor: "warning", site: "default" };

  function Stat({ icon, label, value }) {
    const Odometer = window.LTQ.Odometer;
    const ns = { fontFamily: "var(--font-mono)", fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)" };
    return (
      <Card pad={16} className="lt-card-3d" style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        <span style={{ width: 30, height: 30, borderRadius: 9, display: "grid", placeItems: "center", background: "var(--ink-50)", color: "var(--text-muted)" }}>
          <Icon name={icon} size={16} />
        </span>
        <div>
          {Odometer ? <Odometer value={Number(value) || 0} 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 SeedChip({ seed, onRemove }) {
    return (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 8px 4px 11px", borderRadius: 999,
        border: "1px solid var(--border-subtle)", background: seed.created_by === "gsc" ? "var(--accent-50,#ecfdf5)" : "var(--ink-50)", fontSize: 12.5, fontWeight: 600 }}>
        {seed.created_by === "gsc" && <Icon name="line-chart" size={12} style={{ color: "var(--accent-600,var(--accent-500))" }} />}
        {seed.keyword}
        {seed.gsc_impressions != null && (
          <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-faint)" }}>{seed.gsc_impressions}</span>
        )}
        <button onClick={onRemove} aria-label={t("lab.seed_remove")} style={{ border: "none", background: "transparent", cursor: "pointer", padding: 2, display: "grid", placeItems: "center", color: "var(--text-faint)" }}>
          <Icon name="x" size={12} />
        </button>
      </span>
    );
  }

  function ClusterCard({ c }) {
    const single = c.recommendedFormat === "single-deep";
    return (
      <Card pad={14} className="lt-card-3d" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontWeight: 700, fontSize: 13.5, flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.name}</span>
          {c.fromGsc && <Badge tone="success">GSC</Badge>}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12, color: "var(--text-muted)" }}>
          <span className="lt-num" style={{ fontFamily: "var(--font-mono)" }}>{t("lab.cluster_count", { n: c.count })}</span>
          {c.estVolume != null && <span className="lt-num" style={{ fontFamily: "var(--font-mono)" }}>{t("lab.cluster_volume", { n: c.estVolume })}</span>}
          {c.trafficAt3 > 0 && <span className="lt-num" style={{ fontFamily: "var(--font-mono)", color: "var(--accent-600, var(--accent-500))" }}>{t("lab.cluster_traffic", { n: c.trafficAt3 })}</span>}
          <IntentBadge value={c.intent} />
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Badge tone={single ? "warning" : "default"}>
            {single ? t("lab.single_deep") : t("lab.split_into", { n: c.splitInto || c.count })}
          </Badge>
          {typeof c.cohesion === "number" && (
            <span style={{ fontSize: 11, color: "var(--text-faint)" }}>{t("lab.cohesion")} {Math.round(c.cohesion * 100)}%</span>
          )}
        </div>
        {single && <div style={{ fontSize: 11.5, color: "var(--text-muted)", lineHeight: 1.45 }}>{t("lab.single_deep_hint")}</div>}
      </Card>
    );
  }

  function QuestionRow({ q, onToggle }) {
    return (
      <tr style={{ borderTop: "1px solid var(--border-subtle)" }}>
        <td style={{ padding: "8px 10px", width: 30 }}>
          <input type="checkbox" checked={!!q.is_selected} onChange={(e) => onToggle(q, e.target.checked)} aria-label={t("lab.select_question")} />
        </td>
        <td style={{ padding: "8px 10px", fontSize: 13 }}>
          {q.question}
          {q.why_it_matters && <div style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 2 }}>{q.why_it_matters}</div>}
        </td>
        <td style={{ padding: "8px 10px" }}><Badge tone={SOURCE_TONE[q.source] || "default"}>{q.source}</Badge></td>
        <td style={{ padding: "8px 10px" }}><IntentBadge value={q.intent} /></td>
        <td
          className="lt-num"
          style={{ padding: "8px 10px", fontFamily: "var(--font-mono)", fontSize: 12, textAlign: "right" }}
          title={q.volume_note ? (q.volume_confidence ? `${q.volume_confidence} confidence — ${q.volume_note}` : q.volume_note) : undefined}
        >
          {q.volume == null ? "—" : q.volume_confidence ? `~${q.volume}` : q.volume}
        </td>
        <td
          className="lt-num"
          style={{ padding: "8px 10px", fontFamily: "var(--font-mono)", fontSize: 12, textAlign: "right" }}
          title={q.difficulty_note || undefined}
        >
          {q.difficulty ?? "—"}
        </td>
        <td style={{ padding: "8px 10px", textAlign: "center" }}>
          {q.striking ? <Badge tone="warning">{t("lab.striking")}</Badge> : null}
        </td>
        <td className="lt-num" style={{ padding: "8px 10px", fontFamily: "var(--font-mono)", fontSize: 12, textAlign: "center" }}>{q.pain_level ?? "—"}</td>
      </tr>
    );
  }

  function ResearchLab() {
    const seedsApi = useApi("/api/lab/seeds");
    const statusApi = useApi("/api/lab/status");
    const overviewApi = useApi("/api/lab/overview");
    const batchesApi = useApi("/api/lab/batches");
    const [newSeed, setNewSeed] = React.useState("");
    const [running, setRunning] = React.useState(false);
    const [importing, setImporting] = React.useState(false);

    const seeds = (seedsApi.data && seedsApi.data.seeds) || [];
    const status = statusApi.data || {};
    const ov = overviewApi.data || { questions: [], clusters: [], intents: {}, recommendedIds: [] };
    const batches = (batchesApi.data && batchesApi.data.batches) || [];
    const reloadAll = () => { seedsApi.reload(); overviewApi.reload(); batchesApi.reload(); statusApi.reload(); };

    const addSeed = async () => {
      const kw = newSeed.trim();
      if (kw.length < 2) return;
      const r = await api.post("/api/lab/seeds", { keyword: kw });
      if (r.ok) { setNewSeed(""); seedsApi.reload(); statusApi.reload(); }
      else toast(r.error || t("lab.seed_error"), { tone: "error" });
    };

    const removeSeed = async (seed) => {
      const r = await api.del("/api/lab/seeds/" + seed.id);
      if (!r.ok) toast(r.error || t("lab.seed_error"), { tone: "error" });
      seedsApi.reload();
    };

    const importGsc = async () => {
      setImporting(true);
      const r = await api.post("/api/lab/seeds/import-gsc", {});
      setImporting(false);
      if (r.ok) { toast(t("lab.import_done", { n: r.data.imported }), { tone: "success" }); reloadAll(); }
      else if (r.status === 429) toast(t("lab.import_throttled"), { tone: "warning" });
      else if (r.status === 409) toast(t("lab.gsc_not_connected"), { tone: "warning" });
      else toast(r.error || t("lab.import_error"), { tone: "error" });
    };

    const runBatch = async () => {
      setRunning(true);
      const r = await api.post("/api/lab/research", {});
      setRunning(false);
      if (r.ok) {
        const d = r.data;
        toast(d.saved > 0 ? t("lab.batch_done", { n: d.saved }) : t("lab.batch_empty"), { tone: d.saved > 0 ? "success" : "default" });
        if (d.llmError) toast(t("lab.llm_soft_fail"), { tone: "warning" });
        reloadAll();
      } else if (r.status === 409) toast(t("lab.no_seeds"), { tone: "warning" });
      else if (r.status === 429) toast(t("lab.budget_hit"), { tone: "warning" });
      else toast(r.error || t("lab.batch_error"), { tone: "error" });
    };

    const autoSelect = async () => {
      const r = await api.post("/api/lab/selection/auto", {});
      if (r.ok) { toast(t("lab.auto_done", { n: r.data.selected.length }), { tone: "success" }); overviewApi.reload(); }
      else toast(r.error || t("lab.batch_error"), { tone: "error" });
    };

    const createBriefs = async () => {
      const r = await api.post("/api/lab/selection/briefs", {});
      if (r.ok) {
        const n = (r.data.created || []).length;
        toast(n > 0 ? t("lab.briefs_done", { n }) : t("lab.briefs_none"), { tone: n > 0 ? "success" : "default" });
        overviewApi.reload();
      } else toast(r.error || t("lab.briefs_error"), { tone: "error" });
    };

    const toggle = async (q, selected) => {
      const r = await api.post("/api/lab/questions/" + q.id + "/select", { selected });
      if (!r.ok) toast(r.error || t("lab.batch_error"), { tone: "error" });
      overviewApi.reload();
    };

    const strikingCount = ov.questions.filter((q) => q.striking).length;
    const selectedCount = ov.questions.filter((q) => q.is_selected).length;

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <SectionTitle
          title={t("lab.title")}
          sub={t("lab.subtitle")}
          right={
            <div style={{ display: "flex", gap: 8 }}>
              {status.gsc_connected && (
                <Button variant="secondary" size="sm" onClick={importGsc} disabled={importing}>
                  <Icon name="download" size={14} /> {importing ? t("lab.importing") : t("lab.import_gsc")}
                </Button>
              )}
              <Button size="sm" onClick={runBatch} disabled={running || seeds.length === 0}>
                <Icon name={running ? "loader-2" : "flask-conical"} size={14} /> {running ? t("lab.running") : t("lab.run")}
              </Button>
            </div>
          }
        />

        {/* Seeds — the chips above the pipeline. */}
        <Card pad={16} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)" }}>{t("lab.seeds")}</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
            {seeds.map((s) => <SeedChip key={s.id} seed={s} onRemove={() => removeSeed(s)} />)}
            <span style={{ display: "inline-flex", gap: 6 }}>
              <input
                value={newSeed}
                onChange={(e) => setNewSeed(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") addSeed(); }}
                placeholder={t("lab.seed_placeholder")}
                style={{ height: 30, padding: "0 10px", borderRadius: 999, border: "1px dashed var(--border-strong,var(--border-subtle))", background: "transparent", fontSize: 12.5, fontFamily: "var(--font-sans)", minWidth: 180 }}
              />
              <Button variant="secondary" size="sm" onClick={addSeed} aria-label={t("lab.seed_add")}><Icon name="plus" size={14} /></Button>
            </span>
          </div>
          {status.llm_configured === false && (
            <div style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{t("lab.llm_off_hint")}</div>
          )}
        </Card>

        {/* Stats */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12 }}>
          <Stat icon="message-circle-question" label={t("lab.stat_questions")} value={ov.questions.length} />
          <Stat icon="boxes" label={t("lab.stat_clusters")} value={ov.clusters.length} />
          <Stat icon="target" label={t("lab.stat_striking")} value={strikingCount} />
          <Stat icon="check-check" label={t("lab.stat_selected")} value={selectedCount} />
        </div>

        {ov.questions.length === 0 && !overviewApi.loading ? (
          <EmptyState icon="flask-conical" sq="think" title={t("lab.empty_title")} body={t("lab.empty_body")} />
        ) : (
          <React.Fragment>
            {/* Clusters — the unit we research, select and own. */}
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", marginBottom: 10 }}>{t("lab.clusters")}</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(230px, 1fr))", gap: 12 }}>
                {ov.clusters.slice(0, 12).map((c) => <ClusterCard key={c.name} c={c} />)}
              </div>
            </div>

            {/* Questions table + the automatic selection. */}
            <Card pad={0}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px" }}>
                <span style={{ fontWeight: 700, fontSize: 13.5, flex: 1 }}>{t("lab.questions")}</span>
                <Button variant="secondary" size="sm" onClick={autoSelect}>
                  <Icon name="wand-2" size={14} /> {t("lab.auto_select")}
                </Button>
                <Button size="sm" onClick={createBriefs} disabled={selectedCount === 0}>
                  <Icon name="file-text" size={14} /> {t("lab.create_briefs")}
                </Button>
              </div>
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  <thead>
                    <tr style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--text-faint)", textAlign: "left" }}>
                      <th style={{ padding: "6px 10px" }}></th>
                      <th style={{ padding: "6px 10px" }}>{t("lab.col_question")}</th>
                      <th style={{ padding: "6px 10px" }}>{t("lab.col_source")}</th>
                      <th style={{ padding: "6px 10px" }}>{t("lab.col_intent")}</th>
                      <th style={{ padding: "6px 10px", textAlign: "right" }}>{t("lab.col_volume")}</th>
                      <th style={{ padding: "6px 10px", textAlign: "right" }}>{t("lab.col_difficulty")}</th>
                      <th style={{ padding: "6px 10px", textAlign: "center" }}>{t("lab.col_striking")}</th>
                      <th style={{ padding: "6px 10px", textAlign: "center" }}>{t("lab.col_pain")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {ov.questions.slice(0, 200).map((q) => <QuestionRow key={q.id} q={q} onToggle={toggle} />)}
                  </tbody>
                </table>
              </div>
            </Card>

            {/* Batch history */}
            {batches.length > 0 && (
              <div>
                <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", marginBottom: 10 }}>{t("lab.batches")}</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {batches.map((b) => (
                    <Card key={b.id} pad={12} style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                      <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)" }}>
                        {new Date(b.created_at).toLocaleDateString()}
                      </span>
                      <span style={{ fontSize: 12.5, fontWeight: 600 }}>{t("lab.batch_saved", { n: b.total_questions_saved })}</span>
                      <span style={{ display: "inline-flex", gap: 4 }}>
                        {(b.source_mix || []).map((s) => <Badge key={s} tone={SOURCE_TONE[s] || "default"}>{s}</Badge>)}
                      </span>
                      {Number(b.cost_usd) > 0 && (
                        <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-faint)" }}>${Number(b.cost_usd).toFixed(4)}</span>
                      )}
                      <span style={{ flex: 1, minWidth: 0, fontSize: 12, color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {(b.preview_questions || []).join(" · ")}
                      </span>
                    </Card>
                  ))}
                </div>
              </div>
            )}
          </React.Fragment>
        )}
      </div>
    );
  }

  window.LTQ.ResearchLab = ResearchLab;
})();
