"use client";
import { SectionCard, SegmentedControl, StatusBadge, InlineSpinner, EmptyState, ListCard, ListCardItem, Badge, Button, Avatar, DynamicIslandConfirm, Sheet, Input } from './chunk-JN6IL6OH.mjs';
import { triggerHaptic } from './chunk-D2JF6C3E.mjs';
import { useTranslations, useFormatter } from './chunk-7VJ7CMMT.mjs';
import { useState, useCallback, useEffect } from 'react';
import { UsersIcon, TrashIcon, PlusIcon, EnvelopeIcon, GlobeAltIcon, ArrowPathIcon, CheckCircleIcon } from '@heroicons/react/24/outline';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';

var ALL_TABS = ["members", "invitations", "domains"];
function MembersTabContent({
  organizationId,
  client
}) {
  const t = useTranslations("windsock");
  const [members, setMembers] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [removingId, setRemovingId] = useState(null);
  const [removeTarget, setRemoveTarget] = useState(null);
  const fetchMembers = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await client.listOrganizationMembers(organizationId);
      setMembers(result);
    } catch {
    } finally {
      setIsLoading(false);
    }
  }, [client, organizationId]);
  useEffect(() => {
    fetchMembers();
  }, [fetchMembers]);
  const handleRemoveRequest = useCallback((member) => {
    triggerHaptic("warning");
    setRemoveTarget(member);
  }, []);
  const handleRemoveConfirm = useCallback(async () => {
    if (!removeTarget) return;
    setRemovingId(removeTarget.id);
    triggerHaptic("medium");
    try {
      await client.removeOrganizationMember(organizationId, removeTarget.id);
      setRemoveTarget(null);
      triggerHaptic("success");
      fetchMembers();
    } catch {
      triggerHaptic("error");
    } finally {
      setRemovingId(null);
    }
  }, [removeTarget, client, organizationId, fetchMembers]);
  const handleRemoveCancel = useCallback(() => {
    triggerHaptic("light");
    setRemoveTarget(null);
  }, []);
  const roleBadgeColor = (role) => {
    if (role === "owner") return "purple";
    if (role === "admin") return "blue";
    return "zinc";
  };
  if (isLoading) {
    return /* @__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.organizationDetail.members.loading") })
    ] });
  }
  if (members.length === 0) {
    return /* @__PURE__ */ jsx(
      EmptyState,
      {
        message: t("admin.organizationDetail.members.emptyMessage"),
        description: t("admin.organizationDetail.members.emptyDescription"),
        icon: UsersIcon,
        variant: "card"
      }
    );
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ListCard, { children: members.map((member) => /* @__PURE__ */ jsx(
      ListCardItem,
      {
        leading: /* @__PURE__ */ jsx(
          Avatar,
          {
            src: member.image,
            initials: (member.name ?? member.email).slice(0, 2).toUpperCase(),
            alt: member.name ?? member.email
          }
        ),
        trailing: member.role !== "owner" ? /* @__PURE__ */ jsx(
          Button,
          {
            size: "sm",
            color: "ios-glass-red",
            onClick: () => handleRemoveRequest(member),
            loading: removingId === member.id,
            disabled: removingId !== null,
            children: /* @__PURE__ */ jsx(TrashIcon, { className: "h-3.5 w-3.5" })
          }
        ) : void 0,
        children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
            /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium text-gray-900 dark:text-white", children: member.name ?? member.email }),
            /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-gray-500 dark:text-gray-400", children: member.email })
          ] }),
          /* @__PURE__ */ jsx(Badge, { color: roleBadgeColor(member.role), children: member.role })
        ] })
      },
      member.id
    )) }),
    /* @__PURE__ */ jsx(
      DynamicIslandConfirm,
      {
        open: removeTarget !== null,
        onClose: handleRemoveCancel,
        onConfirm: handleRemoveConfirm,
        title: t("admin.organizationDetail.members.removeConfirmTitle", { name: removeTarget?.name ?? removeTarget?.email ?? "" }),
        icon: /* @__PURE__ */ jsx(TrashIcon, { className: "h-5 w-5 text-white" }),
        iconBackground: "bg-ios-red",
        confirmLabel: t("admin.organizationDetail.members.removeConfirmButton"),
        cancelLabel: t("admin.organizationDetail.members.removeCancelButton")
      }
    )
  ] });
}
function InvitationsTabContent({
  organizationId,
  client
}) {
  const t = useTranslations("windsock");
  const format = useFormatter();
  const [invitations, setInvitations] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isInviteSheetOpen, setIsInviteSheetOpen] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteRole, setInviteRole] = useState("member");
  const [isInviting, setIsInviting] = useState(false);
  const [inviteError, setInviteError] = useState(null);
  const fetchInvitations = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await client.listOrganizationInvitations(organizationId);
      setInvitations(result);
    } catch {
    } finally {
      setIsLoading(false);
    }
  }, [client, organizationId]);
  useEffect(() => {
    fetchInvitations();
  }, [fetchInvitations]);
  const handleOpenInviteSheet = useCallback(() => {
    triggerHaptic("light");
    setInviteEmail("");
    setInviteRole("member");
    setInviteError(null);
    setIsInviteSheetOpen(true);
  }, []);
  const handleCloseInviteSheet = useCallback(() => {
    triggerHaptic("light");
    setIsInviteSheetOpen(false);
  }, []);
  const handleSendInvitation = useCallback(async () => {
    if (!inviteEmail.trim()) {
      setInviteError(t("admin.organizationDetail.invitations.errorEmailRequired"));
      triggerHaptic("error");
      return;
    }
    setInviteError(null);
    setIsInviting(true);
    triggerHaptic("light");
    try {
      const data = {
        email: inviteEmail.trim().toLowerCase(),
        role: inviteRole
      };
      await client.createOrganizationInvitation(organizationId, data);
      triggerHaptic("success");
      setIsInviteSheetOpen(false);
      fetchInvitations();
    } catch {
      setInviteError(t("admin.organizationDetail.invitations.errorSendFailed"));
      triggerHaptic("error");
    } finally {
      setIsInviting(false);
    }
  }, [inviteEmail, inviteRole, client, organizationId, fetchInvitations, t]);
  const statusBadgeColor = (status) => {
    if (status === "accepted") return "green";
    if (status === "pending") return "amber";
    if (status === "revoked" || status === "expired") return "red";
    return "zinc";
  };
  const roleOptions = ["viewer", "member", "admin", "owner"];
  if (isLoading) {
    return /* @__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.organizationDetail.invitations.loading") })
    ] });
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          color: "ios-glass-blue",
          onClick: handleOpenInviteSheet,
          fullWidth: true,
          children: [
            /* @__PURE__ */ jsx(PlusIcon, { className: "mr-1.5 h-4 w-4" }),
            t("admin.organizationDetail.invitations.inviteButton")
          ]
        }
      ),
      invitations.length === 0 ? /* @__PURE__ */ jsx(
        EmptyState,
        {
          message: t("admin.organizationDetail.invitations.emptyMessage"),
          description: t("admin.organizationDetail.invitations.emptyDescription"),
          icon: EnvelopeIcon,
          variant: "card"
        }
      ) : /* @__PURE__ */ jsx(ListCard, { children: invitations.map((invitation) => /* @__PURE__ */ jsx(
        ListCardItem,
        {
          leading: /* @__PURE__ */ jsx("div", { className: "flex h-9 w-9 items-center justify-center rounded-xl bg-gradient-to-br from-amber-500 to-orange-600 shadow-sm", children: /* @__PURE__ */ jsx(EnvelopeIcon, { className: "h-5 w-5 text-white" }) }),
          trailing: /* @__PURE__ */ jsx(Badge, { color: statusBadgeColor(invitation.status), children: invitation.status }),
          children: /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: invitation.email }),
            /* @__PURE__ */ jsxs("p", { className: "mt-0.5 text-xs text-gray-500 dark:text-gray-400", children: [
              t("admin.organizationDetail.invitations.roleLabel", { role: invitation.role }),
              " \xB7 ",
              format.dateTime(new Date(invitation.createdAt), {
                month: "short",
                day: "numeric"
              })
            ] })
          ] })
        },
        invitation.id
      )) })
    ] }),
    /* @__PURE__ */ jsx(
      Sheet,
      {
        open: isInviteSheetOpen,
        onClose: handleCloseInviteSheet,
        title: t("admin.organizationDetail.invitations.sheetTitle"),
        side: "bottom",
        size: "md",
        children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              label: t("admin.organizationDetail.invitations.emailLabel"),
              type: "email",
              value: inviteEmail,
              onChange: (event) => setInviteEmail(event.target.value),
              placeholder: t("admin.organizationDetail.invitations.emailPlaceholder"),
              disabled: isInviting,
              autoFocus: true
            }
          ),
          /* @__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.organizationDetail.invitations.roleSelectLabel") }),
            /* @__PURE__ */ jsx("div", { className: "grid grid-cols-4 gap-2", children: roleOptions.map((role) => /* @__PURE__ */ jsx(
              "button",
              {
                type: "button",
                onClick: () => {
                  setInviteRole(role);
                  triggerHaptic("light");
                },
                className: `rounded-xl border px-2 py-2 text-xs font-semibold backdrop-blur-xl transition ${inviteRole === 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
            )) })
          ] }),
          inviteError && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", role: "alert", children: inviteError }),
          /* @__PURE__ */ jsx(
            Button,
            {
              color: "ios-glass-blue",
              fullWidth: true,
              onClick: handleSendInvitation,
              loading: isInviting,
              disabled: isInviting || !inviteEmail.trim(),
              children: t("admin.organizationDetail.invitations.sendButton")
            }
          )
        ] })
      }
    )
  ] });
}
function DomainsTabContent({
  organizationId,
  client
}) {
  const t = useTranslations("windsock");
  const [domains, setDomains] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isAddSheetOpen, setIsAddSheetOpen] = useState(false);
  const [newDomain, setNewDomain] = useState("");
  const [isAdding, setIsAdding] = useState(false);
  const [addError, setAddError] = useState(null);
  const [verifyingDomain, setVerifyingDomain] = useState(null);
  const fetchDomains = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await client.listOrganizationDomains(organizationId);
      setDomains(result);
    } catch {
    } finally {
      setIsLoading(false);
    }
  }, [client, organizationId]);
  useEffect(() => {
    fetchDomains();
  }, [fetchDomains]);
  const handleOpenAddSheet = useCallback(() => {
    triggerHaptic("light");
    setNewDomain("");
    setAddError(null);
    setIsAddSheetOpen(true);
  }, []);
  const handleCloseAddSheet = useCallback(() => {
    triggerHaptic("light");
    setIsAddSheetOpen(false);
  }, []);
  const handleAddDomain = useCallback(async () => {
    if (!newDomain.trim()) {
      setAddError(t("admin.organizationDetail.domains.errorDomainRequired"));
      triggerHaptic("error");
      return;
    }
    setAddError(null);
    setIsAdding(true);
    triggerHaptic("light");
    try {
      await client.addOrganizationDomain(organizationId, newDomain.trim().toLowerCase());
      triggerHaptic("success");
      setIsAddSheetOpen(false);
      fetchDomains();
    } catch {
      setAddError(t("admin.organizationDetail.domains.errorAddFailed"));
      triggerHaptic("error");
    } finally {
      setIsAdding(false);
    }
  }, [newDomain, client, organizationId, fetchDomains, t]);
  const handleVerifyDomain = useCallback(async (domain) => {
    setVerifyingDomain(domain);
    triggerHaptic("light");
    try {
      await client.verifyOrganizationDomain(organizationId, domain);
      triggerHaptic("success");
      fetchDomains();
    } catch {
      triggerHaptic("error");
    } finally {
      setVerifyingDomain(null);
    }
  }, [client, organizationId, fetchDomains]);
  if (isLoading) {
    return /* @__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.organizationDetail.domains.loading") })
    ] });
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          color: "ios-glass-blue",
          onClick: handleOpenAddSheet,
          fullWidth: true,
          children: [
            /* @__PURE__ */ jsx(PlusIcon, { className: "mr-1.5 h-4 w-4" }),
            t("admin.organizationDetail.domains.addButton")
          ]
        }
      ),
      domains.length === 0 ? /* @__PURE__ */ jsx(
        EmptyState,
        {
          message: t("admin.organizationDetail.domains.emptyMessage"),
          description: t("admin.organizationDetail.domains.emptyDescription"),
          icon: GlobeAltIcon,
          variant: "card"
        }
      ) : /* @__PURE__ */ jsx(ListCard, { children: domains.map((domain) => /* @__PURE__ */ jsx(
        ListCardItem,
        {
          leading: /* @__PURE__ */ jsx("div", { className: `flex h-9 w-9 items-center justify-center rounded-xl shadow-sm ${domain.verified ? "bg-gradient-to-br from-emerald-500 to-green-600" : "bg-gradient-to-br from-amber-500 to-orange-600"}`, children: domain.verified ? /* @__PURE__ */ jsx(CheckCircleIcon, { className: "h-5 w-5 text-white" }) : /* @__PURE__ */ jsx(GlobeAltIcon, { className: "h-5 w-5 text-white" }) }),
          trailing: !domain.verified ? /* @__PURE__ */ jsxs(
            Button,
            {
              size: "sm",
              color: "ios-glass-blue",
              onClick: () => handleVerifyDomain(domain.domain),
              loading: verifyingDomain === domain.domain,
              disabled: verifyingDomain !== null,
              children: [
                /* @__PURE__ */ jsx(ArrowPathIcon, { className: "mr-1 h-3.5 w-3.5" }),
                t("admin.organizationDetail.domains.verifyButton")
              ]
            }
          ) : /* @__PURE__ */ jsx(StatusBadge, { status: "active", label: t("admin.organizationDetail.domains.verifiedLabel"), size: "sm" }),
          children: /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: domain.domain }),
            domain.autoJoinEnabled && /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-xs text-gray-500 dark:text-gray-400", children: t("admin.organizationDetail.domains.autoJoinEnabled") })
          ] })
        },
        domain.id
      )) })
    ] }),
    /* @__PURE__ */ jsx(
      Sheet,
      {
        open: isAddSheetOpen,
        onClose: handleCloseAddSheet,
        title: t("admin.organizationDetail.domains.sheetTitle"),
        side: "bottom",
        size: "md",
        children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              label: t("admin.organizationDetail.domains.domainLabel"),
              value: newDomain,
              onChange: (event) => setNewDomain(event.target.value),
              placeholder: t("admin.organizationDetail.domains.domainPlaceholder"),
              disabled: isAdding,
              autoFocus: true
            }
          ),
          addError && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", role: "alert", children: addError }),
          /* @__PURE__ */ jsx(
            Button,
            {
              color: "ios-glass-blue",
              fullWidth: true,
              onClick: handleAddDomain,
              loading: isAdding,
              disabled: isAdding || !newDomain.trim(),
              children: t("admin.organizationDetail.domains.addDomainButton")
            }
          )
        ] })
      }
    )
  ] });
}
function AdminOrganizationDetail({
  organization,
  client
}) {
  const t = useTranslations("windsock");
  const [activeTab, setActiveTab] = useState("members");
  const segments = ALL_TABS.map((tab) => ({
    value: tab,
    label: t(`admin.organizationDetail.tabs.${tab}`)
  }));
  return /* @__PURE__ */ jsx("div", { className: "space-y-6", children: /* @__PURE__ */ jsx(
    SectionCard,
    {
      header: {
        icon: /* @__PURE__ */ jsx(UsersIcon, { className: "h-5 w-5 text-white" }),
        title: organization.displayName ?? organization.name,
        subtitle: organization.description ?? t("admin.organizationDetail.defaultSubtitle"),
        gradient: "from-emerald-500 via-teal-500 to-cyan-500",
        rightContent: /* @__PURE__ */ jsx(
          StatusBadge,
          {
            status: organization.enabled ? "active" : "inactive",
            label: organization.enabled ? t("admin.organizationDetail.statusEnabled") : t("admin.organizationDetail.statusDisabled"),
            size: "sm"
          }
        )
      },
      children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsx(
          SegmentedControl,
          {
            segments,
            value: activeTab,
            onChange: (value) => setActiveTab(value),
            fullWidth: true
          }
        ),
        activeTab === "members" && /* @__PURE__ */ jsx(MembersTabContent, { organizationId: organization.id, client }),
        activeTab === "invitations" && /* @__PURE__ */ jsx(InvitationsTabContent, { organizationId: organization.id, client }),
        activeTab === "domains" && /* @__PURE__ */ jsx(DomainsTabContent, { organizationId: organization.id, client })
      ] })
    }
  ) });
}

export { AdminOrganizationDetail };
//# sourceMappingURL=chunk-IRPS5UCS.mjs.map
//# sourceMappingURL=chunk-IRPS5UCS.mjs.map