import { jsxs as a, jsx as t, Fragment as C } from "react/jsx-runtime";
import { Ban as K, Eye as S, Star as X, Check as P, Headset as q, X as J, ChevronRight as Q, Layers as Y, Loader2 as Z, User as ee, Shield as M, Lock as te, Play as re, UserPlus as ae, Trash2 as ne, Edit as oe, Plus as se } from "lucide-react";
import { useRef as ce, useState as R, useCallback as k, useMemo as I, useEffect as L } from "react";
import { createPortal as ie } from "react-dom";
import { useTranslation as le } from "react-i18next";
import { useNavigate as de } from "react-router-dom";
function me(o) {
  const d = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
  o.forEach((r) => {
    if (r.level === "resource" && r.parentSectionId) {
      const l = c.get(r.parentSectionId) || [];
      l.push(r), c.set(r.parentSectionId, l);
    }
  });
  const i = /* @__PURE__ */ new Map();
  o.forEach((r) => {
    if (r.level === "section" && r.parentModuleId) {
      const l = i.get(r.parentModuleId) || [], u = r.childResources || c.get(r.id) || [];
      l.push({
        section: r,
        resources: u
      }), i.set(r.parentModuleId, l);
    }
  }), o.filter((r) => r.level === "module").forEach((r) => {
    const l = r.applicationLabel;
    d.has(l) || d.set(l, []);
    const u = i.get(r.id) || [];
    (r.childSections?.length ?? 0) > 0 && u.length === 0 && r.childSections?.forEach((h) => {
      const v = h.childResources || c.get(h.id) || [];
      u.push({
        section: h,
        resources: v
      });
    }), d.get(l).push({
      module: r,
      sections: u
    });
  });
  const b = [];
  return d.forEach((r, l) => {
    b.push({ application: l, modules: r });
  }), b;
}
function fe(o) {
  return me(o).map((c) => ({
    context: c.application,
    applications: [c]
  }));
}
function ye(o, d) {
  let c = 0, i = !1;
  o.permissions.forEach((r) => {
    d(r.id) && (c++, r.action === "read" && (i = !0));
  });
  const n = o.permissions.length;
  return c === 0 ? { status: "none", grantedCount: c } : c === n ? { status: "all", grantedCount: c } : o.permissions.every(
    (r) => !d(r.id) || r.action === "read"
  ) && i ? { status: "read-only", grantedCount: c } : { status: "some", grantedCount: c };
}
function Ne(o, d, c) {
  let i = 0, n = !1, b = !1, r = o.permissions.length;
  return o.permissions.forEach((l) => {
    c(l.id) && (i++, l.action === "read" ? n = !0 : b = !0);
  }), d.forEach((l) => {
    const u = l.section;
    r += u.permissions.length, u.permissions.forEach((h) => {
      c(h.id) && (i++, h.action === "read" ? n = !0 : b = !0);
    }), l.resources.forEach((h) => {
      r += h.permissions.length, h.permissions.forEach((v) => {
        c(v.id) && (i++, v.action === "read" ? n = !0 : b = !0);
      });
    });
  }), i === 0 ? { status: "none", grantedCount: i, totalCount: r } : i === r ? { status: "all", grantedCount: i, totalCount: r } : n && !b ? { status: "read-only", grantedCount: i, totalCount: r } : { status: "some", grantedCount: i, totalCount: r };
}
function we(o) {
  switch (o) {
    case "all":
      return "bg-emerald-500/20 dark:bg-emerald-500/30";
    case "some":
      return "bg-amber-500/20 dark:bg-amber-500/30";
    case "read-only":
      return "bg-sky-500/20 dark:bg-sky-500/30";
    case "none":
      return "";
  }
}
const he = {
  all: {
    icon: P,
    bgColor: "bg-emerald-500/20",
    textColor: "text-emerald-700 dark:text-emerald-300",
    borderColor: "border-emerald-500/30",
    dotColor: "text-[var(--success-dot)]"
  },
  some: {
    icon: X,
    bgColor: "bg-amber-500/20",
    textColor: "text-amber-700 dark:text-amber-300",
    borderColor: "border-amber-500/30",
    dotColor: "text-[var(--warning-dot)]"
  },
  "read-only": {
    icon: S,
    bgColor: "bg-sky-500/20",
    textColor: "text-sky-700 dark:text-sky-300",
    borderColor: "border-sky-500/30",
    dotColor: "text-[var(--info-dot)]"
  },
  none: {
    icon: K,
    bgColor: "bg-red-500/10",
    textColor: "text-red-600 dark:text-red-400",
    borderColor: "border-red-500/20",
    dotColor: "text-[var(--text-muted)]"
  }
};
function Ce({
  status: o,
  grantedCount: d,
  totalCount: c,
  variant: i = "icon"
}) {
  const n = he[o], b = n.icon, r = o === "none" ? `0/${c}` : `${d}/${c}`;
  return i === "badge" ? /* @__PURE__ */ a(
    "span",
    {
      className: `inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${n.bgColor} ${n.textColor} ${n.borderColor}`,
      children: [
        /* @__PURE__ */ t(b, { className: "h-3 w-3" }),
        r
      ]
    }
  ) : /* @__PURE__ */ a("div", { className: "flex flex-col items-center gap-0.5", children: [
    /* @__PURE__ */ t(b, { className: `h-4 w-4 ${n.dotColor}` }),
    o !== "none" && /* @__PURE__ */ t("span", { className: `text-[9px] font-medium ${n.dotColor}`, children: r })
  ] });
}
const T = {
  "*": /* @__PURE__ */ t(M, { className: "h-3.5 w-3.5" }),
  read: /* @__PURE__ */ t(S, { className: "h-3.5 w-3.5" }),
  create: /* @__PURE__ */ t(se, { className: "h-3.5 w-3.5" }),
  update: /* @__PURE__ */ t(oe, { className: "h-3.5 w-3.5" }),
  delete: /* @__PURE__ */ t(ne, { className: "h-3.5 w-3.5" }),
  assign: /* @__PURE__ */ t(ae, { className: "h-3.5 w-3.5" }),
  execute: /* @__PURE__ */ t(re, { className: "h-3.5 w-3.5" })
}, z = {
  "*": "bg-[var(--accent-bg)] text-[var(--accent-text)] border-[var(--accent-border)]",
  read: "bg-[var(--info-bg)] text-[var(--info-text)] border-[var(--info-border)]",
  create: "bg-[var(--success-bg)] text-[var(--success-text)] border-[var(--success-border)]",
  update: "bg-[var(--warning-bg)] text-[var(--warning-text)] border-[var(--warning-border)]",
  delete: "bg-[var(--error-bg)] text-[var(--error-text)] border-[var(--error-border)]",
  assign: "bg-[var(--accent-bg)] text-[var(--accent-text)] border-[var(--accent-border)]",
  execute: "bg-[var(--warning-bg)] text-[var(--warning-text)] border-[var(--warning-border)]"
};
function ke(o) {
  const { resource: d, onClose: c, mode: i } = o, { t: n } = le(["admin", "common"]), b = de(), r = ce(null), [l, u] = R(/* @__PURE__ */ new Set()), [h, v] = R(!1), O = i === "readonly" ? o.title : o.role.name, $ = (e) => e.startsWith("user_") && e.endsWith("_custom"), j = (e) => $(e.name) ? n("admin:userPermissions.customBadge", "Custom") : e.shortName || e.name, B = k((e) => {
    u((s) => {
      const m = new Set(s);
      return m.has(e) ? m.delete(e) : m.add(e), m;
    });
  }, []), w = k((e) => {
    if (i === "readonly")
      return o.effectivePermissions.has(e);
    {
      const s = o.getPermissionInheritance(o.role.id, e), m = s.isDirect || s.isInherited;
      return l.has(e) ? !m : m;
    }
  }, [i, o, l]), F = k(async () => {
    if (i === "editable") {
      if (l.size === 0) {
        c();
        return;
      }
      v(!0);
      try {
        for (const e of l)
          try {
            o.onTogglePermission(e);
          } catch (s) {
            console.error(`Failed to toggle permission ${e}:`, s);
          }
        await new Promise((e) => setTimeout(e, 100)), c();
      } catch (e) {
        console.error("Failed to validate permissions:", e);
      } finally {
        v(!1);
      }
    }
  }, [i, l, c, o]), y = k(() => {
    u(/* @__PURE__ */ new Set()), c();
  }, [c]), E = l.size > 0, N = I(() => {
    const e = [];
    return d.permissions.length > 0 && e.push({
      label: d.moduleLabel,
      path: d.path,
      level: "module",
      permissions: d.permissions
    }), (d.childSections?.length ?? 0) > 0 && d.childSections?.forEach((s) => {
      s.permissions.length > 0 && e.push({
        label: s.label,
        path: s.path,
        level: "section",
        permissions: s.permissions
      });
    }), e;
  }, [d]), { grantedCount: A, totalCount: D } = I(() => {
    let e = 0, s = 0;
    return N.forEach((m) => {
      m.permissions.forEach((g) => {
        s++, w(g.id) && e++;
      });
    }), { grantedCount: e, totalCount: s };
  }, [N, w]);
  L(() => {
    const e = (s) => {
      s.key === "Escape" && y();
    };
    return document.addEventListener("keydown", e), () => document.removeEventListener("keydown", e);
  }, [y]), L(() => {
    r.current && r.current.focus();
  }, []);
  const W = () => {
    const e = {
      component: "PermissionPopover",
      mode: i,
      resource: `${d.applicationLabel}.${d.moduleLabel}`,
      path: d.path,
      url: window.location.href
    };
    b("/support/tickets/new", { state: { context: e } });
  }, _ = (e, s) => {
    const m = s && o.mode === "readonly" ? o.getPermissionSources(e.id) : [], g = z[e.action] || "bg-[var(--bg-secondary)] text-[var(--text-secondary)] border-[var(--border-color)]", p = T[e.action] || /* @__PURE__ */ t(S, { className: "h-3.5 w-3.5" });
    return /* @__PURE__ */ a(
      "div",
      {
        className: `flex items-center gap-3 px-3 py-2 rounded-[var(--radius-card)] ${s ? "bg-[var(--accent-bg)] border border-[var(--accent-border)]" : "bg-[var(--bg-secondary)] border border-transparent opacity-60"}`,
        children: [
          /* @__PURE__ */ t("div", { className: "flex items-center gap-2 flex-shrink-0", children: /* @__PURE__ */ a(
            "div",
            {
              className: `flex items-center gap-2 px-2.5 py-1 rounded-[var(--radius-badge)] border text-xs font-medium ${g}`,
              title: n(`assignments.actions.${e.action === "*" ? "all" : e.action}.description`),
              children: [
                p,
                /* @__PURE__ */ t("span", { className: "capitalize", children: n(`assignments.actions.${e.action === "*" ? "all" : e.action}.label`) })
              ]
            }
          ) }),
          /* @__PURE__ */ t("div", { className: "flex-1 min-w-0", children: s && m.length > 0 && /* @__PURE__ */ t("div", { className: "flex flex-wrap gap-1", children: m.map((x) => {
            const f = $(x.name), H = j(x);
            return /* @__PURE__ */ a(
              "span",
              {
                className: `inline-flex items-center gap-1 px-2 py-0.5 text-[10px] rounded-full ${f ? "bg-[var(--color-accent-100)] text-[var(--color-accent-700)] dark:bg-[var(--color-accent-900)] dark:text-[var(--color-accent-300)] border border-[var(--color-accent-300)] dark:border-[var(--color-accent-700)]" : "bg-[var(--bg-tertiary)] text-[var(--text-secondary)] border border-[var(--border-color)]"}`,
                children: [
                  f ? /* @__PURE__ */ t(ee, { className: "h-2.5 w-2.5" }) : /* @__PURE__ */ t(M, { className: "h-2.5 w-2.5" }),
                  H
                ]
              },
              x.id
            );
          }) }) }),
          s && /* @__PURE__ */ t(P, { className: "h-4 w-4 text-[var(--success-dot)] flex-shrink-0" })
        ]
      },
      e.id
    );
  }, V = (e, s) => {
    if (o.mode !== "editable") return null;
    const m = z[e.action] || "bg-[var(--bg-secondary)] text-[var(--text-secondary)] border-[var(--border-color)]", g = T[e.action] || /* @__PURE__ */ t(S, { className: "h-3.5 w-3.5" }), p = o.getPermissionInheritance(o.role.id, e.id), x = p.isInherited && !p.isDirect, f = l.has(e.id);
    return /* @__PURE__ */ a("div", { className: "relative group/permission", children: [
      /* @__PURE__ */ a(
        "label",
        {
          className: `flex items-center gap-3 px-3 py-2 rounded-[var(--radius-card)] transition-all ${s ? "bg-[var(--accent-bg)] border border-[var(--accent-border)]" : "hover:bg-[var(--bg-hover)] border border-transparent"} ${x ? "cursor-not-allowed opacity-75" : "cursor-pointer"} ${f ? "ring-2 ring-[var(--color-accent-400)] ring-opacity-50" : ""}`,
          children: [
            /* @__PURE__ */ t(
              "input",
              {
                type: "checkbox",
                checked: s,
                onChange: () => !x && B(e.id),
                disabled: x || h,
                className: "h-4 w-4 text-[var(--color-accent-600)] border-[var(--border-color)] rounded-[var(--radius-input)] focus:ring-2 focus:ring-[var(--color-accent-500)] bg-[var(--bg-primary)] transition-colors disabled:cursor-not-allowed disabled:opacity-50"
              }
            ),
            /* @__PURE__ */ a("div", { className: "flex items-center gap-2 flex-1 flex-wrap", children: [
              /* @__PURE__ */ a(
                "div",
                {
                  className: `flex items-center gap-2 px-2.5 py-1 rounded-[var(--radius-badge)] border text-xs font-medium ${m}`,
                  title: n(`assignments.actions.${e.action === "*" ? "all" : e.action}.description`),
                  children: [
                    g,
                    /* @__PURE__ */ t("span", { className: "capitalize", children: n(`assignments.actions.${e.action === "*" ? "all" : e.action}.label`) })
                  ]
                }
              ),
              f && /* @__PURE__ */ t("span", { className: "px-2 py-0.5 text-xs font-medium bg-[var(--color-accent-100)] text-[var(--color-accent-700)] dark:bg-[var(--color-accent-900)] dark:text-[var(--color-accent-300)] border border-[var(--color-accent-300)] dark:border-[var(--color-accent-700)] rounded-[var(--radius-badge)]", children: n("assignments.modified") }),
              !f && p.isDirect && /* @__PURE__ */ t("span", { className: "px-2 py-0.5 text-xs font-medium bg-[var(--success-bg)] text-[var(--success-text)] border border-[var(--success-border)] rounded-[var(--radius-badge)]", children: n("assignments.direct") }),
              x && /* @__PURE__ */ a("span", { className: "px-2 py-0.5 text-xs font-medium bg-[var(--warning-bg)] text-[var(--warning-text)] border border-[var(--warning-border)] rounded-[var(--radius-badge)] flex items-center gap-1", children: [
                /* @__PURE__ */ t(te, { className: "h-3 w-3" }),
                n("assignments.inherited")
              ] })
            ] })
          ]
        }
      ),
      x && p.inheritedFromPath && /* @__PURE__ */ t("div", { className: "absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-1.5 bg-[var(--bg-tertiary)] text-[var(--text-primary)] text-xs rounded-[var(--radius-badge)] whitespace-nowrap opacity-0 group-hover/permission:opacity-100 transition-opacity pointer-events-none z-50 border border-[var(--border-color)]", children: n("assignments.inheritedFrom", { path: p.inheritedFromPath }) })
    ] }, e.id);
  }, U = (e) => {
    const s = w(e.id);
    return i === "readonly" ? _(e, s) : V(e, s);
  }, G = /* @__PURE__ */ a("div", { className: "fixed inset-0 z-[100] flex items-center justify-center", children: [
    /* @__PURE__ */ t(
      "button",
      {
        type: "button",
        className: "absolute inset-0 bg-black/50 backdrop-blur-sm",
        onClick: y,
        "aria-label": "Close popover"
      }
    ),
    /* @__PURE__ */ a(
      "div",
      {
        ref: r,
        tabIndex: -1,
        className: "relative z-10 bg-[var(--bg-card)] border border-[var(--color-accent-500)] dark:border-[var(--color-accent-400)] rounded-[var(--radius-modal)] shadow-2xl overflow-hidden w-[420px] max-w-[90vw] max-h-[80vh] flex flex-col animate-in fade-in zoom-in-95 duration-200",
        children: [
          /* @__PURE__ */ a("div", { className: "bg-gradient-to-r from-[var(--color-accent-500)] to-[var(--color-accent-600)] dark:from-[var(--color-accent-600)] dark:to-[var(--color-accent-700)] px-4 py-3 flex-shrink-0", children: [
            /* @__PURE__ */ a("div", { className: "flex items-start justify-between", children: [
              /* @__PURE__ */ a("div", { className: "flex-1", children: [
                /* @__PURE__ */ t("div", { className: "text-sm font-semibold text-white mb-0.5", children: O }),
                /* @__PURE__ */ a("div", { className: "text-xs text-white/80", children: [
                  d.applicationLabel,
                  " • ",
                  d.moduleLabel
                ] }),
                /* @__PURE__ */ a("div", { className: "mt-1.5 px-2 py-1 bg-black/20 rounded text-[11px] font-mono text-white/90", children: [
                  d.path,
                  ".*"
                ] })
              ] }),
              /* @__PURE__ */ a("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ t(
                  "button",
                  {
                    type: "button",
                    onClick: W,
                    className: "text-white/80 hover:text-white transition-colors p-1 hover:bg-white/10 rounded",
                    title: n("common:actions.createTicket"),
                    children: /* @__PURE__ */ t(q, { className: "h-4 w-4" })
                  }
                ),
                /* @__PURE__ */ t(
                  "button",
                  {
                    type: "button",
                    onClick: y,
                    className: "text-white/80 hover:text-white transition-colors p-1 hover:bg-white/10 rounded",
                    children: /* @__PURE__ */ t(J, { className: "h-4 w-4" })
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ a("div", { className: "mt-2 flex items-center gap-2 text-xs text-white/90", children: [
              /* @__PURE__ */ a("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ t(P, { className: "h-3 w-3" }),
                /* @__PURE__ */ a("span", { children: [
                  A,
                  "/",
                  D
                ] })
              ] }),
              /* @__PURE__ */ t("span", { children: "•" }),
              /* @__PURE__ */ t("span", { children: n("assignments.permissions") }),
              N.length > 1 && /* @__PURE__ */ a(C, { children: [
                /* @__PURE__ */ t("span", { children: "•" }),
                /* @__PURE__ */ a("span", { children: [
                  N.length,
                  " ",
                  n("assignments.groups")
                ] })
              ] }),
              i === "editable" && E && /* @__PURE__ */ a(C, { children: [
                /* @__PURE__ */ t("span", { children: "•" }),
                /* @__PURE__ */ a("span", { className: "bg-white/20 px-2 py-0.5 rounded", children: [
                  l.size,
                  " ",
                  n("assignments.pendingChanges")
                ] })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ t("div", { className: "p-3 overflow-y-auto flex-1", children: /* @__PURE__ */ t("div", { className: "space-y-4", children: N.map((e, s) => {
            const m = e.permissions.filter(
              (g) => w(g.id)
            ).length;
            return /* @__PURE__ */ a("div", { className: "space-y-1.5", children: [
              /* @__PURE__ */ a("div", { className: "px-2 py-1.5 bg-[var(--bg-tertiary)] rounded-[var(--radius-card)] border border-[var(--border-color)]", children: [
                /* @__PURE__ */ a("div", { className: "flex items-center gap-2", children: [
                  e.level === "section" ? /* @__PURE__ */ t(Q, { className: "h-3.5 w-3.5 text-[var(--text-muted)]" }) : /* @__PURE__ */ t(Y, { className: "h-3.5 w-3.5 text-[var(--color-accent-500)]" }),
                  /* @__PURE__ */ t("span", { className: `text-xs font-medium ${e.level === "section" ? "text-[var(--text-secondary)]" : "text-[var(--text-primary)]"}`, children: e.label }),
                  /* @__PURE__ */ a("span", { className: "ml-auto text-[10px] text-[var(--text-muted)]", children: [
                    m,
                    "/",
                    e.permissions.length
                  ] })
                ] }),
                /* @__PURE__ */ a("div", { className: "mt-1 text-[10px] font-mono text-[var(--text-muted)] pl-5", children: [
                  e.path,
                  ".*"
                ] })
              ] }),
              /* @__PURE__ */ t("div", { className: `space-y-1 ${e.level === "section" ? "pl-3" : ""}`, children: e.permissions.map((g) => U(g)) })
            ] }, `${e.level}-${s}`);
          }) }) }),
          i === "readonly" ? /* @__PURE__ */ t("div", { className: "px-4 py-3 border-t border-[var(--border-color)] bg-[var(--bg-secondary)] flex-shrink-0", children: /* @__PURE__ */ a("div", { className: "flex items-center justify-between text-xs text-[var(--text-muted)]", children: [
            /* @__PURE__ */ t("span", { children: n("userPermissions.readOnlyNote") }),
            /* @__PURE__ */ t("kbd", { className: "px-1.5 py-0.5 bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded text-[10px]", children: "ESC" })
          ] }) }) : /* @__PURE__ */ t("div", { className: "px-4 py-3 border-t border-[var(--border-color)] bg-[var(--bg-secondary)] flex-shrink-0", children: /* @__PURE__ */ a("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ t("div", { className: "flex items-center gap-2 text-xs text-[var(--text-muted)]", children: E ? /* @__PURE__ */ a("span", { className: "text-[var(--color-accent-600)] dark:text-[var(--color-accent-400)] font-medium", children: [
              l.size,
              " ",
              n("assignments.pendingChanges")
            ] }) : /* @__PURE__ */ t("span", { children: n("assignments.clickToToggle") }) }),
            /* @__PURE__ */ a("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ t(
                "button",
                {
                  type: "button",
                  onClick: y,
                  disabled: h,
                  className: "px-3 py-1.5 text-xs font-medium text-[var(--text-secondary)] bg-[var(--bg-tertiary)] hover:bg-[var(--bg-hover)] border border-[var(--border-color)] rounded-[var(--radius-button)] transition-colors disabled:opacity-50",
                  children: n("common.cancel")
                }
              ),
              /* @__PURE__ */ t(
                "button",
                {
                  type: "button",
                  onClick: F,
                  disabled: h,
                  className: "px-3 py-1.5 text-xs font-medium text-white bg-[var(--color-accent-600)] hover:bg-[var(--color-accent-700)] rounded-[var(--radius-button)] transition-colors disabled:opacity-50 flex items-center gap-1.5",
                  children: h ? /* @__PURE__ */ a(C, { children: [
                    /* @__PURE__ */ t(Z, { className: "h-3.5 w-3.5 animate-spin" }),
                    n("common.saving")
                  ] }) : /* @__PURE__ */ a(C, { children: [
                    /* @__PURE__ */ t(P, { className: "h-3.5 w-3.5" }),
                    n("assignments.validate")
                  ] })
                }
              )
            ] })
          ] }) })
        ]
      }
    )
  ] });
  return ie(G, document.body);
}
export {
  Ce as P,
  we as a,
  ke as b,
  ye as c,
  Ne as d,
  me as e,
  fe as g
};
//# sourceMappingURL=PermissionPopover-BLRa-xh-.js.map
