"use client";
import { PasswordStrengthMeter } from './chunk-3VYD7QL2.mjs';
import { SectionCard, SearchInput, InlineSpinner, EmptyState, Avatar, StatusBadge, DynamicIslandConfirm, GlassModal, Input, PasswordInput, Sheet } from './chunk-ZQRUAXGP.mjs';
import { useTranslations, useFormatter } from './chunk-7VJ7CMMT.mjs';
import { Badge, Button } from './chunk-WR55H7DH.mjs';
import { triggerHaptic } from './chunk-D2JF6C3E.mjs';
import { useState, useCallback, useEffect } from 'react';
import { UsersIcon, ShieldCheckIcon, KeyIcon, TrashIcon, UserPlusIcon, BuildingOffice2Icon, PencilSquareIcon, PlusIcon } from '@heroicons/react/24/outline';
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';

var PAGE_SIZE = 20;
function AdminUserList({ client, onUserSelect }) {
  const t = useTranslations("windsock");
  const format = useFormatter();
  const [users, setUsers] = useState([]);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [offset, setOffset] = useState(0);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [isDeletingUser, setIsDeletingUser] = useState(false);
  const fetchUsers = useCallback(async (searchQuery, pageOffset) => {
    setIsLoading(true);
    try {
      const result = await client.listUsers({
        search: searchQuery || void 0,
        limit: PAGE_SIZE,
        offset: pageOffset
      });
      setUsers(result.items);
      setTotal(result.total);
    } catch {
    } finally {
      setIsLoading(false);
    }
  }, [client]);
  useEffect(() => {
    fetchUsers(search, offset);
  }, [fetchUsers, search, offset]);
  const handleSearch = useCallback((value) => {
    setSearch(value);
    setOffset(0);
  }, []);
  const handleNextPage = useCallback(() => {
    triggerHaptic("light");
    setOffset((previous) => previous + PAGE_SIZE);
  }, []);
  const handlePreviousPage = useCallback(() => {
    triggerHaptic("light");
    setOffset((previous) => Math.max(0, previous - PAGE_SIZE));
  }, []);
  const handleDeleteRequest = useCallback((user) => {
    triggerHaptic("warning");
    setDeleteTarget(user);
  }, []);
  const handleDeleteConfirm = useCallback(async () => {
    if (!deleteTarget) return;
    setIsDeletingUser(true);
    triggerHaptic("medium");
    try {
      await client.deleteUser(deleteTarget.id);
      setDeleteTarget(null);
      triggerHaptic("success");
      fetchUsers(search, offset);
    } catch {
      triggerHaptic("error");
    } finally {
      setIsDeletingUser(false);
    }
  }, [deleteTarget, client, fetchUsers, search, offset]);
  const handleDeleteCancel = useCallback(() => {
    triggerHaptic("light");
    setDeleteTarget(null);
  }, []);
  const handleUserClick = useCallback((user) => {
    triggerHaptic("light");
    onUserSelect?.(user);
  }, [onUserSelect]);
  const totalPages = Math.ceil(total / PAGE_SIZE);
  const currentPage = Math.floor(offset / PAGE_SIZE) + 1;
  const roleBadgeColor = (role) => {
    if (role === "owner" || role === "super_admin") return "purple";
    if (role === "admin") return "blue";
    if (role === "manager") return "amber";
    return "zinc";
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(
      SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsx(UsersIcon, { className: "h-5 w-5 text-white" }),
          title: t("admin.users.title"),
          subtitle: t("admin.users.subtitle"),
          gradient: "from-blue-500 via-indigo-500 to-violet-500"
        },
        padded: false,
        children: [
          /* @__PURE__ */ jsx("div", { className: "border-b border-gray-200/60 p-4 dark:border-white/10", children: /* @__PURE__ */ jsx(
            SearchInput,
            {
              value: search,
              onChange: (event) => handleSearch(event.target.value),
              placeholder: t("admin.users.searchPlaceholder")
            }
          ) }),
          isLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-2 p-8 text-sm text-gray-500 dark:text-gray-400", children: [
            /* @__PURE__ */ jsx(InlineSpinner, {}),
            /* @__PURE__ */ jsx("span", { children: t("admin.users.loading") })
          ] }) : users.length === 0 ? /* @__PURE__ */ jsx("div", { className: "p-4 sm:p-6", children: /* @__PURE__ */ jsx(
            EmptyState,
            {
              message: t("admin.users.emptyMessage"),
              description: t("admin.users.emptyDescription"),
              icon: UsersIcon,
              variant: "card"
            }
          ) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
              /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b border-gray-200/60 dark:border-white/10", children: [
                /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.users.columnUser") }),
                /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.users.columnRole") }),
                /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.users.columnStatus") }),
                /* @__PURE__ */ jsx("th", { className: "hidden px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 sm:table-cell", children: t("admin.users.columnSecurity") }),
                /* @__PURE__ */ jsx("th", { className: "hidden px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 md:table-cell", children: t("admin.users.columnLastLogin") }),
                /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.users.columnActions") })
              ] }) }),
              /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-gray-200/60 dark:divide-white/10", children: users.map((user) => /* @__PURE__ */ jsxs(
                "tr",
                {
                  className: "cursor-pointer transition-colors hover:bg-white/40 dark:hover:bg-white/5",
                  onClick: () => handleUserClick(user),
                  children: [
                    /* @__PURE__ */ jsx("td", { className: "px-4 py-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                      /* @__PURE__ */ jsx(
                        Avatar,
                        {
                          src: user.image ?? void 0,
                          initials: (user.name ?? user.email).slice(0, 2).toUpperCase(),
                          alt: user.name ?? user.email
                        }
                      ),
                      /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                        /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium text-gray-900 dark:text-white", children: user.name ?? user.email }),
                        /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-gray-500 dark:text-gray-400", children: user.email })
                      ] })
                    ] }) }),
                    /* @__PURE__ */ jsx("td", { className: "px-4 py-3", children: /* @__PURE__ */ jsx(Badge, { color: roleBadgeColor(user.role), children: user.role }) }),
                    /* @__PURE__ */ jsx("td", { className: "px-4 py-3", children: /* @__PURE__ */ jsx(
                      StatusBadge,
                      {
                        status: user.status === "active" ? "active" : "inactive",
                        label: user.status,
                        size: "sm"
                      }
                    ) }),
                    /* @__PURE__ */ jsx("td", { className: "hidden px-4 py-3 sm:table-cell", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                      user.mfaEnabled && /* @__PURE__ */ jsx("span", { title: t("admin.users.mfaEnabled"), children: /* @__PURE__ */ jsx(ShieldCheckIcon, { className: "h-4 w-4 text-emerald-500" }) }),
                      user.emailVerified && /* @__PURE__ */ jsx("span", { title: t("admin.users.emailVerified"), children: /* @__PURE__ */ jsx(KeyIcon, { className: "h-4 w-4 text-blue-500" }) })
                    ] }) }),
                    /* @__PURE__ */ jsx("td", { className: "hidden px-4 py-3 text-gray-500 dark:text-gray-400 md:table-cell", children: user.lastLoginAt ? format.relativeTime(new Date(user.lastLoginAt)) : t("admin.users.neverLoggedIn") }),
                    /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-right", children: /* @__PURE__ */ jsx(
                      Button,
                      {
                        size: "sm",
                        color: "ios-glass-red",
                        onClick: (event) => {
                          event.stopPropagation();
                          handleDeleteRequest(user);
                        },
                        children: /* @__PURE__ */ jsx(TrashIcon, { className: "h-3.5 w-3.5" })
                      }
                    ) })
                  ]
                },
                user.id
              )) })
            ] }) }),
            totalPages > 1 && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-t border-gray-200/60 px-4 py-3 dark:border-white/10", children: [
              /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: t("admin.users.pagination", { current: currentPage, total: totalPages, count: total }) }),
              /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "sm",
                    outline: true,
                    onClick: handlePreviousPage,
                    disabled: offset === 0,
                    children: t("admin.users.previousPage")
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "sm",
                    outline: true,
                    onClick: handleNextPage,
                    disabled: offset + PAGE_SIZE >= total,
                    children: t("admin.users.nextPage")
                  }
                )
              ] })
            ] })
          ] })
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      DynamicIslandConfirm,
      {
        open: deleteTarget !== null,
        onClose: handleDeleteCancel,
        onConfirm: handleDeleteConfirm,
        title: t("admin.users.deleteConfirmTitle", { name: deleteTarget?.name ?? deleteTarget?.email ?? "" }),
        icon: /* @__PURE__ */ jsx(TrashIcon, { className: "h-5 w-5 text-white" }),
        iconBackground: "bg-ios-red",
        confirmLabel: t("admin.users.deleteConfirmButton"),
        cancelLabel: t("admin.users.deleteCancelButton")
      }
    )
  ] });
}
var DEFAULT_ROLES = ["viewer", "member", "operator", "analyst", "manager", "admin", "owner"];
function AdminUserForm({
  open,
  onClose,
  onSubmit,
  roles = DEFAULT_ROLES
}) {
  const t = useTranslations("windsock");
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [selectedRole, setSelectedRole] = useState("viewer");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const resetForm = useCallback(() => {
    setEmail("");
    setName("");
    setPassword("");
    setSelectedRole("viewer");
    setError(null);
  }, []);
  const handleClose = useCallback(() => {
    resetForm();
    onClose();
  }, [resetForm, onClose]);
  const handleSubmit = useCallback(async () => {
    if (!email.trim()) {
      setError(t("admin.userForm.errorEmailRequired"));
      triggerHaptic("error");
      return;
    }
    setError(null);
    setIsSubmitting(true);
    triggerHaptic("light");
    try {
      const data = {
        email: email.trim().toLowerCase(),
        name: name.trim() || void 0,
        password: password || void 0,
        role: selectedRole
      };
      await onSubmit(data);
      triggerHaptic("success");
      resetForm();
      onClose();
    } catch {
      setError(t("admin.userForm.errorCreateFailed"));
      triggerHaptic("error");
    } finally {
      setIsSubmitting(false);
    }
  }, [email, name, password, selectedRole, onSubmit, onClose, resetForm, t]);
  return /* @__PURE__ */ jsx(
    GlassModal,
    {
      open,
      onClose: handleClose,
      title: t("admin.userForm.title"),
      subtitle: t("admin.userForm.subtitle"),
      icon: /* @__PURE__ */ jsx(UserPlusIcon, { className: "h-5 w-5 text-white" }),
      maxWidth: "md",
      children: /* @__PURE__ */ jsxs(
        "form",
        {
          onSubmit: (event) => {
            event.preventDefault();
            handleSubmit();
          },
          className: "space-y-4 p-4 sm:p-6",
          children: [
            /* @__PURE__ */ jsx(
              Input,
              {
                label: t("admin.userForm.emailLabel"),
                type: "email",
                value: email,
                onChange: (event) => setEmail(event.target.value),
                placeholder: t("admin.userForm.emailPlaceholder"),
                disabled: isSubmitting,
                autoComplete: "email",
                autoFocus: true
              }
            ),
            /* @__PURE__ */ jsx(
              Input,
              {
                label: t("admin.userForm.nameLabel"),
                value: name,
                onChange: (event) => setName(event.target.value),
                placeholder: t("admin.userForm.namePlaceholder"),
                disabled: isSubmitting,
                autoComplete: "name"
              }
            ),
            /* @__PURE__ */ jsx(
              PasswordInput,
              {
                label: t("admin.userForm.passwordLabel"),
                value: password,
                onChange: (event) => setPassword(event.target.value),
                placeholder: t("admin.userForm.passwordPlaceholder"),
                disabled: isSubmitting,
                autoComplete: "new-password"
              }
            ),
            password && /* @__PURE__ */ jsx(PasswordStrengthMeter, { password }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "mb-1.5 block text-sm font-medium text-gray-900 dark:text-white", children: t("admin.userForm.roleLabel") }),
              /* @__PURE__ */ jsx("div", { className: "grid grid-cols-3 gap-2 sm:grid-cols-4", children: roles.map((role) => /* @__PURE__ */ jsx(
                "button",
                {
                  type: "button",
                  onClick: () => {
                    setSelectedRole(role);
                    triggerHaptic("light");
                  },
                  className: `rounded-xl border px-2 py-2 text-xs font-semibold backdrop-blur-xl transition ${selectedRole === role ? "border-indigo-400/80 bg-gradient-to-br from-indigo-100/85 via-white/80 to-sky-100/75 text-slate-900 dark:border-indigo-300/70 dark:bg-[linear-gradient(140deg,rgba(99,102,241,0.32)_0%,rgba(30,41,59,0.72)_100%)] dark:text-indigo-100" : "border-white/55 bg-gradient-to-br from-white/82 via-white/66 to-slate-100/62 text-slate-700 hover:from-white/92 hover:to-sky-100/72 dark:border-white/15 dark:bg-[linear-gradient(140deg,rgba(30,41,59,0.72)_0%,rgba(15,23,42,0.62)_100%)] dark:text-slate-100 dark:hover:bg-[linear-gradient(140deg,rgba(51,65,85,0.76)_0%,rgba(30,41,59,0.68)_100%)]"}`,
                  children: role
                },
                role
              )) })
            ] }),
            error && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", role: "alert", children: error }),
            /* @__PURE__ */ jsxs("div", { className: "flex gap-3 pt-2", children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  outline: true,
                  onClick: handleClose,
                  disabled: isSubmitting,
                  className: "flex-1",
                  children: t("admin.userForm.cancelButton")
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "submit",
                  color: "ios-glass-blue",
                  loading: isSubmitting,
                  disabled: isSubmitting || !email.trim(),
                  className: "flex-1",
                  children: t("admin.userForm.createButton")
                }
              )
            ] })
          ]
        }
      )
    }
  );
}
function AdminOrganizationList({ client, onOrganizationSelect }) {
  const t = useTranslations("windsock");
  const format = useFormatter();
  const [organizations, setOrganizations] = useState([]);
  const [filteredOrganizations, setFilteredOrganizations] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const fetchOrganizations = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await client.listOrganizations();
      setOrganizations(result);
    } catch {
    } finally {
      setIsLoading(false);
    }
  }, [client]);
  useEffect(() => {
    fetchOrganizations();
  }, [fetchOrganizations]);
  useEffect(() => {
    if (!search.trim()) {
      setFilteredOrganizations(organizations);
      return;
    }
    const query = search.toLowerCase();
    setFilteredOrganizations(
      organizations.filter(
        (organization) => organization.name.toLowerCase().includes(query) || organization.displayName?.toLowerCase().includes(query) || organization.description?.toLowerCase().includes(query)
      )
    );
  }, [organizations, search]);
  const handleOrganizationClick = useCallback((organization) => {
    triggerHaptic("light");
    onOrganizationSelect?.(organization);
  }, [onOrganizationSelect]);
  const handleDeleteRequest = useCallback((organization) => {
    triggerHaptic("warning");
    setDeleteTarget(organization);
  }, []);
  const handleDeleteConfirm = useCallback(async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    triggerHaptic("medium");
    try {
      await client.deleteOrganization(deleteTarget.id);
      setDeleteTarget(null);
      triggerHaptic("success");
      fetchOrganizations();
    } catch {
      triggerHaptic("error");
    } finally {
      setIsDeleting(false);
    }
  }, [deleteTarget, client, fetchOrganizations]);
  const handleDeleteCancel = useCallback(() => {
    triggerHaptic("light");
    setDeleteTarget(null);
  }, []);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(
      SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsx(BuildingOffice2Icon, { className: "h-5 w-5 text-white" }),
          title: t("admin.organizations.title"),
          subtitle: t("admin.organizations.subtitle"),
          gradient: "from-emerald-500 via-teal-500 to-cyan-500"
        },
        padded: false,
        children: [
          /* @__PURE__ */ jsx("div", { className: "border-b border-gray-200/60 p-4 dark:border-white/10", children: /* @__PURE__ */ jsx(
            SearchInput,
            {
              value: search,
              onChange: (event) => setSearch(event.target.value),
              placeholder: t("admin.organizations.searchPlaceholder")
            }
          ) }),
          isLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-2 p-8 text-sm text-gray-500 dark:text-gray-400", children: [
            /* @__PURE__ */ jsx(InlineSpinner, {}),
            /* @__PURE__ */ jsx("span", { children: t("admin.organizations.loading") })
          ] }) : filteredOrganizations.length === 0 ? /* @__PURE__ */ jsx("div", { className: "p-4 sm:p-6", children: /* @__PURE__ */ jsx(
            EmptyState,
            {
              message: t("admin.organizations.emptyMessage"),
              description: t("admin.organizations.emptyDescription"),
              icon: BuildingOffice2Icon,
              variant: "card"
            }
          ) }) : /* @__PURE__ */ jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
            /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b border-gray-200/60 dark:border-white/10", children: [
              /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.organizations.columnName") }),
              /* @__PURE__ */ jsx("th", { className: "hidden px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 sm:table-cell", children: t("admin.organizations.columnDisplayName") }),
              /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.organizations.columnStatus") }),
              /* @__PURE__ */ jsx("th", { className: "hidden px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 md:table-cell", children: t("admin.organizations.columnCreated") }),
              /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.organizations.columnActions") })
            ] }) }),
            /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-gray-200/60 dark:divide-white/10", children: filteredOrganizations.map((organization) => /* @__PURE__ */ jsxs(
              "tr",
              {
                className: "cursor-pointer transition-colors hover:bg-white/40 dark:hover:bg-white/5",
                onClick: () => handleOrganizationClick(organization),
                children: [
                  /* @__PURE__ */ jsxs("td", { className: "px-4 py-3", children: [
                    /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: organization.name }),
                    organization.description && /* @__PURE__ */ jsx("p", { className: "mt-0.5 truncate text-xs text-gray-500 dark:text-gray-400", children: organization.description })
                  ] }),
                  /* @__PURE__ */ jsx("td", { className: "hidden px-4 py-3 text-gray-500 dark:text-gray-400 sm:table-cell", children: organization.displayName ?? "\u2014" }),
                  /* @__PURE__ */ jsx("td", { className: "px-4 py-3", children: /* @__PURE__ */ jsx(
                    StatusBadge,
                    {
                      status: organization.enabled ? "active" : "inactive",
                      label: organization.enabled ? t("admin.organizations.statusEnabled") : t("admin.organizations.statusDisabled"),
                      size: "sm"
                    }
                  ) }),
                  /* @__PURE__ */ jsx("td", { className: "hidden px-4 py-3 text-gray-500 dark:text-gray-400 md:table-cell", children: format.dateTime(new Date(organization.createdAt), {
                    year: "numeric",
                    month: "short",
                    day: "numeric"
                  }) }),
                  /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-right", children: /* @__PURE__ */ jsx(
                    Button,
                    {
                      size: "sm",
                      color: "ios-glass-red",
                      onClick: (event) => {
                        event.stopPropagation();
                        handleDeleteRequest(organization);
                      },
                      children: /* @__PURE__ */ jsx(TrashIcon, { className: "h-3.5 w-3.5" })
                    }
                  ) })
                ]
              },
              organization.id
            )) })
          ] }) })
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      DynamicIslandConfirm,
      {
        open: deleteTarget !== null,
        onClose: handleDeleteCancel,
        onConfirm: handleDeleteConfirm,
        title: t("admin.organizations.deleteConfirmTitle", { name: deleteTarget?.displayName ?? deleteTarget?.name ?? "" }),
        icon: /* @__PURE__ */ jsx(TrashIcon, { className: "h-5 w-5 text-white" }),
        iconBackground: "bg-ios-red",
        confirmLabel: t("admin.organizations.deleteConfirmButton"),
        cancelLabel: t("admin.organizations.deleteCancelButton")
      }
    )
  ] });
}
function AdminOrganizationForm({
  open,
  onClose,
  organization,
  onSubmit
}) {
  const t = useTranslations("windsock");
  const isEditing = organization !== null && organization !== void 0;
  const [name, setName] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [description, setDescription] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);
  useEffect(() => {
    if (organization) {
      setName(organization.name);
      setDisplayName(organization.displayName ?? "");
      setDescription(organization.description ?? "");
    } else {
      setName("");
      setDisplayName("");
      setDescription("");
    }
    setError(null);
  }, [organization, open]);
  const handleClose = useCallback(() => {
    setError(null);
    onClose();
  }, [onClose]);
  const handleSubmit = useCallback(async () => {
    if (!name.trim()) {
      setError(t("admin.organizationForm.errorNameRequired"));
      triggerHaptic("error");
      return;
    }
    setError(null);
    setIsSubmitting(true);
    triggerHaptic("light");
    try {
      if (isEditing) {
        const data = {
          name: name.trim(),
          displayName: displayName.trim() || null,
          description: description.trim() || null
        };
        await onSubmit(data);
      } else {
        const data = {
          name: name.trim(),
          displayName: displayName.trim() || void 0,
          description: description.trim() || void 0
        };
        await onSubmit(data);
      }
      triggerHaptic("success");
      onClose();
    } catch {
      setError(
        isEditing ? t("admin.organizationForm.errorUpdateFailed") : t("admin.organizationForm.errorCreateFailed")
      );
      triggerHaptic("error");
    } finally {
      setIsSubmitting(false);
    }
  }, [name, displayName, description, isEditing, onSubmit, onClose, t]);
  return /* @__PURE__ */ jsx(
    GlassModal,
    {
      open,
      onClose: handleClose,
      title: isEditing ? t("admin.organizationForm.editTitle") : t("admin.organizationForm.createTitle"),
      subtitle: isEditing ? t("admin.organizationForm.editSubtitle") : t("admin.organizationForm.createSubtitle"),
      icon: /* @__PURE__ */ jsx(BuildingOffice2Icon, { className: "h-5 w-5 text-white" }),
      maxWidth: "md",
      children: /* @__PURE__ */ jsxs(
        "form",
        {
          onSubmit: (event) => {
            event.preventDefault();
            handleSubmit();
          },
          className: "space-y-4 p-4 sm:p-6",
          children: [
            /* @__PURE__ */ jsx(
              Input,
              {
                label: t("admin.organizationForm.nameLabel"),
                value: name,
                onChange: (event) => setName(event.target.value),
                placeholder: t("admin.organizationForm.namePlaceholder"),
                disabled: isSubmitting,
                autoFocus: true
              }
            ),
            /* @__PURE__ */ jsx(
              Input,
              {
                label: t("admin.organizationForm.displayNameLabel"),
                value: displayName,
                onChange: (event) => setDisplayName(event.target.value),
                placeholder: t("admin.organizationForm.displayNamePlaceholder"),
                disabled: isSubmitting
              }
            ),
            /* @__PURE__ */ jsx(
              Input,
              {
                label: t("admin.organizationForm.descriptionLabel"),
                value: description,
                onChange: (event) => setDescription(event.target.value),
                placeholder: t("admin.organizationForm.descriptionPlaceholder"),
                disabled: isSubmitting
              }
            ),
            error && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", role: "alert", children: error }),
            /* @__PURE__ */ jsxs("div", { className: "flex gap-3 pt-2", children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  outline: true,
                  onClick: handleClose,
                  disabled: isSubmitting,
                  className: "flex-1",
                  children: t("admin.organizationForm.cancelButton")
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "submit",
                  color: "ios-glass-blue",
                  loading: isSubmitting,
                  disabled: isSubmitting || !name.trim(),
                  className: "flex-1",
                  children: isEditing ? t("admin.organizationForm.saveButton") : t("admin.organizationForm.createButton")
                }
              )
            ] })
          ]
        }
      )
    }
  );
}
function AdminPermissionList({ client }) {
  const t = useTranslations("windsock");
  const format = useFormatter();
  const [permissions, setPermissions] = useState([]);
  const [filteredPermissions, setFilteredPermissions] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingPermission, setEditingPermission] = useState(null);
  const [formId, setFormId] = useState("");
  const [formName, setFormName] = useState("");
  const [formDescription, setFormDescription] = useState("");
  const [formResource, setFormResource] = useState("");
  const [formAction, setFormAction] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formError, setFormError] = useState(null);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const fetchPermissions = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await client.listPermissions();
      setPermissions(result);
    } catch {
    } finally {
      setIsLoading(false);
    }
  }, [client]);
  useEffect(() => {
    fetchPermissions();
  }, [fetchPermissions]);
  useEffect(() => {
    if (!search.trim()) {
      setFilteredPermissions(permissions);
      return;
    }
    const query = search.toLowerCase();
    setFilteredPermissions(
      permissions.filter(
        (permission) => permission.name.toLowerCase().includes(query) || permission.description?.toLowerCase().includes(query) || permission.resource?.toLowerCase().includes(query) || permission.action?.toLowerCase().includes(query)
      )
    );
  }, [permissions, search]);
  const handleOpenCreate = useCallback(() => {
    triggerHaptic("light");
    setEditingPermission(null);
    setFormId("");
    setFormName("");
    setFormDescription("");
    setFormResource("");
    setFormAction("");
    setFormError(null);
    setIsFormOpen(true);
  }, []);
  const handleOpenEdit = useCallback((permission) => {
    triggerHaptic("light");
    setEditingPermission(permission);
    setFormId(permission.id);
    setFormName(permission.name);
    setFormDescription(permission.description ?? "");
    setFormResource(permission.resource ?? "");
    setFormAction(permission.action ?? "");
    setFormError(null);
    setIsFormOpen(true);
  }, []);
  const handleCloseForm = useCallback(() => {
    triggerHaptic("light");
    setIsFormOpen(false);
  }, []);
  const handleSubmitForm = useCallback(async () => {
    const isEditing = editingPermission !== null;
    if (!isEditing && !formId.trim()) {
      setFormError(t("admin.permissions.errorIdRequired"));
      triggerHaptic("error");
      return;
    }
    if (!formName.trim()) {
      setFormError(t("admin.permissions.errorNameRequired"));
      triggerHaptic("error");
      return;
    }
    setFormError(null);
    setIsSubmitting(true);
    triggerHaptic("light");
    try {
      if (isEditing) {
        const data = {
          name: formName.trim(),
          description: formDescription.trim() || void 0,
          resource: formResource.trim() || void 0,
          action: formAction.trim() || void 0
        };
        await client.updatePermission(editingPermission.id, data);
      } else {
        const data = {
          id: formId.trim(),
          name: formName.trim(),
          description: formDescription.trim() || void 0,
          resource: formResource.trim() || void 0,
          action: formAction.trim() || void 0
        };
        await client.createPermission(data);
      }
      triggerHaptic("success");
      setIsFormOpen(false);
      fetchPermissions();
    } catch {
      setFormError(
        isEditing ? t("admin.permissions.errorUpdateFailed") : t("admin.permissions.errorCreateFailed")
      );
      triggerHaptic("error");
    } finally {
      setIsSubmitting(false);
    }
  }, [editingPermission, formId, formName, formDescription, formResource, formAction, client, fetchPermissions, t]);
  const handleDeleteRequest = useCallback((permission) => {
    triggerHaptic("warning");
    setDeleteTarget(permission);
  }, []);
  const handleDeleteConfirm = useCallback(async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    triggerHaptic("medium");
    try {
      await client.deletePermission(deleteTarget.id);
      setDeleteTarget(null);
      triggerHaptic("success");
      fetchPermissions();
    } catch {
      triggerHaptic("error");
    } finally {
      setIsDeleting(false);
    }
  }, [deleteTarget, client, fetchPermissions]);
  const handleDeleteCancel = useCallback(() => {
    triggerHaptic("light");
    setDeleteTarget(null);
  }, []);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(
      SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsx(KeyIcon, { className: "h-5 w-5 text-white" }),
          title: t("admin.permissions.title"),
          subtitle: t("admin.permissions.subtitle"),
          gradient: "from-violet-500 via-purple-500 to-pink-500",
          rightContent: /* @__PURE__ */ jsxs(Button, { size: "sm", color: "ios-glass-blue", onClick: handleOpenCreate, children: [
            /* @__PURE__ */ jsx(PlusIcon, { className: "mr-1 h-3.5 w-3.5" }),
            t("admin.permissions.createButton")
          ] })
        },
        padded: false,
        children: [
          /* @__PURE__ */ jsx("div", { className: "border-b border-gray-200/60 p-4 dark:border-white/10", children: /* @__PURE__ */ jsx(
            SearchInput,
            {
              value: search,
              onChange: (event) => setSearch(event.target.value),
              placeholder: t("admin.permissions.searchPlaceholder")
            }
          ) }),
          isLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-2 p-8 text-sm text-gray-500 dark:text-gray-400", children: [
            /* @__PURE__ */ jsx(InlineSpinner, {}),
            /* @__PURE__ */ jsx("span", { children: t("admin.permissions.loading") })
          ] }) : filteredPermissions.length === 0 ? /* @__PURE__ */ jsx("div", { className: "p-4 sm:p-6", children: /* @__PURE__ */ jsx(
            EmptyState,
            {
              message: t("admin.permissions.emptyMessage"),
              description: t("admin.permissions.emptyDescription"),
              icon: KeyIcon,
              action: {
                label: t("admin.permissions.createButton"),
                onClick: handleOpenCreate
              },
              variant: "card"
            }
          ) }) : /* @__PURE__ */ jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
            /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b border-gray-200/60 dark:border-white/10", children: [
              /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.permissions.columnName") }),
              /* @__PURE__ */ jsx("th", { className: "hidden px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 sm:table-cell", children: t("admin.permissions.columnResource") }),
              /* @__PURE__ */ jsx("th", { className: "hidden px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 sm:table-cell", children: t("admin.permissions.columnAction") }),
              /* @__PURE__ */ jsx("th", { className: "hidden px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 md:table-cell", children: t("admin.permissions.columnCreated") }),
              /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("admin.permissions.columnActions") })
            ] }) }),
            /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-gray-200/60 dark:divide-white/10", children: filteredPermissions.map((permission) => /* @__PURE__ */ jsxs("tr", { className: "transition-colors hover:bg-white/40 dark:hover:bg-white/5", children: [
              /* @__PURE__ */ jsx("td", { className: "px-4 py-3", children: /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: permission.name }),
                permission.description && /* @__PURE__ */ jsx("p", { className: "mt-0.5 truncate text-xs text-gray-500 dark:text-gray-400", children: permission.description })
              ] }) }),
              /* @__PURE__ */ jsx("td", { className: "hidden px-4 py-3 sm:table-cell", children: permission.resource ? /* @__PURE__ */ jsx(Badge, { color: "blue", children: permission.resource }) : /* @__PURE__ */ jsx("span", { className: "text-gray-400 dark:text-gray-500", children: "\u2014" }) }),
              /* @__PURE__ */ jsx("td", { className: "hidden px-4 py-3 sm:table-cell", children: permission.action ? /* @__PURE__ */ jsx(Badge, { color: "amber", children: permission.action }) : /* @__PURE__ */ jsx("span", { className: "text-gray-400 dark:text-gray-500", children: "\u2014" }) }),
              /* @__PURE__ */ jsx("td", { className: "hidden px-4 py-3 text-gray-500 dark:text-gray-400 md:table-cell", children: format.dateTime(new Date(permission.createdAt), {
                year: "numeric",
                month: "short",
                day: "numeric"
              }) }),
              /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-right", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-1", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "sm",
                    outline: true,
                    onClick: () => handleOpenEdit(permission),
                    children: /* @__PURE__ */ jsx(PencilSquareIcon, { className: "h-3.5 w-3.5" })
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "sm",
                    color: "ios-glass-red",
                    onClick: () => handleDeleteRequest(permission),
                    children: /* @__PURE__ */ jsx(TrashIcon, { className: "h-3.5 w-3.5" })
                  }
                )
              ] }) })
            ] }, permission.id)) })
          ] }) })
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      Sheet,
      {
        open: isFormOpen,
        onClose: handleCloseForm,
        title: editingPermission ? t("admin.permissions.editSheetTitle") : t("admin.permissions.createSheetTitle"),
        side: "bottom",
        size: "md",
        children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
          !editingPermission && /* @__PURE__ */ jsx(
            Input,
            {
              label: t("admin.permissions.formIdLabel"),
              value: formId,
              onChange: (event) => setFormId(event.target.value),
              placeholder: t("admin.permissions.formIdPlaceholder"),
              disabled: isSubmitting,
              autoFocus: true
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              label: t("admin.permissions.formNameLabel"),
              value: formName,
              onChange: (event) => setFormName(event.target.value),
              placeholder: t("admin.permissions.formNamePlaceholder"),
              disabled: isSubmitting,
              autoFocus: !!editingPermission
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              label: t("admin.permissions.formDescriptionLabel"),
              value: formDescription,
              onChange: (event) => setFormDescription(event.target.value),
              placeholder: t("admin.permissions.formDescriptionPlaceholder"),
              disabled: isSubmitting
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
            /* @__PURE__ */ jsx(
              Input,
              {
                label: t("admin.permissions.formResourceLabel"),
                value: formResource,
                onChange: (event) => setFormResource(event.target.value),
                placeholder: t("admin.permissions.formResourcePlaceholder"),
                disabled: isSubmitting
              }
            ),
            /* @__PURE__ */ jsx(
              Input,
              {
                label: t("admin.permissions.formActionLabel"),
                value: formAction,
                onChange: (event) => setFormAction(event.target.value),
                placeholder: t("admin.permissions.formActionPlaceholder"),
                disabled: isSubmitting
              }
            )
          ] }),
          formError && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", role: "alert", children: formError }),
          /* @__PURE__ */ jsxs("div", { className: "flex gap-3", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                outline: true,
                onClick: handleCloseForm,
                disabled: isSubmitting,
                className: "flex-1",
                children: t("admin.permissions.formCancelButton")
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                color: "ios-glass-blue",
                onClick: handleSubmitForm,
                loading: isSubmitting,
                disabled: isSubmitting || !formName.trim() || !editingPermission && !formId.trim(),
                className: "flex-1",
                children: editingPermission ? t("admin.permissions.formSaveButton") : t("admin.permissions.formCreateButton")
              }
            )
          ] })
        ] })
      }
    ),
    /* @__PURE__ */ jsx(
      DynamicIslandConfirm,
      {
        open: deleteTarget !== null,
        onClose: handleDeleteCancel,
        onConfirm: handleDeleteConfirm,
        title: t("admin.permissions.deleteConfirmTitle", { name: deleteTarget?.name ?? "" }),
        icon: /* @__PURE__ */ jsx(TrashIcon, { className: "h-5 w-5 text-white" }),
        iconBackground: "bg-ios-red",
        confirmLabel: t("admin.permissions.deleteConfirmButton"),
        cancelLabel: t("admin.permissions.deleteCancelButton")
      }
    )
  ] });
}

export { AdminOrganizationForm, AdminOrganizationList, AdminPermissionList, AdminUserForm, AdminUserList };
//# sourceMappingURL=chunk-ZQEMKEEH.mjs.map
//# sourceMappingURL=chunk-ZQEMKEEH.mjs.map