import { For, Show, createMemo, createSignal, onMount } from "solid-js";

const API = "";

type PersonaType = {
  code: string;
  name: string;
  description: string;
};

type Module = {
  id: string;
  module_key: string;
  module_name: string;
  category: string;
  description: string;
  default_sidebar_label: string;
  is_core: boolean;
};

type RolePermission = {
  id: string;
  module_id: string;
  module_key: string;
  module_name: string;
  category: string;
  can_view: boolean;
  can_list: boolean;
  can_create: boolean;
  can_update: boolean;
  can_delete: boolean;
};

type ExternalRole = {
  id: string;
  key: string;
  name: string;
  persona_type: string;
  is_active: boolean;
  assigned_users: number;
  created_date: string;
};

const CATEGORY_LABELS: Record<string, string> = {
  core: "Core",
  content: "Content",
  marketplace: "Marketplace",
  work: "Work",
  financial: "Financial",
};

const PERMISSION_ACTIONS = ["View", "List", "Create", "Update", "Delete"] as const;
type PermissionAction = typeof PERMISSION_ACTIONS[number];

export default function ExternalRoleManagementPage() {
  const [personaTypes, setPersonaTypes] = createSignal<PersonaType[]>([]);
  const [modules, setModules] = createSignal<Module[]>([]);
  const [roles, setRoles] = createSignal<ExternalRole[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [error, setError] = createSignal("");
  const [selectedPersona, setSelectedPersona] = createSignal<string | null>(null);
  const [view, setView] = createSignal<"list" | "form" | "detail">("list");
  const [listTab, setListTab] = createSignal<"all" | "create">("all");
  const [statusFilter, setStatusFilter] = createSignal("all");
  const [formTab, setFormTab] = createSignal<"general" | "permissions" | "settings">("general");
  const [editingId, setEditingId] = createSignal<string | null>(null);
  const [viewingRole, setViewingRole] = createSignal<ExternalRole | null>(null);
  const [rolePermissions, setRolePermissions] = createSignal<RolePermission[]>([]);
  const [isSaving, setIsSaving] = createSignal(false);
  const [formError, setFormError] = createSignal("");

  const [name, setName] = createSignal("");
  const [code, setCode] = createSignal("");
  const [personaType, setPersonaType] = createSignal("");
  const [isActive, setIsActive] = createSignal(true);
  const [description, setDescription] = createSignal("");

  const loadData = async () => {
    setLoading(true);
    setError("");
    try {
      const accessToken =
        typeof sessionStorage !== "undefined"
          ? sessionStorage.getItem("nxtgauge_admin_access_token") || ""
          : "";
      const headers = {
        Accept: "application/json",
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      };

      const [personaRes, modulesRes, rolesRes] = await Promise.all([
        fetch(`${API}/api/admin/persona-types`, { headers, credentials: "include" }),
        fetch(`${API}/api/admin/modules`, { headers, credentials: "include" }),
        fetch(`${API}/api/admin/external-roles?per_page=100`, { headers, credentials: "include" }),
      ]);

      if (!personaRes.ok) throw new Error(`Failed to load persona types (${personaRes.status})`);
      if (!modulesRes.ok) throw new Error(`Failed to load modules (${modulesRes.status})`);
      if (!rolesRes.ok) throw new Error(`Failed to load roles (${rolesRes.status})`);

      const personaData = await personaRes.json();
      const modulesData = await modulesRes.json();
      const rolesData = await rolesRes.json();

      setPersonaTypes(personaData.items || personaData || []);
      setModules(modulesData.items || modulesData || []);

      const rolesList: any[] = rolesData.roles || rolesData.items || rolesData || [];
      const externalRoles: ExternalRole[] = rolesList
        .map((r: any) => ({
          id: r.id,
          key: r.code || r.key,
          name: r.name,
          persona_type: r.persona_type || "PROFESSIONAL",
          is_active: r.status === "ACTIVE",
          assigned_users: r.assigned_users || 0,
          created_date: r.created_date || r.created_at,
        }));

      setRoles(externalRoles);
    } catch (e: any) {
      setError(e?.message || "Failed to load data");
    } finally {
      setLoading(false);
    }
  };

  onMount(() => void loadData());

  const filteredRoles = createMemo(() => {
    let list = roles();
    if (statusFilter() !== "all") {
      const isActive = statusFilter() === "ACTIVE";
      list = list.filter((r) => r.is_active === isActive);
    }
    if (selectedPersona()) {
      list = list.filter((r) => r.persona_type === selectedPersona());
    }
    return list;
  });

  const orderedModules = createMemo(() => {
    const cats: Record<string, Module[]> = {};
    for (const m of modules()) {
      const c = m.category || "other";
      if (!cats[c]) cats[c] = [];
      cats[c].push(m);
    }
    return Object.entries(cats).sort(([a], [b]) => a.localeCompare(b));
  });

  const roleModulesByCategory = createMemo(() => {
    const cats: Record<string, RolePermission[]> = {};
    for (const p of rolePermissions()) {
      const c = p.category || "other";
      if (!cats[c]) cats[c] = [];
      cats[c].push(p);
    }
    return Object.entries(cats).sort(([a], [b]) => a.localeCompare(b));
  });

  const resetForm = () => {
    setName("");
    setCode("");
    setPersonaType("");
    setIsActive(true);
    setDescription("");
    setEditingId(null);
    setFormError("");
    setFormTab("general");
  };

  const openCreate = () => {
    resetForm();
    setView("form");
    setListTab("create");
  };

  const openEdit = async (role: ExternalRole) => {
    setEditingId(role.id);
    setName(role.name);
    setCode(role.key);
    setPersonaType(role.persona_type);
    setIsActive(role.is_active);
    setDescription("");
    setFormTab("permissions");
    setView("form");
    await loadRolePermissions(role.id);
  };

  const openDetail = async (role: ExternalRole) => {
    setViewingRole(role);
    setView("detail");
    await loadRolePermissions(role.id);
  };

  const closeDetail = () => {
    setViewingRole(null);
    setView("list");
    setRolePermissions([]);
  };

  const loadRolePermissions = async (roleId: string) => {
    try {
      const accessToken = sessionStorage.getItem("nxtgauge_admin_access_token") || "";
      const headers = {
        Accept: "application/json",
        Authorization: `Bearer ${accessToken}`,
      };
      const res = await fetch(`${API}/api/admin/roles/${roleId}/permissions`, {
        headers,
        credentials: "include",
      });
      if (res.ok) {
        const data = await res.json();
        setRolePermissions(data || []);
      }
    } catch {
      setRolePermissions([]);
    }
  };

  const getPermission = (moduleKey: string): RolePermission | undefined => rolePermissions().find((p) => p.module_key === moduleKey);

  const hasAnyPermission = (moduleKey: string) => {
    const p = getPermission(moduleKey);
    return p && (p.can_view || p.can_list || p.can_create || p.can_update || p.can_delete);
  };

  const permissionKeyFor = (moduleKey: string, action: string) => `${moduleKey}_${action.toLowerCase()}`;

  const isAllSelectedForAction = (action: PermissionAction) => {
    const actionKey = action.toLowerCase();
    const key = `can_${actionKey}`;
    const mods = modules();
    if (mods.length === 0) return false;
    return mods.every((m) => {
      const p = getPermission(m.module_key);
      return p && (p as any)[key];
    });
  };

  const isAllSelectedForModule = (moduleKey: string) => {
    const p = getPermission(moduleKey);
    return p && (p.can_view && p.can_list && p.can_create && p.can_update && p.can_delete);
  };

  const togglePermission = async (moduleKey: string, action: PermissionAction, current: boolean) => {
    const role = editingId() ? { id: editingId()! } : viewingRole();
    if (!role) return;

    const actionKey = action.toLowerCase();
    const payload = {
      module_key: moduleKey,
      permission: actionKey,
      enabled: !current,
    };

    try {
      const accessToken = sessionStorage.getItem("nxtgauge_admin_access_token") || "";
      const res = await fetch(`${API}/api/admin/roles/${role.id}/permissions`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${accessToken}`,
        },
        credentials: "include",
        body: JSON.stringify(payload),
      });

      if (!res.ok) throw new Error("Failed to update permission");
      await loadRolePermissions(role.id);
    } catch (e: any) {
      setFormError(e?.message || "Failed to update permission");
    }
  };

  const toggleAllForAction = async (action: PermissionAction, current: boolean) => {
    const role = editingId() ? { id: editingId()! } : viewingRole();
    if (!role) return;

    const actionKey = action.toLowerCase();
    const mods = modules();

    for (const mod of mods) {
      const p = getPermission(mod.module_key);
      if (p) {
        const currentVal = (p as any)[`can_${actionKey}`];
        if (currentVal !== !current) {
          await togglePermission(mod.module_key, action, currentVal);
        }
      }
    }
  };

  const toggleAllForModule = async (moduleKey: string, current: boolean) => {
    const role = editingId() ? { id: editingId()! } : viewingRole();
    if (!role) return;

    for (const action of PERMISSION_ACTIONS) {
      const p = getPermission(moduleKey);
      if (p) {
        const currentVal = (p as any)[`can_${action.toLowerCase()}`];
        if (currentVal !== !current) {
          await togglePermission(moduleKey, action, currentVal);
        }
      }
    }
  };

  const save = async () => {
    if (!name().trim()) {
      setFormError("Role name is required");
      return;
    }
    if (!code().trim()) {
      setFormError("Role key is required");
      return;
    }
    if (!personaType()) {
      setFormError("Persona type is required");
      return;
    }

    setIsSaving(true);
    setFormError("");

    try {
      const accessToken = sessionStorage.getItem("nxtgauge_admin_access_token") || "";
      const method = editingId() ? "PUT" : "POST";
      const url = editingId()
        ? `${API}/api/admin/external-roles/${editingId()}`
        : `${API}/api/admin/external-roles`;

      const payload = {
        name: name(),
        code: code(),
        is_active: isActive(),
        persona_type: personaType(),
        description: description(),
      };

      const res = await fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${accessToken}`,
        },
        credentials: "include",
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.message || "Failed to save role");
      }

      setView("list");
      setListTab("all");
      resetForm();
      await loadData();
    } catch (e: any) {
      setFormError(e?.message || "Failed to save role");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div class="w-full space-y-6 pb-8">
      <div style="margin-bottom: 1.5rem">
        <h1 class="text-[28px] font-bold leading-tight text-[#111827]">External Role Management</h1>
        <p class="mt-1 text-[14px] text-[#6B7280]">
          Manage external roles and their module access permissions
        </p>
      </div>

      {/* ── LIST VIEW ── */}
      <Show when={view() === "list"}>
        <div style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
          <button
            type="button"
            onClick={() => { setListTab("all"); void loadData(); }}
            style={`padding-bottom:12px;font-size:14px;font-weight:500;background:none;border:none;cursor:pointer;${listTab() === "all" ? "color:#FF5E13;border-bottom:2px solid #FF5E13;margin-bottom:-1px" : "color:#6B7280"}`}
          >
            All Roles
          </button>
          <button
            type="button"
            onClick={() => openCreate()}
            style={`padding-bottom:12px;font-size:14px;font-weight:500;background:none;border:none;cursor:pointer;${listTab() === "create" ? "color:#FF5E13;border-bottom:2px solid #FF5E13;margin-bottom:-1px" : "color:#6B7280"}`}
          >
            Create Role
          </button>
        </div>

        <Show when={error()}>
          <div style="margin-top:16px;border-radius:10px;border:1px solid #FECACA;background:#FEF2F2;padding:12px 16px;font-size:13px;color:#B91C1C">
            {error()}
          </div>
        </Show>

        <div style="margin-top:1.5rem;margin-left:-24px;margin-right:-24px;overflow:hidden;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
          <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6">
            <div style="position:relative">
              <button
                type="button"
                onClick={() => setStatusFilter(statusFilter() === "all" ? "ACTIVE" : statusFilter() === "ACTIVE" ? "INACTIVE" : "all")}
                style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
              >
                {statusFilter() === "all" ? "All Status" : statusFilter()}
              </button>
            </div>
            <div style="margin-left:auto;display:flex;gap:8px">
              <button
                onClick={() => setSelectedPersona(null)}
                style={`height:34px;padding:0 14px;border-radius:8px;font-size:12px;font-weight:600;border:1px solid ${!selectedPersona() ? "#FF5E13" : "#E5E7EB"};background:${!selectedPersona() ? "#FFF1EB" : "white"};color:${!selectedPersona() ? "#FF5E13" : "#374151"};cursor:pointer`}
              >
                All
              </button>
              <For each={personaTypes()}>
                {(pt) => (
                  <button
                    onClick={() => setSelectedPersona(pt.code)}
                    style={`height:34px;padding:0 14px;border-radius:8px;font-size:12px;font-weight:600;border:1px solid ${selectedPersona() === pt.code ? "#FF5E13" : "#E5E7EB"};background:${selectedPersona() === pt.code ? "#FFF1EB" : "white"};color:${selectedPersona() === pt.code ? "#FF5E13" : "#374151"};cursor:pointer`}
                  >
                    {pt.name}
                  </button>
                )}
              </For>
            </div>
          </div>

          <div class="overflow-x-auto">
            <table class="min-w-full">
              <thead>
                <tr style="background:#0D0D2A;text-align:left">
                  <For each={["Role Name", "Key", "Persona Type", "Users", "Status", "Actions"]}>
                    {(h) => (
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">
                        {h}
                      </th>
                    )}
                  </For>
                </tr>
              </thead>
              <tbody>
                <Show when={loading()}>
                  <tr>
                    <td colspan="6" style="padding:48px 24px;text-align:center">
                      <p class="text-sm text-slate-400">Loading...</p>
                    </td>
                  </tr>
                </Show>
                <Show when={!loading() && filteredRoles().length === 0}>
                  <tr>
                    <td colspan="6" style="padding:48px 24px;text-align:center">
                      <p class="text-base font-semibold text-gray-900">No external roles found</p>
                      <p class="mt-1.5 text-sm text-gray-500">Create your first role to get started.</p>
                    </td>
                  </tr>
                </Show>
                <Show when={!loading() && filteredRoles().length > 0}>
                  <For each={filteredRoles()}>
                    {(role) => (
                      <tr style="border-bottom:1px solid #F3F4F6" class="hover:bg-[#FAFAFA] transition-colors">
                        <td style="padding:12px 20px">
                          <p class="text-sm font-semibold text-gray-900">{role.name}</p>
                        </td>
                        <td style="padding:12px 20px">
                          <code class="text-xs bg-gray-100 px-1.5 py-0.5 rounded">{role.key}</code>
                        </td>
                        <td style="padding:12px 20px">
                          <span class="inline-flex rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-medium text-blue-700">
                            {role.persona_type}
                          </span>
                        </td>
                        <td style="padding:12px 20px;font-size:13px;color:#374151">
                          {role.assigned_users} users
                        </td>
                        <td style="padding:12px 20px">
                          <span class={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${role.is_active ? "bg-green-100 text-green-800" : "bg-red-100 text-red-700"}`}>
                            {role.is_active ? "Active" : "Inactive"}
                          </span>
                        </td>
                        <td style="padding:12px 20px">
                          <div class="flex items-center gap-2">
                            <button
                              class="rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                              onClick={() => openDetail(role)}
                            >
                              View
                            </button>
                            <button
                              class="rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                              onClick={() => openEdit(role)}
                            >
                              Edit
                            </button>
                          </div>
                        </td>
                      </tr>
                    )}
                  </For>
                </Show>
              </tbody>
            </table>
          </div>
        </div>
      </Show>

      {/* ── FORM VIEW (Create/Edit) ── */}
      <Show when={view() === "form"}>
        <div style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
          <button
            type="button"
            onClick={() => {
              setView("list");
              setListTab("all");
              resetForm();
            }}
            style="padding-bottom:12px;font-size:14px;font-weight:500;color:#6B7280;background:none;border:none;cursor:pointer"
          >
            All Roles
          </button>
          <button
            type="button"
            style="padding-bottom:12px;font-size:14px;font-weight:500;color:#FF5E13;border-bottom:2px solid #FF5E13;background:none;cursor:pointer;margin-bottom:-1px"
          >
            {editingId() ? "Edit Role" : "Create Role"}
          </button>
        </div>

        <div style="margin-top:24px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
          <div style="display:flex;align-items:center;gap:4px;border-bottom:1px solid #E5E7EB;padding:0 24px">
            <For each={["general", "permissions", "settings"] as const}>
              {(tab, getI) => {
                const labels = ["General Information", "Module Access", "Role Settings"];
                const i = getI();
                const active = () => formTab() === tab;
                return (
                  <button
                    type="button"
                    onClick={() => setFormTab(tab)}
                    style={`position:relative;padding:14px 8px;font-size:13px;font-weight:500;background:none;border:none;cursor:pointer;color:${active() ? "#FF5E13" : "#6B7280"}`}
                  >
                    {labels[i]}
                    <Show when={active()}>
                      <span style="position:absolute;left:0;right:0;bottom:0;height:2px;background:#FF5E13;border-radius:2px 2px 0 0" />
                    </Show>
                  </button>
                );
              }}
            </For>
          </div>

          <div style="padding:24px">
            <Show when={formError()}>
              <div style="margin-bottom:20px;border-radius:10px;border:1px solid #FECACA;background:#FEF2F2;padding:12px 16px;font-size:13px;color:#B91C1C">
                {formError()}
              </div>
            </Show>

            {/* General */}
            <Show when={formTab() === "general"}>
              <div style="display:flex;flex-direction:column;gap:20px">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                  <div>
                    <label style="display:block;margin-bottom:6px;font-size:13px;font-weight:600;color:#374151">
                      Role Name <span style="color:#FF5E13">*</span>
                    </label>
                    <input
                      type="text"
                      value={name()}
                      onInput={(e) => setName(e.currentTarget.value)}
                      placeholder="e.g. Photographer"
                      style="display:block;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                    />
                  </div>
                  <div>
                    <label style="display:block;margin-bottom:6px;font-size:13px;font-weight:600;color:#374151">
                      Role Key <span style="color:#FF5E13">*</span>
                    </label>
                    <input
                      type="text"
                      value={code()}
                      onInput={(e) => setCode(e.currentTarget.value.toUpperCase())}
                      placeholder="e.g. PHOTOGRAPHER"
                      style="display:block;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                    />
                    <p style="margin-top:6px;font-size:11px;color:#6B7280">Use uppercase letters and underscores only</p>
                  </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                  <div>
                    <label style="display:block;margin-bottom:6px;font-size:13px;font-weight:600;color:#374151">
                      Persona Type <span style="color:#FF5E13">*</span>
                    </label>
                    <select
                      value={personaType()}
                      onChange={(e) => setPersonaType(e.currentTarget.value)}
                      style="display:block;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                    >
                      <option value="">Select persona type</option>
                      <For each={personaTypes()}>
                        {(pt) => <option value={pt.code}>{pt.name}</option>}
                      </For>
                    </select>
                  </div>
                  <div>
                    <label style="display:block;margin-bottom:6px;font-size:13px;font-weight:600;color:#374151">Status</label>
                    <div style="margin-top:0;display:flex;gap:8px">
                      <button
                        type="button"
                        onClick={() => setIsActive(true)}
                        style={`flex:1;height:40px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer;border:1px solid ${isActive() ? "#FF5E13" : "#E5E7EB"};background:${isActive() ? "#FFF3EE" : "white"};color:${isActive() ? "#FF5E13" : "#6B7280"}`}
                      >
                        Active
                      </button>
                      <button
                        type="button"
                        onClick={() => setIsActive(false)}
                        style={`flex:1;height:40px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer;border:1px solid ${!isActive() ? "#FF5E13" : "#E5E7EB"};background:${!isActive() ? "#FFF3EE" : "white"};color:${!isActive() ? "#FF5E13" : "#6B7280"}`}
                      >
                        Inactive
                      </button>
                    </div>
                  </div>
                </div>
                <div>
                  <label style="display:block;margin-bottom:6px;font-size:13px;font-weight:600;color:#374151">Description</label>
                  <textarea
                    value={description()}
                    onInput={(e) => setDescription(e.currentTarget.value)}
                    placeholder="Brief description of this role..."
                    rows="3"
                    style="display:block;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:10px 14px;font-size:13px;color:#111827;outline:none;resize:none;box-sizing:border-box;font-family:inherit"
                  />
                </div>
              </div>
            </Show>

            {/* Permissions */}
            <Show when={formTab() === "permissions"}>
              <div>
                <p style="margin-bottom:16px;font-size:13px;color:#6B7280">
                  Configure module access permissions for this role.
                </p>
                <div style="border:1px solid #E5E7EB;border-radius:12px;overflow:hidden">
                  <table style="width:100%;border-collapse:collapse">
                    <thead style="background:#F9FAFB">
                      <tr style="text-align:left">
                        <th style="padding:12px 16px;font-size:11px;font-weight:600;color:#6B7280;text-transform:uppercase;width:40px">
                          <span title="Select all">All</span>
                        </th>
                        <th style="padding:12px 16px;font-size:11px;font-weight:600;color:#6B7280;text-transform:uppercase">
                          Module
                        </th>
                        <For each={PERMISSION_ACTIONS}>
                          {(action) => (
                            <th style="padding:12px 16px;font-size:11px;font-weight:600;color:#6B7280;text-transform:uppercase;text-align:center;width:80px">
                              <div style="display:flex;flex-direction:column;align-items:center;gap:6px">
                                <span>{action}</span>
                              </div>
                            </th>
                          )}
                        </For>
                      </tr>
                    </thead>
                    <tbody>
                      <For each={roleModulesByCategory()}>
                        {([category, perms]) => (
                          <>
                            <tr style="background:#F3F4F6">
                              <td colspan={PERMISSION_ACTIONS.length + 2} style="padding:8px 16px;font-size:11px;font-weight:600;color:#6B7280;text-transform:uppercase">
                                {CATEGORY_LABELS[category] || category}
                              </td>
                            </tr>
                            <For each={perms}>
                              {(perm) => {
                                const isAll = () => perm.can_view && perm.can_list && perm.can_create && perm.can_update && perm.can_delete;
                                return (
                                  <tr style="border-top:1px solid #E5E7EB">
                                    <td style="padding:8px 12px;text-align:center">
                                      <input
                                        type="checkbox"
                                        checked={isAll()}
                                        onChange={() => toggleAllForModule(perm.module_key, isAll())}
                                        style="width:16px;height:16px;accent-color:#FF5E13;cursor:pointer"
                                      />
                                    </td>
                                    <td style="padding:12px 16px">
                                      <div style="font-size:13px;font-weight:500;color:#111827">{perm.module_name}</div>
                                      <div style="font-size:11px;color:#6B7280;margin-top:2px">{perm.module_key}</div>
                                    </td>
                                    <For each={PERMISSION_ACTIONS}>
                                      {(action) => {
                                        const val = () => (perm as any)[`can_${action.toLowerCase()}`];
                                        return (
                                          <td style="padding:12px 16px;text-align:center">
                                            <input
                                              type="checkbox"
                                              checked={val()}
                                              onChange={() => togglePermission(perm.module_key, action, val())}
                                              style="width:16px;height:16px;accent-color:#FF5E13;cursor:pointer"
                                            />
                                          </td>
                                        );
                                      }}
                                    </For>
                                  </tr>
                                );
                              }}
                            </For>
                          </>
                        )}
                      </For>
                    </tbody>
                  </table>
                </div>
              </div>
            </Show>

            {/* Settings */}
            <Show when={formTab() === "settings"}>
              <div style="padding:32px;text-align:center">
                <p style="font-size:14px;color:#6B7280">
                  Role settings and access permissions are configured in the Module Access tab.
                </p>
                <p style="font-size:13px;color:#9CA3AF;margin-top:8px">
                  Select "Module Access" to configure permissions for this role.
                </p>
              </div>
            </Show>
          </div>

          <div style="display:flex;align-items:center;justify-content:flex-end;gap:10px;border-top:1px solid #E5E7EB;padding:14px 24px">
            <button
              type="button"
              onClick={() => {
                setView("list");
                setListTab("all");
                resetForm();
              }}
              style="height:38px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 20px;font-size:13px;font-weight:600;color:#374151;cursor:pointer"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={() => void save()}
              disabled={isSaving()}
              style="height:38px;border-radius:10px;background:#0D0D2A;padding:0 24px;font-size:13px;font-weight:600;color:white;border:none;cursor:pointer"
            >
              {isSaving() ? "Saving..." : editingId() ? "Update Role" : "Create Role"}
            </button>
          </div>
        </div>
      </Show>

      {/* ── DETAIL VIEW ── */}
      <Show when={view() === "detail" && viewingRole()}>
        <div style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
          <button
            type="button"
            onClick={closeDetail}
            style="padding-bottom:12px;font-size:14px;font-weight:500;color:#6B7280;background:none;border:none;cursor:pointer"
          >
            All Roles
          </button>
          <button
            type="button"
            style="padding-bottom:12px;font-size:14px;font-weight:500;color:#FF5E13;border-bottom:2px solid #FF5E13;background:none;cursor:pointer;margin-bottom:-1px"
          >
            View Role
          </button>
        </div>

        <div style="margin-top:24px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
          <div style="padding:24px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between">
            <div>
              <div style="display:flex;align-items:center;gap:12px">
                <h2 style="font-size:20px;font-weight:700;color:#111827">{viewingRole()!.name}</h2>
                <span class={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${viewingRole()!.is_active ? "bg-green-100 text-green-800" : "bg-red-100 text-red-700"}`}>
                  {viewingRole()!.is_active ? "Active" : "Inactive"}
                </span>
              </div>
              <p style="font-size:13px;color:#6B7280;margin-top:4px">
                Key:{" "}
                <code style="font-family:monospace;background:#F3F4F6;padding:1px 6px;border-radius:4px">
                  {viewingRole()!.key || "—"}
                </code>
                {` • ${viewingRole()!.persona_type}`}
                {` • ${viewingRole()!.assigned_users} users assigned`}
              </p>
            </div>
            <button
              type="button"
              onClick={() => openEdit(viewingRole()!)}
              style="height:36px;border-radius:8px;background:#0D0D2A;padding:0 16px;font-size:13px;font-weight:600;color:white;border:none;cursor:pointer"
            >
              Edit Role
            </button>
          </div>

          <div style="padding:24px">
            <h3 style="font-size:14px;font-weight:600;color:#111827;margin-bottom:16px">Module Permissions</h3>
            <div style="border:1px solid #E5E7EB;border-radius:12px;overflow:hidden">
              <table style="width:100%;border-collapse:collapse">
                <thead style="background:#F9FAFB">
                  <tr style="text-align:left">
                    <th style="padding:12px 16px;font-size:11px;font-weight:600;color:#6B7280;text-transform:uppercase">
                      Module
                    </th>
                    <For each={PERMISSION_ACTIONS}>
                      {(action) => (
                        <th style="padding:12px 16px;font-size:11px;font-weight:600;color:#6B7280;text-transform:uppercase;text-align:center;width:80px">
                          {action}
                        </th>
                      )}
                    </For>
                  </tr>
                </thead>
                <tbody>
                  <For each={roleModulesByCategory()}>
                    {([category, perms]) => (
                      <>
                        <tr style="background:#F3F4F6">
                          <td colspan={PERMISSION_ACTIONS.length + 1} style="padding:8px 16px;font-size:11px;font-weight:600;color:#6B7280;text-transform:uppercase">
                            {CATEGORY_LABELS[category] || category}
                          </td>
                        </tr>
                        <For each={perms}>
                          {(perm) => (
                            <tr style="border-top:1px solid #E5E7EB">
                              <td style="padding:12px 16px">
                                <div style="font-size:13px;font-weight:500;color:#111827">{perm.module_name}</div>
                                <div style="font-size:11px;color:#6B7280;margin-top:2px">{perm.module_key}</div>
                              </td>
                              <For each={PERMISSION_ACTIONS}>
                                {(action) => {
                                  const val = () => (perm as any)[`can_${action.toLowerCase()}`];
                                  return (
                                    <td style="padding:12px 16px;text-align:center">
                                      <Show when={val()}>
                                        <svg style="width:16px;height:16px;color:#10B981;margin:auto" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                          <path d="M20 6L9 17l-5-5" />
                                        </svg>
                                      </Show>
                                      <Show when={!val()}>
                                        <svg style="width:16px;height:16px;color:#D1D5DB;margin:auto" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                          <path d="M18 6L6 18M6 6l12 12" />
                                        </svg>
                                      </Show>
                                    </td>
                                  );
                                }}
                              </For>
                            </tr>
                          )}
                        </For>
                      </>
                    )}
                  </For>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </Show>
    </div>
  );
}