// DeepDivesAdmin — the /deep-dives-admin schedule surface.
//
// This is NOT a CMS: dossier content is authored as committed essay_<slug>.js
// files. This page only manages the thin deep_dives scheduling rows, and it
// mirrors the repo's only privileged-write pattern (api/weekend-pick.js): there
// is no client admin login — the editor pastes the shared WEBHOOK_SECRET, which
// is sent as x-webhook-secret to api/deep-dives.js (service-role writes).
// The secret is held in component state only (never persisted) and the page is
// unlinked from the nav (reachable by typing /deep-dives-admin).
function DeepDivesAdmin({ onHome, onDeepDives }) {
  const { useState } = React;
  const CFG = window.BBR_DEEPDIVES || {};
  const DD_SERIES = CFG.SERIES || "deep-dive";

  const blank = () => ({
    id: null, slug: "", title: "", artist: "", year: "", genre: "", country: "",
    cover_url: "", excerpt: "", pillar: "", related_album_slug: "",
    status: "draft", featured: false, published_at: "",
  });

  const [secret, setSecret] = useState("");
  const [authed, setAuthed] = useState(false);
  const [rows, setRows] = useState([]);
  const [form, setForm] = useState(blank());
  const [msg, setMsg] = useState("");
  const [busy, setBusy] = useState(false);

  const api = async (payload) => {
    const r = await fetch("/api/deep-dives", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-webhook-secret": secret },
      body: JSON.stringify(payload),
    });
    const j = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(j.error || ("HTTP " + r.status));
    return j;
  };

  const refresh = async () => { const j = await api({ action: "list" }); setRows(j.rows || []); setAuthed(true); };

  const run = async (fn, okMsg) => {
    setBusy(true); setMsg("");
    try { await fn(); if (okMsg) setMsg(okMsg); }
    catch (e) { setMsg("⚠ " + (e.message || "failed")); }
    setBusy(false);
  };

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const edit = (r) => { setForm({ ...blank(), ...r, year: r.year || "", published_at: r.published_at ? r.published_at.slice(0, 16) : "" }); setMsg(""); window.scrollTo(0, 0); };

  // Soft, client-side slug check: the authoritative gate is server+article route
  // (a row can't render unless ESSAYS_FULL[slug] is deployed with the deep-dive
  // series), but warn the editor early if the dossier JS isn't loaded here.
  const dossier = form.slug && window.ESSAYS_FULL && window.ESSAYS_FULL[form.slug];
  const slugKnown = !!dossier;
  const slugIsDeepDive = !!(dossier && dossier.series === DD_SERIES);

  const cleanForm = () => {
    const out = {};
    ["slug", "title", "artist", "year", "genre", "country", "cover_url", "excerpt", "pillar", "related_album_slug", "status", "published_at"].forEach(k => { out[k] = form[k]; });
    if (form.id) out.id = form.id;
    return out;
  };

  const saveDraft = () => run(async () => {
    await api({ action: "save", row: { ...cleanForm(), status: "draft" } });
    await refresh(); setForm(blank());
  }, "Saved as draft.");

  const schedule = () => run(async () => {
    if (!form.published_at) throw new Error("Set a future publish date to schedule.");
    await api({ action: "save", row: { ...cleanForm(), status: "scheduled" } });
    await refresh(); setForm(blank());
  }, "Scheduled.");

  const publish = () => run(async () => {
    // Persist any field edits first (as their current status), then flip live.
    await api({ action: "save", row: { ...cleanForm(), status: form.status === "scheduled" ? "scheduled" : "draft" } });
    await api({ action: "publish", slug: form.slug, featured: !!form.featured });
    await refresh(); setForm(blank());
  }, "Published.");

  const remove = (r) => run(async () => {
    if (!window.confirm("Delete the schedule row for “" + r.title + "”? (The dossier JS file is untouched.)")) return;
    await api({ action: "delete", id: r.id });
    await refresh();
  }, "Deleted.");

  // ---- gate ---------------------------------------------------------------
  if (!authed) {
    return (
      <div className="dda" style={{ maxWidth: 460, margin: "14vh auto", padding: "0 24px" }}>
        <h1 style={{ fontFamily: "var(--serif, Georgia)", fontSize: 26, marginBottom: 6 }}>Deep Dives — schedule</h1>
        <p style={{ opacity: 0.75, lineHeight: 1.5, marginBottom: 16 }}>Enter the editorial secret to manage the publish schedule. Dossier content is authored as committed files, not here.</p>
        <input type="password" className="dda-input" placeholder="WEBHOOK_SECRET" value={secret}
          onChange={e => setSecret(e.target.value)} onKeyDown={e => { if (e.key === "Enter") run(refresh); }}
          style={{ width: "100%", padding: "10px 12px", marginBottom: 12 }} />
        <button className="cta" disabled={busy || !secret} onClick={() => run(refresh)}>{busy ? "Checking…" : "Unlock"}</button>
        {msg && <p style={{ marginTop: 12, color: "var(--accent, #cf4827)" }}>{msg}</p>}
      </div>
    );
  }

  // ---- editor -------------------------------------------------------------
  return (
    <div className="dda" style={{ maxWidth: 920, margin: "40px auto 80px", padding: "0 24px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 10 }}>
        <h1 style={{ fontFamily: "var(--serif, Georgia)", fontSize: 26 }}>Deep Dives — schedule</h1>
        <div style={{ display: "flex", gap: 12 }}>
          <a onClick={onDeepDives} style={{ cursor: "pointer", opacity: 0.8 }}>View archive ↗</a>
          <a onClick={onHome} style={{ cursor: "pointer", opacity: 0.8 }}>Home</a>
        </div>
      </div>

      <div className="dda-form" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, margin: "20px 0", background: "var(--card, #fffdf8)", padding: 18, borderRadius: 12, border: "1px solid var(--rule, #d8d0bd)" }}>
        <label className="dda-f">Slug (matches ESSAYS_FULL key)
          <input className="dda-input" value={form.slug} onChange={e => set("slug", e.target.value.trim())} placeholder="back-in-black" />
          {form.slug && (
            slugIsDeepDive
              ? <span style={{ fontSize: 12, color: "#2e7d32" }}>✓ dossier loaded (series: deep-dive)</span>
              : slugKnown
                ? <span style={{ fontSize: 12, color: "var(--accent,#cf4827)" }}>⚠ that slug exists but isn’t marked series:"deep-dive"</span>
                : <span style={{ fontSize: 12, opacity: 0.7 }}>⚠ no dossier loaded for this slug in this browser — it won’t render until essay_{form.slug}.js is deployed</span>
          )}
        </label>
        <label className="dda-f">Status
          <select className="dda-input" value={form.status} onChange={e => set("status", e.target.value)}>
            <option value="draft">draft</option>
            <option value="scheduled">scheduled</option>
            <option value="published">published</option>
          </select>
        </label>
        <label className="dda-f">Title<input className="dda-input" value={form.title} onChange={e => set("title", e.target.value)} /></label>
        <label className="dda-f">Artist<input className="dda-input" value={form.artist} onChange={e => set("artist", e.target.value)} /></label>
        <label className="dda-f">Year<input className="dda-input" value={form.year} onChange={e => set("year", e.target.value)} placeholder="1980" /></label>
        <label className="dda-f">Genre<input className="dda-input" value={form.genre} onChange={e => set("genre", e.target.value)} placeholder="Hard rock" /></label>
        <label className="dda-f">Country<input className="dda-input" value={form.country} onChange={e => set("country", e.target.value)} placeholder="Australia" /></label>
        <label className="dda-f">Pillar (optional)<input className="dda-input" value={form.pillar} onChange={e => set("pillar", e.target.value)} /></label>
        <label className="dda-f">Cover URL (blank → /covers/{form.slug || "slug"}.jpg)<input className="dda-input" value={form.cover_url} onChange={e => set("cover_url", e.target.value)} /></label>
        <label className="dda-f">Related album slug (optional cross-link)<input className="dda-input" value={form.related_album_slug} onChange={e => set("related_album_slug", e.target.value.trim())} /></label>
        <label className="dda-f" style={{ gridColumn: "1 / -1" }}>Excerpt (card + email preview)
          <textarea className="dda-input" rows={2} value={form.excerpt} onChange={e => set("excerpt", e.target.value)} />
        </label>
        <label className="dda-f">Publish date/time (for scheduling)
          <input className="dda-input" type="datetime-local" value={form.published_at} onChange={e => set("published_at", e.target.value)} />
        </label>
        <label className="dda-f" style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
          <input type="checkbox" checked={form.featured} onChange={e => set("featured", e.target.checked)} />
          Featured (the single hero + the Wednesday email pick)
        </label>
      </div>

      <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
        <button className="cta cta-ghost" disabled={busy} onClick={saveDraft}>Save draft</button>
        <button className="cta cta-ghost" disabled={busy} onClick={schedule}>Schedule</button>
        <button className="cta" disabled={busy} onClick={publish}>Publish{form.featured ? " + feature" : ""}</button>
        {form.id && <button className="cta cta-ghost" disabled={busy} onClick={() => setForm(blank())}>New / clear</button>}
      </div>
      {msg && <p style={{ marginTop: 12 }}>{msg}</p>}

      <h2 style={{ fontFamily: "var(--serif, Georgia)", fontSize: 20, margin: "32px 0 12px" }}>All rows</h2>
      <table className="dda-table" style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
        <thead><tr style={{ textAlign: "left", opacity: 0.6 }}>
          <th style={{ padding: "6px 8px" }}>Status</th><th>Slug</th><th>Title</th><th>Published</th><th>★</th><th></th>
        </tr></thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.id} style={{ borderTop: "1px solid var(--rule, #e7dfce)" }}>
              <td style={{ padding: "6px 8px" }}>{r.status}</td>
              <td>{r.slug}</td>
              <td>{r.title}</td>
              <td>{r.published_at ? r.published_at.slice(0, 10) : "—"}</td>
              <td>{r.featured ? "★" : ""}</td>
              <td style={{ whiteSpace: "nowrap" }}>
                <a onClick={() => edit(r)} style={{ cursor: "pointer", marginRight: 12 }}>Edit</a>
                <a onClick={() => remove(r)} style={{ cursor: "pointer", color: "var(--accent,#cf4827)" }}>Delete</a>
              </td>
            </tr>
          ))}
          {!rows.length && <tr><td colSpan={6} style={{ padding: "16px 8px", opacity: 0.6 }}>No rows yet.</td></tr>}
        </tbody>
      </table>
    </div>
  );
}

window.DeepDivesAdmin = DeepDivesAdmin;
