import { jsxs as a, jsx as t, Fragment as C } from "react/jsx-runtime";
import { Ban as X, Eye as $, Star as q, Check as P, Headset as G, 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 I, useCallback as k, useMemo as R, 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 pe(o) {
  const l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map();
  o.forEach((r) => {
    if (r.level === "resource" && r.parentSectionId) {
      const i = d.get(r.parentSectionId) || [];
      i.push(r), d.set(r.parentSectionId, i);
    }
  });
  const c = /* @__PURE__ */ new Map();
  o.forEach((r) => {
    if (r.level === "section" && r.parentModuleId) {
      const i = c.get(r.parentModuleId) || [], u = r.childResources || d.get(r.id) || [];
      i.push({
        section: r,
        resources: u
      }), c.set(r.parentModuleId, i);
    }
  }), o.filter((r) => r.level === "module").forEach((r) => {
    const i = r.applicationLabel;
    l.has(i) || l.set(i, []);
    const u = c.get(r.id) || [];
    (r.childSections?.length ?? 0) > 0 && u.length === 0 && r.childSections?.forEach((b) => {
      const v = b.childResources || d.get(b.id) || [];
      u.push({
        section: b,
        resources: v
      });
    }), l.get(i).push({
      module: r,
      sections: u
    });
  });
  const h = [];
  return l.forEach((r, i) => {
    h.push({ application: i, modules: r });
  }), h;
}
function fe(o, l) {
  let d = 0, c = !1;
  o.permissions.forEach((r) => {
    l(r.id) && (d++, r.action === "read" && (c = !0));
  });
  const n = o.permissions.length;
  return d === 0 ? { status: "none", grantedCount: d } : d === n ? { status: "all", grantedCount: d } : o.permissions.every(
    (r) => !l(r.id) || r.action === "read"
  ) && c ? { status: "read-only", grantedCount: d } : { status: "some", grantedCount: d };
}
function ye(o, l, d) {
  let c = 0, n = !1, h = !1, r = o.permissions.length;
  return o.permissions.forEach((i) => {
    d(i.id) && (c++, i.action === "read" ? n = !0 : h = !0);
  }), l.forEach((i) => {
    const u = i.section;
    r += u.permissions.length, u.permissions.forEach((b) => {
      d(b.id) && (c++, b.action === "read" ? n = !0 : h = !0);
    }), i.resources.forEach((b) => {
      r += b.permissions.length, b.permissions.forEach((v) => {
        d(v.id) && (c++, v.action === "read" ? n = !0 : h = !0);
      });
    });
  }), c === 0 ? { status: "none", grantedCount: c, totalCount: r } : c === r ? { status: "all", grantedCount: c, totalCount: r } : n && !h ? { status: "read-only", grantedCount: c, totalCount: r } : { status: "some", grantedCount: c, totalCount: r };
}
function Ne(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 me = {
  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: q,
    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: $,
    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: X,
    bgColor: "bg-red-500/10",
    textColor: "text-red-600 dark:text-red-400",
    borderColor: "border-red-500/20",
    dotColor: "text-[var(--text-muted)]"
  }
};
function we({
  status: o,
  grantedCount: l,
  totalCount: d,
  variant: c = "icon"
}) {
  const n = me[o], h = n.icon, r = o === "none" ? `0/${d}` : `${l}/${d}`;
  return c === "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(h, { className: "h-3 w-3" }),
        r
      ]
    }
  ) : /* @__PURE__ */ a("div", { className: "flex flex-col items-center gap-0.5", children: [
    /* @__PURE__ */ t(h, { 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($, { 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 Ce(o) {
  const { resource: l, onClose: d, mode: c } = o, { t: n } = le(["admin", "common"]), h = de(), r = ce(null), [i, u] = I(/* @__PURE__ */ new Set()), [b, v] = I(!1), O = c === "readonly" ? o.title : o.role.name, S = (e) => e.startsWith("user_") && e.endsWith("_custom"), j = (e) => S(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 (c === "readonly")
      return o.effectivePermissions.has(e);
    {
      const s = o.getPermissionInheritance(o.role.id, e), m = s.isDirect || s.isInherited;
      return i.has(e) ? !m : m;
    }
  }, [c, o, i]), F = k(async () => {
    if (c === "editable") {
      if (i.size === 0) {
        d();
        return;
      }
      v(!0);
      try {
        for (const e of i)
          try {
            o.onTogglePermission(e);
          } catch (s) {
            console.error(`Failed to toggle permission ${e}:`, s);
          }
        await new Promise((e) => setTimeout(e, 100)), d();
      } catch (e) {
        console.error("Failed to validate permissions:", e);
      } finally {
        v(!1);
      }
    }
  }, [c, i, d, o]), y = k(() => {
    u(/* @__PURE__ */ new Set()), d();
  }, [d]), E = i.size > 0, N = R(() => {
    const e = [];
    return l.permissions.length > 0 && e.push({
      label: l.moduleLabel,
      path: l.path,
      level: "module",
      permissions: l.permissions
    }), (l.childSections?.length ?? 0) > 0 && l.childSections?.forEach((s) => {
      s.permissions.length > 0 && e.push({
        label: s.label,
        path: s.path,
        level: "section",
        permissions: s.permissions
      });
    }), e;
  }, [l]), { grantedCount: A, totalCount: D } = R(() => {
    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: c,
      resource: `${l.applicationLabel}.${l.moduleLabel}`,
      path: l.path,
      url: window.location.href
    };
    h("/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($, { 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 = S(x.name), K = 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" }),
                  K
                ]
              },
              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($, { className: "h-3.5 w-3.5" }), p = o.getPermissionInheritance(o.role.id, e.id), x = p.isInherited && !p.isDirect, f = i.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 || b,
                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 c === "readonly" ? _(e, s) : V(e, s);
  }, H = /* @__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: [
                  l.applicationLabel,
                  " • ",
                  l.moduleLabel
                ] }),
                /* @__PURE__ */ a("div", { className: "mt-1.5 px-2 py-1 bg-black/20 rounded text-[11px] font-mono text-white/90", children: [
                  l.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(G, { 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")
                ] })
              ] }),
              c === "editable" && E && /* @__PURE__ */ a(C, { children: [
                /* @__PURE__ */ t("span", { children: "•" }),
                /* @__PURE__ */ a("span", { className: "bg-white/20 px-2 py-0.5 rounded", children: [
                  i.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}`);
          }) }) }),
          c === "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: [
              i.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: b,
                  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: b,
                  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: b ? /* @__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(H, document.body);
}
export {
  we as P,
  Ne as a,
  Ce as b,
  fe as c,
  ye as d,
  pe as g
};
//# sourceMappingURL=PermissionPopover-CR6SD8ch.js.map
