/* Work dashboard: Supabase-auth login, paid job queue, earnings, coach panel,
   and the admin panel. Server APIs: /api/bd-jobs, /api/bd-coach, /api/bd-admin. */

const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;

const BD_SUPA = "https://iqjkwsbsqmkyzgzigcik.supabase.co";
const BD_ANON = "sb_publishable_iUEl9piSPjxMiJBhJe9eyw_izK_e2T6";
const BD_SESSION_KEY = "bd.session.v1";

/* ───────── auth ───────── */
function bdSession() {
  try { return JSON.parse(localStorage.getItem(BD_SESSION_KEY) || "null"); } catch { return null; }
}
function bdSaveSession(s) {
  try {
    if (s) localStorage.setItem(BD_SESSION_KEY, JSON.stringify(s));
    else localStorage.removeItem(BD_SESSION_KEY);
  } catch {}
}
async function bdLogin(email, password) {
  const r = await fetch(`${BD_SUPA}/auth/v1/token?grant_type=password`, {
    method: "POST",
    headers: { apikey: BD_ANON, "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  const data = await r.json();
  if (!r.ok) throw new Error(data.error_description || data.msg || "Sign-in failed");
  const s = {
    access_token: data.access_token,
    refresh_token: data.refresh_token,
    expires_at: Date.now() + (data.expires_in - 60) * 1000,
    email: data.user && data.user.email,
  };
  bdSaveSession(s);
  try { sessionStorage.setItem("bydelaney.unlocked", "1"); } catch {} // legacy pages
  return s;
}
async function bdRefresh(s) {
  const r = await fetch(`${BD_SUPA}/auth/v1/token?grant_type=refresh_token`, {
    method: "POST",
    headers: { apikey: BD_ANON, "Content-Type": "application/json" },
    body: JSON.stringify({ refresh_token: s.refresh_token }),
  });
  if (!r.ok) { bdSaveSession(null); throw new Error("session expired"); }
  const data = await r.json();
  const ns = {
    access_token: data.access_token,
    refresh_token: data.refresh_token,
    expires_at: Date.now() + (data.expires_in - 60) * 1000,
    email: (data.user && data.user.email) || s.email,
  };
  bdSaveSession(ns);
  return ns;
}
async function bdToken() {
  let s = bdSession();
  if (!s) return null;
  if (Date.now() > s.expires_at) {
    try { s = await bdRefresh(s); } catch { return null; }
  }
  return s.access_token;
}
async function bdApi(path, opts = {}) {
  const token = await bdToken();
  if (!token) throw new Error("signed out");
  const r = await fetch(path, {
    ...opts,
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, ...(opts.headers || {}) },
  });
  const data = await r.json().catch(() => ({}));
  if (!r.ok) throw new Error(data.error || `request failed (${r.status})`);
  return data;
}
function bdSignOut() { bdSaveSession(null); window.location.hash = "#/work-login"; }

/* ───────── login page ───────── */
function WorkLoginPage({ setRoute }) {
  const [email, setEmail] = useStateW("delaney@bydelaney.com");
  const [pw, setPw] = useStateW("");
  const [err, setErr] = useStateW("");
  const [busy, setBusy] = useStateW(false);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr("");
    try {
      const s = await bdLogin(email.trim(), pw);
      const admin = s.email && s.email !== "delaney@bydelaney.com";
      (setRoute || ((r) => { window.location.hash = "#/" + r; }))(admin ? "admin" : "jobs");
    } catch (e2) { setErr(e2.message); }
    setBusy(false);
  };

  return (
    <main className="page-enter" style={{ padding: "clamp(72px,12vw,160px) 0" }}>
      <div className="shell">
        <div className="card" style={{ maxWidth: 460, margin: "0 auto", textAlign: "center", padding: "56px 48px" }}>
          <div className="serif" style={{ fontSize: 64, lineHeight: 1, color: "var(--terracotta-deep)", fontStyle: "italic" }}>¹</div>
          <h1 className="serif" style={{ fontSize: "clamp(36px,4.5vw,48px)", margin: "8px 0 4px" }}>Clock in.</h1>
          <p style={{ color: "var(--ink-2)", fontFamily: "var(--serif)", fontSize: 17, margin: "0 0 20px" }}>Your jobs are waiting.</p>
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
            <input className="input" type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="Password" autoFocus />
            <button className="btn" type="submit" disabled={busy}>{busy ? "Signing in…" : "Sign in"} <span aria-hidden="true">→</span></button>
          </form>
          {err && <div style={{ color: "var(--terracotta-deep)", fontSize: 13, marginTop: 10 }}>{err}</div>}
        </div>
      </div>
    </main>
  );
}

/* ───────── shared bits ───────── */
const BD_STATUS = {
  open:        { label: "Ready",        cls: "tag tag--terracotta" },
  in_progress: { label: "In progress",  cls: "tag tag--terracotta" },
  revise:      { label: "Notes back",   cls: "tag tag--charcoal" },
  submitted:   { label: "In review",    cls: "tag tag--charcoal" },
  flagged:     { label: "With Dad",     cls: "tag tag--charcoal" },
  approved:    { label: "Approved",     cls: "tag tag--sage" },
  paid:        { label: "Paid",         cls: "tag tag--paid" },
  locked:      { label: "Locked",       cls: "tag" },
};
function BdPill({ status }) {
  const m = BD_STATUS[status] || BD_STATUS.locked;
  return <span className={m.cls}>{m.label}</span>;
}
function bdMoney(n) { return "$" + Number(n).toLocaleString(); }

/* ───────── coach panel ───────── */
function CoachPanel({ jobId }) {
  const aiName = (() => { try { return localStorage.getItem("delaney.ai.name") || "Coach"; } catch { return "Coach"; } })();
  const [open, setOpen] = useStateW(false);
  const [msgs, setMsgs] = useStateW(() => {
    try { return JSON.parse(localStorage.getItem("bd.coach.msgs") || "[]"); } catch { return []; }
  });
  const [input, setInput] = useStateW("");
  const [busy, setBusy] = useStateW(false);
  const endRef = useRefW(null);

  useEffectW(() => {
    try { localStorage.setItem("bd.coach.msgs", JSON.stringify(msgs.slice(-60))); } catch {}
    if (endRef.current) endRef.current.scrollIntoView({ behavior: "smooth" });
  }, [msgs, open]);

  const send = async () => {
    const text = input.trim();
    if (!text || busy) return;
    setInput("");
    setMsgs((m) => [...m, { role: "user", content: text }]);
    setBusy(true);
    try {
      const data = await bdApi("/api/bd-coach", {
        method: "POST",
        body: JSON.stringify({ message: text, job_id: jobId || null, ai_name: aiName }),
      });
      setMsgs((m) => [...m, { role: "assistant", content: data.reply }]);
    } catch (e) {
      setMsgs((m) => [...m, { role: "assistant", content: "Hit a snag (" + e.message + "). Try again?" }]);
    }
    setBusy(false);
  };

  return (
    <>
      <button onClick={() => setOpen(!open)} style={{
        position: "fixed", right: 18, bottom: 18, zIndex: 60, border: "none", cursor: "pointer",
        background: "var(--charcoal)", color: "var(--cream)", borderRadius: 999,
        padding: "14px 22px", fontFamily: "var(--sans)", fontSize: 14, fontWeight: 600,
        boxShadow: "0 8px 24px rgba(26,26,26,.25)",
      }}>
        {open ? "Close" : aiName}
      </button>
      {open && (
        <div style={{
          position: "fixed", right: 12, bottom: 76, zIndex: 60,
          width: "min(400px, calc(100vw - 24px))", height: "min(540px, 70vh)",
          background: "var(--cream)", border: "1px solid var(--line-strong)", borderRadius: 8,
          display: "flex", flexDirection: "column", boxShadow: "0 16px 48px rgba(26,26,26,.22)",
        }}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <strong className="serif" style={{ fontSize: 18 }}>{aiName}</strong>
            <span className="eyebrow">on the clock with you</span>
          </div>
          <div style={{ flex: 1, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 10 }}>
            {msgs.length === 0 && (
              <p style={{ color: "var(--ink-3)", fontSize: 14, fontFamily: "var(--serif)", fontStyle: "italic" }}>
                Ask about the job, bounce an idea, or paste a draft.
              </p>
            )}
            {msgs.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.role === "user" ? "flex-end" : "flex-start",
                maxWidth: "85%", padding: "10px 14px", borderRadius: 10, fontSize: 14, lineHeight: 1.5,
                background: m.role === "user" ? "var(--charcoal)" : "var(--cream-deep)",
                color: m.role === "user" ? "var(--cream)" : "var(--charcoal)",
                whiteSpace: "pre-wrap",
              }}>{m.content}</div>
            ))}
            {busy && <div style={{ color: "var(--ink-3)", fontSize: 13 }}>…</div>}
            <div ref={endRef} />
          </div>
          <div style={{ padding: 12, borderTop: "1px solid var(--line)", display: "flex", gap: 8 }}>
            <textarea className="textarea" rows={1} value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder="Talk to your coach…" style={{ flex: 1, resize: "none" }} />
            <button className="btn btn--sm" onClick={send} disabled={busy}>Send</button>
          </div>
        </div>
      )}
    </>
  );
}

/* ───────── jobs dashboard ───────── */
function JobsPage() {
  const [data, setData] = useStateW(null);
  const [err, setErr] = useStateW("");
  const [submitFor, setSubmitFor] = useStateW(null);
  const [subText, setSubText] = useStateW("");
  const [subUrl, setSubUrl] = useStateW("");
  const [busy, setBusy] = useStateW(false);
  const [result, setResult] = useStateW(null);
  const [reqBusy, setReqBusy] = useStateW(false);

  const load = async () => {
    try { setData(await bdApi("/api/bd-jobs")); setErr(""); }
    catch (e) { setErr(e.message); }
  };
  useEffectW(() => { load(); }, []);

  if (err === "signed out" || err.includes("sign in")) { window.location.hash = "#/work-login"; return null; }
  if (!data) return <main className="page-enter"><div className="shell" style={{ padding: "80px 0" }}>{err || "Loading your desk…"}</div></main>;

  const jobs = data.jobs || [];
  const main = jobs.filter((j) => j.phase !== 9).sort((a, b) => a.sort_order - b.sort_order);
  const bonus = jobs.filter((j) => j.phase === 9).sort((a, b) => a.sort_order - b.sort_order);
  const active = main.find((j) => ["open", "in_progress", "revise", "submitted", "flagged"].includes(j.status));
  const queue = main.filter((j) => j.status === "locked");
  const done = main.filter((j) => ["approved", "paid"].includes(j.status));

  const payouts = data.payouts || [];
  const earnedAll = payouts.reduce((s, p) => s + Number(p.amount), 0);
  const earnedPaid = payouts.filter((p) => p.paid).reduce((s, p) => s + Number(p.amount), 0);
  const pending = earnedAll - earnedPaid;
  const toNext100 = earnedAll % 100;
  const requested = payouts.some((p) => !p.paid && p.requested_at);

  const ai = (() => { try { return localStorage.getItem("delaney.ai.name") || "your coach"; } catch { return "your coach"; } })();

  const start = async (id) => { try { await bdApi("/api/bd-jobs", { method: "POST", body: JSON.stringify({ action: "start", id }) }); load(); } catch (e) { alert(e.message); } };
  const requestPayout = async () => {
    if (reqBusy) return;
    setReqBusy(true);
    try { await bdApi("/api/bd-jobs", { method: "POST", body: JSON.stringify({ action: "request_payout" }) }); await load(); }
    catch (e) { alert(e.message); }
    setReqBusy(false);
  };
  const doSubmit = async () => {
    if (busy) return;
    setBusy(true); setResult(null);
    try {
      const r = await bdApi("/api/bd-jobs", {
        method: "POST",
        body: JSON.stringify({ action: "submit", id: submitFor.id, text: subText, url: subUrl, ai_name: ai }),
      });
      setResult(r); setSubText(""); setSubUrl("");
      load();
    } catch (e) { setResult({ verdict: "ERROR", message: e.message }); }
    setBusy(false);
  };

  return (
    <main className="page-enter">
      <div className="shell" style={{ padding: "48px 0 120px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 8 }}>
          <h1 className="serif" style={{ fontSize: "clamp(34px,5vw,52px)" }}>Your desk.</h1>
          <div style={{ display: "flex", gap: 14, alignItems: "baseline" }}>
            <a href="#/dashboard" className="link-underline" style={{ fontSize: 13 }}>earlier work</a>
            <button onClick={bdSignOut} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", fontSize: 13, fontFamily: "var(--sans)" }}>sign out</button>
          </div>
        </div>

        {/* earnings */}
        <div className="card card--inset" style={{ marginTop: 24, display: "flex", flexWrap: "wrap", gap: 28, alignItems: "center" }}>
          <div>
            <div className="eyebrow">Earned so far</div>
            <div className="serif mono-num" style={{ fontSize: "clamp(40px,6vw,64px)", lineHeight: 1.05 }}>{bdMoney(earnedAll)}</div>
          </div>
          <div style={{ flex: 1, minWidth: 220 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--ink-3)", marginBottom: 6 }}>
              <span>{done.length} jobs approved</span><span>{bdMoney(100 - toNext100)} to your next $100</span>
            </div>
            <div style={{ height: 10, background: "var(--cream-edge)", borderRadius: 999, overflow: "hidden" }}>
              <div style={{ width: `${toNext100}%`, height: "100%", background: "var(--terracotta)", borderRadius: 999, transition: "width .4s var(--ease)" }} />
            </div>
            <div style={{ display: "flex", gap: 16, marginTop: 10, fontSize: 13 }}>
              <span><strong className="mono-num">{bdMoney(earnedPaid)}</strong> <span style={{ color: "var(--ink-3)" }}>paid out</span></span>
              <span><strong className="mono-num">{bdMoney(pending)}</strong> <span style={{ color: "var(--ink-3)" }}>{requested ? "requested" : "approved, ready to cash out"}</span></span>
            </div>
            {pending > 0 && (
              <div style={{ marginTop: 12 }}>
                {requested ? (
                  <span className="tag tag--sage">Payout requested — Dad's been pinged ✓</span>
                ) : (
                  <button className="btn btn--sm btn--terracotta" onClick={requestPayout} disabled={reqBusy}>
                    {reqBusy ? "Sending…" : `Request my payout · ${bdMoney(pending)}`}
                  </button>
                )}
              </div>
            )}
          </div>
        </div>

        {/* active job */}
        {active ? (
          <div className="card" style={{ marginTop: 28, borderColor: "var(--terracotta)", borderWidth: 1.5 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12, flexWrap: "wrap" }}>
              <div>
                <div className="eyebrow" style={{ color: "var(--terracotta-deep)" }}>Active job · {active.phase_label}</div>
                <h2 className="serif" style={{ fontSize: "clamp(24px,3.5vw,34px)", margin: "6px 0" }}>{active.title}</h2>
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <span className="tag tag--terracotta mono-num" style={{ fontSize: 14 }}>{bdMoney(active.payout_usd)}</span>
                <span className="tag">{active.eta}</span>
                <BdPill status={active.status} />
              </div>
            </div>
            <p style={{ marginTop: 10, lineHeight: 1.6, maxWidth: 720 }}>{active.brief}</p>
            {active.deliverable_spec && (
              <p style={{ marginTop: 10, fontSize: 14, color: "var(--ink-2)" }}><strong>Deliverable:</strong> {active.deliverable_spec}</p>
            )}
            {active.status === "revise" && active.revision_notes && active.revision_notes.length > 0 && (
              <div className="card card--inset" style={{ marginTop: 14, padding: 18 }}>
                <div className="eyebrow">Notes from {ai}</div>
                <ul style={{ margin: "8px 0 0 18px", lineHeight: 1.6, fontSize: 14 }}>
                  {(active.revision_notes[active.revision_notes.length - 1].notes || []).map((n, i) => <li key={i}>{n}</li>)}
                </ul>
              </div>
            )}
            {active.status === "flagged" ? (
              <p style={{ marginTop: 14, fontSize: 14, color: "var(--ink-3)", fontStyle: "italic" }}>This one's with Dad — he'll get back to you.</p>
            ) : (
              <div style={{ marginTop: 18, display: "flex", gap: 10, flexWrap: "wrap" }}>
                {active.status === "open" && <button className="btn btn--ghost" onClick={() => start(active.id)}>Start the clock</button>}
                <button className="btn btn--terracotta" onClick={() => { setSubmitFor(active); setResult(null); }}>Submit work <span aria-hidden="true">→</span></button>
              </div>
            )}
          </div>
        ) : (
          <div className="card" style={{ marginTop: 28 }}>
            <h2 className="serif" style={{ fontSize: 28 }}>Queue's clear.</h2>
            <p style={{ color: "var(--ink-2)" }}>Nothing active — Dad's loading more work. Check the bonus missions below.</p>
          </div>
        )}

        {/* upcoming */}
        {queue.length > 0 && (
          <>
            <h3 className="eyebrow" style={{ marginTop: 36 }}>Up next</h3>
            <div style={{ display: "grid", gap: 12, marginTop: 12 }}>
              {queue.map((j) => (
                <div key={j.id} className="card" style={{ padding: 20, opacity: 0.75, display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
                  <div>
                    <strong className="serif" style={{ fontSize: 18 }}>{j.title}</strong>
                    <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>{j.phase_label} · {j.eta}</div>
                  </div>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <span className="tag mono-num">{bdMoney(j.payout_usd)}</span>
                    <span className="tag">🔒</span>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}

        {/* bonus missions */}
        {bonus.length > 0 && (
          <>
            <h3 className="eyebrow" style={{ marginTop: 36 }}>Bonus missions — claim anytime</h3>
            <div style={{ display: "grid", gap: 12, marginTop: 12 }}>
              {bonus.map((j) => (
                <div key={j.id} className="card" style={{ padding: 20, display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
                  <div style={{ maxWidth: 560 }}>
                    <strong className="serif" style={{ fontSize: 18 }}>{j.title}</strong>
                    <p style={{ fontSize: 14, color: "var(--ink-2)", margin: "6px 0 0" }}>{j.brief}</p>
                  </div>
                  <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                    <span className="tag tag--terracotta mono-num">{bdMoney(j.payout_usd)}</span>
                    <BdPill status={j.status} />
                    {["open", "in_progress", "revise"].includes(j.status) && (
                      <button className="btn btn--sm btn--ghost" onClick={() => { setSubmitFor(j); setResult(null); }}>Claim it</button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </>
        )}

        {/* completed */}
        {done.length > 0 && (
          <>
            <h3 className="eyebrow" style={{ marginTop: 36 }}>Done & dusted</h3>
            <div style={{ display: "grid", gap: 8, marginTop: 12 }}>
              {done.map((j) => (
                <div key={j.id} style={{ display: "flex", justifyContent: "space-between", padding: "10px 4px", borderBottom: "1px solid var(--line-soft)", fontSize: 14 }}>
                  <span>{j.title}</span>
                  <span style={{ display: "flex", gap: 10 }}><span className="mono-num">{bdMoney(j.payout_usd)}</span><BdPill status={j.status} /></span>
                </div>
              ))}
            </div>
          </>
        )}
      </div>

      {/* submit modal */}
      {submitFor && (
        <div style={{ position: "fixed", inset: 0, zIndex: 70, background: "rgba(26,26,26,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}
          onClick={(e) => { if (e.target === e.currentTarget && !busy) setSubmitFor(null); }}>
          <div className="card" style={{ width: "min(640px, 100%)", maxHeight: "86vh", overflowY: "auto", background: "var(--cream)" }}>
            <div className="eyebrow">Submitting</div>
            <h3 className="serif" style={{ fontSize: 24, margin: "4px 0 12px" }}>{submitFor.title}</h3>
            {!result || result.verdict === "ERROR" ? (
              <>
                <textarea className="textarea" rows={8} value={subText} onChange={(e) => setSubText(e.target.value)}
                  placeholder="Paste the work here (or describe it and drop a link below)." style={{ width: "100%" }} />
                <input className="input" value={subUrl} onChange={(e) => setSubUrl(e.target.value)}
                  placeholder="Link (Google Doc, Canva, video…) — optional" style={{ width: "100%", marginTop: 10 }} />
                {result && result.verdict === "ERROR" && <p style={{ color: "var(--terracotta-deep)", fontSize: 13, marginTop: 8 }}>{result.message}</p>}
                <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
                  <button className="btn btn--terracotta" onClick={doSubmit} disabled={busy}>{busy ? "Reviewing…" : "Send it in"}</button>
                  <button className="btn btn--ghost" onClick={() => setSubmitFor(null)} disabled={busy}>Not yet</button>
                </div>
                {busy && <p style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 10 }}>Getting it reviewed — takes a few seconds…</p>}
              </>
            ) : (
              <div>
                {result.verdict === "APPROVE" && (
                  <>
                    <h4 className="serif" style={{ fontSize: 30, color: "var(--sage-deep)" }}>Approved. {bdMoney(result.amount)} logged.</h4>
                    {result.praise && <p style={{ marginTop: 8, fontFamily: "var(--serif)", fontStyle: "italic" }}>"{result.praise}"</p>}
                    <p style={{ fontSize: 14, color: "var(--ink-2)", marginTop: 8 }}>Next job's unlocked on your desk.</p>
                  </>
                )}
                {result.verdict === "REVISE" && (
                  <>
                    <h4 className="serif" style={{ fontSize: 26 }}>Close — a couple notes.</h4>
                    {result.praise && <p style={{ marginTop: 8, fontFamily: "var(--serif)", fontStyle: "italic" }}>"{result.praise}"</p>}
                    <ul style={{ margin: "10px 0 0 18px", lineHeight: 1.7, fontSize: 14 }}>
                      {(result.notes || []).map((n, i) => <li key={i}>{n}</li>)}
                    </ul>
                  </>
                )}
                {result.verdict === "FLAGGED" && (
                  <>
                    <h4 className="serif" style={{ fontSize: 26 }}>Sent up to Dad.</h4>
                    <p style={{ marginTop: 8, fontSize: 14 }}>{result.message}</p>
                  </>
                )}
                <button className="btn" style={{ marginTop: 16 }} onClick={() => setSubmitFor(null)}>Back to the desk</button>
              </div>
            )}
          </div>
        </div>
      )}

      <CoachPanel jobId={active ? active.id : null} />
    </main>
  );
}

/* ───────── admin panel ───────── */
const BD_TEMPLATE = {
  id: "J-NEW", sort_order: 999, phase: 2, phase_label: "Client work",
  title: "New job", brief: "What she sees.", deliverable_spec: "What she hands in.",
  payout_usd: 25, eta: "~1 hour", rubric: "What the reviewer checks (she never sees this).",
  skill: "hidden skill", status: "locked",
};

function AdminPage() {
  const [data, setData] = useStateW(null);
  const [err, setErr] = useStateW("");
  const [editing, setEditing] = useStateW(null);
  const [busyOp, setBusyOp] = useStateW("");

  const load = async () => {
    try { setData(await bdApi("/api/bd-admin")); setErr(""); }
    catch (e) { setErr(e.message); }
  };
  useEffectW(() => { load(); }, []);

  if (err) return <main className="page-enter"><div className="shell" style={{ padding: "80px 0" }}>{err} — <a className="link-underline" href="#/work-login">sign in as admin</a></div></main>;
  if (!data) return <main className="page-enter"><div className="shell" style={{ padding: "80px 0" }}>Loading…</div></main>;

  const op = async (opName, args, label) => {
    setBusyOp(label || opName);
    try { await bdApi("/api/bd-admin", { method: "POST", body: JSON.stringify({ op: opName, args }) }); await load(); }
    catch (e) { alert(e.message); }
    setBusyOp("");
  };

  const jobs = (data.jobs || []).slice().sort((a, b) => a.sort_order - b.sort_order);
  const flagged = jobs.filter((j) => j.status === "flagged");
  const payouts = data.payouts || [];
  const summaries = data.summaries || [];
  const jobTitle = (id) => { const j = jobs.find((x) => x.id === id); return j ? j.title : id; };
  const requestedPayouts = payouts.filter((p) => !p.paid && p.requested_at);
  const requestedTotal = requestedPayouts.reduce((s, p) => s + Number(p.amount), 0);

  const F = ({ label, k, rows }) => (
    <label style={{ display: "block", marginTop: 10 }}>
      <span className="field-label">{label}</span>
      {rows ? (
        <textarea className="textarea" rows={rows} style={{ width: "100%" }} value={editing[k] == null ? "" : editing[k]}
          onChange={(e) => setEditing({ ...editing, [k]: e.target.value })} />
      ) : (
        <input className="input" style={{ width: "100%" }} value={editing[k] == null ? "" : editing[k]}
          onChange={(e) => setEditing({ ...editing, [k]: e.target.value })} />
      )}
    </label>
  );

  return (
    <main className="page-enter">
      <div className="shell" style={{ padding: "48px 0 120px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap" }}>
          <h1 className="serif" style={{ fontSize: "clamp(34px,5vw,52px)" }}>Back office.</h1>
          <div style={{ display: "flex", gap: 14 }}>
            <a href="#/jobs" className="link-underline" style={{ fontSize: 13 }}>her view</a>
            <button onClick={bdSignOut} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", fontSize: 13, fontFamily: "var(--sans)" }}>sign out</button>
          </div>
        </div>

        {flagged.length > 0 && (
          <div className="card" style={{ marginTop: 24, borderColor: "var(--terracotta-deep)" }}>
            <div className="eyebrow" style={{ color: "var(--terracotta-deep)" }}>Needs your review</div>
            {flagged.map((j) => (
              <div key={j.id} style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--line-soft)" }}>
                <strong className="serif" style={{ fontSize: 18 }}>{j.title}</strong> <span className="mono-num">({bdMoney(j.payout_usd)})</span>
                {j.deliverable_url && <div style={{ fontSize: 13, marginTop: 4 }}><a className="link-underline" href={j.deliverable_url} target="_blank" rel="noreferrer">{j.deliverable_url}</a></div>}
                {j.deliverable_text && <p style={{ fontSize: 13, whiteSpace: "pre-wrap", marginTop: 6, maxHeight: 160, overflowY: "auto", background: "var(--cream-deep)", padding: 10, borderRadius: 4 }}>{j.deliverable_text}</p>}
                <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
                  <button className="btn btn--sm" onClick={() => op("job_approve", { id: j.id, amount: j.payout_usd }, j.id)} disabled={!!busyOp}>Approve + pay {bdMoney(j.payout_usd)}</button>
                  <button className="btn btn--sm btn--ghost" onClick={() => { const n = prompt("Revision note for Delaney:"); if (n) op("job_revise", { id: j.id, notes: [n] }); }} disabled={!!busyOp}>Send back</button>
                </div>
              </div>
            ))}
          </div>
        )}

        {requestedPayouts.length > 0 && (
          <div className="card" style={{ marginTop: 24, borderColor: "var(--terracotta-deep)", background: "var(--cream-deep)" }}>
            <div className="eyebrow" style={{ color: "var(--terracotta-deep)" }}>💰 Delaney requested her payout</div>
            <p style={{ marginTop: 6, fontSize: 15, lineHeight: 1.5 }}>
              She's asking to be paid <strong className="mono-num">{bdMoney(requestedTotal)}</strong> for {requestedPayouts.length} job{requestedPayouts.length > 1 ? "s" : ""}: {requestedPayouts.map((p) => jobTitle(p.job_id)).join(", ")}. Venmo her, then hit <em>Mark paid</em> below so the ledger stays straight.
            </p>
          </div>
        )}

        {/* payouts */}
        <h3 className="eyebrow" style={{ marginTop: 36 }}>Payout ledger</h3>
        <div className="card" style={{ marginTop: 12, padding: 0, overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
            <thead><tr style={{ textAlign: "left", borderBottom: "1px solid var(--line)" }}>
              {["Job", "Approved", "Amount", "Status", ""].map((h) => <th key={h} style={{ padding: "10px 14px", fontWeight: 600 }}>{h}</th>)}
            </tr></thead>
            <tbody>
              {payouts.map((p) => (
                <tr key={p.id} style={{ borderBottom: "1px solid var(--line-soft)" }}>
                  <td style={{ padding: "10px 14px" }}>{jobTitle(p.job_id)}</td>
                  <td style={{ padding: "10px 14px", whiteSpace: "nowrap" }}>{new Date(p.approved_at).toLocaleDateString()}</td>
                  <td style={{ padding: "10px 14px" }} className="mono-num">{bdMoney(p.amount)}</td>
                  <td style={{ padding: "10px 14px" }}>{p.paid ? <span className="tag tag--paid">Paid</span> : (p.requested_at ? <span className="tag tag--terracotta">Requested</span> : <span className="tag tag--sage">Owed</span>)}</td>
                  <td style={{ padding: "10px 14px" }}>
                    <button className="btn btn--sm btn--ghost" disabled={!!busyOp}
                      onClick={() => op("payout_set_paid", { id: p.id, paid: !p.paid })}>{p.paid ? "Unmark" : "Mark paid"}</button>
                  </td>
                </tr>
              ))}
              {payouts.length === 0 && <tr><td style={{ padding: 14, color: "var(--ink-3)" }}>Nothing approved yet.</td></tr>}
            </tbody>
          </table>
        </div>

        {/* jobs */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 36 }}>
          <h3 className="eyebrow">Jobs ({jobs.length})</h3>
          <button className="btn btn--sm" onClick={() => setEditing({ ...BD_TEMPLATE, id: "J-" + String(Date.now()).slice(-5) })}>+ Add job from template</button>
        </div>
        <div style={{ display: "grid", gap: 8, marginTop: 12 }}>
          {jobs.map((j) => (
            <div key={j.id} style={{ display: "flex", justifyContent: "space-between", gap: 10, padding: "10px 4px", borderBottom: "1px solid var(--line-soft)", fontSize: 14, flexWrap: "wrap" }}>
              <span style={{ minWidth: 0 }}><span className="mono-num" style={{ color: "var(--ink-3)" }}>{String(j.sort_order).padStart(3, "0")}</span> · <strong>{j.title}</strong> <span style={{ color: "var(--ink-3)" }}>({j.phase_label})</span></span>
              <span style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <span className="mono-num">{bdMoney(j.payout_usd)}</span>
                <BdPill status={j.status} />
                <button className="btn btn--sm btn--ghost" onClick={() => setEditing({ ...j })}>Edit</button>
              </span>
            </div>
          ))}
        </div>

        {/* coach summaries */}
        <h3 className="eyebrow" style={{ marginTop: 36 }}>Coach notes per job</h3>
        <div style={{ display: "grid", gap: 10, marginTop: 12 }}>
          {summaries.length === 0 && <p style={{ color: "var(--ink-3)", fontSize: 14 }}>None yet — they appear as jobs get approved.</p>}
          {summaries.map((s) => (
            <div key={s.id} className="card" style={{ padding: 16 }}>
              <div className="eyebrow">{jobTitle(s.job_id)} · {new Date(s.created_at).toLocaleDateString()}</div>
              <p style={{ fontSize: 14, marginTop: 6 }}>{s.summary}</p>
            </div>
          ))}
        </div>
      </div>

      {/* job editor */}
      {editing && (
        <div style={{ position: "fixed", inset: 0, zIndex: 70, background: "rgba(26,26,26,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}
          onClick={(e) => { if (e.target === e.currentTarget) setEditing(null); }}>
          <div className="card" style={{ width: "min(680px,100%)", maxHeight: "88vh", overflowY: "auto", background: "var(--cream)" }}>
            <h3 className="serif" style={{ fontSize: 24 }}>Edit {editing.id}</h3>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 14px" }}>
              <F label="ID" k="id" /><F label="Sort order" k="sort_order" />
              <F label="Phase (number)" k="phase" /><F label="Phase label" k="phase_label" />
              <F label="Payout $" k="payout_usd" /><F label="ETA" k="eta" />
            </div>
            <F label="Title" k="title" />
            <F label="Brief (she sees this)" k="brief" rows={4} />
            <F label="Deliverable spec (she sees this)" k="deliverable_spec" rows={2} />
            <F label="Rubric (HIDDEN from her)" k="rubric" rows={4} />
            <F label="Skill (HIDDEN from her)" k="skill" />
            <label style={{ display: "block", marginTop: 10 }}>
              <span className="field-label">Status</span>
              <select className="select" style={{ width: "100%" }} value={editing.status}
                onChange={(e) => setEditing({ ...editing, status: e.target.value })}>
                {Object.keys(BD_STATUS).map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
            </label>
            <div style={{ display: "flex", gap: 10, marginTop: 16, flexWrap: "wrap" }}>
              <button className="btn" disabled={!!busyOp} onClick={async () => {
                await op("job_upsert", {
                  ...editing,
                  sort_order: Number(editing.sort_order), phase: Number(editing.phase), payout_usd: Number(editing.payout_usd),
                });
                setEditing(null);
              }}>Save</button>
              <button className="btn btn--ghost" onClick={() => setEditing(null)}>Cancel</button>
              <button className="btn btn--ghost" style={{ marginLeft: "auto", color: "var(--terracotta-deep)" }} disabled={!!busyOp}
                onClick={async () => { if (confirm("Delete " + editing.id + "?")) { await op("job_delete", { id: editing.id }); setEditing(null); } }}>Delete</button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}

Object.assign(window, { WorkLoginPage, JobsPage, AdminPage, bdSession });
