// CORE-08 · Role & permissions matrix  (route: permissions)  — Admin Web
// Configure permissions per role.
const PermissionsPage = ({ tweaks }) => {
  const Ic = window.Icons;
  const toast = useToast();
  const MD = window.MD;
  const initRole = (tweaks && tweaks.permRole) || "procurement-officer";
  const [roleId, setRoleId] = useState(initRole);
  useEffect(() => { if (tweaks && tweaks.permRole) setRoleId(tweaks.permRole); }, [tweaks && tweaks.permRole]);

  const role = MD.ROLES.find(r => r.id === roleId) || MD.ROLES[0];
  const LEVELS = MD.PERM_LEVELS; // none view edit approve full
  const LEVEL_IC = { none: Ic.X, view: Ic.Eye, edit: Ic.Edit, approve: Ic.Check, full: Ic.Shield };
  const LEVEL_LABEL = { none: "None", view: "View", edit: "Edit", approve: "Approve", full: "Full" };

  // local editable copy of perms
  const [perms, setPerms] = useState(role.perms);
  useEffect(() => { setPerms(role.perms); }, [roleId]);
  const [dirty, setDirty] = useState(false);
  const setLevel = (modKey, lvl) => { setPerms(p => ({ ...p, [modKey]: lvl })); setDirty(true); };

  return (
    <div className="page" style={{ maxWidth: 1320 }}>
      <div className="page-head">
        <div><h1 className="page-title">Roles &amp; permissions</h1><div className="page-sub">Configure module access per role · {MD.ROLES.length} roles</div></div>
        <div className="page-actions">
          <Button variant="outline" icon={Ic.UserPlus} onClick={()=> toast({ title: "New role", desc: "Create a custom role" })}>New role</Button>
          <Button variant="primary" icon={Ic.Check} disabled={!dirty} onClick={()=> { setDirty(false); toast({ title: `${role.name} permissions saved` }); }}>Save changes</Button>
        </div>
      </div>

      <div className="rbac-layout">
        {/* Role list */}
        <Card>
          <CardHead title="Roles"/>
          <div className="card-body" style={{ paddingTop: 4 }}>
            <div className="rbac-roles">
              {MD.ROLES.map(r => (
                <button key={r.id} className={`rbac-role ${r.id === roleId ? "on" : ""}`} onClick={()=> setRoleId(r.id)}>
                  <span className="rbac-role-ic">{r.system ? <Ic.ShieldCheck size={16}/> : <Ic.Shield size={16}/>}</span>
                  <div style={{ flex: 1, minWidth: 0 }}><div className="nm">{r.name}</div><div className="ct">{r.users} {r.users === 1 ? "user" : "users"}{r.system ? " · system" : ""}</div></div>
                  {r.id === roleId && <Ic.ChevronRight size={15} style={{ color: "var(--avocado-fg)" }}/>}
                </button>
              ))}
            </div>
          </div>
        </Card>

        {/* Matrix */}
        <Card>
          <CardHead title={role.name} desc={role.desc}
            action={role.system ? <span className="badge badge-soil"><Ic.Lock size={11}/> System role — locked</span> : <span className="badge badge-avocado">{role.users} {role.users === 1 ? "user" : "users"}</span>}/>
          <div className="card-body" style={{ paddingTop: 4 }}>
            <div className="perm-legend" style={{ marginBottom: 14 }}>
              <span><span className="dot-sm" style={{ background: "var(--muted-foreground)" }}/>None</span>
              <span><span className="dot-sm" style={{ background: "var(--info)" }}/>View</span>
              <span><span className="dot-sm" style={{ background: "var(--avocado)" }}/>Edit</span>
              <span><span className="dot-sm" style={{ background: "oklch(0.55 0.13 145)" }}/>Approve</span>
              <span><span className="dot-sm" style={{ background: "var(--soil)" }}/>Full</span>
            </div>
            <div className="tbl-wrap">
              <table className="rbac-matrix">
                <thead><tr><th>Module</th>{LEVELS.map(l => <th key={l}>{LEVEL_LABEL[l]}</th>)}</tr></thead>
                <tbody>
                  {MD.MODULES.map(m => {
                    const cur = perms[m.key] || "none";
                    return (
                      <tr key={m.key}>
                        <td>{m.label}</td>
                        {LEVELS.map(l => {
                          const LI = LEVEL_IC[l];
                          const on = cur === l;
                          return (
                            <td key={l}>
                              <button className={`perm-cell${on ? " on lvl-" + l : ""}`} title={LEVEL_LABEL[l]}
                                onClick={()=> !role.system && setLevel(m.key, l)}
                                style={role.system ? { cursor: "not-allowed", opacity: on ? 1 : 0.45 } : undefined}>
                                <LI size={14}/>
                              </button>
                            </td>
                          );
                        })}
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
            {role.system && <div className="field-hint" style={{ marginTop: 12, display: "flex", gap: 7, alignItems: "center" }}><Ic.Info size={13}/> The System Administrator role has full access to every module and cannot be edited.</div>}
          </div>
        </Card>
      </div>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { permissions: PermissionsPage });
