/* Feedback — DEMO-ONLY per-section comment instrument + admin review tab.
   Lets task-force demo users leave a comment on the specific section they're
   viewing. Each submission records who (user_id + email), when (created_at), and
   where (page + section) via window.LedgerAPI.submitFeedback → ledger_feedback.

   This whole module is temporary: it gets pulled out at go-live. To remove,
   delete this file + its <script> tag in index.html, the `feedback` nav entry
   (config.js), the route case/guard/ready lines (app.jsx), and grep
   `LedgerComment` to strip the placed tags. See status/app.md.

   Assigns:
     window.LedgerComment       — <CommentDot section="…" [context="…"] /> affordance
     window.LedgerFeedbackAdmin — admin-only review tab */
(function () {
  // The current page label is set by app.jsx each render
  // (window.LedgerFeedbackCtx.page); MatterDetail adds the open matter as context.
  function currentPage() {
    return (window.LedgerFeedbackCtx && window.LedgerFeedbackCtx.page) || "App";
  }
  function currentContext() {
    return (window.LedgerFeedbackCtx && window.LedgerFeedbackCtx.context) || null;
  }

  // ── window.LedgerComment — drop next to any section/card header ─────────────
  function CommentDot({ section, context }) {
    const [open, setOpen] = React.useState(false);
    const [text, setText] = React.useState("");
    const [busy, setBusy] = React.useState(false);
    const [done, setDone] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const wrap = React.useRef(null);
    const ta = React.useRef(null);

    React.useEffect(() => { setTimeout(() => window.lucide && window.lucide.createIcons(), 10); }, [open, done]);

    React.useEffect(() => {
      if (!open) return;
      function onDoc(e) { if (wrap.current && !wrap.current.contains(e.target)) close(); }
      function onEsc(e) { if (e.key === "Escape") close(); }
      document.addEventListener("mousedown", onDoc);
      document.addEventListener("keydown", onEsc);
      setTimeout(() => ta.current && ta.current.focus(), 20);
      return () => { document.removeEventListener("mousedown", onDoc); document.removeEventListener("keydown", onEsc); };
    }, [open]);

    function close() { setOpen(false); setErr(null); }
    function toggle() { if (open) close(); else { setDone(false); setOpen(true); } }

    async function submit() {
      const t = text.trim();
      if (!t) return;
      setBusy(true); setErr(null);
      try {
        await window.LedgerAPI.submitFeedback({
          page: currentPage(), section, context: context || currentContext(), comment: t,
        });
        setText(""); setOpen(false); setDone(true);
        setTimeout(() => setDone(false), 2600);
      } catch (e) { setErr(e.message || String(e)); }
      finally { setBusy(false); }
    }
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); submit(); }
    }

    return (
      <span className="cmt" ref={wrap}>
        <button type="button"
          className={"cmt-dot" + (open ? " cmt-dot--on" : "") + (done ? " cmt-dot--done" : "")}
          onClick={toggle} aria-label={`Comment on ${section}`}
          title={done ? "Comment sent" : `Comment on “${section}”`}>
          <i data-lucide={done ? "check" : "message-square-plus"} />
        </button>
        {open && (
          <div className="cmt-pop" role="dialog" aria-label={`Comment on ${section}`}>
            <div className="cmt-pop__head">
              <span className="cmt-pop__sect">{section}</span>
              <span className="cmt-pop__page">{currentPage()}</span>
            </div>
            <textarea ref={ta} className="cmt-pop__ta" rows={4} value={text}
              placeholder="What works, what's confusing, what's missing…"
              onChange={(e) => setText(e.target.value)} onKeyDown={onKey} />
            {err && <div className="cmt-pop__err">{err}</div>}
            <div className="cmt-pop__foot">
              <span className="cmt-pop__hint">⌘↵ to send</span>
              <span style={{ flex: 1 }} />
              <button type="button" className="cmt-pop__cancel" onClick={close} disabled={busy}>Cancel</button>
              <button type="button" className="cmt-pop__send" onClick={submit} disabled={busy || !text.trim()}>
                {busy ? "Sending…" : "Send"}
              </button>
            </div>
          </div>
        )}
      </span>
    );
  }

  // ── window.LedgerFeedbackAdmin — admin-only review tab ──────────────────────
  function FeedbackAdmin() {
    const { Badge } = window.LawCrimeDesignSystem_e18d68;
    const [rows, setRows] = React.useState(null);
    const [err, setErr] = React.useState(null);

    const load = React.useCallback(async () => {
      setErr(null);
      try { setRows(await window.LedgerAPI.listFeedback()); }
      catch (e) { setErr(e.message || String(e)); }
    }, []);
    React.useEffect(() => { load(); }, [load]);
    React.useEffect(() => { setTimeout(() => window.lucide && window.lucide.createIcons(), 20); });

    function fmt(ts) { try { return new Date(ts).toLocaleString(); } catch (e) { return ts; } }

    return (
      <div>
        <div className="page-head">
          <div>
            <div className="eyebrow">Administration · Feedback</div>
            <h1 className="page-title">Feedback</h1>
          </div>
          <button className="access-btn" onClick={load} title="Reload"><i data-lucide="refresh-cw" /> Refresh</button>
        </div>
        <p style={{ color: "var(--text-muted)", fontSize: 13, maxWidth: 760, marginTop: -4 }}>
          Comments demo users leave on individual sections, newest first. Each row records who
          submitted it, when, and the page + section they were viewing. <b>Demo-only</b> — this
          surface is removed at go-live.
        </p>

        {err && <div className="login__err" style={{ margin: "12px 0" }}>{err}</div>}
        {rows === null && !err && <div className="ai-empty">Loading…</div>}
        {rows && rows.length === 0 && <div className="ai-empty">No comments yet.</div>}
        {rows && rows.length > 0 && (
          <table className="access-table fb-table">
            <thead>
              <tr><th>When</th><th>Who</th><th>Page</th><th>Section</th><th>Comment</th></tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.feedback_id}>
                  <td className="access-when fb-when">{fmt(r.created_at)}</td>
                  <td className="fb-who">{r.user_email || "—"}</td>
                  <td>{r.page || "—"}{r.context ? <span className="fb-ctx"> · {r.context}</span> : null}</td>
                  <td>{r.section ? <Badge>{r.section}</Badge> : "—"}</td>
                  <td className="fb-comment">{r.comment}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    );
  }

  window.LedgerComment = CommentDot;
  window.LedgerFeedbackAdmin = FeedbackAdmin;
})();
