"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { FormHeader } from "@open-mercato/ui/backend/forms";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { PasswordInput } from "@open-mercato/ui/primitives/password-input";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { SwitchField } from "@open-mercato/ui/primitives/switch-field";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { RecordNotFoundState, ErrorMessage } from "@open-mercato/ui/backend/detail";
function formatDate(value, fallback) {
  if (!value) return fallback;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return fallback;
  return date.toLocaleString();
}
function ResetPasswordDialog({
  open,
  onOpenChange,
  userId,
  onRunMutation
}) {
  const t = useT();
  const [newPassword, setNewPassword] = React.useState("");
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const handleSubmit = React.useCallback(async (event) => {
    event.preventDefault();
    if (!newPassword.trim() || newPassword.length < 8) {
      flash(t("customer_accounts.admin.detail.resetPassword.error.minLength", "Password must be at least 8 characters"), "error");
      return;
    }
    setIsSubmitting(true);
    try {
      await onRunMutation(async () => {
        const call = await apiCall(
          `/api/customer_accounts/admin/users/${encodeURIComponent(userId)}/reset-password`,
          {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ newPassword })
          }
        );
        if (!call.ok) {
          flash(call.result?.error || t("customer_accounts.admin.detail.resetPassword.error.save", "Failed to reset password"), "error");
          return;
        }
        flash(t("customer_accounts.admin.detail.resetPassword.flash.success", "Password reset successfully"), "success");
        setNewPassword("");
        onOpenChange(false);
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.detail.resetPassword.error.save", "Failed to reset password");
      flash(message, "error");
    } finally {
      setIsSubmitting(false);
    }
  }, [newPassword, onOpenChange, onRunMutation, t, userId]);
  const handleKeyDown = React.useCallback((event) => {
    if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
      event.preventDefault();
      const form = event.target.closest("form");
      if (form) form.requestSubmit();
    }
  }, []);
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (next) => {
    if (!next) setNewPassword("");
    onOpenChange(next);
  }, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-md", children: [
    /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("customer_accounts.admin.detail.resetPassword.title", "Reset Password") }) }),
    /* @__PURE__ */ jsxs("form", { onSubmit: (event) => {
      void handleSubmit(event);
    }, onKeyDown: handleKeyDown, className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", htmlFor: "reset-password", children: t("customer_accounts.admin.detail.resetPassword.fields.newPassword", "New Password") }),
        /* @__PURE__ */ jsx(
          PasswordInput,
          {
            id: "reset-password",
            required: true,
            minLength: 8,
            value: newPassword,
            onChange: (event) => setNewPassword(event.target.value),
            placeholder: t("customer_accounts.admin.detail.resetPassword.fields.placeholder", "Min. 8 characters"),
            autoComplete: "new-password"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2 pt-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => {
          setNewPassword("");
          onOpenChange(false);
        }, children: t("customer_accounts.admin.detail.resetPassword.actions.cancel", "Cancel") }),
        /* @__PURE__ */ jsx(Button, { type: "submit", disabled: isSubmitting, children: isSubmitting ? t("customer_accounts.admin.detail.resetPassword.actions.resetting", "Resetting...") : t("customer_accounts.admin.detail.resetPassword.actions.reset", "Reset Password") })
      ] })
    ] })
  ] }) });
}
function CustomerUserDetailPage({ params }) {
  const id = params?.id;
  const t = useT();
  const router = useRouter();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [data, setData] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [isSaving, setIsSaving] = React.useState(false);
  const [editActive, setEditActive] = React.useState(null);
  const [editDisplayName, setEditDisplayName] = React.useState("");
  const [availableRoles, setAvailableRoles] = React.useState([]);
  const [selectedRoleIds, setSelectedRoleIds] = React.useState([]);
  const [resetPasswordOpen, setResetPasswordOpen] = React.useState(false);
  const [isVerifying, setIsVerifying] = React.useState(false);
  const [editPersonEntityId, setEditPersonEntityId] = React.useState(null);
  const [editCustomerEntityId, setEditCustomerEntityId] = React.useState(null);
  const [personSearchQuery, setPersonSearchQuery] = React.useState("");
  const [companySearchQuery, setCompanySearchQuery] = React.useState("");
  const [personResults, setPersonResults] = React.useState([]);
  const [companyResults, setCompanyResults] = React.useState([]);
  const [personName, setPersonName] = React.useState(null);
  const [companyName, setCompanyName] = React.useState(null);
  const [isSendingResetLink, setIsSendingResetLink] = React.useState(false);
  const [resetLinkUrl, setResetLinkUrl] = React.useState(null);
  const mutationContextId = `customer_accounts:user:${id ?? "pending"}`;
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId
  });
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => {
      return runMutation({
        operation,
        mutationPayload,
        context: { entityType: "customer_accounts:user", entityId: id }
      });
    },
    [id, runMutation]
  );
  React.useEffect(() => {
    if (!id) {
      setIsNotFound(true);
      setIsLoading(false);
      return;
    }
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      setError(null);
      setIsNotFound(false);
      try {
        const payload = await readApiResultOrThrow(
          `/api/customer_accounts/admin/users/${encodeURIComponent(id)}`,
          void 0,
          { errorMessage: t("customer_accounts.admin.detail.error.load", "Failed to load user") }
        );
        if (cancelled) return;
        setData(payload);
        setEditActive(payload.isActive);
        setEditDisplayName(payload.displayName);
        setSelectedRoleIds(payload.roles.map((role) => role.id));
        setEditPersonEntityId(payload.personEntityId);
        setEditCustomerEntityId(payload.customerEntityId);
      } catch (err) {
        if (cancelled) return;
        if (err.status === 404) {
          setIsNotFound(true);
        } else {
          const message = err instanceof Error ? err.message : t("customer_accounts.admin.detail.error.load", "Failed to load user");
          setError(message);
        }
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [id, t]);
  React.useEffect(() => {
    let cancelled = false;
    async function loadRoles() {
      try {
        const call = await apiCall(
          "/api/customer_accounts/admin/roles?pageSize=100"
        );
        if (cancelled || !call.ok) return;
        const items = Array.isArray(call.result?.items) ? call.result.items : [];
        setAvailableRoles(
          items.filter((item) => typeof item?.id === "string" && typeof item?.name === "string")
        );
      } catch {
      }
    }
    loadRoles();
    return () => {
      cancelled = true;
    };
  }, []);
  React.useEffect(() => {
    if (!data) return;
    let cancelled = false;
    async function loadPersonName() {
      if (!data.personEntityId) return;
      try {
        const call = await apiCall(`/api/customers/people/${encodeURIComponent(data.personEntityId)}`);
        if (!cancelled && call.ok && call.result) {
          setPersonName([call.result.firstName, call.result.lastName].filter(Boolean).join(" ") || call.result.id || null);
        }
      } catch {
      }
    }
    async function loadCompanyName() {
      if (!data.customerEntityId) return;
      try {
        const call = await apiCall(`/api/customers/${encodeURIComponent(data.customerEntityId)}`);
        if (!cancelled && call.ok && call.result) {
          setCompanyName(call.result.name || call.result.id || null);
        }
      } catch {
      }
    }
    void Promise.all([loadPersonName(), loadCompanyName()]);
    return () => {
      cancelled = true;
    };
  }, [data]);
  const handleSearchPeople = React.useCallback(async (query) => {
    setPersonSearchQuery(query);
    if (query.trim().length < 2) {
      setPersonResults([]);
      return;
    }
    try {
      const call = await apiCall(
        `/api/customers/people?search=${encodeURIComponent(query.trim())}&pageSize=10`
      );
      if (call.ok && Array.isArray(call.result?.items)) {
        setPersonResults(call.result.items.map((person) => ({
          id: person.id,
          label: [person.firstName, person.lastName].filter(Boolean).join(" ") || person.email || person.id
        })));
      }
    } catch {
    }
  }, []);
  const handleSearchCompanies = React.useCallback(async (query) => {
    setCompanySearchQuery(query);
    if (query.trim().length < 2) {
      setCompanyResults([]);
      return;
    }
    try {
      const call = await apiCall(
        `/api/customers?search=${encodeURIComponent(query.trim())}&pageSize=10`
      );
      if (call.ok && Array.isArray(call.result?.items)) {
        setCompanyResults(call.result.items.map((company) => ({
          id: company.id,
          label: company.name || company.id
        })));
      }
    } catch {
    }
  }, []);
  const handleSendResetLink = React.useCallback(async () => {
    if (!id) return;
    setIsSendingResetLink(true);
    try {
      await runMutationWithContext(async () => {
        const call = await apiCall(
          `/api/customer_accounts/admin/users/${encodeURIComponent(id)}/send-reset-link`,
          { method: "POST" }
        );
        if (!call.ok || !call.result?.resetLink) {
          flash(call.result?.error || t("customer_accounts.admin.detail.sendResetLink.error", "Failed to generate reset link"), "error");
          return;
        }
        setResetLinkUrl(call.result.resetLink);
        flash(t("customer_accounts.admin.detail.sendResetLink.flash.success", "Reset link generated"), "success");
      }, { id });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.detail.sendResetLink.error", "Failed to generate reset link");
      flash(message, "error");
    } finally {
      setIsSendingResetLink(false);
    }
  }, [id, runMutationWithContext, t]);
  const handleSave = React.useCallback(async () => {
    if (!data || !id) return;
    setIsSaving(true);
    try {
      await runMutationWithContext(async () => {
        const call = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(data.updatedAt),
          () => apiCall(
            `/api/customer_accounts/admin/users/${encodeURIComponent(id)}`,
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({
                displayName: editDisplayName.trim() || void 0,
                isActive: editActive,
                roleIds: selectedRoleIds,
                personEntityId: editPersonEntityId,
                customerEntityId: editCustomerEntityId
              })
            }
          )
        );
        if (!call.ok) {
          if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return;
          flash(call.result?.error || t("customer_accounts.admin.detail.error.save", "Failed to save user"), "error");
          return;
        }
        flash(t("customer_accounts.admin.detail.flash.saved", "User updated"), "success");
        setData((prev) => prev ? {
          ...prev,
          isActive: editActive ?? prev.isActive,
          displayName: editDisplayName.trim() || prev.displayName,
          personEntityId: editPersonEntityId,
          customerEntityId: editCustomerEntityId,
          updatedAt: call.result?.updatedAt ?? prev.updatedAt
        } : prev);
      }, { displayName: editDisplayName, isActive: editActive, roleIds: selectedRoleIds, personEntityId: editPersonEntityId, customerEntityId: editCustomerEntityId });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.detail.error.save", "Failed to save user");
      flash(message, "error");
    } finally {
      setIsSaving(false);
    }
  }, [data, editActive, editCustomerEntityId, editDisplayName, editPersonEntityId, id, runMutationWithContext, selectedRoleIds, t]);
  const handleDelete = React.useCallback(async () => {
    if (!data || !id) return;
    const confirmed = await confirm({
      title: t("customer_accounts.admin.confirm.delete", 'Delete user "{{name}}"?', {
        name: data.displayName || data.email
      }),
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runMutationWithContext(async () => {
        const call = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(data.updatedAt),
          () => apiCall(
            `/api/customer_accounts/admin/users/${encodeURIComponent(id)}`,
            { method: "DELETE" }
          )
        );
        if (!call.ok) {
          if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return;
          flash(t("customer_accounts.admin.error.delete", "Failed to delete user"), "error");
          return;
        }
        flash(t("customer_accounts.admin.flash.deleted", "User deleted"), "success");
        router.push("/backend/customer_accounts/users");
      }, { id });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.error.delete", "Failed to delete user");
      flash(message, "error");
    }
  }, [confirm, data, id, router, runMutationWithContext, t]);
  const handleVerifyEmail = React.useCallback(async () => {
    if (!data || !id) return;
    const confirmed = await confirm({
      title: t("customer_accounts.admin.detail.verifyEmail.confirm", 'Mark email as verified for "{{name}}"?', {
        name: data.displayName || data.email
      })
    });
    if (!confirmed) return;
    setIsVerifying(true);
    try {
      await runMutationWithContext(async () => {
        const call = await apiCall(
          `/api/customer_accounts/admin/users/${encodeURIComponent(id)}/verify-email`,
          { method: "POST" }
        );
        if (!call.ok) {
          flash(call.result?.error || t("customer_accounts.admin.detail.verifyEmail.error", "Failed to verify email"), "error");
          return;
        }
        flash(t("customer_accounts.admin.detail.verifyEmail.flash.success", "Email marked as verified"), "success");
        setData((prev) => prev ? { ...prev, emailVerifiedAt: (/* @__PURE__ */ new Date()).toISOString() } : prev);
      }, { id });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.detail.verifyEmail.error", "Failed to verify email");
      flash(message, "error");
    } finally {
      setIsVerifying(false);
    }
  }, [confirm, data, id, runMutationWithContext, t]);
  const handleRevokeSession = React.useCallback(async (sessionId) => {
    if (!id) return;
    try {
      await runMutationWithContext(async () => {
        const call = await apiCall(
          `/api/customer_accounts/admin/users/${encodeURIComponent(id)}/sessions/${encodeURIComponent(sessionId)}`,
          { method: "DELETE" }
        );
        if (!call.ok) {
          flash(t("customer_accounts.admin.detail.error.revokeSession", "Failed to revoke session"), "error");
          return;
        }
        flash(t("customer_accounts.admin.detail.flash.sessionRevoked", "Session revoked"), "success");
        setData((prev) => {
          if (!prev) return prev;
          return { ...prev, sessions: prev.sessions.filter((session) => session.id !== sessionId) };
        });
      }, { sessionId });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.detail.error.revokeSession", "Failed to revoke session");
      flash(message, "error");
    }
  }, [id, runMutationWithContext, t]);
  const handleRoleToggle = React.useCallback((roleId) => {
    setSelectedRoleIds(
      (prev) => prev.includes(roleId) ? prev.filter((existingId) => existingId !== roleId) : [...prev, roleId]
    );
  }, []);
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex h-[50vh] flex-col items-center justify-center gap-2 text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6" }),
      /* @__PURE__ */ jsx("span", { children: t("customer_accounts.admin.detail.loading", "Loading user...") })
    ] }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("customer_accounts.admin.detail.error.notFound", "User not found"),
        backHref: "/backend/customer_accounts/users",
        backLabel: t("customer_accounts.admin.detail.actions.backToList", "Back to list")
      }
    ) }) });
  }
  if (error || !data) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: error ?? t("customer_accounts.admin.detail.error.notFound", "User not found"),
        action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/customer_accounts/users", children: t("customer_accounts.admin.detail.actions.backToList", "Back to list") }) })
      }
    ) }) });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsxs(PageBody, { className: "space-y-6", children: [
      /* @__PURE__ */ jsx(
        FormHeader,
        {
          mode: "detail",
          backHref: "/backend/customer_accounts/users",
          backLabel: t("customer_accounts.admin.detail.actions.backToList", "Back to list"),
          title: data.displayName,
          subtitle: data.email,
          onDelete: () => {
            void handleDelete();
          },
          deleteLabel: t("customer_accounts.admin.detail.actions.delete", "Delete")
        }
      ),
      /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-status-info-border bg-status-info-bg p-4", children: /* @__PURE__ */ jsx("div", { className: "flex items-start gap-3", children: /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium text-status-info-text", children: t("customer_accounts.admin.detail.portalAccess.title", "Customer Portal Access") }),
        /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-status-info-text", children: t("customer_accounts.admin.detail.portalAccess.description", "This user can access the customer portal at the URL below. The portal provides self-service access to orders, invoices, quotes, and account management.") }),
        /* @__PURE__ */ jsx("p", { className: "mt-2 text-xs text-status-info-text", children: t("customer_accounts.admin.detail.portalAccess.url", "Portal URL: {url}", {
          url: `${typeof window !== "undefined" ? window.location.origin : ""}/[org-slug]/portal`
        }) })
      ] }) }) }),
      /* @__PURE__ */ jsxs("div", { className: "grid gap-6 md:grid-cols-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "rounded-lg border p-4 space-y-3", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold", children: t("customer_accounts.admin.detail.sections.info", "User Information") }),
          /* @__PURE__ */ jsxs("dl", { className: "space-y-2 text-sm", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("customer_accounts.admin.detail.fields.email", "Email") }),
              /* @__PURE__ */ jsx("dd", { children: data.email })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-center", children: [
              /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("customer_accounts.admin.detail.fields.emailVerified", "Email Verified") }),
              /* @__PURE__ */ jsxs("dd", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${data.emailVerifiedAt ? "bg-status-success-bg text-status-success-text" : "bg-status-warning-bg text-status-warning-text"}`, children: data.emailVerifiedAt ? t("customer_accounts.admin.verified", "Yes") : t("customer_accounts.admin.unverified", "No") }),
                !data.emailVerifiedAt && /* @__PURE__ */ jsx(
                  Button,
                  {
                    variant: "outline",
                    size: "sm",
                    onClick: () => {
                      void handleVerifyEmail();
                    },
                    disabled: isVerifying,
                    children: isVerifying ? t("customer_accounts.admin.detail.verifyEmail.actions.verifying", "Verifying...") : t("customer_accounts.admin.detail.verifyEmail.actions.verify", "Mark Verified")
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("customer_accounts.admin.detail.fields.lastLogin", "Last Login") }),
              /* @__PURE__ */ jsx("dd", { children: formatDate(data.lastLoginAt, "-") })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("customer_accounts.admin.detail.fields.createdAt", "Created") }),
              /* @__PURE__ */ jsx("dd", { children: formatDate(data.createdAt, "-") })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "rounded-lg border p-4 space-y-3", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold", children: t("customer_accounts.admin.detail.sections.crmLinks", "CRM Links") }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-3 text-sm", children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
              /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: t("customer_accounts.admin.detail.fields.personEntity", "Linked Person") }),
              editPersonEntityId ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsx(Link, { href: `/backend/customers/people/${editPersonEntityId}`, className: "text-primary hover:underline", children: personName || editPersonEntityId }),
                /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => {
                  setEditPersonEntityId(null);
                  setPersonName(null);
                }, children: t("customer_accounts.admin.detail.actions.unlink", "Unlink") })
              ] }) : /* @__PURE__ */ jsx("div", { className: "space-y-1", children: /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    type: "text",
                    value: personSearchQuery,
                    onChange: (event) => {
                      void handleSearchPeople(event.target.value);
                    },
                    placeholder: t("customer_accounts.admin.detail.fields.searchPerson", "Search people by name...")
                  }
                ),
                personResults.length > 0 && /* @__PURE__ */ jsx("div", { className: "absolute z-10 mt-1 w-full rounded-md border bg-background shadow-lg max-h-40 overflow-y-auto", children: personResults.map((person) => /* @__PURE__ */ jsx(
                  "button",
                  {
                    type: "button",
                    className: "w-full px-3 py-2 text-left text-sm hover:bg-muted",
                    onClick: () => {
                      setEditPersonEntityId(person.id);
                      setPersonName(person.label);
                      setPersonSearchQuery("");
                      setPersonResults([]);
                    },
                    children: person.label
                  },
                  person.id
                )) })
              ] }) })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
              /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: t("customer_accounts.admin.detail.fields.customerEntity", "Linked Company") }),
              editCustomerEntityId ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsx(Link, { href: `/backend/customers/companies/${editCustomerEntityId}`, className: "text-primary hover:underline", children: companyName || editCustomerEntityId }),
                /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => {
                  setEditCustomerEntityId(null);
                  setCompanyName(null);
                }, children: t("customer_accounts.admin.detail.actions.unlink", "Unlink") })
              ] }) : /* @__PURE__ */ jsx("div", { className: "space-y-1", children: /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    type: "text",
                    value: companySearchQuery,
                    onChange: (event) => {
                      void handleSearchCompanies(event.target.value);
                    },
                    placeholder: t("customer_accounts.admin.detail.fields.searchCompany", "Search companies by name...")
                  }
                ),
                companyResults.length > 0 && /* @__PURE__ */ jsx("div", { className: "absolute z-10 mt-1 w-full rounded-md border bg-background shadow-lg max-h-40 overflow-y-auto", children: companyResults.map((company) => /* @__PURE__ */ jsx(
                  "button",
                  {
                    type: "button",
                    className: "w-full px-3 py-2 text-left text-sm hover:bg-muted",
                    onClick: () => {
                      setEditCustomerEntityId(company.id);
                      setCompanyName(company.label);
                      setCompanySearchQuery("");
                      setCompanyResults([]);
                    },
                    children: company.label
                  },
                  company.id
                )) })
              ] }) })
            ] }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customer_accounts.admin.detail.crmLinks.hint", "Changes to CRM links are saved when you click Save Changes below.") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border p-4 space-y-4", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold", children: t("customer_accounts.admin.detail.sections.settings", "Account Settings") }),
        /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", htmlFor: "user-display-name", children: t("customer_accounts.admin.detail.fields.displayName", "Display Name") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "user-display-name",
                  type: "text",
                  value: editDisplayName,
                  onChange: (event) => setEditDisplayName(event.target.value)
                }
              )
            ] }),
            /* @__PURE__ */ jsx(
              SwitchField,
              {
                id: "user-active-toggle",
                label: t("customer_accounts.admin.detail.fields.isActive", "Active"),
                checked: editActive ?? data.isActive,
                onCheckedChange: (next) => setEditActive(next)
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("customer_accounts.admin.detail.fields.roles", "Roles") }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
              availableRoles.map((role) => {
                const isSelected = selectedRoleIds.includes(role.id);
                return /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    size: "sm",
                    onClick: () => handleRoleToggle(role.id),
                    className: `rounded-full ${isSelected ? "border-primary bg-primary/10 text-primary" : ""}`,
                    children: role.name
                  },
                  role.id
                );
              }),
              availableRoles.length === 0 && /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: t("customer_accounts.admin.detail.noRolesAvailable", "No roles available") })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsx(Button, { onClick: () => {
          void handleSave();
        }, disabled: isSaving, children: isSaving ? t("customer_accounts.admin.detail.actions.saving", "Saving...") : t("customer_accounts.admin.detail.actions.save", "Save Changes") }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border p-4 space-y-3", children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between", children: /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold", children: t("customer_accounts.admin.detail.sections.security", "Security") }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
          /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setResetPasswordOpen(true), children: t("customer_accounts.admin.detail.resetPassword.actions.open", "Reset Password") }),
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: "outline",
              onClick: () => {
                void handleSendResetLink();
              },
              disabled: isSendingResetLink,
              children: isSendingResetLink ? t("customer_accounts.admin.detail.sendResetLink.actions.sending", "Generating...") : t("customer_accounts.admin.detail.sendResetLink.actions.send", "Send Reset Link")
            }
          )
        ] }),
        resetLinkUrl && /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-status-info-border bg-status-info-bg p-3", children: [
          /* @__PURE__ */ jsx("p", { className: "mb-1.5 text-sm font-medium text-status-info-text", children: t("customer_accounts.admin.detail.sendResetLink.linkLabel", "Password reset link (valid for 60 minutes):") }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx("code", { className: "flex-1 break-all rounded bg-status-info-bg px-2 py-1 text-xs text-status-info-text", children: resetLinkUrl }),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                size: "sm",
                onClick: () => {
                  void navigator.clipboard.writeText(resetLinkUrl);
                  flash(t("customer_accounts.admin.detail.sendResetLink.flash.copied", "Link copied to clipboard"), "success");
                },
                children: t("customer_accounts.admin.detail.sendResetLink.actions.copy", "Copy")
              }
            )
          ] }),
          /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-xs text-status-info-text", children: t("customer_accounts.admin.detail.sendResetLink.hint", "Share this link with the customer to let them set a new password.") })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border p-4 space-y-3", children: [
        /* @__PURE__ */ jsxs("h2", { className: "text-sm font-semibold", children: [
          t("customer_accounts.admin.detail.sections.sessions", "Active Sessions"),
          data.sessions.length > 0 && /* @__PURE__ */ jsxs("span", { className: "ml-2 text-xs font-normal text-muted-foreground", children: [
            "(",
            data.sessions.length,
            ")"
          ] })
        ] }),
        data.sessions.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("customer_accounts.admin.detail.noSessions", "No active sessions") }) : /* @__PURE__ */ jsx("div", { className: "divide-y", children: data.sessions.map((session) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between py-2 text-sm", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
            /* @__PURE__ */ jsx("p", { className: "font-medium", children: session.ipAddress || t("customer_accounts.admin.detail.unknownIp", "Unknown IP") }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground truncate max-w-xs", children: session.userAgent || t("customer_accounts.admin.detail.unknownDevice", "Unknown device") }),
            /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
              t("customer_accounts.admin.detail.fields.lastUsed", "Last used"),
              ": ",
              formatDate(session.lastUsedAt, "-")
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => {
                void handleRevokeSession(session.id);
              },
              children: t("customer_accounts.admin.detail.actions.revoke", "Revoke")
            }
          )
        ] }, session.id)) })
      ] }),
      /* @__PURE__ */ jsx(
        ResetPasswordDialog,
        {
          open: resetPasswordOpen,
          onOpenChange: setResetPasswordOpen,
          userId: id,
          onRunMutation: runMutationWithContext
        }
      )
    ] }),
    ConfirmDialogElement
  ] });
}
export {
  CustomerUserDetailPage as default
};
//# sourceMappingURL=page.js.map
