"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import toast from "react-hot-toast";
import styles from "./PermissionManager.module.css";
import { fetchApi, API_BASE_URL } from "@/lib/api/http";

// ══════════════════════════════════════════════
//  Types
// ══════════════════════════════════════════════

interface ModuleRaw {
  id: number;
  name: string;
  slug: string;
  description?: string;
  api_prefix?: string;
  is_active: boolean;
  button_config?: ButtonConfig[];
  column_config?: ColumnConfig[];
}

interface ButtonConfig {
  key: string;
  label: string;
  icon?: string;
  color?: string;
  position: "toolbar" | "row" | "both";
  order?: number;
}

interface ColumnConfig {
  key: string;
  label: string;
  type: "text" | "number" | "currency" | "date" | "badge" | "boolean";
  sortable?: boolean;
  default_visible?: boolean;
  order?: number;
  show_in?: string[]; // ✅ NEW - supports ["table"], ["form"], or ["table","form"]
  required?: boolean; // ✅ NEW - for form fields
}

interface RoleRaw {
  id: number;
  name: string;
  description?: string;
  is_active?: boolean;
  permissions?: PermissionRaw[];
}

interface PermissionRaw {
  id: number;
  name: string;
  action: string;
  description?: string;
  module_id?: number;
  module?: { id: number; name: string; slug: string };
  created_at?: string;
  updated_at?: string;
}

interface UserBasic {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  isActive?: boolean;
}

interface UserPermissionRaw {
  id: number;
  permission?: PermissionRaw;
  user?: UserBasic;
}

interface ConditionRaw {
  id: number;
  condition_field: string;
  condition_value: string;
  logic?: string;
  module?: { id: number; name: string; slug: string } | null;
  userPermission?: {
    id: number;
    permission?: PermissionRaw;
    user?: { id: number; name: string; email: string };
  };
}

interface Props {
  refreshFlag?: boolean;
  refreshData?: () => void;
  defaultTab?: TabKey;
}

type TabKey = "modules" | "roles" | "users" | "matrix" | "conditions";

// ══════════════════════════════════════════════
//  API Helpers
// ══════════════════════════════════════════════

const api = {
  getModules: () => fetchApi<ModuleRaw[]>(`${API_BASE_URL}/modules`),
  createModule: (data: Partial<ModuleRaw>) =>
    fetchApi<ModuleRaw>(`${API_BASE_URL}/modules`, { method: "POST", body: JSON.stringify(data) }),
  updateModule: (id: number, data: Partial<ModuleRaw>) =>
    fetchApi<ModuleRaw>(`${API_BASE_URL}/modules/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
  deleteModule: (id: number) =>
    fetchApi<void>(`${API_BASE_URL}/modules/${id}`, { method: "DELETE" }),

  getRoles: () => fetchApi<RoleRaw[]>(`${API_BASE_URL}/roles`),
  createRole: (data: any) =>
    fetchApi<RoleRaw>(`${API_BASE_URL}/roles`, { method: "POST", body: JSON.stringify(data) }),
  updateRole: (id: number, data: any) =>
    fetchApi<RoleRaw>(`${API_BASE_URL}/roles/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
  deleteRole: (id: number) =>
    fetchApi<void>(`${API_BASE_URL}/roles/${id}`, { method: "DELETE" }),

  getPermissions: () => fetchApi<PermissionRaw[]>(`${API_BASE_URL}/permissions`),
  createPermission: (data: any) =>
    fetchApi<PermissionRaw>(`${API_BASE_URL}/permissions`, { method: "POST", body: JSON.stringify(data) }),
  deletePermission: (id: number) =>
    fetchApi<void>(`${API_BASE_URL}/permissions/${id}`, { method: "DELETE" }),

  getUsers: () => fetchApi<UserBasic[]>(`${API_BASE_URL}/users`),

  getUserPermissions: (userId: number) =>
    fetchApi<UserPermissionRaw[]>(`${API_BASE_URL}/user-permissions/user/${userId}`),
  createUserPermission: (data: { userId: number; permissionId: number }) =>
    fetchApi<UserPermissionRaw>(`${API_BASE_URL}/user-permissions`, { method: "POST", body: JSON.stringify(data) }),
  deleteUserPermission: (id: number) =>
    fetchApi<void>(`${API_BASE_URL}/user-permissions/${id}`, { method: "DELETE" }),

  getConditions: () =>
    fetchApi<ConditionRaw[]>(`${API_BASE_URL}/user-permission-conditions`).catch(() => [] as ConditionRaw[]),
  createCondition: (data: any) =>
    fetchApi<ConditionRaw>(`${API_BASE_URL}/user-permission-conditions`, { method: "POST", body: JSON.stringify(data) }),
  updateCondition: (id: number, data: any) =>
    fetchApi<ConditionRaw>(`${API_BASE_URL}/user-permission-conditions/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
  deleteCondition: (id: number) =>
    fetchApi<void>(`${API_BASE_URL}/user-permission-conditions/${id}`, { method: "DELETE" }),
};

// ══════════════════════════════════════════════
//  Badge & Color Helpers
// ══════════════════════════════════════════════

function actionBadgeClass(action: string, s: any): string {
  const map: Record<string, string> = {
    view: s.badgeView, create: s.badgeCreate,
    edit: s.badgeEdit, delete: s.badgeDelete,
    export: s.badgeExport, approve: s.badgeApprove,
  };
  return map[action?.toLowerCase()] || s.badgeCustom;
}

function getActionColor(action: string): string {
  const map: Record<string, string> = {
    view: "#16a34a", view_all: "#0284c7", edit: "#9333ea",
    create: "#2563eb", delete: "#dc2626", export: "#d97706",
    print: "#0891b2", approve: "#059669",
  };
  return map[action?.toLowerCase()] ?? "#6b7280";
}

function formatAction(action: string): string {
  return action.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

// ══════════════════════════════════════════════
//  Main Component
// ══════════════════════════════════════════════

export default function PermissionManager({ refreshFlag, refreshData, defaultTab }: Props) {
  const [activeTab, setActiveTab] = useState<TabKey>(defaultTab ?? "modules");
  const [loading, setLoading] = useState(true);

  // ── Data ──────────────────────────────────────
  const [modules, setModules]         = useState<ModuleRaw[]>([]);
  const [roles, setRoles]             = useState<RoleRaw[]>([]);
  const [permissions, setPermissions] = useState<PermissionRaw[]>([]);
  const [users, setUsers]             = useState<UserBasic[]>([]);
  const [conditions, setConditions]   = useState<ConditionRaw[]>([]);

  // ── Tab 1: Module Config ──────────────────────
  const [selectedModuleId, setSelectedModuleId] = useState<number | null>(null);
  const [showCreateModule, setShowCreateModule] = useState(false);
  const [newModuleForm, setNewModuleForm] = useState({ name: "", slug: "", description: "", api_prefix: "" });
  const [showAddButton, setShowAddButton] = useState(false);
  const [showAddColumn, setShowAddColumn] = useState(false);
  const [newButton, setNewButton] = useState<ButtonConfig>({ key: "", label: "", icon: "", color: "#8b14d4", position: "toolbar", order: 99 });
  const [newColumn, setNewColumn] = useState<ColumnConfig>({ key: "", label: "", type: "text", sortable: true, default_visible: true, order: 99 });

  // ── Tab 2: Roles ──────────────────────────────
  const [showRoleModal, setShowRoleModal] = useState(false);
  const [editingRole, setEditingRole]     = useState<RoleRaw | null>(null);
  const [roleForm, setRoleForm]           = useState({ name: "", description: "" });
  const [rolePermIds, setRolePermIds]     = useState<number[]>([]);
  const [roleModuleFilter, setRoleModuleFilter] = useState<number | null>(null);

  // ── Tab 3: User Permissions ───────────────────
  const [selectedUserId, setSelectedUserId]       = useState<number | null>(null);
  const [userPermissions, setUserPermissions]     = useState<UserPermissionRaw[]>([]);
  const [userPermModuleFilter, setUserPermModuleFilter] = useState<number | null>(null);
  const [savingKey, setSavingKey]                 = useState<string | null>(null);
  const [loadingUserPerms, setLoadingUserPerms]   = useState(false);
  const [userSearch, setUserSearch]               = useState("");

  // ── Tab 5: Conditions ─────────────────────────
  const [showConditionModal, setShowConditionModal] = useState(false);
  const [condUserId, setCondUserId]           = useState<number | null>(null);
  const [condModuleId, setCondModuleId]       = useState<number | null>(null);
  const [condUserPerms, setCondUserPerms]     = useState<UserPermissionRaw[]>([]);
  const [condColChecks, setCondColChecks]     = useState<Record<string, boolean>>({});
  const [condField, setCondField]             = useState("visible_columns");
  const [condManualVal, setCondManualVal]     = useState("");
  const [condLogic, setCondLogic]             = useState("equals");
  const [savingCondition, setSavingCondition] = useState(false);

  // ── Load All Data ─────────────────────────────
  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [mods, rls, perms, usrs, conds] = await Promise.all([
        api.getModules(),
        api.getRoles(),
        api.getPermissions(),
        api.getUsers(),
        api.getConditions(),
      ]);
      const activeMods = mods.filter((m) => m.is_active);
      setModules(activeMods);
      setRoles(rls);
      setPermissions(perms);
      setUsers(Array.isArray(usrs) ? usrs : (usrs as any)?.data || []);
      setConditions(conds);
      if (activeMods.length > 0 && !selectedModuleId) {
        setSelectedModuleId(activeMods[0].id);
      }
    } catch (err) {
      console.error("Failed to load:", err);
      toast.error("Failed to load data");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { loadData(); }, [refreshFlag, loadData]);

  // ── Load User Permissions ─────────────────────
  const loadUserPerms = useCallback(async (userId: number) => {
    setLoadingUserPerms(true);
    try {
      const data = await api.getUserPermissions(userId);
      setUserPermissions(data);
    } catch { setUserPermissions([]); }
    finally { setLoadingUserPerms(false); }
  }, []);

  useEffect(() => {
    if (selectedUserId) loadUserPerms(selectedUserId);
  }, [selectedUserId, loadUserPerms]);

  // ── Load Cond User Perms ──────────────────────
  useEffect(() => {
    if (condUserId) {
      api.getUserPermissions(condUserId)
        .then(setCondUserPerms)
        .catch(() => setCondUserPerms([]));
    } else { setCondUserPerms([]); }
  }, [condUserId]);

  useEffect(() => {
    if (condModuleId) {
      const mod = modules.find((m) => m.id === condModuleId);
      if (mod?.column_config) {
        const checks: Record<string, boolean> = {};
        mod.column_config.forEach((col) => { checks[col.key] = true; });
        setCondColChecks(checks);
      }
    }
  }, [condModuleId, modules]);

  // ── Derived ───────────────────────────────────
  const selectedModule = useMemo(() => modules.find((m) => m.id === selectedModuleId) || null, [modules, selectedModuleId]);
  const moduleButtons  = useMemo(() => (selectedModule?.button_config || []).sort((a, b) => (a.order || 0) - (b.order || 0)), [selectedModule]);
  const moduleColumns  = useMemo(() => (selectedModule?.column_config || []).sort((a, b) => (a.order || 0) - (b.order || 0)), [selectedModule]);
  const filteredUsers  = useMemo(() =>
    users.filter((u) => `${u.firstName} ${u.lastName} ${u.email}`.toLowerCase().includes(userSearch.toLowerCase())),
  [users, userSearch]);

  const permissionsByModule = useMemo(() =>
    modules
      .filter((mod) => !userPermModuleFilter || mod.id === userPermModuleFilter)
      .map((mod) => ({
        module: mod,
        perms: permissions.filter((p) => (p as any).module_id === mod.id || (p as any).module?.id === mod.id),
      }))
      .filter((g) => g.perms.length > 0),
  [modules, permissions, userPermModuleFilter]);

  const condViewPerm = useMemo(() => {
    if (!condUserId || !condModuleId) return null;
    return condUserPerms.find((up) => {
      const action = up.permission?.action?.toLowerCase();
      const modId = up.permission?.module?.id || (up.permission as any)?.module_id;
      return action === "view" && modId === condModuleId;
    });
  }, [condUserPerms, condUserId, condModuleId]);

  const condModCols = useMemo(() => modules.find((m) => m.id === condModuleId)?.column_config || [], [modules, condModuleId]);

  // ✅ NEW — Filter columns based on selected condition type
  // visible_columns → show only fields that appear in the TABLE
  // visible_fields  → show only fields that appear in the FORM
  const condFilteredCols = useMemo(() => {
    if (condField === "visible_fields") {
      return condModCols.filter((c: any) =>
        c.show_in?.includes("form") || !c.show_in
      );
    }
    if (condField === "visible_columns") {
      return condModCols.filter((c: any) =>
        c.show_in?.includes("table") || !c.show_in
      );
    }
    return condModCols;
  }, [condModCols, condField]);

  // ✅ UPDATED — Find existing condition matching the currently selected condField
  const existingVisCond = useMemo(() => {
    if (!condViewPerm) return null;
    return conditions.find((c: any) =>
      c.userPermission?.id === condViewPerm.id && c.condition_field === condField
    );
  }, [conditions, condViewPerm, condField]);

  useEffect(() => {
    if (existingVisCond && condFilteredCols.length > 0) {
      const keys = (existingVisCond as any).condition_value.split(",").map((k: string) => k.trim());
      const checks: Record<string, boolean> = {};
      condFilteredCols.forEach((col) => { checks[col.key] = keys.includes(col.key); });
      setCondColChecks(checks);
    } else if (condFilteredCols.length > 0) {
      // No existing condition — default everything to checked
      const checks: Record<string, boolean> = {};
      condFilteredCols.forEach((col) => { checks[col.key] = true; });
      setCondColChecks(checks);
    }
  }, [existingVisCond, condFilteredCols]);

  // ── Permission Checkbox Helpers ───────────────
  const hasPermission = (permId: number) =>
    userPermissions.some((up) => up.permission?.id === permId);

  const getUpRowId = (permId: number): number | null =>
    userPermissions.find((up) => up.permission?.id === permId)?.id ?? null;

  const handleTogglePermission = async (perm: PermissionRaw) => {
    if (!selectedUserId) return;
    const key = `${(perm as any).module_id ?? perm.module?.id}-${perm.action}`;
    setSavingKey(key);
    const has = hasPermission(perm.id);
    try {
      if (has) {
        const rowId = getUpRowId(perm.id);
        if (!rowId) return;
        await api.deleteUserPermission(rowId);
        setUserPermissions((prev) => prev.filter((up) => up.id !== rowId));
        toast.success(`Removed "${formatAction(perm.action)}"`);
      } else {
        const res: any = await api.createUserPermission({ userId: selectedUserId, permissionId: perm.id });
        setUserPermissions((prev) => [...prev, { id: res?.id ?? Date.now(), permission: perm }]);
        toast.success(`Assigned "${formatAction(perm.action)}"`);
      }
    } catch (err: any) { toast.error(err?.message || "Failed"); }
    finally { setSavingKey(null); }
  };

  const handleToggleAllModulePerms = async (modId: number, assign: boolean) => {
    if (!selectedUserId) return;
    const modPerms = permissions.filter((p) => (p as any).module_id === modId || p.module?.id === modId);
    for (const perm of modPerms) {
      const has = hasPermission(perm.id);
      if (assign && !has) {
        try {
          const res: any = await api.createUserPermission({ userId: selectedUserId, permissionId: perm.id });
          setUserPermissions((prev) => [...prev, { id: res?.id ?? Date.now(), permission: perm }]);
        } catch {}
      } else if (!assign && has) {
        const rowId = getUpRowId(perm.id);
        if (rowId) {
          try {
            await api.deleteUserPermission(rowId);
            setUserPermissions((prev) => prev.filter((up) => up.id !== rowId));
          } catch {}
        }
      }
    }
    toast.success(assign ? "All permissions assigned" : "All permissions removed");
  };

  // ── Module Actions ────────────────────────────
  const handleCreateModule = async () => {
    const { name, slug } = newModuleForm;
    if (!name.trim() || !slug.trim()) { toast.error("Name and Slug required"); return; }
    try {
      const created = await api.createModule({
        name: name.trim(), slug: slug.trim().toLowerCase().replace(/\s+/g, "-"),
        description: newModuleForm.description,
        api_prefix: newModuleForm.api_prefix || slug.trim().toLowerCase(), is_active: true,
      });
      toast.success(`Module "${created.name}" created`);
      setShowCreateModule(false);
      setNewModuleForm({ name: "", slug: "", description: "", api_prefix: "" });
      setSelectedModuleId(created.id);
      await loadData();
    } catch (err: any) { toast.error(err?.message || "Failed"); }
  };

  const handleDeleteModule = async () => {
    if (!selectedModule || !confirm(`Delete module "${selectedModule.name}"?`)) return;
    try {
      await api.deleteModule(selectedModule.id);
      toast.success("Module deleted");
      setSelectedModuleId(null);
      await loadData();
    } catch { toast.error("Failed to delete module"); }
  };

  const handleAddButton = async () => {
    if (!selectedModule || !newButton.key || !newButton.label) { toast.error("Key and Label required"); return; }
    const existing = selectedModule.button_config || [];
    if (existing.find((b) => b.key === newButton.key)) { toast.error("Key already exists"); return; }
    try {
      await api.updateModule(selectedModule.id, { button_config: [...existing, newButton] });
      const permExists = permissions.find((p) => p.action === newButton.key && ((p as any).module_id === selectedModule.id || p.module?.id === selectedModule.id));
      if (!permExists) {
        await api.createPermission({ name: `${selectedModule.name} - ${newButton.key}`, action: newButton.key, module_id: selectedModule.id });
      }
      toast.success(`Button "${newButton.label}" added`);
      setNewButton({ key: "", label: "", icon: "", color: "#8b14d4", position: "toolbar", order: 99 });
      setShowAddButton(false);
      await loadData();
    } catch { toast.error("Failed"); }
  };

  const handleRemoveButton = async (key: string) => {
    if (!selectedModule) return;
    try {
      await api.updateModule(selectedModule.id, { button_config: (selectedModule.button_config || []).filter((b) => b.key !== key) });
      toast.success("Button removed");
      await loadData();
    } catch { toast.error("Failed"); }
  };

  const handleAddColumn = async () => {
    if (!selectedModule || !newColumn.key || !newColumn.label) { toast.error("Key and Label required"); return; }
    const existing = selectedModule.column_config || [];
    if (existing.find((c) => c.key === newColumn.key)) { toast.error("Key already exists"); return; }
    try {
      await api.updateModule(selectedModule.id, { column_config: [...existing, newColumn] });
      toast.success(`Column "${newColumn.label}" added`);
      setNewColumn({ key: "", label: "", type: "text", sortable: true, default_visible: true, order: 99 });
      setShowAddColumn(false);
      await loadData();
    } catch { toast.error("Failed"); }
  };

  const handleRemoveColumn = async (key: string) => {
    if (!selectedModule) return;
    try {
      await api.updateModule(selectedModule.id, { column_config: (selectedModule.column_config || []).filter((c) => c.key !== key) });
      toast.success("Column removed");
      await loadData();
    } catch { toast.error("Failed"); }
  };

  // ── Role Actions ──────────────────────────────
  const openRoleModal = (role?: RoleRaw) => {
    if (role) {
      setEditingRole(role);
      setRoleForm({ name: role.name, description: (role as any).description || "" });
      setRolePermIds((role.permissions || []).map((p) => p.id));
    } else {
      setEditingRole(null);
      setRoleForm({ name: "", description: "" });
      setRolePermIds([]);
    }
    setRoleModuleFilter(null);
    setShowRoleModal(true);
  };

  const handleSaveRole = async () => {
    if (!roleForm.name.trim()) { toast.error("Name required"); return; }
    try {
      if (editingRole) {
        await api.updateRole(editingRole.id, { ...roleForm, permissionIds: rolePermIds });
        toast.success("Role updated");
      } else {
        await api.createRole({ ...roleForm, permissionIds: rolePermIds });
        toast.success("Role created");
      }
      setShowRoleModal(false);
      await loadData();
    } catch { toast.error("Failed to save role"); }
  };

  const handleDeleteRole = async (id: number) => {
    if (!confirm("Delete this role?")) return;
    try { await api.deleteRole(id); toast.success("Deleted"); await loadData(); }
    catch { toast.error("Failed"); }
  };

  // ── Condition Actions ─────────────────────────
  const openConditionModal = () => {
    setCondUserId(null); setCondModuleId(null);
    setCondUserPerms([]); setCondColChecks({});
    setCondField("visible_columns"); setCondManualVal(""); setCondLogic("equals");
    setShowConditionModal(true);
  };

  const handleSaveCondition = async () => {
    if (!condViewPerm) { toast.error("User needs 'view' permission for this module first"); return; }
    if (!condModuleId) return;
    setSavingCondition(true);
    let value = "";
    // ✅ UPDATED — Support both visible_columns and visible_fields
    if (condField === "visible_columns" || condField === "visible_fields") {
      const keys = Object.entries(condColChecks).filter(([, v]) => v).map(([k]) => k);
      if (!keys.length) { toast.error("At least one field required"); setSavingCondition(false); return; }
      value = keys.join(",");
    } else {
      value = condManualVal;
      if (!value.trim()) { toast.error("Value required"); setSavingCondition(false); return; }
    }
    try {
      if (existingVisCond && (condField === "visible_columns" || condField === "visible_fields")) {
        await api.updateCondition((existingVisCond as any).id, { condition_value: value, logic: condLogic });
        toast.success("Condition updated!");
      } else {
        await api.createCondition({ user_permission_id: condViewPerm.id, module_id: condModuleId, condition_field: condField, condition_value: value, logic: condLogic });
        toast.success("Condition created!");
      }
      setShowConditionModal(false);
      setConditions(await api.getConditions());
    } catch (err: any) { toast.error(err?.message || "Failed"); }
    finally { setSavingCondition(false); }
  };

  const handleDeleteCondition = async (id: number) => {
    if (!confirm("Delete this condition?")) return;
    try { await api.deleteCondition(id); toast.success("Deleted"); setConditions(await api.getConditions()); }
    catch { toast.error("Failed"); }
  };

  // ══════════════════════════════════════════════
  //  RENDER
  // ══════════════════════════════════════════════

  if (loading) return <div className={styles.loader}>⏳ Loading Permission Manager...</div>;

  const checkedCount = Object.values(condColChecks).filter(Boolean).length;
  const selectedUser = users.find((u) => u.id === selectedUserId);

  return (
    <div className={styles.container}>

      {/* ── Stats ── */}
      <div className={styles.statsRow}>
        {[
          { label: "Modules",     value: modules.length     },
          { label: "Permissions", value: permissions.length },
          { label: "Roles",       value: roles.length       },
          { label: "Users",       value: users.length       },
        ].map((s) => (
          <div key={s.label} className={styles.statCard}>
            <span className={styles.statValue}>{s.value}</span>
            <span className={styles.statLabel}>{s.label}</span>
          </div>
        ))}
      </div>

      {/* ── Tabs ── */}
      <div className={styles.tabs}>
        {([
          ["modules",    "🏗️ Module Config"],
          ["roles",      "👔 Roles"],
          ["users",      "👥 User Permissions"],
          ["matrix",     "🔐 Matrix"],
          ["conditions", "⚙️ Conditions"],
        ] as [TabKey, string][]).map(([key, label]) => (
          <button
            key={key}
            className={`${styles.tab} ${activeTab === key ? styles.tabActive : ""}`}
            onClick={() => setActiveTab(key)}
          >
            {label}
          </button>
        ))}
      </div>

      {/* ══════════════════════════════════════════
           TAB 1 — MODULE CONFIG
         ══════════════════════════════════════════ */}
      {activeTab === "modules" && (
        <>
          <div className={`${styles.banner} ${styles.bannerPurple}`}>
            🏗️ <strong>Module Config</strong> — Define buttons and columns for each module. Adding a button auto-creates its permission.
          </div>

          {/* Module selector */}
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
            {modules.map((m) => (
              <button
                key={m.id}
                className={`${styles.moduleTab} ${selectedModuleId === m.id ? styles.moduleTabActive : ""}`}
                onClick={() => { setSelectedModuleId(m.id); setShowCreateModule(false); }}
              >
                {m.name}
              </button>
            ))}
            <button className={styles.btnPrimary} onClick={() => setShowCreateModule(!showCreateModule)} style={{ marginLeft: "auto" }}>
              {showCreateModule ? "✕ Cancel" : "➕ New Module"}
            </button>
          </div>

          {/* Create module form */}
          {showCreateModule && (
            <div className={styles.card} style={{ marginBottom: 16 }}>
              <div className={styles.cardHeader}><span className={styles.cardTitle}>Create New Module</span></div>
              <div className={styles.cardBody}>
                <div className={`${styles.formGrid} ${styles.formGrid4}`}>
                  <div>
                    <label className={styles.label}>Module Name *</label>
                    <input className={styles.input} value={newModuleForm.name}
                      onChange={(e) => { const name = e.target.value; setNewModuleForm({ ...newModuleForm, name, slug: name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "") }); }}
                      placeholder="e.g. Invoices" />
                  </div>
                  <div>
                    <label className={styles.label}>Slug *</label>
                    <input className={styles.input} value={newModuleForm.slug}
                      onChange={(e) => setNewModuleForm({ ...newModuleForm, slug: e.target.value })}
                      placeholder="e.g. invoices" />
                  </div>
                  <div>
                    <label className={styles.label}>API Prefix</label>
                    <input className={styles.input} value={newModuleForm.api_prefix}
                      onChange={(e) => setNewModuleForm({ ...newModuleForm, api_prefix: e.target.value })}
                      placeholder="e.g. invoices" />
                  </div>
                  <div>
                    <label className={styles.label}>Description</label>
                    <input className={styles.input} value={newModuleForm.description}
                      onChange={(e) => setNewModuleForm({ ...newModuleForm, description: e.target.value })}
                      placeholder="Optional" />
                  </div>
                </div>
                <div className={styles.formActions}>
                  <button className={styles.btnSecondary} onClick={() => setShowCreateModule(false)}>Cancel</button>
                  <button className={styles.btnPrimary} onClick={handleCreateModule}>✅ Create Module</button>
                </div>
              </div>
            </div>
          )}

          {/* Module detail */}
          {selectedModule && !showCreateModule && (
            <div className={styles.card}>
              <div className={styles.cardHeader}>
                <div>
                  <span className={styles.cardTitle}>{selectedModule.name}</span>
                  <span className={styles.cardSub}>/{selectedModule.slug}</span>
                </div>
                <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <span className={styles.cardCount}>{moduleButtons.length} buttons • {moduleColumns.length} columns</span>
                  <button className={styles.btnDanger} onClick={handleDeleteModule}>🗑 Delete</button>
                </div>
              </div>
              <div className={styles.cardBody}>

                {/* Buttons section */}
                <div style={{ marginBottom: 24 }}>
                  <div className={styles.sectionTitle}>
                    <span>🔘 BUTTON CONFIG</span>
                    <button className={styles.btnGhost} onClick={() => setShowAddButton(!showAddButton)}>
                      {showAddButton ? "✕ Cancel" : "+ Add Button"}
                    </button>
                  </div>

                  {showAddButton && (
                    <div style={{ padding: 14, border: "1px dashed #d4c9ef", borderRadius: 10, background: "#faf9ff", marginBottom: 12 }}>
                      <div className={`${styles.formGrid} ${styles.formGrid4}`}>
                        <div>
                          <label className={styles.label}>Key (action) *</label>
                          <input className={styles.input} value={newButton.key}
                            onChange={(e) => setNewButton({ ...newButton, key: e.target.value.toLowerCase().replace(/\s/g, "_") })}
                            placeholder="e.g. bulk_import" />
                        </div>
                        <div>
                          <label className={styles.label}>Label *</label>
                          <input className={styles.input} value={newButton.label}
                            onChange={(e) => setNewButton({ ...newButton, label: e.target.value })}
                            placeholder="e.g. Bulk Import" />
                        </div>
                        <div>
                          <label className={styles.label}>Position</label>
                          <select className={styles.select} value={newButton.position}
                            onChange={(e) => setNewButton({ ...newButton, position: e.target.value as any })}>
                            <option value="toolbar">Toolbar</option>
                            <option value="row">Row</option>
                            <option value="both">Both</option>
                          </select>
                        </div>
                        <div>
                          <label className={styles.label}>Color</label>
                          <input type="color" className={styles.input} value={newButton.color}
                            onChange={(e) => setNewButton({ ...newButton, color: e.target.value })}
                            style={{ height: 38, padding: 2 }} />
                        </div>
                      </div>
                      <div className={styles.formActions} style={{ borderTop: "none", paddingTop: 8 }}>
                        <button className={styles.btnPrimary} onClick={handleAddButton}>✅ Add Button + Create Permission</button>
                      </div>
                    </div>
                  )}

                  {moduleButtons.length === 0 ? (
                    <p style={{ color: "#9ca3af", fontSize: 12, fontStyle: "italic" }}>No buttons configured.</p>
                  ) : moduleButtons.map((btn) => (
                    <div className={styles.configRow} key={btn.key}>
                      <span className={styles.configPreview} style={{ background: btn.color || "#8b14d4" }}>{btn.icon} {btn.label}</span>
                      <span className={styles.configAction}>{btn.key}</span>
                      <span className={`${styles.badge} ${btn.position === "toolbar" ? styles.badgeToolbar : styles.badgeRow}`}>{btn.position}</span>
                      <span style={{ flex: 1 }} />
                      <button className={styles.btnDanger} onClick={() => handleRemoveButton(btn.key)}>×</button>
                    </div>
                  ))}
                </div>

                {/* Columns section */}
                <div>
                  <div className={styles.sectionTitle}>
                    <span>📊 COLUMN CONFIG</span>
                    <button className={styles.btnGhost} onClick={() => setShowAddColumn(!showAddColumn)}>
                      {showAddColumn ? "✕ Cancel" : "+ Add Column"}
                    </button>
                  </div>

                  {showAddColumn && (
                    <div style={{ padding: 14, border: "1px dashed #d4c9ef", borderRadius: 10, background: "#faf9ff", marginBottom: 12 }}>
                      <div className={`${styles.formGrid} ${styles.formGrid4}`}>
                        <div>
                          <label className={styles.label}>Key *</label>
                          <input className={styles.input} value={newColumn.key}
                            onChange={(e) => setNewColumn({ ...newColumn, key: e.target.value.toLowerCase().replace(/\s/g, "_") })}
                            placeholder="e.g. tax_id" />
                        </div>
                        <div>
                          <label className={styles.label}>Label *</label>
                          <input className={styles.input} value={newColumn.label}
                            onChange={(e) => setNewColumn({ ...newColumn, label: e.target.value })}
                            placeholder="e.g. Tax ID" />
                        </div>
                        <div>
                          <label className={styles.label}>Type</label>
                          <select className={styles.select} value={newColumn.type}
                            onChange={(e) => setNewColumn({ ...newColumn, type: e.target.value as any })}>
                            <option value="text">Text</option>
                            <option value="number">Number</option>
                            <option value="currency">Currency</option>
                            <option value="date">Date</option>
                            <option value="badge">Badge</option>
                            <option value="boolean">Boolean</option>
                          </select>
                        </div>
                        <div style={{ display: "flex", gap: 16, alignItems: "flex-end", paddingBottom: 2 }}>
                          <label style={{ fontSize: 11, display: "flex", alignItems: "center", gap: 4, cursor: "pointer", color: "#7c6b9e", fontWeight: 600 }}>
                            <input type="checkbox" checked={newColumn.sortable} onChange={(e) => setNewColumn({ ...newColumn, sortable: e.target.checked })} style={{ accentColor: "#8b14d4" }} /> Sortable
                          </label>
                          <label style={{ fontSize: 11, display: "flex", alignItems: "center", gap: 4, cursor: "pointer", color: "#7c6b9e", fontWeight: 600 }}>
                            <input type="checkbox" checked={newColumn.default_visible} onChange={(e) => setNewColumn({ ...newColumn, default_visible: e.target.checked })} style={{ accentColor: "#8b14d4" }} /> Visible
                          </label>
                        </div>
                      </div>
                      <div className={styles.formActions} style={{ borderTop: "none", paddingTop: 8 }}>
                        <button className={styles.btnPrimary} onClick={handleAddColumn}>✅ Add Column</button>
                      </div>
                    </div>
                  )}

                  {moduleColumns.length === 0 ? (
                    <p style={{ color: "#9ca3af", fontSize: 12, fontStyle: "italic" }}>No columns configured.</p>
                  ) : moduleColumns.map((col) => (
                    <div className={styles.configRow} key={col.key}>
                      <span className={styles.colKey}>{col.key}</span>
                      <span className={styles.colLabel}>{col.label}</span>
                      <span className={styles.colType}>{col.type}</span>
                      {/* ✅ NEW — show where this column appears */}
                      {(col as any).show_in && (
                        <span style={{ fontSize: 10, color: "#7c6b9e", fontFamily: "monospace" }}>
                          {(col as any).show_in.join(" + ")}
                        </span>
                      )}
                      <span style={{ fontSize: 10, color: col.default_visible ? "#8b14d4" : "#9ca3af" }}>
                        {col.default_visible ? "👁 visible" : "🙈 hidden"}
                      </span>
                      <span style={{ flex: 1 }} />
                      <button className={styles.btnDanger} onClick={() => handleRemoveColumn(col.key)}>×</button>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </>
      )}

      {/* ══════════════════════════════════════════
           TAB 2 — ROLES
         ══════════════════════════════════════════ */}
      {activeTab === "roles" && (
        <>
          <div className={`${styles.banner} ${styles.bannerPurple}`}>
            👔 <strong>Roles</strong> — Group permissions together and assign to users.
          </div>
          <div style={{ marginBottom: 16 }}>
            <button className={styles.btnPrimary} onClick={() => openRoleModal()}>➕ Create New Role</button>
          </div>

          {roles.length === 0 ? (
            <div className={styles.empty}><div className={styles.emptyIcon}>👔</div>No roles yet.</div>
          ) : roles.map((role) => (
            <div className={styles.card} key={role.id}>
              <div className={styles.cardHeader}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span className={`${styles.badge} ${styles.badgeRole}`}>{role.name.toUpperCase()}</span>
                  <span className={styles.cardTitle}>{role.name}</span>
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  <button className={`${styles.btnSecondary} ${styles.btnSmall}`} onClick={() => openRoleModal(role)}>✏️ Edit</button>
                  <button className={styles.btnDanger} onClick={() => handleDeleteRole(role.id)}>🗑 Delete</button>
                </div>
              </div>
              <div className={styles.cardBody}>
                {(role as any).description && (
                  <p style={{ fontSize: 12, color: "#7c6b9e", marginBottom: 12 }}>{(role as any).description}</p>
                )}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: 12 }}>
                  {modules.map((mod) => {
                    const modPerms = (role.permissions || []).filter((p: any) => p.module_id === mod.id || p.module?.id === mod.id);
                    if (!modPerms.length) return null;
                    return (
                      <div key={mod.id}>
                        <div style={{ fontSize: 10, fontWeight: 700, color: "#7c6b9e", marginBottom: 5, textTransform: "uppercase", letterSpacing: "0.4px" }}>{mod.name}</div>
                        <div className={styles.chips}>
                          {modPerms.map((p: any) => (
                            <span className={styles.chip} key={p.id}>
                              <span className={`${styles.badge} ${actionBadgeClass(p.action, styles)}`}>{p.action}</span>
                            </span>
                          ))}
                        </div>
                      </div>
                    );
                  })}
                  {!(role.permissions || []).length && (
                    <p style={{ color: "#9ca3af", fontSize: 12, fontStyle: "italic" }}>No permissions. Click Edit to assign.</p>
                  )}
                </div>
              </div>
            </div>
          ))}

          {/* Role Modal */}
          {showRoleModal && (
            <div className={styles.overlay} onClick={() => setShowRoleModal(false)}>
              <div className={styles.modal} onClick={(e) => e.stopPropagation()} style={{ maxWidth: 700 }}>
                <div className={styles.modalHeader}>
                  <span className={styles.modalTitle}>{editingRole ? `Edit: ${editingRole.name}` : "Create Role"}</span>
                  <button className={styles.modalClose} onClick={() => setShowRoleModal(false)}>×</button>
                </div>
                <div className={styles.modalBody}>
                  <div className={`${styles.formGrid} ${styles.formGrid2}`}>
                    <div>
                      <label className={styles.label}>Role Name *</label>
                      <input className={styles.input} value={roleForm.name}
                        onChange={(e) => setRoleForm({ ...roleForm, name: e.target.value })}
                        placeholder="e.g. Manager" />
                    </div>
                    <div>
                      <label className={styles.label}>Description</label>
                      <input className={styles.input} value={roleForm.description}
                        onChange={(e) => setRoleForm({ ...roleForm, description: e.target.value })}
                        placeholder="e.g. Can view and edit" />
                    </div>
                  </div>
                  <div style={{ marginTop: 16 }}>
                    <label className={styles.label} style={{ marginBottom: 10 }}>Assign Permissions</label>
                    <div className={styles.moduleTabs} style={{ marginBottom: 10 }}>
                      <button className={`${styles.moduleTab} ${!roleModuleFilter ? styles.moduleTabActive : ""}`} onClick={() => setRoleModuleFilter(null)}>All</button>
                      {modules.map((m) => (
                        <button key={m.id} className={`${styles.moduleTab} ${roleModuleFilter === m.id ? styles.moduleTabActive : ""}`} onClick={() => setRoleModuleFilter(m.id)}>{m.name}</button>
                      ))}
                    </div>
                    <div className={styles.checkGrid}>
                      {permissions
                        .filter((p) => !roleModuleFilter || (p as any).module_id === roleModuleFilter || p.module?.id === roleModuleFilter)
                        .map((perm) => {
                          const isOn = rolePermIds.includes(perm.id);
                          const modName = perm.module?.name || modules.find((m) => m.id === (perm as any).module_id)?.name || "";
                          return (
                            <div key={perm.id} className={`${styles.checkItem} ${isOn ? styles.checkItemActive : ""}`}
                              onClick={() => setRolePermIds((prev) => isOn ? prev.filter((id) => id !== perm.id) : [...prev, perm.id])}>
                              <input type="checkbox" className={styles.checkInput} checked={isOn} readOnly />
                              <div>
                                <div className={styles.checkLabel}>
                                  <span className={`${styles.badge} ${actionBadgeClass(perm.action, styles)}`}>{perm.action}</span>
                                </div>
                                <div style={{ fontSize: 9, color: "#9ca3af", marginTop: 2 }}>{modName}</div>
                              </div>
                            </div>
                          );
                        })}
                    </div>
                  </div>
                </div>
                <div className={styles.modalFooter}>
                  <button className={styles.btnSecondary} onClick={() => setShowRoleModal(false)}>Cancel</button>
                  <button className={styles.btnPrimary} onClick={handleSaveRole}>{editingRole ? "Update Role" : "Create Role"}</button>
                </div>
              </div>
            </div>
          )}
        </>
      )}

      {/* ══════════════════════════════════════════
           TAB 3 — USER PERMISSIONS
         ══════════════════════════════════════════ */}
      {activeTab === "users" && (
        <div style={{ display: "flex", gap: 0, height: "calc(100vh - 280px)", border: "1px solid #e8e2f7", borderRadius: 14, overflow: "hidden", background: "#fff" }}>

          {/* Left panel */}
          <div style={{ width: 260, minWidth: 260, borderRight: "1px solid #e8e2f7", display: "flex", flexDirection: "column", background: "#faf9ff" }}>
            <div style={{ padding: "14px 12px 10px", borderBottom: "1px solid #e8e2f7" }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: "#7c6b9e", marginBottom: 8, textTransform: "uppercase", letterSpacing: "0.5px" }}>
                👥 Users ({users.length})
              </div>
              <input type="text" placeholder="Search users..." value={userSearch}
                onChange={(e) => setUserSearch(e.target.value)}
                style={{ width: "100%", padding: "7px 10px", borderRadius: 8, border: "1.5px solid #e8e2f7", fontSize: 12, outline: "none", boxSizing: "border-box", fontFamily: "inherit" }}
                onFocus={(e) => { e.target.style.borderColor = "#8b14d4"; }}
                onBlur={(e) => { e.target.style.borderColor = "#e8e2f7"; }}
              />
            </div>
            <div style={{ flex: 1, overflowY: "auto" }}>
              {filteredUsers.map((user) => {
                const isSelected = user.id === selectedUserId;
                const initials = `${user.firstName?.[0] ?? ""}${user.lastName?.[0] ?? ""}`.toUpperCase();
                return (
                  <div key={user.id} onClick={() => setSelectedUserId(user.id)} style={{
                    display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", cursor: "pointer",
                    background: isSelected ? "rgba(139,20,212,0.08)" : "transparent",
                    borderLeft: isSelected ? "3px solid #8b14d4" : "3px solid transparent",
                    transition: "all 0.12s",
                  }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: "50%", flexShrink: 0,
                      background: isSelected ? "#8b14d4" : "#e8e2f7",
                      color: isSelected ? "#fff" : "#7c6b9e",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontSize: 11, fontWeight: 700,
                    }}>{initials || "?"}</div>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontSize: 12, fontWeight: isSelected ? 700 : 500, color: isSelected ? "#1a0440" : "#374151", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {user.firstName} {user.lastName}
                      </div>
                      <div style={{ fontSize: 10, color: "#9ca3af", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user.email}</div>
                    </div>
                    {isSelected && (
                      <div style={{ fontSize: 10, fontWeight: 700, color: "#8b14d4", background: "rgba(139,20,212,0.1)", borderRadius: 10, padding: "2px 6px", flexShrink: 0 }}>
                        {userPermissions.length}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Right panel */}
          <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
            {/* Header */}
            <div style={{ padding: "12px 16px", borderBottom: "1px solid #e8e2f7", display: "flex", alignItems: "center", justifyContent: "space-between", background: "#fff", flexWrap: "wrap", gap: 8 }}>
              {selectedUser ? (
                <div>
                  <div style={{ fontSize: 14, fontWeight: 700, color: "#1a0440" }}>{selectedUser.firstName} {selectedUser.lastName}</div>
                  <div style={{ fontSize: 11, color: "#7c6b9e" }}>{selectedUser.email} — <strong style={{ color: "#8b14d4" }}>{userPermissions.length}</strong> permission(s)</div>
                </div>
              ) : (
                <div style={{ fontSize: 13, color: "#9ca3af" }}>← Select a user to manage permissions</div>
              )}
              {selectedUser && (
                <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
                  <button onClick={() => setUserPermModuleFilter(null)} style={{ padding: "4px 10px", borderRadius: 20, fontSize: 11, cursor: "pointer", border: !userPermModuleFilter ? "1.5px solid #8b14d4" : "1.5px solid #e8e2f7", background: !userPermModuleFilter ? "rgba(139,20,212,0.08)" : "#faf9ff", color: !userPermModuleFilter ? "#8b14d4" : "#7c6b9e", fontWeight: !userPermModuleFilter ? 700 : 500 }}>All</button>
                  {modules.map((m) => (
                    <button key={m.id} onClick={() => setUserPermModuleFilter(m.id)} style={{ padding: "4px 10px", borderRadius: 20, fontSize: 11, cursor: "pointer", border: userPermModuleFilter === m.id ? "1.5px solid #8b14d4" : "1.5px solid #e8e2f7", background: userPermModuleFilter === m.id ? "rgba(139,20,212,0.08)" : "#faf9ff", color: userPermModuleFilter === m.id ? "#8b14d4" : "#7c6b9e", fontWeight: userPermModuleFilter === m.id ? 700 : 500 }}>{m.name}</button>
                  ))}
                </div>
              )}
            </div>

            {/* Checkbox grid */}
            <div style={{ flex: 1, overflowY: "auto", padding: 16 }}>
              {!selectedUserId ? (
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: "100%", color: "#9ca3af" }}>
                  <div style={{ fontSize: 44, marginBottom: 10 }}>🔐</div>
                  <p style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>Select a user from the left</p>
                </div>
              ) : loadingUserPerms ? (
                <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", color: "#7c6b9e", fontSize: 13 }}>Loading permissions...</div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  {permissionsByModule.map(({ module: mod, perms }) => {
                    const assignedCount = perms.filter((p) => hasPermission(p.id)).length;
                    return (
                      <div key={mod.id} style={{ border: "1px solid #e8e2f7", borderRadius: 12, overflow: "hidden" }}>
                        <div style={{ padding: "10px 14px", background: assignedCount > 0 ? "rgba(139,20,212,0.05)" : "#faf9ff", borderBottom: "1px solid #e8e2f7", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                            <div style={{ width: 7, height: 7, borderRadius: "50%", background: assignedCount > 0 ? "#8b14d4" : "#d4c9ef" }} />
                            <span style={{ fontSize: 13, fontWeight: 700, color: "#1a0440" }}>{mod.name}</span>
                            <span style={{ fontSize: 10, color: "#7c6b9e", fontFamily: "monospace", background: "#ede8f7", padding: "1px 5px", borderRadius: 3 }}>{mod.slug}</span>
                            <span style={{ fontSize: 11, color: assignedCount > 0 ? "#8b14d4" : "#9ca3af", fontWeight: 700 }}>{assignedCount}/{perms.length}</span>
                          </div>
                          <div style={{ display: "flex", gap: 5 }}>
                            <button onClick={() => handleToggleAllModulePerms(mod.id, true)} style={{ fontSize: 10, padding: "3px 8px", borderRadius: 5, border: "1px solid var(--pm-border)", background: "rgba(139,20,212,0.08)", color: "#8b14d4", cursor: "pointer", fontWeight: 700 }}>✅ All</button>
                            <button onClick={() => handleToggleAllModulePerms(mod.id, false)} style={{ fontSize: 10, padding: "3px 8px", borderRadius: 5, border: "1px solid #fecaca", background: "#fef2f2", color: "#dc2626", cursor: "pointer", fontWeight: 700 }}>🚫 None</button>
                          </div>
                        </div>
                        <div style={{ padding: "10px 14px", display: "flex", flexWrap: "wrap", gap: 8 }}>
                          {perms.map((perm) => {
                            const checked = hasPermission(perm.id);
                            const key = `${(perm as any).module_id ?? perm.module?.id}-${perm.action}`;
                            const isSaving = savingKey === key;
                            const color = getActionColor(perm.action);
                            return (
                              <label key={perm.id} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: 8, cursor: isSaving ? "wait" : "pointer", border: `1.5px solid ${checked ? color + "55" : "#e8e2f7"}`, background: checked ? color + "10" : "#faf9ff", opacity: isSaving ? 0.6 : 1, transition: "all 0.15s", userSelect: "none" }}
                                onMouseEnter={(e) => { if (!isSaving) { e.currentTarget.style.borderColor = color; e.currentTarget.style.background = color + "18"; } }}
                                onMouseLeave={(e) => { e.currentTarget.style.borderColor = checked ? color + "55" : "#e8e2f7"; e.currentTarget.style.background = checked ? color + "10" : "#faf9ff"; }}>
                                <input type="checkbox" checked={checked} disabled={isSaving} onChange={() => handleTogglePermission(perm)} style={{ display: "none" }} />
                                <div style={{ width: 15, height: 15, borderRadius: 3, flexShrink: 0, border: `2px solid ${checked ? color : "#d4c9ef"}`, background: checked ? color : "#fff", display: "flex", alignItems: "center", justifyContent: "center", transition: "all 0.15s" }}>
                                  {isSaving ? <span style={{ fontSize: 7, color: "#fff" }}>⋯</span> : checked ? <svg width="8" height="6" viewBox="0 0 9 7" fill="none"><path d="M1 3.5L3.5 6L8 1" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg> : null}
                                </div>
                                <span style={{ fontSize: 12, fontWeight: checked ? 700 : 500, color: checked ? color : "#7c6b9e", textTransform: "capitalize" }}>{formatAction(perm.action)}</span>
                              </label>
                            );
                          })}
                        </div>
                      </div>
                    );
                  })}
                  {permissionsByModule.length === 0 && (
                    <div style={{ textAlign: "center", padding: 40, color: "#9ca3af", fontSize: 13 }}>No permissions found</div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════
           TAB 4 — PERMISSION MATRIX
         ══════════════════════════════════════════ */}
      {activeTab === "matrix" && (
        <>
          <div className={`${styles.banner} ${styles.bannerPurple}`}>
            🔐 <strong>Permission Matrix</strong> — Overview of all role permissions per module.
          </div>
          {modules.map((mod) => {
            const modPerms = permissions.filter((p) => (p as any).module_id === mod.id || p.module?.id === mod.id);
            if (!modPerms.length) return null;
            return (
              <div className={styles.card} key={mod.id}>
                <div className={styles.cardHeader}>
                  <span className={styles.cardTitle}>{mod.name} <span className={styles.cardSub}>/{mod.slug}</span></span>
                  <span className={styles.cardCount}>{modPerms.length} permissions</span>
                </div>
                <div className={styles.tableWrap}>
                  <table className={styles.table}>
                    <thead>
                      <tr>
                        <th>Permission</th>
                        <th>Action</th>
                        {roles.map((r) => <th key={r.id} className={styles.matrixCenter}>{r.name}</th>)}
                      </tr>
                    </thead>
                    <tbody>
                      {modPerms.map((perm) => (
                        <tr key={perm.id}>
                          <td style={{ fontWeight: 600, color: "#1a0440" }}>{perm.name}</td>
                          <td><span className={`${styles.badge} ${actionBadgeClass(perm.action, styles)}`}>{perm.action}</span></td>
                          {roles.map((role) => {
                            const has = (role.permissions || []).some((rp) => rp.id === perm.id);
                            return <td key={role.id} className={`${styles.matrixCheck} ${has ? styles.matrixCheckOn : styles.matrixCheckOff}`}>{has ? "✅" : "—"}</td>;
                          })}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            );
          })}
        </>
      )}

      {/* ══════════════════════════════════════════
           TAB 5 — CONDITIONS
         ══════════════════════════════════════════ */}
      {activeTab === "conditions" && (
        <>
          <div className={`${styles.banner} ${styles.bannerPurple}`}>
            ⚙️ <strong>Conditions</strong> — Control which columns each user can see per module.
          </div>
          <div style={{ marginBottom: 16 }}>
            <button className={styles.btnPrimary} onClick={openConditionModal}>➕ Manage Column Visibility</button>
          </div>
          <div className={styles.card}>
            <div className={styles.cardHeader}>
              <span className={styles.cardTitle}>All Conditions</span>
              <span className={styles.cardCount}>{conditions.length} condition(s)</span>
            </div>
            <div className={styles.tableWrap}>
              <table className={styles.table}>
                <thead>
                  <tr>
                    <th>User</th><th>Permission</th><th>Module</th>
                    <th>Field</th><th>Value</th><th>Logic</th>
                    <th style={{ width: 50 }}></th>
                  </tr>
                </thead>
                <tbody>
                  {conditions.length === 0 ? (
                    <tr><td colSpan={7} style={{ textAlign: "center", padding: 24, color: "#9ca3af" }}>No conditions yet.</td></tr>
                  ) : conditions.map((cond: any) => (
                    <tr key={cond.id}>
                      <td style={{ fontWeight: 600, color: "#1a0440" }}>
                        {cond.userPermission?.user?.firstName || cond.userPermission?.user?.name || cond.userPermission?.user?.email || "—"}
                      </td>
                      <td>
                        {cond.userPermission?.permission
                          ? <span className={`${styles.badge} ${actionBadgeClass(cond.userPermission.permission.action, styles)}`}>{cond.userPermission.permission.action}</span>
                          : "—"}
                      </td>
                      <td className={styles.mono}>{cond.module?.name || "—"}</td>
                      <td className={styles.monoB}>{cond.condition_field}</td>
                      <td style={{ maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: 11 }} title={cond.condition_value}>{cond.condition_value}</td>
                      <td><span className={`${styles.badge} ${styles.badgeCustom}`}>{cond.logic || "equals"}</span></td>
                      <td><button className={styles.btnDanger} onClick={() => handleDeleteCondition(cond.id)}>×</button></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Condition Modal */}
          {showConditionModal && (
            <div className={styles.overlay} onClick={() => setShowConditionModal(false)}>
              <div className={styles.modal} onClick={(e) => e.stopPropagation()} style={{ maxWidth: 640 }}>
                <div className={styles.modalHeader}>
                  <span className={styles.modalTitle}>Manage Column Visibility</span>
                  <button className={styles.modalClose} onClick={() => setShowConditionModal(false)}>×</button>
                </div>
                <div className={styles.modalBody}>
                  <div style={{ marginBottom: 14 }}>
                    <label className={styles.label}>Select User</label>
                    <select className={styles.select} value={condUserId || ""} onChange={(e) => { setCondUserId(e.target.value ? +e.target.value : null); setCondModuleId(null); }}>
                      <option value="">— Choose a user —</option>
                      {users.map((u) => <option key={u.id} value={u.id}>{u.firstName} {u.lastName} ({u.email})</option>)}
                    </select>
                  </div>
                  {condUserId && (
                    <div style={{ marginBottom: 14 }}>
                      <label className={styles.label}>Select Module</label>
                      <select className={styles.select} value={condModuleId || ""} onChange={(e) => setCondModuleId(e.target.value ? +e.target.value : null)}>
                        <option value="">— Choose a module —</option>
                        {modules.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
                      </select>
                    </div>
                  )}
                  {condUserId && condModuleId && (
                    <div style={{ marginBottom: 14 }}>
                      <label className={styles.label}>Condition Type</label>
                      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                        {/* ✅ NEW — Added "visible_fields" to the list */}
                        {["visible_columns", "visible_fields", "site", "status", "created_by"].map((field) => (
                          <button key={field} onClick={() => setCondField(field)} style={{ padding: "7px 14px", borderRadius: 8, border: condField === field ? "2px solid #8b14d4" : "1px solid #e8e2f7", background: condField === field ? "rgba(139,20,212,0.08)" : "#fff", color: condField === field ? "#8b14d4" : "#374151", fontWeight: condField === field ? 700 : 500, fontSize: 12, cursor: "pointer", fontFamily: "inherit" }}>
                            {field}
                          </button>
                        ))}
                      </div>
                      {/* ✅ NEW — Helpful hint for the user */}
                      <div style={{ fontSize: 11, color: "#9ca3af", marginTop: 6, fontStyle: "italic" }}>
                        {condField === "visible_columns" && "🔸 Controls which columns this user sees in the data TABLE"}
                        {condField === "visible_fields" && "🔸 Controls which fields this user sees in the FORM"}
                      </div>
                    </div>
                  )}
                  {/* ✅ UPDATED — Now handles both visible_columns AND visible_fields */}
                  {condUserId && condModuleId && (condField === "visible_columns" || condField === "visible_fields") && (
                    <>
                      {!condViewPerm ? (
                        <div style={{ padding: "12px 16px", background: "#fef2f2", border: "1px solid #fecaca", borderRadius: 8, marginBottom: 12, fontSize: 12, color: "#dc2626" }}>
                          ⚠️ This user does NOT have a <strong>view</strong> permission for this module. Assign it first in User Permissions tab.
                        </div>
                      ) : (
                        <>
                          {existingVisCond && (
                            <div style={{ padding: "8px 14px", background: "#fefce8", border: "1px solid #fde68a", borderRadius: 8, marginBottom: 10, fontSize: 12, color: "#92400e" }}>
                              ✏️ Existing condition found — editing it.
                            </div>
                          )}
                          {condFilteredCols.length === 0 ? (
                            <div style={{ padding: "12px 16px", background: "#fff7ed", border: "1px solid #fed7aa", borderRadius: 8, fontSize: 12, color: "#9a3412" }}>
                              ⚠️ No {condField === "visible_fields" ? "form" : "table"} fields defined for this module. Add columns with <code>show_in: ["{condField === "visible_fields" ? "form" : "table"}"]</code> first.
                            </div>
                          ) : (
                            <>
                              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                                <span style={{ fontSize: 12, fontWeight: 600, color: "#7c6b9e" }}>{checkedCount}/{condFilteredCols.length} visible</span>
                                <div style={{ display: "flex", gap: 6 }}>
                                  <button onClick={() => { const c: Record<string, boolean> = {}; condFilteredCols.forEach((col) => { c[col.key] = true; }); setCondColChecks(c); }} style={{ fontSize: 11, padding: "4px 10px", border: "1px solid #d4c9ef", borderRadius: 6, cursor: "pointer", background: "rgba(139,20,212,0.06)", color: "#8b14d4" }}>✅ Show All</button>
                                  <button onClick={() => { const c: Record<string, boolean> = {}; condFilteredCols.forEach((col) => { c[col.key] = false; }); setCondColChecks(c); }} style={{ fontSize: 11, padding: "4px 10px", border: "1px solid #fecaca", borderRadius: 6, cursor: "pointer", background: "#fef2f2", color: "#dc2626" }}>🚫 Hide All</button>
                                </div>
                              </div>
                              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(210px, 1fr))", gap: 6, maxHeight: 320, overflowY: "auto", padding: 4 }}>
                                {condFilteredCols.map((col) => {
                                  const isChecked = condColChecks[col.key] ?? true;
                                  return (
                                    <div key={col.key} onClick={() => setCondColChecks((prev) => ({ ...prev, [col.key]: !prev[col.key] }))} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderRadius: 9, border: isChecked ? "2px solid #8b14d4" : "2px solid #e8e2f7", background: isChecked ? "rgba(139,20,212,0.06)" : "#faf9ff", cursor: "pointer", transition: "all 0.15s" }}>
                                      <div style={{ width: 36, height: 20, borderRadius: 12, background: isChecked ? "#8b14d4" : "#d4c9ef", position: "relative", transition: "background 0.15s", flexShrink: 0 }}>
                                        <div style={{ width: 16, height: 16, borderRadius: "50%", background: "#fff", position: "absolute", top: 2, left: isChecked ? 18 : 2, transition: "left 0.15s", boxShadow: "0 1px 3px rgba(0,0,0,0.2)" }} />
                                      </div>
                                      <div>
                                        <div style={{ fontSize: 12, fontWeight: 600, color: isChecked ? "#8b14d4" : "#9ca3af" }}>{col.label}</div>
                                        <div style={{ fontSize: 10, color: "#9ca3af", fontFamily: "monospace" }}>{col.key}</div>
                                      </div>
                                      <span style={{ marginLeft: "auto", fontSize: 14 }}>{isChecked ? "👁" : "🙈"}</span>
                                    </div>
                                  );
                                })}
                              </div>
                            </>
                          )}
                        </>
                      )}
                    </>
                  )}
                  {condUserId && condModuleId && condField !== "visible_columns" && condField !== "visible_fields" && condViewPerm && (
                    <div style={{ display: "flex", gap: 12 }}>
                      <div style={{ flex: 1 }}>
                        <label className={styles.label}>Value</label>
                        <input className={styles.input} value={condManualVal} onChange={(e) => setCondManualVal(e.target.value)} placeholder="Enter value..." />
                      </div>
                      <div style={{ width: 150 }}>
                        <label className={styles.label}>Logic</label>
                        <select className={styles.select} value={condLogic} onChange={(e) => setCondLogic(e.target.value)}>
                          <option value="equals">equals</option>
                          <option value="not_equals">not_equals</option>
                          <option value="includes">includes</option>
                        </select>
                      </div>
                    </div>
                  )}
                </div>
                <div className={styles.modalFooter}>
                  <button className={styles.btnSecondary} onClick={() => setShowConditionModal(false)}>Cancel</button>
                  {condViewPerm && (
                    <button className={styles.btnPrimary} onClick={handleSaveCondition} disabled={savingCondition} style={{ opacity: savingCondition ? 0.6 : 1 }}>
                      {savingCondition ? "Saving..." : existingVisCond && (condField === "visible_columns" || condField === "visible_fields") ? "✅ Update Condition" : "✅ Create Condition"}
                    </button>
                  )}
                </div>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}