/* ============================================================
   HALO SMS — shared form & detail helpers (window globals)
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  function fmtDate(d) { if (!d) return "—"; const x = new Date(d); if (isNaN(x)) return d; return x.toLocaleDateString("en-NG", { day: "numeric", month: "short", year: "numeric" }); }

  function PageHead({ eyebrow, title, sub, actions, back }) {
    return h("div", null,
      back && h(Button, { kind: "quiet", icon: "arrowleft", onClick: back.onClick, style: { marginBottom: 14 } }, back.label),
      h("div", { style: { display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 20, flexWrap: "wrap" } },
        h("div", null,
          eyebrow && h("div", { className: "eyebrow", style: { marginBottom: 7 } }, eyebrow),
          h("h1", { style: { fontSize: 27 } }, title),
          sub && h("div", { className: "muted", style: { fontSize: 13.5, marginTop: 4 } }, sub)),
        actions && h("div", { className: "wrap-actions noprint" }, actions)));
  }

  // form section (label-left layout)
  function FSection({ step, title, desc, children }) {
    return h("div", { className: "formsec" },
      h("div", { className: "secinfo" }, step && h("div", { className: "step" }, "STEP " + step), h("h3", { style: { marginTop: step ? 4 : 0 } }, title), desc && h("p", null, desc)),
      h("div", null, children));
  }
  function Fld(label, opts, control) {
    opts = opts || {};
    return h(Field, { label, required: opts.req, error: opts.error, hint: opts.hint, full: opts.full }, control);
  }

  // detail block (card with kv grid)
  function DetailBlock({ title, action, cols = 3, children }) {
    return h("div", { className: "card", style: { marginBottom: 16 } },
      h("div", { className: "card-h" }, h("h3", null, title), action),
      h("div", { className: "card-pad", style: { display: "grid", gridTemplateColumns: `repeat(${cols},1fr)`, gap: 18 } }, children));
  }
  function KVRow({ k, v }) { return h("div", { className: "kv" }, h("span", { className: "k" }, k), h("span", { className: "v" }, v == null || v === "" ? "—" : v)); }

  function Dropzone({ label }) {
    const [done, setDone] = useState(false);
    return h("button", { type: "button", onClick: () => { setDone(true); toast(label + " attached"); },
      style: { border: "1.5px dashed var(--line)", borderRadius: 12, background: done ? "var(--ok-bg)" : "var(--surface-2)", padding: "20px 14px", display: "flex", flexDirection: "column", alignItems: "center", gap: 8, color: done ? "var(--ok-fg)" : "var(--ink-500)", textAlign: "center", width: "100%" } },
      h(Icon, { name: done ? "check" : "upload", style: { fontSize: 20 } }),
      h("span", { style: { fontSize: 13, fontWeight: 600 } }, label),
      h("span", { style: { fontSize: 11.5 } }, done ? "Attached" : "Click to upload"));
  }

  // confirm modal (reason optional)
  function ConfirmModal({ icon = "alert", tone = "warn", title, body, confirmLabel, danger, needReason, reasonHint, onClose, onConfirm }) {
    const [reason, setReason] = useState("");
    return h(Modal, { icon, iconTone: danger ? "bad" : tone, title, onClose,
      footer: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: onClose }, "Cancel"),
        h(Button, { kind: danger ? "danger" : "primary", disabled: needReason && !reason.trim(), onClick: () => onConfirm(reason) }, confirmLabel)) },
      body && h("p", { style: { fontSize: 14, color: "var(--ink-600)", lineHeight: 1.55, marginBottom: needReason ? 14 : 0 } }, body),
      needReason && h(Field, { label: "Reason", required: true, hint: reasonHint || "Recorded in the audit log" },
        h(Textarea, { value: reason, onChange: (e) => setReason(e.target.value), placeholder: "Add a brief reason…" })));
  }

  // desktop-only wrapper -> graceful mobile redirect
  function DesktopScreen({ title, children }) {
    return h(React.Fragment, null,
      h("div", { className: "desktop-only" }, children),
      h("div", { className: "mobile-only" },
        h("div", { className: "page-pad" }, h("div", { className: "card" },
          h("div", { className: "deskonly" },
            h("div", { className: "glyph" }, h(Icon, { name: "staff" })),
            h("h3", null, "Best viewed on desktop"),
            h("p", null, (title || "This screen") + " is a dense management view built for a wider screen. Open Halo on a laptop to work here — your dashboard snapshot stays available on mobile."))))));
  }

  // account-admin actions modal (reset password / status)
  function AccountAdminModal({ subject, onClose, onAction }) {
    const [view, setView] = useState("menu");
    if (view === "reset") return h(ConfirmModal, { icon: "key", tone: "brand", title: "Reset password",
      body: "A temporary password will be generated for " + subject.name + ". They'll be forced to set a new one on next sign-in.",
      confirmLabel: "Reset & send invite", onClose, onConfirm: () => { onAction("reset"); onClose(); } });
    if (view === "disable") return h(ConfirmModal, { icon: "lock", tone: "warn", danger: true, title: "Disable login",
      body: "This blocks " + subject.name + " from signing in. Their data is kept and access can be restored anytime.",
      confirmLabel: "Disable login", needReason: true, onClose, onConfirm: () => { onAction("disable"); onClose(); } });
    return h(Modal, { icon: "shield", title: "Manage account · " + subject.name, onClose,
      footer: h(Button, { kind: "ghost", onClick: onClose }, "Close") },
      h("div", { style: { display: "flex", alignItems: "center", gap: 9, padding: "10px 12px", borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--line)", marginBottom: 12, fontSize: 13 } },
        h("span", { className: "chip " + (subject.disabled ? "chip-bad" : subject.locked ? "chip-warn" : "chip-ok") }, subject.disabled ? "Login disabled" : subject.locked ? "Locked" : "Active"),
        h("span", { className: "muted" }, subject.email || "")),
      h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
        actionRow("key", "Reset password", "Force a password change on next login", () => setView("reset")),
        actionRow("mail", "Resend invite", "Email a fresh sign-in link", () => { onAction("invite"); onClose(); }),
        actionRow("google", "Unlink Google", "Remove the linked Google sign-in method", () => { onAction("unlink"); onClose(); }),
        subject.disabled
          ? actionRow("key", "Re-enable login", "Restore sign-in for this account", () => { onAction("enable"); onClose(); })
          : actionRow("lock", "Lock for 24 hours", "Temporary lock — auto-restores", () => { onAction("lock"); onClose(); }),
        actionRow("lock", "Disable login", "Block sign-in without deleting data", () => setView("disable"), true)));
  }
  function actionRow(icon, title, sub, onClick, danger) {
    return h("button", { onClick, style: { display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", borderRadius: 11, border: "1px solid var(--line)", background: "var(--surface)", textAlign: "left", width: "100%" } },
      h("div", { className: "iconbtn", style: { cursor: "pointer", color: danger ? "var(--bad-fg)" : "var(--ink-700)" } }, h(Icon, { name: icon })),
      h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14, color: danger ? "var(--bad-fg)" : "inherit" } }, title), h("div", { className: "muted", style: { fontSize: 12.5 } }, sub)),
      h(Icon, { name: "chevright", style: { color: "var(--ink-400)" } }));
  }

  Object.assign(window, { fmtDate, PageHead, FSection, Fld, DetailBlock, KVRow, Dropzone, ConfirmModal, DesktopScreen, AccountAdminModal });
})();
