"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Check,
  X,
  Lock,
  Unlock,
  Eye,
  Edit3,
  Trash2,
  PlusCircle,
  FileText,
  FileSpreadsheet,
  Printer,
  Users,
  Sliders,
  Settings,
  Shield,
  CalendarCheck,
  Save,
  CheckCircle2,
  Award,
  Sparkles,
  Layers,
} from "lucide-react";
import { toast } from "sonner";

interface PermissionAction {
  id: string;
  name: string;
  category: "Attendance Operations" | "Data & Record CRUD" | "Reporting & Exports" | "System Governance";
  description: string;
  icon: React.ElementType;
}

// The 14 Granular Actions explicitly mandated by client PRD §15
const GRANULAR_ACTIONS: PermissionAction[] = [
  // 1. Attendance Operations
  {
    id: "attendance_entry",
    name: "Attendance Entry",
    category: "Attendance Operations",
    description: "Record daily class and laboratory attendance using P, A, C, H status codes",
    icon: CalendarCheck,
  },
  {
    id: "attendance_modification",
    name: "Attendance Modification",
    category: "Attendance Operations",
    description: "Update attendance records within authorized timeframes and audit reasons",
    icon: Edit3,
  },
  {
    id: "attendance_lock",
    name: "Attendance Lock",
    category: "Attendance Operations",
    description: "Finalize and freeze daily class attendance sessions to prevent tampering",
    icon: Lock,
  },
  {
    id: "attendance_unlock",
    name: "Attendance Unlock",
    category: "Attendance Operations",
    description: "Authorize reopening locked attendance sessions for statutory corrections",
    icon: Unlock,
  },

  // 2. Data & Record CRUD
  {
    id: "view",
    name: "View",
    category: "Data & Record CRUD",
    description: "Access and view academic sessions, students, faculty, and timetable master records",
    icon: Eye,
  },
  {
    id: "add",
    name: "Add",
    category: "Data & Record CRUD",
    description: "Create new students, faculty accounts, subjects, allocations, and room masters",
    icon: PlusCircle,
  },
  {
    id: "edit",
    name: "Edit",
    category: "Data & Record CRUD",
    description: "Modify existing student profiles, courses, credit units, and teaching assignments",
    icon: Edit3,
  },
  {
    id: "delete",
    name: "Delete",
    category: "Data & Record CRUD",
    description: "Remove or decommission unassigned courses, draft schedules, or obsolete allocations",
    icon: Trash2,
  },

  // 3. Reporting & Exports
  {
    id: "report_generation",
    name: "Report Generation",
    category: "Reporting & Exports",
    description: "Generate 12 statutory attendance registers, APRs, and percentage analytics",
    icon: FileText,
  },
  {
    id: "export",
    name: "Export",
    category: "Reporting & Exports",
    description: "Export institutional registers and defaulter rosters to Excel (.xlsx) and CSV",
    icon: FileSpreadsheet,
  },
  {
    id: "print",
    name: "Print",
    category: "Reporting & Exports",
    description: "Send official APR hall tickets, clearance slips, and registers to physical printers",
    icon: Printer,
  },

  // 4. System Governance
  {
    id: "user_management",
    name: "User Management",
    category: "System Governance",
    description: "Administer user credentials, security roles, password resets, and account access",
    icon: Users,
  },
  {
    id: "academic_settings",
    name: "Academic Settings",
    category: "System Governance",
    description: "Configure academic sessions, 75% thresholds, medical ceilings, and condonation rules",
    icon: Sliders,
  },
  {
    id: "system_configuration",
    name: "System Configuration",
    category: "System Governance",
    description: "Full control over institutional profile, database backups, and global system parameters",
    icon: Settings,
  },
];

const ROLES = [
  { id: "super_admin", name: "Super Administrator", badge: "Full Access", color: "bg-red-50 text-red-700 border-red-200" },
  { id: "department_admin", name: "Academic / Department Administrator", badge: "Academic & Dept Ops", color: "bg-indigo-50 text-indigo-700 border-indigo-200" },
  { id: "academic_admin", name: "Academic Administrator", badge: "Academic Ops", color: "bg-blue-50 text-blue-700 border-blue-200" },
  { id: "faculty", name: "Faculty / Teachers", badge: "Instructional", color: "bg-emerald-50 text-emerald-700 border-emerald-200" },
  { id: "student_parent", name: "Student / Parent", badge: "Personal View", color: "bg-purple-50 text-purple-700 border-purple-200" },
  { id: "auditor", name: "External Auditor", badge: "Read-Only", color: "bg-amber-50 text-amber-700 border-amber-200" },
];

export default function PermissionsMatrixPage() {
  const [selectedRole, setSelectedRole] = useState<string>("department_admin");
  const [activeTab, setActiveTab] = useState<"role_editor" | "full_matrix">("role_editor");
  const [searchQuery, setSearchQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("All");

  // Initial State mapping all 14 actions for all roles
  const [permissionsState, setPermissionsState] = useState<Record<string, Record<string, boolean>>>({
    super_admin: {
      view: true,
      add: true,
      edit: true,
      delete: true,
      attendance_entry: true,
      attendance_modification: true,
      attendance_lock: true,
      attendance_unlock: true,
      report_generation: true,
      export: true,
      print: true,
      user_management: true,
      academic_settings: true,
      system_configuration: true,
    },
    department_admin: {
      view: true,
      add: true,
      edit: true,
      delete: true,
      attendance_entry: true,
      attendance_modification: true,
      attendance_lock: true,
      attendance_unlock: true,
      report_generation: true,
      export: true,
      print: true,
      user_management: true,
      academic_settings: true,
      system_configuration: false,
    },
    academic_admin: {
      view: true,
      add: true,
      edit: true,
      delete: true,
      attendance_entry: true,
      attendance_modification: true,
      attendance_lock: true,
      attendance_unlock: true,
      report_generation: true,
      export: true,
      print: true,
      user_management: true,
      academic_settings: true,
      system_configuration: false,
    },
    faculty: {
      view: true,
      add: false,
      edit: false,
      delete: false,
      attendance_entry: true,
      attendance_modification: true,
      attendance_lock: true,
      attendance_unlock: false,
      report_generation: true,
      export: true,
      print: true,
      user_management: false,
      academic_settings: false,
      system_configuration: false,
    },
    student_parent: {
      view: true,
      add: false,
      edit: false,
      delete: false,
      attendance_entry: false,
      attendance_modification: false,
      attendance_lock: false,
      attendance_unlock: false,
      report_generation: true,
      export: false,
      print: true,
      user_management: false,
      academic_settings: false,
      system_configuration: false,
    },
    auditor: {
      view: true,
      add: false,
      edit: false,
      delete: false,
      attendance_entry: false,
      attendance_modification: false,
      attendance_lock: false,
      attendance_unlock: false,
      report_generation: true,
      export: true,
      print: true,
      user_management: false,
      academic_settings: false,
      system_configuration: false,
    },
  });

  const togglePermission = (roleId: string, actionId: string) => {
    // Prevent removing super_admin critical access
    if (roleId === "super_admin" && (actionId === "user_management" || actionId === "system_configuration")) {
      toast.error("Super Administrator must retain root security & system privileges");
      return;
    }

    setPermissionsState((prev) => ({
      ...prev,
      [roleId]: {
        ...prev[roleId],
        [actionId]: !prev[roleId]?.[actionId],
      },
    }));
  };

  const handleGrantAll = (roleId: string) => {
    const updated: Record<string, boolean> = {};
    GRANULAR_ACTIONS.forEach((action) => {
      updated[action.id] = true;
    });
    setPermissionsState((prev) => ({ ...prev, [roleId]: updated }));
    toast.success(`Granted all 14 permissions to ${ROLES.find((r) => r.id === roleId)?.name}`);
  };

  const handleRevokeAll = (roleId: string) => {
    if (roleId === "super_admin") {
      toast.error("Cannot revoke all permissions from Super Administrator");
      return;
    }
    const updated: Record<string, boolean> = {};
    GRANULAR_ACTIONS.forEach((action) => {
      updated[action.id] = false;
    });
    setPermissionsState((prev) => ({ ...prev, [roleId]: updated }));
    toast.info(`Revoked non-essential permissions for ${ROLES.find((r) => r.id === roleId)?.name}`);
  };

  const handleSaveMatrix = () => {
    toast.success("Security configuration saved! Granular role permissions active across all institutional endpoints.");
  };

  // Filter actions for display
  const filteredActions = GRANULAR_ACTIONS.filter((action) => {
    const matchesSearch =
      searchQuery === "" ||
      action.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      action.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCat = categoryFilter === "All" || action.category === categoryFilter;
    return matchesSearch && matchesCat;
  });

  const currentRoleObj = ROLES.find((r) => r.id === selectedRole) || ROLES[1];
  const rolePermissions = permissionsState[selectedRole] || {};
  const enabledCount = Object.values(rolePermissions).filter(Boolean).length;

  return (
    <div className="space-y-6 pb-12 font-sans bg-[#F8FAFC] min-h-screen text-slate-800">
      {/* 1. Header Bar */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/admin/dashboard" className="hover:text-[#1769E8] transition-colors">
            Home
          </Link>
          <span>&gt;</span>
          <Link href="/admin/roles" className="hover:text-[#1769E8] transition-colors">
            Users & Roles
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Permissions Matrix</span>
        </div>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <div className="flex items-center gap-2.5">
              <h1 className="text-2xl sm:text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
                Role & Permission Management
              </h1>
              <span className="px-2.5 py-0.5 rounded-full text-[11px] font-extrabold bg-[#F4B400]/20 text-[#7a5e1e] border border-[#F4B400]/40">
                PRD §15 Compliant
              </span>
            </div>
            <p className="text-xs sm:text-sm text-[#64748B] mt-1 font-normal">
              Granular access controls for all 14 administrative actions. Configure role permissions dynamically without code changes.
            </p>
          </div>

          <div className="flex items-center gap-2.5">
            <button
              onClick={() => toast.success("Exporting security permission matrix to Excel...")}
              className="px-3.5 py-2 bg-white border border-[#E2E8F0] rounded-lg text-xs font-semibold text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-1.5 shadow-2xs cursor-pointer"
            >
              <FileSpreadsheet className="w-3.5 h-3.5 text-emerald-600" />
              <span>Export Matrix</span>
            </button>
            <button
              onClick={handleSaveMatrix}
              className="px-4 py-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-bold transition-colors flex items-center gap-1.5 shadow-xs cursor-pointer"
            >
              <Save className="w-3.5 h-3.5" />
              <span>Save Configuration</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Top PRD §15 Compliance Banner */}
      <div className="p-4 rounded-xl bg-gradient-to-r from-[#081A2E] via-[#0F2844] to-[#17385A] text-white shadow-xs border border-[#1b3d63] flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-lg bg-[#F4B400] text-[#081A2E] flex items-center justify-center shrink-0 font-bold shadow-xs">
            <Shield className="w-5 h-5" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="text-sm font-bold text-white tracking-wide">
                Institutional Access Safeguards Active
              </span>
              <span className="text-[10px] font-bold px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-400/30">
                14 Operational Actions
              </span>
            </div>
            <p className="text-xs text-slate-300 mt-0.5">
              Empowers administrators to configure operational permissions independently for View, Add, Edit, Delete, Attendance Entry, Modification, Lock, Unlock, Reports, Export, Print, and Governance.
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          <div className="px-3 py-1.5 rounded-lg bg-white/10 text-center border border-white/15">
            <span className="text-[10px] text-slate-300 block font-mono">Roles Active</span>
            <span className="text-sm font-extrabold text-[#F4B400]">{ROLES.length}</span>
          </div>
          <div className="px-3 py-1.5 rounded-lg bg-white/10 text-center border border-white/15">
            <span className="text-[10px] text-slate-300 block font-mono">Actions</span>
            <span className="text-sm font-extrabold text-[#F4B400]">{GRANULAR_ACTIONS.length}</span>
          </div>
        </div>
      </div>

      {/* 3. View Switcher Tabs & Filter Bar */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-3.5 space-y-3">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-100 pb-3">
          {/* Main Navigation Tabs */}
          <div className="flex items-center gap-1.5 bg-slate-100 p-1 rounded-lg">
            <button
              onClick={() => setActiveTab("role_editor")}
              className={`px-3 py-1.5 rounded-md text-xs font-bold transition-all cursor-pointer ${
                activeTab === "role_editor"
                  ? "bg-white text-[#071A4D] shadow-xs"
                  : "text-slate-600 hover:text-slate-900"
              }`}
            >
              Role-wise Interactive Editor
            </button>
            <button
              onClick={() => setActiveTab("full_matrix")}
              className={`px-3 py-1.5 rounded-md text-xs font-bold transition-all cursor-pointer ${
                activeTab === "full_matrix"
                  ? "bg-white text-[#071A4D] shadow-xs"
                  : "text-slate-600 hover:text-slate-900"
              }`}
            >
              Complete Cross-Role Matrix (14 × 5)
            </button>
          </div>

          {/* Category Filter Chips */}
          <div className="flex items-center gap-1 overflow-x-auto text-[11px] font-semibold">
            {["All", "Attendance Operations", "Data & Record CRUD", "Reporting & Exports", "System Governance"].map(
              (cat) => (
                <button
                  key={cat}
                  onClick={() => setCategoryFilter(cat)}
                  className={`px-2.5 py-1 rounded-md transition-colors shrink-0 cursor-pointer ${
                    categoryFilter === cat
                      ? "bg-[#071A4D] text-white"
                      : "bg-slate-50 text-slate-600 hover:bg-slate-100 border border-slate-200"
                  }`}
                >
                  {cat}
                </button>
              )
            )}
          </div>
        </div>

        {/* Search & Actions Bar */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div className="relative flex-1 max-w-md">
            <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search by action name, operational category, or description..."
              className="w-full pl-8 pr-3 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-xs text-slate-900 focus:outline-none focus:border-[#1769E8] focus:bg-white transition-all"
            />
          </div>

          {activeTab === "role_editor" && (
            <div className="flex items-center gap-2">
              <button
                onClick={() => handleGrantAll(selectedRole)}
                className="px-3 py-1.5 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 border border-emerald-200 rounded-lg text-xs font-bold transition-colors cursor-pointer"
              >
                + Grant All Actions
              </button>
              <button
                onClick={() => handleRevokeAll(selectedRole)}
                className="px-3 py-1.5 bg-rose-50 text-rose-700 hover:bg-rose-100 border border-rose-200 rounded-lg text-xs font-bold transition-colors cursor-pointer"
              >
                - Revoke Non-Essential
              </button>
            </div>
          )}
        </div>
      </div>

      {/* ============================================================ */}
      {/* TAB 1: ROLE-WISE INTERACTIVE EDITOR                           */}
      {/* ============================================================ */}
      {activeTab === "role_editor" && (
        <div className="space-y-4">
          {/* Role Selector Badges */}
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
            {ROLES.map((role) => {
              const isSelected = selectedRole === role.id;
              const count = Object.values(permissionsState[role.id] || {}).filter(Boolean).length;
              return (
                <button
                  key={role.id}
                  onClick={() => setSelectedRole(role.id)}
                  className={`p-3 rounded-xl border text-left transition-all cursor-pointer flex flex-col justify-between ${
                    isSelected
                      ? "bg-white border-[#1769E8] ring-2 ring-[#1769E8]/20 shadow-xs"
                      : "bg-white border-slate-200 hover:border-slate-300"
                  }`}
                >
                  <div className="flex items-center justify-between mb-1">
                    <span className={`text-[10px] font-bold px-1.5 py-0.2 rounded border ${role.color}`}>
                      {role.badge}
                    </span>
                    <span className="text-[11px] font-mono font-bold text-slate-500">
                      {count}/14
                    </span>
                  </div>
                  <div className="text-xs font-bold text-[#071A4D] truncate mt-1">
                    {role.name}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">
                    {count === 14 ? "Full Administrative" : `${count} Actions Active`}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Action List with Interactive Toggle Switches */}
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
            <div className="p-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/60">
              <div className="flex items-center gap-2">
                <span className="text-xs font-bold text-slate-900">
                  Configuring Privileges for:
                </span>
                <span className="px-2.5 py-0.5 rounded-full text-xs font-extrabold bg-[#1769E8] text-white">
                  {currentRoleObj.name}
                </span>
              </div>
              <span className="text-xs font-mono font-bold text-slate-500">
                {enabledCount} of {GRANULAR_ACTIONS.length} Actions Enabled
              </span>
            </div>

            <div className="divide-y divide-slate-100">
              {filteredActions.map((action, idx) => {
                const Icon = action.icon;
                const isEnabled = !!permissionsState[selectedRole]?.[action.id];

                return (
                  <div
                    key={action.id}
                    className="p-4 hover:bg-slate-50/70 transition-colors flex items-center justify-between gap-4"
                  >
                    <div className="flex items-start gap-3.5 min-w-0 flex-1">
                      <div
                        className={`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 border transition-colors ${
                          isEnabled
                            ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                            : "bg-slate-100 text-slate-400 border-slate-200"
                        }`}
                      >
                        <Icon className="w-4 h-4" />
                      </div>

                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-xs font-bold text-[#071A4D]">
                            {idx + 1}. {action.name}
                          </span>
                          <span className="text-[10px] font-semibold px-2 py-0.2 rounded-full bg-slate-100 text-slate-600 border border-slate-200">
                            {action.category}
                          </span>
                          <span className="text-[10px] font-mono text-slate-400">
                            ID: {action.id}
                          </span>
                        </div>
                        <p className="text-xs text-slate-500 mt-0.5 leading-relaxed">
                          {action.description}
                        </p>
                      </div>
                    </div>

                    {/* Interactive Toggle Switch */}
                    <div className="flex items-center gap-3 shrink-0">
                      <span
                        className={`text-[11px] font-bold font-mono ${
                          isEnabled ? "text-emerald-700" : "text-slate-400"
                        }`}
                      >
                        {isEnabled ? "AUTHORIZED" : "REVOKED"}
                      </span>

                      <button
                        type="button"
                        onClick={() => togglePermission(selectedRole, action.id)}
                        className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-hidden ${
                          isEnabled ? "bg-[#1769E8]" : "bg-slate-200"
                        }`}
                        role="switch"
                        aria-checked={isEnabled}
                        title={`Click to ${isEnabled ? "revoke" : "grant"} ${action.name}`}
                      >
                        <span
                          aria-hidden="true"
                          className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow-xs ring-0 transition duration-200 ease-in-out ${
                            isEnabled ? "translate-x-5" : "translate-x-0"
                          }`}
                        />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>

            <div className="p-4 bg-slate-50 border-t border-slate-100 flex items-center justify-between">
              <span className="text-xs text-slate-500">
                Changes apply instantly across API authorization gates and frontend UI controls.
              </span>
              <button
                onClick={handleSaveMatrix}
                className="px-4 py-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-bold transition-colors flex items-center gap-1.5 shadow-xs cursor-pointer"
              >
                <Save className="w-3.5 h-3.5" />
                <span>Save Role Privileges</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ============================================================ */}
      {/* TAB 2: COMPLETE CROSS-ROLE COMPARATIVE MATRIX (14 × 5)        */}
      {/* ============================================================ */}
      {activeTab === "full_matrix" && (
        <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
          <div className="p-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/60">
            <div>
              <h3 className="text-sm font-bold text-[#071A4D]">
                Comprehensive Institutional Capabilities Matrix
              </h3>
              <p className="text-xs text-slate-500 mt-0.5">
                Side-by-side comparison of all 14 actions across all 5 institutional user roles.
              </p>
            </div>
            <button
              onClick={handleSaveMatrix}
              className="px-3.5 py-1.5 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-bold transition-colors flex items-center gap-1.5 shadow-xs cursor-pointer"
            >
              <Save className="w-3.5 h-3.5" />
              <span>Save Matrix</span>
            </button>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs border-collapse">
              <thead>
                <tr className="bg-slate-50 border-b border-slate-200 text-slate-600 font-bold uppercase tracking-wider text-[10px]">
                  <th className="py-3 px-4 w-10 text-center">#</th>
                  <th className="py-3 px-4">Mandated Action (PRD §15)</th>
                  <th className="py-3 px-3">Category</th>
                  {ROLES.map((role) => (
                    <th key={role.id} className="py-3 px-3 text-center">
                      <span className="block text-slate-800">{role.name}</span>
                      <span className={`inline-block text-[9px] px-1.5 py-0.2 rounded border font-semibold mt-0.5 ${role.color}`}>
                        {role.badge}
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filteredActions.map((action, idx) => {
                  const Icon = action.icon;
                  return (
                    <tr key={action.id} className="hover:bg-slate-50/80 transition-colors">
                      <td className="py-3 px-4 text-center font-mono text-slate-400 text-xs">
                        {idx + 1}
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 rounded-md bg-slate-100 text-slate-700 flex items-center justify-center shrink-0 border border-slate-200">
                            <Icon className="w-3.5 h-3.5" />
                          </div>
                          <div>
                            <span className="font-bold text-[#071A4D] block">
                              {action.name}
                            </span>
                            <span className="text-[10px] text-slate-400 truncate block max-w-xs">
                              {action.description}
                            </span>
                          </div>
                        </div>
                      </td>
                      <td className="py-3 px-3">
                        <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 border border-slate-200 whitespace-nowrap">
                          {action.category}
                        </span>
                      </td>

                      {ROLES.map((role) => {
                        const isGranted = !!permissionsState[role.id]?.[action.id];
                        return (
                          <td key={role.id} className="py-3 px-3 text-center">
                            <button
                              type="button"
                              onClick={() => togglePermission(role.id, action.id)}
                              className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-[11px] font-bold font-mono transition-all cursor-pointer ${
                                isGranted
                                  ? "bg-emerald-50 text-emerald-700 hover:bg-emerald-100 border border-emerald-200"
                                  : "bg-slate-100 text-slate-400 hover:bg-slate-200 border border-slate-200"
                              }`}
                              title={`Toggle ${action.name} for ${role.name}`}
                            >
                              {isGranted ? (
                                <>
                                  <Check className="w-3 h-3 text-emerald-600 stroke-[2.5]" />
                                  <span>Enabled</span>
                                </>
                              ) : (
                                <>
                                  <X className="w-3 h-3 text-slate-400 stroke-[2.5]" />
                                  <span>Revoked</span>
                                </>
                              )}
                            </button>
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div className="p-4 bg-slate-50 border-t border-slate-100 flex items-center justify-between text-xs text-slate-500">
            <span>Showing all 14 statutory operational actions across 5 user roles.</span>
            <span className="font-mono text-slate-400">Total capability gates: 70 operational checkpoints</span>
          </div>
        </div>
      )}
    </div>
  );
}

