/* ============================================================
   Screen: Staff Directory & Settings
   ============================================================ */
(function () {
  const DB = window.DB;
  const TABS = [["directory", "Directory"], ["roles", "Roles & Access"], ["audit", "Audit log"]];
  const TRAIN = { current: { label: "Current", cls: "stable" }, expiring: { label: "Expiring", cls: "watch" }, gap: { label: "Gap", cls: "crit" }, "n/a": { label: "—", cls: "" } };
  const LAST = { "T-01": "12m ago", "T-02": "1h ago", "T-03": "3h ago", "T-04": "Yesterday", "T-05": "2h ago", "T-06": "Yesterday", "T-07": "45m ago", "T-08": "4h ago", "T-09": "2d ago", "T-10": "5h ago", "T-11": "3d ago", "T-12": "Yesterday" };

  // role × capability matrix
  const ROLES = [
    { k: "dir", label: "Exec Director" }, { k: "acad", label: "Academic Dir." }, { k: "reg", label: "Registrar" },
    { k: "subj", label: "Subject Tchr" }, { k: "home", label: "Homeroom" }, { k: "couns", label: "Counsellor" },
  ];
  const CAPS = [
    { cap: "At-Risk Radar", a: { dir: "full", acad: "full", reg: "view", subj: "own", home: "own", couns: "view" } },
    { cap: "Student 360° profile", a: { dir: "full", acad: "full", reg: "view", subj: "own", home: "own", couns: "view" } },
    { cap: "Behaviour escalation & sign-off", a: { dir: "full", acad: "full", reg: "none", subj: "own", home: "own", couns: "view" } },
    { cap: "ILP — medical / diagnostic", a: { dir: "none", acad: "none", reg: "none", subj: "none", home: "none", couns: "full" } },
    { cap: "Compliance Cockpit", a: { dir: "full", acad: "full", reg: "view", subj: "none", home: "none", couns: "none" } },
    { cap: "IA / EE Monitor", a: { dir: "full", acad: "full", reg: "view", subj: "own", home: "none", couns: "none" } },
    { cap: "Document Hub", a: { dir: "full", acad: "full", reg: "view", subj: "view", home: "view", couns: "view" } },
    { cap: "Staff admin & roles", a: { dir: "full", acad: "none", reg: "none", subj: "none", home: "none", couns: "none" } },
    { cap: "Audit log", a: { dir: "full", acad: "view", reg: "none", subj: "none", home: "none", couns: "none" } },
  ];
  const CELL = { full: { t: "Full", c: "var(--stable)", b: "var(--stable-soft)" }, view: { t: "View", c: "var(--info)", b: "oklch(0.95 0.03 230)" }, own: { t: "Own only", c: "oklch(0.5 0.12 90)", b: "var(--monitor-soft)" }, none: { t: "—", c: "var(--faint)", b: "transparent" } };

  const AUDIT = [
    { t: "2026-06-04 09:42", who: "T-07", act: "confidential", what: "Viewed medical & diagnostic fields", tgt: "Elyor D. (S-108)" },
    { t: "2026-06-04 08:15", who: "T-02", act: "approve", what: "Approved Red Report — week 2", tgt: "Dilnoza R. (S-101)" },
    { t: "2026-06-03 16:30", who: "T-01", act: "export", what: "Exported IB readiness report", tgt: "Compliance Cockpit" },
    { t: "2026-06-03 14:02", who: "T-03", act: "edit", what: "Updated enrolment record", tgt: "Bekzod U. (S-102)" },
    { t: "2026-06-03 11:20", who: "T-04", act: "edit", what: "Submitted IA mark & late penalty", tgt: "Chemistry HL — Dilnoza R." },
    { t: "2026-06-02 15:48", who: "T-05", act: "edit", what: "Amended attendance marks", tgt: "Class A · Week 8" },
    { t: "2026-06-02 10:05", who: "T-02", act: "approve", what: "Granted IA extension (medical)", tgt: "Sevara N. (S-105)" },
    { t: "2026-06-01 17:30", who: "T-01", act: "invite", what: "Invited new staff member", tgt: "pending · Subject Teacher" },
    { t: "2026-06-01 09:12", who: "T-07", act: "edit", what: "Updated ILP review & next date", tgt: "Sevara N. (S-105)" },
    { t: "2026-05-30 13:40", who: "T-06", act: "view", what: "Viewed At-Risk Radar", tgt: "Class A" },
    { t: "2026-05-29 16:10", who: "T-02", act: "approve", what: "Escalated Yellow → Red Report", tgt: "Timur A. (S-104)" },
    { t: "2026-05-29 08:30", who: "T-01", act: "edit", what: "Changed role permissions", tgt: "Charlotte M. → Subject Teacher" },
  ];
  const ACT = { confidential: { ic: "compliance", c: "var(--critical)" }, approve: { ic: "check", c: "var(--stable)" }, export: { ic: "download", c: "var(--info)" }, edit: { ic: "note", c: "var(--accent)" }, invite: { ic: "plus", c: "oklch(0.5 0.14 300)" }, view: { ic: "search", c: "var(--muted)" } };

  function StaffSettings({ navigate }) {
    const [tab, setTab] = React.useState("directory");
    const [q, setQ] = React.useState("");
    const [roleF, setRoleF] = React.useState("all");
    const [invite, setInvite] = React.useState(false);
    const [pending, setPending] = React.useState([]);
    const [form, setForm] = React.useState({ name: "", email: "", role: "Subject Teacher" });
    const [menuFor, setMenuFor] = React.useState(null);

    const staff = DB.TEACHERS.filter((tch) => (roleF === "all" || tch.role.includes(roleF)) && (!q || tch.name.toLowerCase().includes(q.toLowerCase()) || tch.role.toLowerCase().includes(q.toLowerCase())));
    const roleOpts = ["Executive Director", "Academic Director / IB Coordinator", "Registrar", "Subject Teacher", "Homeroom Teacher", "Counsellor"];

    const sendInvite = () => {
      if (!form.email.trim()) return;
      setPending((p) => [{ ...form, name: form.name || form.email.split("@")[0], id: "P-" + Date.now() }, ...p]);
      setInvite(false); setForm({ name: "", email: "", role: "Subject Teacher" });
    };

    return (
      <div className="screen">
        <div className="between" style={{ marginBottom: 16 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{t("Staff Directory & Settings")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t("Manage staff, roles and access — and review who accessed what.")}</p>
          </div>
          <button className="btn btn-sm btn-primary" onClick={() => setInvite(true)}><Icon name="plus" size={14} />{t("Invite staff")}</button>
        </div>

        {/* tabs */}
        <div className="subtabs">
          {TABS.map(([k, label]) => (
            <button key={k} className={"subtab" + (tab === k ? " on" : "")} onClick={() => setTab(k)}>{t(label)}{k === "audit" ? <span className="sb-count mono" style={{ marginLeft: 6 }}>{AUDIT.length}</span> : null}</button>
          ))}
        </div>

        {/* DIRECTORY */}
        {tab === "directory" ? (
          <React.Fragment>
            <div className="toolbar">
              <select className="input" style={{ width: "auto", height: 32 }} value={roleF} onChange={(e) => setRoleF(e.target.value)}>
                <option value="all">{t("All roles")}</option>
                <option value="Director">{t("Directors")}</option><option value="Teacher">{t("Teachers")}</option>
                <option value="Registrar">{t("Registrar")}</option><option value="Counsellor">{t("Counsellor")}</option>
              </select>
              <div className="tb-input" style={{ marginLeft: "auto" }}><Icon name="search" size={15} /><input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("Search staff…")} /></div>
            </div>
            <div className="panel" style={{ overflow: "hidden" }}>
              <div style={{ overflowX: "auto" }}>
              <table className="tbl staff-tbl">
                <thead><tr><th>{t("Name")}</th><th>{t("Role")}</th><th>{t("Subjects")}</th><th style={{ width: 110 }}>{t("IB training")}</th><th style={{ width: 100 }}>{t("Last active")}</th><th style={{ width: 40 }}></th></tr></thead>
                <tbody>
                  {pending.map((p) => (
                    <tr key={p.id} style={{ background: "var(--accent-soft)" }}>
                      <td><div className="row" style={{ gap: 9 }}><Avatar name={p.name} color="#9aa3b2" size={26} /><span style={{ fontWeight: 600, fontSize: 12.5 }}>{p.name}</span></div></td>
                      <td style={{ fontSize: 12.5 }}>{t(p.role)}</td>
                      <td className="faint" style={{ fontSize: 12 }}>—</td>
                      <td><span className="badge">{t("Pending")}</span></td>
                      <td className="muted mono" style={{ fontSize: 11 }}>{p.email}</td>
                      <td><span className="badge accent">{t("Invited")}</span></td>
                    </tr>
                  ))}
                  {staff.map((tch) => {
                    const tr = TRAIN[tch.training];
                    return (
                      <tr key={tch.id}>
                        <td><div className="row" style={{ gap: 9 }}><Avatar name={tch.name} color={tch.avatar} size={26} /><div><div style={{ fontWeight: 600, fontSize: 12.5 }}>{tch.name}</div><div className="muted mono" style={{ fontSize: 10 }}>{tch.email}</div></div></div></td>
                        <td style={{ fontSize: 12.5, whiteSpace: "nowrap" }}>{t(tch.role)}</td>
                        <td><div className="row wrap" style={{ gap: 4 }}>{tch.subjects.length ? tch.subjects.map((s, i) => <span key={i} className="reason-pill" style={{ fontSize: 10, padding: "2px 7px" }}>{s}</span>) : <span className="faint" style={{ fontSize: 11 }}>—</span>}</div></td>
                        <td>{tch.training === "n/a" ? <span className="faint" style={{ fontSize: 12 }}>—</span> : <span className={"badge " + tr.cls}><span className="dot"></span>{t(tr.label)}</span>}</td>
                        <td className="muted mono" style={{ fontSize: 11 }}>{t(LAST[tch.id])}</td>
                        <td style={{ position: "relative" }}>
                          <button className="icon-btn" onClick={() => setMenuFor(menuFor === tch.id ? null : tch.id)}><Icon name="dots" size={16} /></button>
                          {menuFor === tch.id ? (
                            <div className="tb-pop" style={{ right: 8, minWidth: 190 }} onMouseLeave={() => setMenuFor(null)}>
                              {[["settings", "Edit role & access"], ["send", "Message"], ["compliance", "View training record"], ["logout", "Deactivate account"]].map(([ic, label]) => (
                                <button key={label} className="tb-pop-item" onClick={() => { setMenuFor(null); window.toast(t(label) + " · " + tch.name); }}>
                                  <Icon name={ic} size={15} />{t(label)}
                                </button>
                              ))}
                            </div>
                          ) : null}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              </div>
            </div>
          </React.Fragment>
        ) : null}

        {/* ROLES & ACCESS */}
        {tab === "roles" ? (
          <React.Fragment>
            <div className="row wrap" style={{ gap: 14, marginBottom: 14 }}>
              {Object.entries(CELL).map(([k, v]) => k === "none" ? null : (
                <span key={k} className="row" style={{ gap: 6 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: v.b, border: "1px solid " + v.c }}></span><span style={{ fontSize: 11.5, color: "var(--muted)" }}>{t(v.t)}</span></span>
              ))}
              <span className="muted" style={{ fontSize: 11.5, marginLeft: "auto" }}>{t("The role you switch with (top-right) changes what the whole portal shows.")}</span>
            </div>
            <div className="panel" style={{ overflow: "hidden" }}>
              <div style={{ overflowX: "auto" }}>
                <table className="tbl access-matrix">
                  <thead><tr><th style={{ minWidth: 220 }}>{t("Capability")}</th>{ROLES.map((r) => <th key={r.k} className="num" style={{ width: 110 }}>{t(r.label)}</th>)}</tr></thead>
                  <tbody>
                    {CAPS.map((row) => (
                      <tr key={row.cap}>
                        <td style={{ fontWeight: 500, fontSize: 12.5 }}>{t(row.cap)}</td>
                        {ROLES.map((r) => {
                          const v = CELL[row.a[r.k]];
                          return <td key={r.k} style={{ textAlign: "center" }}><span className="acc-cell" style={{ color: v.c, background: v.b, borderColor: row.a[r.k] === "none" ? "transparent" : v.c }}>{row.a[r.k] === "none" ? "·" : t(v.t)}</span></td>;
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </React.Fragment>
        ) : null}

        {/* AUDIT LOG */}
        {tab === "audit" ? (
          <div className="panel">
            <div className="panel-h"><h3>{t("Access audit log")}</h3><span className="muted" style={{ fontSize: 11.5 }}>{t("Immutable · last 30 days")}</span></div>
            <div>
              {AUDIT.map((e, i) => {
                const a = ACT[e.act]; const who = DB.teacher(e.who);
                return (
                  <div key={i} className="audit-row">
                    <span className="audit-ic" style={{ color: a.c, background: "color-mix(in oklab, " + a.c + " 12%, transparent)" }}><Icon name={a.ic} size={14} /></span>
                    <Avatar name={who.name} color={who.avatar} size={24} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5 }}><b>{who.name}</b> <span className="muted">{t(e.what)}</span></div>
                      <div className="muted" style={{ fontSize: 11, marginTop: 1 }}>{t(who.role)} · <span style={{ color: "var(--ink-2)" }}>{e.tgt}</span></div>
                    </div>
                    {e.act === "confidential" ? <span className="badge crit" style={{ marginRight: 8 }}><Icon name="compliance" size={11} />{t("Confidential")}</span> : null}
                    <span className="mono faint" style={{ fontSize: 10.5, whiteSpace: "nowrap" }}>{e.t}</span>
                  </div>
                );
              })}
            </div>
          </div>
        ) : null}

        {/* INVITE MODAL */}
        {invite ? (
          <div className="cmd-overlay" onMouseDown={() => setInvite(false)} style={{ alignItems: "center", paddingTop: 0 }}>
            <div className="invite-modal" onMouseDown={(e) => e.stopPropagation()}>
              <div className="between" style={{ marginBottom: 4 }}><h3 style={{ fontSize: 16 }}>{t("Invite a staff member")}</h3><button className="icon-btn" onClick={() => setInvite(false)}><Icon name="close" size={18} /></button></div>
              <p className="muted" style={{ fontSize: 12.5, marginBottom: 18 }}>{t("They'll receive a secure invite. Their role determines exactly what they can see.")}</p>
              <div className="col" style={{ gap: 14 }}>
                <div className="field"><label>{t("Full name")}</label><input className="input" placeholder={t("e.g. Anvar T.")} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
                <div className="field"><label>{t("Work email")}</label><input className="input" placeholder="name@al-beruni.uz" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></div>
                <div className="field"><label>{t("Role")}</label><select className="input" value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>{roleOpts.map((r) => <option key={r} value={r}>{t(r)}</option>)}</select></div>
              </div>
              <div className="row" style={{ gap: 8, marginTop: 22, justifyContent: "flex-end" }}>
                <button className="btn" onClick={() => setInvite(false)}>{t("Cancel")}</button>
                <button className="btn btn-primary" onClick={sendInvite} disabled={!form.email.trim()}><Icon name="send" size={14} />{t("Send invite")}</button>
              </div>
            </div>
          </div>
        ) : null}
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.staff = StaffSettings;
})();
