/* global React, Icon, Chip, Button, api */

/* ─── Module definitions ─── */
const PERM_MODULES = [
  { id: "dashboard",      label: "Dashboard",          icon: "layout-dashboard", group: "Operations" },
  { id: "leads",          label: "Leads",               icon: "inbox",            group: "Operations" },
  { id: "customers",      label: "Customers",           icon: "users",            group: "Operations" },
  { id: "engagements",    label: "Engagements",         icon: "briefcase",        group: "Operations" },
  { id: "renewals",       label: "Renewals",            icon: "calendar-clock",   group: "Operations" },
  { id: "payments",       label: "Payments",            icon: "wallet",           group: "Operations" },
  { id: "documents",      label: "Documents",           icon: "folder",           group: "Operations" },
  { id: "services",       label: "Service Catalogue",   icon: "list-checks",      group: "Setup"      },
  { id: "service-master", label: "Service Master",      icon: "layout-list",      group: "Setup"      },
  { id: "sub-services",   label: "Sub-service Master",  icon: "list-tree",        group: "Setup"      },
  { id: "stage-master",   label: "Stage Master",        icon: "layers",           group: "Setup"      },
  { id: "team",           label: "Team & Roles",        icon: "user-cog",         group: "Setup"      },
  { id: "roles",          label: "Roles & Permissions", icon: "shield-check",     group: "Setup"      },
  { id: "integrations",   label: "Integrations",        icon: "plug",             group: "Setup"      },
];

const PERM_KEYS   = ["view", "create", "edit", "delete"];
const PERM_GROUPS = ["Operations", "Setup"];

const ROLE_COLORS = [
  { hex: "#7B1D3F", label: "Burgundy"  },
  { hex: "#4A2060", label: "Plum"      },
  { hex: "#1A5276", label: "Navy"      },
  { hex: "#1E6B3E", label: "Green"     },
  { hex: "#7E5109", label: "Amber"     },
  { hex: "#515A5A", label: "Slate"     },
  { hex: "#922B21", label: "Red"       },
  { hex: "#154360", label: "Indigo"    },
];

/* ─── Permission seed helpers ─── */
function makePerms(val) {
  return Object.fromEntries(
    PERM_MODULES.map(m => [m.id, Object.fromEntries(PERM_KEYS.map(p => [p, val]))])
  );
}
function seedPerms(grants) {
  const base = makePerms(false);
  Object.entries(grants).forEach(([mod, perms]) => {
    perms.forEach(p => { if (base[mod]) base[mod][p] = true; });
  });
  return base;
}

/* ─── Seed roles ─── */
const INITIAL_ROLES = [
  {
    id: "ROLE-001", name: "Super Admin",        initials: "SA", color: "#7B1D3F",
    desc: "Full access to all modules and settings.",
    users: 2, status: "active",
    permissions: makePerms(true),
  },
  {
    id: "ROLE-002", name: "Operations Manager", initials: "OM", color: "#4A2060",
    desc: "Manages engagements, customers, leads and team operations.",
    users: 3, status: "active",
    permissions: seedPerms({
      dashboard:   ["view"],
      leads:       ["view","create","edit"],
      customers:   ["view","create","edit"],
      engagements: ["view","create","edit"],
      renewals:    ["view","edit"],
      payments:    ["view"],
      documents:   ["view","create"],
      services:    ["view"],
      team:        ["view"],
    }),
  },
  {
    id: "ROLE-003", name: "PRO Officer",         initials: "PR", color: "#1A5276",
    desc: "Handles government liaison, document clearance and field engagements.",
    users: 4, status: "active",
    permissions: seedPerms({
      dashboard:   ["view"],
      leads:       ["view"],
      customers:   ["view"],
      engagements: ["view","edit"],
      renewals:    ["view"],
      documents:   ["view","create","edit"],
    }),
  },
  {
    id: "ROLE-004", name: "Finance Manager",     initials: "FM", color: "#1E6B3E",
    desc: "Manages payments, invoicing and financial reporting.",
    users: 1, status: "active",
    permissions: seedPerms({
      dashboard: ["view"],
      payments:  ["view","create","edit"],
      customers: ["view"],
      renewals:  ["view"],
      documents: ["view"],
    }),
  },
  {
    id: "ROLE-005", name: "Sales Executive",     initials: "SE", color: "#7E5109",
    desc: "Manages leads, customer onboarding and new service requests.",
    users: 2, status: "active",
    permissions: seedPerms({
      dashboard:   ["view"],
      leads:       ["view","create","edit"],
      customers:   ["view","create"],
      engagements: ["view"],
      services:    ["view"],
    }),
  },
  {
    id: "ROLE-006", name: "Viewer",              initials: "VW", color: "#515A5A",
    desc: "Read-only access to all operational modules.",
    users: 1, status: "active",
    permissions: seedPerms({
      dashboard:   ["view"],
      leads:       ["view"],
      customers:   ["view"],
      engagements: ["view"],
      renewals:    ["view"],
      payments:    ["view"],
      documents:   ["view"],
    }),
  },
];

function newRoleId() { return "ROLE-" + Date.now().toString(36).toUpperCase(); }

function autoInitials(name) {
  const words = name.trim().split(/\s+/).filter(Boolean);
  if (!words.length) return "";
  if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
  return (words[0][0] + words[words.length - 1][0]).toUpperCase();
}

/* ─── Permission toggle cell ─── */
function PermToggle({ active, onChange }) {
  return (
    <button type="button" title={active ? "Click to revoke" : "Click to grant"}
      onClick={() => onChange(!active)}
      style={{
        width: 32, height: 32, borderRadius: 7, border: "none", cursor: "pointer",
        display: "flex", alignItems: "center", justifyContent: "center",
        background: active ? "var(--plum-50)" : "var(--ink-50)",
        color:      active ? "var(--brand-burgundy)" : "var(--ink-300)",
        transition: "background 0.12s, color 0.12s",
      }}>
      <Icon name={active ? "check-circle-2" : "circle"} size={17} />
    </button>
  );
}

/* ─── Permission Matrix (right panel) ─── */
function PermissionMatrix({ role, onUpdate }) {
  const [perms,  setPerms]  = React.useState(() => JSON.parse(JSON.stringify(role.permissions)));
  const [saved,  setSaved]  = React.useState(false);
  const [dirty,  setDirty]  = React.useState(false);

  React.useEffect(() => {
    setPerms(JSON.parse(JSON.stringify(role.permissions)));
    setSaved(false);
    setDirty(false);
  }, [role.id]);

  const toggle = (modId, perm) => {
    setPerms(prev => ({ ...prev, [modId]: { ...prev[modId], [perm]: !prev[modId]?.[perm] } }));
    setDirty(true);
    setSaved(false);
  };

  const toggleColumn = perm => {
    const allOn = PERM_MODULES.every(m => perms[m.id]?.[perm]);
    setPerms(prev => {
      const next = { ...prev };
      PERM_MODULES.forEach(m => { next[m.id] = { ...next[m.id], [perm]: !allOn }; });
      return next;
    });
    setDirty(true);
    setSaved(false);
  };

  const toggleRow = modId => {
    const allOn = PERM_KEYS.every(p => perms[modId]?.[p]);
    setPerms(prev => ({ ...prev, [modId]: Object.fromEntries(PERM_KEYS.map(p => [p, !allOn])) }));
    setDirty(true);
    setSaved(false);
  };

  const handleSave = () => {
    onUpdate({ ...role, permissions: perms });
    setSaved(true);
    setDirty(false);
    setTimeout(() => setSaved(false), 2500);
  };

  const thStyle = {
    padding: "10px 14px", fontSize: 10.5, fontWeight: 700,
    color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.1em",
    textAlign: "center", width: 88,
  };

  return (
    <div>
      {/* Panel header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 20, gap: 12 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>Module permissions</h2>
          <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 3 }}>
            Configuring access for <b style={{ color: "var(--fg-1)" }}>{role.name}</b>
            {role.users > 0 && <span style={{ marginLeft: 6, color: "var(--fg-4)" }}>· {role.users} member{role.users !== 1 ? "s" : ""} assigned</span>}
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center", flexShrink: 0 }}>
          {saved && (
            <span style={{ fontSize: 13, color: "var(--success-700)", display: "flex", alignItems: "center", gap: 5 }}>
              <Icon name="check-circle-2" size={14} />Saved
            </span>
          )}
          <Button icon={saved ? "check" : "save"} onClick={handleSave} disabled={!dirty}>
            Save permissions
          </Button>
        </div>
      </div>

      {/* Legend */}
      <div style={{ display: "flex", gap: 16, marginBottom: 14, fontSize: 12, color: "var(--fg-3)", alignItems: "center" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 5 }}><Icon name="check-circle-2" size={13} style={{ color: "var(--brand-burgundy)" }} />Granted</span>
        <span style={{ display: "flex", alignItems: "center", gap: 5 }}><Icon name="circle" size={13} style={{ color: "var(--ink-300)" }} />Not granted</span>
        <span style={{ marginLeft: "auto", fontStyle: "italic" }}>Click a row icon to toggle all permissions for that module · Click column "all" to toggle the full column</span>
      </div>

      {/* Matrix table */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ background: "var(--plum-50)", borderBottom: "2px solid var(--border-subtle)" }}>
              <th style={{ padding: "10px 20px", textAlign: "left", fontSize: 10.5, fontWeight: 700, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.1em" }}>
                Module
              </th>
              {PERM_KEYS.map(p => (
                <th key={p} style={thStyle}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                    <span>{p}</span>
                    <button type="button" onClick={() => toggleColumn(p)}
                      style={{ fontSize: 10, color: "var(--brand-burgundy)", background: "var(--plum-100)", border: "none", cursor: "pointer", fontFamily: "inherit", padding: "2px 8px", borderRadius: 4 }}>
                      all
                    </button>
                  </div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {PERM_GROUPS.map(group => (
              <React.Fragment key={group}>
                {/* Group label row */}
                <tr>
                  <td colSpan={5} style={{
                    padding: "7px 20px", background: "var(--ink-50)",
                    fontSize: 10.5, fontWeight: 700, color: "var(--fg-3)",
                    textTransform: "uppercase", letterSpacing: "0.1em",
                    borderTop: "1px solid var(--border-subtle)", borderBottom: "1px solid var(--border-subtle)",
                  }}>
                    {group}
                  </td>
                </tr>
                {PERM_MODULES.filter(m => m.group === group).map(mod => {
                  const rowPerms  = perms[mod.id] || {};
                  const allActive = PERM_KEYS.every(p => rowPerms[p]);
                  return (
                    <tr key={mod.id} style={{ borderTop: "1px solid var(--border-subtle)" }}>
                      {/* Module label */}
                      <td style={{ padding: "10px 20px" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                          <button type="button" title={allActive ? "Revoke all for this module" : "Grant all for this module"}
                            onClick={() => toggleRow(mod.id)}
                            style={{
                              width: 28, height: 28, borderRadius: 6, border: "none", cursor: "pointer",
                              display: "flex", alignItems: "center", justifyContent: "center",
                              background: allActive ? "var(--plum-50)" : "var(--ink-100)",
                              color: allActive ? "var(--brand-burgundy)" : "var(--fg-3)",
                              flexShrink: 0,
                            }}>
                            <Icon name={mod.icon} size={14} />
                          </button>
                          <span style={{ fontSize: 13.5, fontWeight: 500 }}>{mod.label}</span>
                        </div>
                      </td>
                      {/* Permission cells */}
                      {PERM_KEYS.map(p => (
                        <td key={p} style={{ padding: "10px 14px", textAlign: "center" }}>
                          <PermToggle active={!!rowPerms[p]} onChange={() => toggle(mod.id, p)} />
                        </td>
                      ))}
                    </tr>
                  );
                })}
              </React.Fragment>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ─── Add / Edit Role Modal ─── */
function RoleFormModal({ role, onClose, onSave }) {
  const isEdit = !!role;
  const blank  = { name: "", initials: "", color: ROLE_COLORS[0].hex, desc: "", status: "active" };
  const [form, setForm]     = React.useState(isEdit ? { ...role } : blank);
  const [errors, setErrors] = React.useState({});

  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const onNameChange = e => {
    const name = e.target.value;
    setForm(f => ({ ...f, name, initials: autoInitials(name) }));
    if (errors.name) setErrors(ev => ({ ...ev, name: "" }));
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Role name is required";
    return e;
  };

  const handleSave = () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    onSave({ ...form });
  };

  const errStyle = { color: "var(--danger-500)", fontSize: 11.5, marginTop: 3 };

  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Roles & Permissions</div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{isEdit ? "Edit role" : "Add role"}</h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="modal-body">
          {/* Preview badge */}
          <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "14px 16px", background: "var(--ink-50)", borderRadius: 10, marginBottom: 4 }}>
            <div style={{
              width: 48, height: 48, borderRadius: 10, background: form.color, color: "#fff",
              display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 16, flexShrink: 0,
            }}>
              {form.initials || "??"}
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 15 }}>{form.name || <span style={{ color: "var(--fg-4)" }}>Role name</span>}</div>
              <div style={{ fontSize: 12.5, color: "var(--fg-3)", marginTop: 2 }}>{form.desc || <span style={{ color: "var(--fg-4)" }}>No description</span>}</div>
            </div>
          </div>

          {/* Name + Initials */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 100px", gap: 14 }}>
            <div className="field">
              <label>Role name <span style={{ color: "var(--danger-500)" }}>*</span></label>
              <input value={form.name} onChange={onNameChange} placeholder="e.g. Operations Manager" />
              {errors.name && <div style={errStyle}>{errors.name}</div>}
            </div>
            <div className="field">
              <label>Initials</label>
              <input value={form.initials} onChange={set("initials")} maxLength={2} placeholder="OM"
                style={{ textTransform: "uppercase" }} />
            </div>
          </div>

          {/* Description */}
          <div className="field">
            <label>Description</label>
            <textarea rows={2} value={form.desc} onChange={set("desc")}
              placeholder="Brief description of this role's responsibilities…"
              style={{ resize: "vertical" }} />
          </div>

          {/* Color picker */}
          <div className="field">
            <label>Badge colour</label>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 4 }}>
              {ROLE_COLORS.map(c => (
                <button key={c.hex} type="button" title={c.label}
                  onClick={() => setForm(f => ({ ...f, color: c.hex }))}
                  style={{
                    width: 32, height: 32, borderRadius: 8, background: c.hex,
                    border: form.color === c.hex ? "3px solid var(--fg-1)" : "2px solid transparent",
                    cursor: "pointer", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                  {form.color === c.hex && <Icon name="check" size={14} style={{ color: "#fff" }} />}
                </button>
              ))}
            </div>
          </div>

          {/* Status */}
          <div className="field">
            <label>Status</label>
            <div style={{ display: "flex", gap: 8, marginTop: 2 }}>
              {["active", "inactive"].map(s => (
                <button key={s} type="button" onClick={() => setForm(f => ({ ...f, status: s }))}
                  style={{
                    padding: "7px 20px", borderRadius: 6, cursor: "pointer",
                    fontFamily: "inherit", fontSize: 13, fontWeight: 500,
                    border: form.status === s ? "2px solid var(--brand-burgundy)" : "1px solid var(--border-subtle)",
                    background: form.status === s ? "var(--plum-50)" : "#fff",
                    color:      form.status === s ? "var(--brand-burgundy)" : "var(--fg-3)",
                  }}>
                  {s === "active" ? "Active" : "Inactive"}
                </button>
              ))}
            </div>
          </div>

          <div className="modal-footer">
            <Button variant="secondary" type="button" onClick={onClose}>Cancel</Button>
            <Button icon="check" onClick={handleSave}>{isEdit ? "Save changes" : "Add role"}</Button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Delete Confirmation ─── */
function RoleDeleteModal({ role, onClose, onConfirm }) {
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" style={{ maxWidth: 420 }}>
        <div className="modal-head">
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Delete role?</h2>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="modal-body">
          <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", background: "var(--ink-50)", borderRadius: 8, marginBottom: 18 }}>
            <div style={{ width: 40, height: 40, borderRadius: 9, background: role.color, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 13, flexShrink: 0 }}>
              {role.initials}
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{role.name}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 1 }}>{role.users} member{role.users !== 1 ? "s" : ""} assigned</div>
            </div>
          </div>
          {role.users > 0 && (
            <div style={{ display: "flex", gap: 8, padding: "10px 12px", background: "#FFF8E1", border: "1px solid #FFE082", borderRadius: 8, marginBottom: 14, fontSize: 13, color: "#7E5109" }}>
              <Icon name="triangle-alert" size={16} style={{ flexShrink: 0, marginTop: 1 }} />
              <span><b>{role.users} team member{role.users !== 1 ? "s" : ""}</b> currently hold this role. They will lose their module access until reassigned.</span>
            </div>
          )}
          <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "0 0 4px" }}>
            This role and all its permission settings will be permanently deleted.
          </p>
          <div className="modal-footer" style={{ marginTop: 20 }}>
            <Button variant="secondary" onClick={onClose}>Cancel</Button>
            <button className="btn" onClick={onConfirm}
              style={{ background: "var(--danger-500)", color: "#fff", border: "1px solid var(--danger-500)", display: "flex", alignItems: "center", gap: 6, padding: "8px 16px", borderRadius: 6, cursor: "pointer", fontFamily: "inherit", fontSize: 13.5, fontWeight: 600 }}>
              <Icon name="trash-2" size={14} />Delete role
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Main Page ─── */
function RoleMasterPage() {
  const [roles,    setRoles]    = React.useState([]);
  const [loading,  setLoading]  = React.useState(true);
  const [selected, setSelected] = React.useState(null);
  const [modal,    setModal]    = React.useState(null);
  const [delRole,  setDelRole]  = React.useState(null);

  React.useEffect(() => {
    api.get("/roles")
      .then(res => {
        const mapped = (res.data || []).map(r => ({
          ...api.map.role(r),
          permissions: r.permissions && Object.keys(r.permissions).length ? r.permissions : makePerms(false),
        }));
        setRoles(mapped);
        setSelected(mapped[0] || null);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const selectRole = role => setSelected(role);

  const handleSaveRole = async (role) => {
    try {
      const payload = { name: role.name, initials: role.initials, color: role.color, desc: role.desc, status: role.status };
      if (role._id) {
        const res = await api.put("/roles/" + role._id, payload);
        const updated = { ...api.map.role(res.data), users: role.users || 0, permissions: role.permissions };
        setRoles(prev => prev.map(r => r._id === updated._id ? updated : r));
        setSelected(prev => prev?._id === updated._id ? updated : prev);
      } else {
        const res = await api.post("/roles", payload);
        const created = { ...api.map.role(res.data), permissions: makePerms(false) };
        setRoles(prev => [...prev, created]);
        setSelected(created);
      }
      setModal(null);
    } catch (err) {
      alert(err.message);
    }
  };

  const handleUpdatePerms = async (role) => {
    try {
      await api.put("/roles/" + role._id, { permissions: role.permissions });
      setRoles(prev => prev.map(r => r._id === role._id ? role : r));
      setSelected(role);
    } catch (err) {
      alert(err.message);
    }
  };

  const handleDeleteRole = async () => {
    try {
      await api.delete("/roles/" + delRole._id);
      const remaining = roles.filter(r => r._id !== delRole._id);
      setRoles(remaining);
      if (selected?._id === delRole._id) setSelected(remaining[0] || null);
      setDelRole(null);
    } catch (err) {
      alert(err.message);
    }
  };

  const totalMembers = roles.reduce((a, r) => a + (r.users || 0), 0);

  return (
    <>
    <div className="page" style={{ maxWidth: "none" }}>
      {/* Header */}
      <div className="page-head">
        <div>
          <div className="eyebrow">Setup</div>
          <h1 className="page-title">Roles &amp; permissions</h1>
          <div className="page-sub">{roles.length} roles &nbsp;·&nbsp; {totalMembers} team member{totalMembers !== 1 ? "s" : ""} assigned</div>
        </div>
        <Button icon="plus" onClick={() => setModal("add")}>Add role</Button>
      </div>

      {/* Split layout */}
      <div style={{ display: "grid", gridTemplateColumns: "290px 1fr", gap: 22, alignItems: "start" }}>

        {/* ── Left: Roles list ── */}
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 4 }}>
            Roles ({roles.length})
          </div>
          {loading && (
            <div style={{ padding: "32px 0", textAlign: "center", color: "var(--fg-3)", fontSize: 13 }}>Loading roles…</div>
          )}
          {!loading && roles.length === 0 && (
            <div style={{ padding: "32px 0", textAlign: "center", color: "var(--fg-3)", fontSize: 13 }}>No roles found. Add one to get started.</div>
          )}
          {roles.map(role => {
            const isSel = selected?.id === role.id;
            return (
              <div key={role.id}
                onClick={() => selectRole(role)}
                style={{
                  padding: "13px 14px", borderRadius: 10, cursor: "pointer",
                  border: isSel ? "2px solid var(--brand-burgundy)" : "1px solid var(--border-subtle)",
                  background: isSel ? "var(--plum-50)" : "#fff",
                  transition: "border-color 0.15s, background 0.15s",
                }}>
                {/* Role header */}
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 8, flexShrink: 0,
                    background: role.color, color: "#fff",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontWeight: 700, fontSize: 12,
                  }}>
                    {role.initials}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: isSel ? "var(--brand-burgundy)" : "var(--fg-1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {role.name}
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--fg-3)", marginTop: 1 }}>
                      {role.users} member{role.users !== 1 ? "s" : ""} &nbsp;·&nbsp;
                      <span style={{ color: role.status === "active" ? "var(--success-700)" : "var(--fg-4)" }}>
                        {role.status === "active" ? "Active" : "Inactive"}
                      </span>
                    </div>
                  </div>
                  {isSel && <Icon name="chevron-right" size={15} style={{ color: "var(--brand-burgundy)", flexShrink: 0 }} />}
                </div>

                {/* Description */}
                {role.desc && (
                  <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 7, lineHeight: 1.4 }}>{role.desc}</div>
                )}

                {/* Action buttons — visible on selected */}
                {isSel && (
                  <div style={{ display: "flex", gap: 6, marginTop: 10, paddingTop: 10, borderTop: "1px solid var(--plum-200)" }}>
                    <button className="btn btn-ghost btn-sm"
                      onClick={e => { e.stopPropagation(); setModal(role); }}>
                      <Icon name="pencil" size={12} />Edit role
                    </button>
                    <button className="btn btn-ghost btn-sm" style={{ color: "var(--danger-500)" }}
                      onClick={e => { e.stopPropagation(); setDelRole(role); }}>
                      <Icon name="trash-2" size={12} />Delete
                    </button>
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* ── Right: Permission matrix ── */}
        {selected ? (
          <PermissionMatrix
            key={selected.id}
            role={selected}
            onUpdate={handleUpdatePerms}
          />
        ) : (
          <div className="card" style={{ textAlign: "center", padding: "80px 20px", color: "var(--fg-3)" }}>
            <Icon name="shield" size={36} />
            <div style={{ marginTop: 14, fontSize: 15, fontWeight: 500, color: "var(--fg-2)" }}>Select a role</div>
            <div style={{ fontSize: 13, marginTop: 4 }}>Click a role on the left to view and edit its module permissions.</div>
          </div>
        )}
      </div>
    </div>

    {/* Add / Edit modal */}
    {modal !== null && (
      <RoleFormModal
        role={modal === "add" ? null : modal}
        onClose={() => setModal(null)}
        onSave={handleSaveRole}
      />
    )}

    {/* Delete confirmation */}
    {delRole && (
      <RoleDeleteModal
        role={delRole}
        onClose={() => setDelRole(null)}
        onConfirm={handleDeleteRole}
      />
    )}
    </>
  );
}

Object.assign(window, { RoleMasterPage });
