"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { Fragment } from "react";
import { Check, X } from "lucide-react";
import { Badge } from "../../ui/badge.js";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "../../ui/table.js";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
function RolesPermissionsMatrix({
  roles,
  hierarchy,
  permissions,
  allPermissions,
  permissionsData
}) {
  const sortedRoles = [...roles].sort(
    (a, b) => (hierarchy[b] ?? 0) - (hierarchy[a] ?? 0)
  );
  const hasPermission = (role, permission) => {
    var _a;
    return ((_a = permissions[role]) == null ? void 0 : _a.includes(permission)) ?? false;
  };
  const getRoleBadgeVariant = (role) => {
    const h = hierarchy[role] ?? 0;
    if (h >= 100) return "destructive";
    if (h >= 50) return "default";
    if (h >= 10) return "secondary";
    return "outline";
  };
  const permissionCategoryMap = /* @__PURE__ */ new Map();
  const permissionLabelMap = /* @__PURE__ */ new Map();
  const permissionDangerousMap = /* @__PURE__ */ new Map();
  if (permissionsData) {
    permissionsData.forEach((p) => {
      permissionCategoryMap.set(p.id, p.category);
      permissionLabelMap.set(p.id, p.label);
      permissionDangerousMap.set(p.id, p.dangerous ?? false);
    });
  }
  const getPermissionCategory = (permissionId) => {
    if (permissionCategoryMap.has(permissionId)) {
      return permissionCategoryMap.get(permissionId);
    }
    const parts = permissionId.split(".");
    return parts[0] || "general";
  };
  const permissionsByCategory = allPermissions.reduce(
    (acc, permission) => {
      const category = getPermissionCategory(permission);
      if (!acc[category]) acc[category] = [];
      acc[category].push(permission);
      return acc;
    },
    {}
  );
  const categoryOrder = {
    // Core system permissions
    "Team": 1,
    "Settings": 2,
    // Theme features
    "Page Builder": 10,
    "Blog": 11,
    "Media": 12
    // Entities come after (alphabetically)
  };
  const sortedCategories = Object.keys(permissionsByCategory).sort((a, b) => {
    const orderA = categoryOrder[a] ?? 100;
    const orderB = categoryOrder[b] ?? 100;
    if (orderA !== orderB) return orderA - orderB;
    return a.localeCompare(b);
  });
  const formatCategoryLabel = (category) => {
    if (category.includes(" ") || category.includes("-")) {
      return category.split(/[-\s]/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
    }
    return category.charAt(0).toUpperCase() + category.slice(1);
  };
  return /* @__PURE__ */ jsx("div", { className: "rounded-md border", children: /* @__PURE__ */ jsxs(Table, { children: [
    /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
      /* @__PURE__ */ jsx(TableHead, { className: "w-[280px]", children: "Permission" }),
      sortedRoles.map((role) => /* @__PURE__ */ jsx(TableHead, { className: "text-center min-w-[100px]", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1.5", children: [
        /* @__PURE__ */ jsx("span", { className: "capitalize font-semibold", children: role }),
        /* @__PURE__ */ jsx(
          Badge,
          {
            variant: getRoleBadgeVariant(role),
            className: "text-[10px] px-1.5 py-0",
            children: hierarchy[role] ?? 0
          }
        )
      ] }) }, role))
    ] }) }),
    /* @__PURE__ */ jsx(TableBody, { children: sortedCategories.map((category) => /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(TableRow, { className: "bg-muted/50 hover:bg-muted/50", children: /* @__PURE__ */ jsx(
        TableCell,
        {
          colSpan: sortedRoles.length + 1,
          className: "font-semibold text-sm py-3",
          children: formatCategoryLabel(category)
        }
      ) }),
      permissionsByCategory[category].map((permission) => /* @__PURE__ */ jsxs(
        TableRow,
        {
          "data-cy": sel("superadmin.teamRoles.rbac.matrix.permissionRow", { permission: permission.replace(/\./g, "-") }),
          className: "hover:bg-muted/30",
          children: [
            /* @__PURE__ */ jsxs(TableCell, { className: "font-mono text-sm text-muted-foreground pl-6", children: [
              /* @__PURE__ */ jsx("span", { className: cn(
                permissionDangerousMap.get(permission) && "text-red-600"
              ), children: permission }),
              permissionDangerousMap.get(permission) && /* @__PURE__ */ jsx(Badge, { variant: "destructive", className: "ml-2 text-[10px] px-1 py-0", children: "dangerous" })
            ] }),
            sortedRoles.map((role) => /* @__PURE__ */ jsx(
              TableCell,
              {
                className: "text-center",
                children: hasPermission(role, permission) ? /* @__PURE__ */ jsx(Check, { className: "h-4 w-4 text-green-600 mx-auto" }) : /* @__PURE__ */ jsx(X, { className: "h-4 w-4 text-red-400/60 mx-auto" })
              },
              `${role}-${permission}`
            ))
          ]
        },
        permission
      ))
    ] }, category)) })
  ] }) });
}
export {
  RolesPermissionsMatrix
};
