"use client";
import { OtpInput, BackupCodeGrid, PasswordStrengthMeter } from './chunk-3VYD7QL2.mjs';
import { useAuth, StepFormPage, OptionGrid, Spinner, FormCheckbox, SectionCard, EmptyState, ListCard, ListCardItem, StatusBadge, Sheet, PasswordInput, BaseForm, Avatar, InlineSpinner, Input, SegmentedControl } from './chunk-ZQRUAXGP.mjs';
import { useTranslations, useFormatter, useLocale } from './chunk-7VJ7CMMT.mjs';
import { Button, Badge } from './chunk-WR55H7DH.mjs';
import { triggerHaptic } from './chunk-D2JF6C3E.mjs';
import { useState, useCallback, useRef, useEffect } from 'react';
import { ShieldCheckIcon, PlusIcon, ArrowPathIcon, CameraIcon, UserIcon, CheckCircleIcon, GlobeAltIcon, ComputerDesktopIcon, LinkIcon } from '@heroicons/react/24/outline';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { ShieldExclamationIcon } from '@heroicons/react/20/solid';
import * as sharedI18n from '@datatechsolutions/shared-domain/i18n';

function MfaSetup({
  onSuccess,
  onCancel,
  enforcement = "optional",
  onGenerateSecret,
  onVerifySetup
}) {
  const t = useTranslations("windsock");
  const { client } = useAuth();
  const setupSteps = [
    {
      id: "method",
      title: t("mfa.setup.stepMethodTitle"),
      description: t("mfa.setup.stepMethodDescription")
    },
    {
      id: "scan",
      title: t("mfa.setup.stepScanTitle"),
      description: t("mfa.setup.stepScanDescription")
    },
    {
      id: "verify",
      title: t("mfa.setup.stepVerifyTitle"),
      description: t("mfa.setup.stepVerifyDescription")
    },
    {
      id: "backup",
      title: t("mfa.setup.stepBackupTitle"),
      description: t("mfa.setup.stepBackupDescription")
    }
  ];
  const [currentStep, setCurrentStep] = useState(0);
  const [selectedMethod, setSelectedMethod] = useState("totp");
  const [qrCodeUri, setQrCodeUri] = useState("");
  const [secret, setSecret] = useState("");
  const [verifyCode, setVerifyCode] = useState("");
  const [verifyError, setVerifyError] = useState(null);
  const [backupCodes, setBackupCodes] = useState([]);
  const [savedBackupCodes, setSavedBackupCodes] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const handleStepChange = useCallback(
    async (step) => {
      if (step === 1 && currentStep === 0) {
        setIsLoading(true);
        try {
          if (onGenerateSecret) {
            const result = await onGenerateSecret();
            setSecret(result.secret);
            setQrCodeUri(result.qrCodeUri);
          } else {
            const result = await client.generateMfaSecret();
            setSecret(result.secret);
            setQrCodeUri(result.qrCode);
            setBackupCodes(result.backupCodes);
          }
        } catch {
          return;
        } finally {
          setIsLoading(false);
        }
      }
      triggerHaptic("light");
      setCurrentStep(step);
    },
    [currentStep, onGenerateSecret, client]
  );
  const handleMethodSelect = useCallback((method) => {
    triggerHaptic("light");
    setSelectedMethod(method);
  }, []);
  const handleVerifyComplete = useCallback(
    async (code) => {
      setVerifyError(null);
      setIsLoading(true);
      try {
        if (onVerifySetup) {
          const result = await onVerifySetup(code);
          if (result.success) {
            triggerHaptic("success");
            if (result.backupCodes?.length) {
              setBackupCodes(result.backupCodes);
            }
            setCurrentStep(3);
          } else {
            triggerHaptic("error");
            setVerifyError(t("mfa.setup.errorInvalidCode"));
          }
        } else {
          const result = await client.verifyMfaSetup(code);
          if (result.success) {
            triggerHaptic("success");
            setCurrentStep(3);
          } else {
            triggerHaptic("error");
            setVerifyError(t("mfa.setup.errorInvalidCode"));
          }
        }
      } catch {
        triggerHaptic("error");
        setVerifyError(t("mfa.setup.errorVerificationFailed"));
      } finally {
        setIsLoading(false);
      }
    },
    [onVerifySetup, client, t]
  );
  const handleSubmit = useCallback(() => {
    triggerHaptic("success");
    onSuccess?.();
  }, [onSuccess]);
  const handleCancel = useCallback(() => {
    triggerHaptic("light");
    onCancel?.();
  }, [onCancel]);
  const canAdvance = (() => {
    switch (currentStep) {
      case 0:
        return !!selectedMethod;
      case 1:
        return !!qrCodeUri;
      case 2:
        return false;
      // Advance via OTP complete callback
      case 3:
        return savedBackupCodes;
      default:
        return false;
    }
  })();
  return /* @__PURE__ */ jsxs(
    StepFormPage,
    {
      title: t("mfa.setup.title"),
      subtitle: enforcement === "required" ? t("mfa.setup.subtitleRequired") : t("mfa.setup.subtitleOptional"),
      label: t("mfa.setup.label"),
      icon: /* @__PURE__ */ jsx(ShieldCheckIcon, { className: "h-5 w-5" }),
      gradient: "from-emerald-500 via-teal-500 to-cyan-500",
      steps: setupSteps,
      currentStep,
      onStepChange: handleStepChange,
      onSubmit: handleSubmit,
      onCancel: handleCancel,
      isSubmitting: isLoading,
      submitLabel: t("mfa.setup.submitLabel"),
      canAdvance,
      children: [
        currentStep === 0 && /* @__PURE__ */ jsx(
          OptionGrid,
          {
            icon: /* @__PURE__ */ jsx(ShieldCheckIcon, { className: "h-4 w-4" }),
            title: t("mfa.setup.methodGridTitle"),
            options: [
              {
                code: "totp",
                flag: "\u{1F4F1}",
                label: t("mfa.setup.methodAuthenticatorApp")
              }
            ],
            selected: selectedMethod,
            onSelect: handleMethodSelect,
            columns: 2
          }
        ),
        currentStep === 1 && /* @__PURE__ */ jsx("div", { className: "space-y-4", children: isLoading ? /* @__PURE__ */ jsx("div", { className: "flex justify-center py-8", children: /* @__PURE__ */ jsx(Spinner, {}) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          qrCodeUri && /* @__PURE__ */ jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-white p-4", children: /* @__PURE__ */ jsx(
            "img",
            {
              src: qrCodeUri,
              alt: t("mfa.setup.qrCodeAlt"),
              className: "h-48 w-48"
            }
          ) }) }),
          secret && /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mb-1", children: t("mfa.setup.manualSecretLabel") }),
            /* @__PURE__ */ jsx("code", { className: "font-mono text-sm font-medium text-gray-900 dark:text-white tracking-widest", children: secret })
          ] })
        ] }) }),
        currentStep === 2 && /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsx(
            OtpInput,
            {
              value: verifyCode,
              onChange: setVerifyCode,
              onComplete: handleVerifyComplete,
              error: verifyError ?? void 0,
              disabled: isLoading,
              autoFocus: true
            }
          ),
          isLoading && /* @__PURE__ */ jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsx(Spinner, {}) })
        ] }),
        currentStep === 3 && /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsx(
            BackupCodeGrid,
            {
              codes: backupCodes,
              revealed: true
            }
          ),
          /* @__PURE__ */ jsx(
            FormCheckbox,
            {
              label: t("mfa.setup.backupCodesSavedConfirm"),
              checked: savedBackupCodes,
              onChange: setSavedBackupCodes
            }
          )
        ] })
      ]
    }
  );
}
function MfaManage({
  mfaEnabled,
  enrolledMethods = [],
  onEnroll,
  onDisable,
  onRegenerateBackupCodes
}) {
  const t = useTranslations("windsock");
  const format = useFormatter();
  const { client } = useAuth();
  const [isBackupSheetOpen, setIsBackupSheetOpen] = useState(false);
  const [newBackupCodes, setNewBackupCodes] = useState([]);
  const [isRegenerating, setIsRegenerating] = useState(false);
  const [isConfirmDisableOpen, setIsConfirmDisableOpen] = useState(false);
  const [disablePassword, setDisablePassword] = useState("");
  const [disableError, setDisableError] = useState(null);
  const [isDisabling, setIsDisabling] = useState(false);
  const handleOpenBackupSheet = useCallback(async () => {
    triggerHaptic("medium");
    setIsRegenerating(true);
    try {
      const codes = onRegenerateBackupCodes ? await onRegenerateBackupCodes() : await client.regenerateBackupCodes();
      setNewBackupCodes(codes);
      setIsBackupSheetOpen(true);
    } catch {
    } finally {
      setIsRegenerating(false);
    }
  }, [onRegenerateBackupCodes, client]);
  const handleCloseBackupSheet = useCallback(() => {
    triggerHaptic("light");
    setIsBackupSheetOpen(false);
    setNewBackupCodes([]);
  }, []);
  const handleRequestDisable = useCallback(() => {
    triggerHaptic("warning");
    setDisablePassword("");
    setDisableError(null);
    setIsConfirmDisableOpen(true);
  }, []);
  const handleConfirmDisable = useCallback(async () => {
    if (!disablePassword.trim()) {
      setDisableError(t("mfa.manage.disablePasswordRequired"));
      triggerHaptic("error");
      return;
    }
    setDisableError(null);
    setIsDisabling(true);
    triggerHaptic("medium");
    try {
      if (onDisable) {
        onDisable();
      } else {
        const result = await client.disableMfa(disablePassword);
        if (!result.success) {
          setDisableError(result.error ?? t("mfa.manage.disableError"));
          triggerHaptic("error");
          return;
        }
      }
      setIsConfirmDisableOpen(false);
      triggerHaptic("success");
    } catch {
      setDisableError(t("mfa.manage.disableError"));
      triggerHaptic("error");
    } finally {
      setIsDisabling(false);
    }
  }, [disablePassword, onDisable, client, t]);
  const handleCancelDisable = useCallback(() => {
    triggerHaptic("light");
    setIsConfirmDisableOpen(false);
    setDisablePassword("");
    setDisableError(null);
  }, []);
  const handleEnroll = useCallback(() => {
    triggerHaptic("light");
    onEnroll?.();
  }, [onEnroll]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsx(ShieldCheckIcon, { className: "h-5 w-5 text-white" }),
          title: t("mfa.manage.title"),
          subtitle: t("mfa.manage.subtitle"),
          gradient: "from-emerald-500 via-teal-500 to-cyan-500",
          rightContent: mfaEnabled ? /* @__PURE__ */ jsx(StatusBadge, { status: "active", label: t("mfa.manage.statusEnabled"), size: "sm" }) : /* @__PURE__ */ jsx(StatusBadge, { status: "inactive", label: t("mfa.manage.statusDisabled"), size: "sm" })
        },
        padded: false,
        children: !mfaEnabled ? (
          /* MFA not enabled — show empty state with enable CTA */
          /* @__PURE__ */ jsx("div", { className: "p-4 sm:p-6", children: /* @__PURE__ */ jsx(
            EmptyState,
            {
              message: t("mfa.manage.emptyStateMessage"),
              description: t("mfa.manage.emptyStateDescription"),
              icon: ShieldExclamationIcon,
              action: {
                label: t("mfa.manage.enableButton"),
                onClick: handleEnroll
              },
              variant: "card"
            }
          ) })
        ) : (
          /* MFA enabled — show enrolled methods list + action buttons */
          /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
            enrolledMethods.length > 0 && /* @__PURE__ */ jsx(ListCard, { children: enrolledMethods.map((method, index) => /* @__PURE__ */ jsxs(
              ListCardItem,
              {
                leading: /* @__PURE__ */ jsx("div", { className: "h-9 w-9 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center shadow-sm", children: /* @__PURE__ */ jsx(ShieldCheckIcon, { className: "h-5 w-5 text-white" }) }),
                trailing: /* @__PURE__ */ jsx(StatusBadge, { status: "active", label: t("mfa.manage.methodStatusActive"), size: "sm" }),
                children: [
                  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: method.label }),
                  method.createdAt && /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: t("mfa.manage.methodEnrolledAt", {
                    date: format.dateTime(new Date(method.createdAt), {
                      year: "numeric",
                      month: "short",
                      day: "numeric"
                    })
                  }) })
                ]
              },
              `${method.type}-${index}`
            )) }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:gap-3", children: [
              onEnroll && /* @__PURE__ */ jsxs(
                Button,
                {
                  color: "ios-glass-blue",
                  onClick: handleEnroll,
                  className: "flex-1",
                  children: [
                    /* @__PURE__ */ jsx(PlusIcon, { className: "h-4 w-4 mr-1.5" }),
                    t("mfa.manage.addMethodButton")
                  ]
                }
              ),
              /* @__PURE__ */ jsxs(
                Button,
                {
                  outline: true,
                  onClick: handleOpenBackupSheet,
                  loading: isRegenerating,
                  disabled: isRegenerating,
                  className: "flex-1",
                  children: [
                    /* @__PURE__ */ jsx(ArrowPathIcon, { className: "h-4 w-4 mr-1.5" }),
                    t("mfa.manage.regenerateBackupCodesButton")
                  ]
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  color: "ios-glass-red",
                  onClick: handleRequestDisable,
                  className: "flex-1",
                  children: t("mfa.manage.disableMfaButton")
                }
              )
            ] })
          ] })
        )
      }
    ),
    /* @__PURE__ */ jsx(
      Sheet,
      {
        open: isBackupSheetOpen,
        onClose: handleCloseBackupSheet,
        title: t("mfa.manage.backupCodesSheetTitle"),
        side: "bottom",
        size: "md",
        children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("mfa.manage.backupCodesSheetDescription") }),
          /* @__PURE__ */ jsx(
            BackupCodeGrid,
            {
              codes: newBackupCodes,
              revealed: true
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              color: "ios-glass-blue",
              fullWidth: true,
              onClick: handleCloseBackupSheet,
              children: t("mfa.manage.backupCodesDoneButton")
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsx(
      Sheet,
      {
        open: isConfirmDisableOpen,
        onClose: handleCancelDisable,
        title: t("mfa.manage.confirmDisableTitle"),
        side: "bottom",
        size: "md",
        children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-xl bg-ios-red shadow-sm", children: /* @__PURE__ */ jsx(ShieldExclamationIcon, { className: "h-5 w-5 text-white" }) }),
            /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("mfa.manage.confirmDisableDescription") })
          ] }),
          /* @__PURE__ */ jsx(
            PasswordInput,
            {
              label: t("mfa.manage.disablePasswordLabel"),
              value: disablePassword,
              onChange: (event) => setDisablePassword(event.target.value),
              placeholder: t("mfa.manage.disablePasswordPlaceholder"),
              disabled: isDisabling,
              autoFocus: true,
              autoComplete: "current-password"
            }
          ),
          disableError && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", role: "alert", children: disableError }),
          /* @__PURE__ */ jsxs("div", { className: "flex gap-3", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                outline: true,
                onClick: handleCancelDisable,
                disabled: isDisabling,
                className: "flex-1",
                children: t("mfa.manage.confirmDisableCancelLabel")
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                color: "ios-glass-red",
                onClick: handleConfirmDisable,
                loading: isDisabling,
                disabled: isDisabling || !disablePassword.trim(),
                className: "flex-1",
                children: t("mfa.manage.confirmDisableConfirmLabel")
              }
            )
          ] })
        ] })
      }
    )
  ] });
}
var ALL_TABS = ["profile", "security", "sessions", "linked-accounts"];
function ProfileTabContent({ onProfileUpdate }) {
  const t = useTranslations("windsock");
  const currentLocale = useLocale();
  const { user, client } = useAuth();
  const [name, setName] = useState(user?.name ?? "");
  const [avatarPreview, setAvatarPreview] = useState(user?.image ?? null);
  const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
  const fileInputRef = useRef(null);
  const [selectedLocale, setSelectedLocale] = useState(currentLocale);
  const [isSaving, setIsSaving] = useState(false);
  const [saveError, setSaveError] = useState(null);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const handleAvatarChange = useCallback(async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    if (!["image/jpeg", "image/png", "image/webp"].includes(file.type)) {
      setSaveError(t("userProfile.profile.avatarInvalidType"));
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      setSaveError(t("userProfile.profile.avatarTooLarge"));
      return;
    }
    const previewUrl = URL.createObjectURL(file);
    setAvatarPreview(previewUrl);
    setSaveError(null);
    setIsUploadingAvatar(true);
    triggerHaptic("light");
    try {
      const uploadResult = await client.uploadFile(file, "avatars");
      if (!uploadResult.success || !uploadResult.key) {
        throw new Error(uploadResult.error ?? "Upload failed");
      }
      const updateResult = await client.updateProfile({ image: uploadResult.key });
      if (!updateResult.success) {
        throw new Error(updateResult.error ?? "Profile update failed");
      }
      triggerHaptic("success");
    } catch (error) {
      setSaveError(error instanceof Error ? error.message : "Upload failed");
      setAvatarPreview(user?.image ?? null);
      triggerHaptic("error");
    } finally {
      setIsUploadingAvatar(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  }, [client, user, t]);
  const handleSave = useCallback(async () => {
    setSaveError(null);
    setSaveSuccess(false);
    setIsSaving(true);
    triggerHaptic("light");
    try {
      if (onProfileUpdate) {
        await onProfileUpdate({ name, email: user?.email ?? "", locale: selectedLocale });
      } else {
        const result = await client.updateProfile({ name, locale: selectedLocale });
        if (!result.success) {
          throw new Error(result.error);
        }
      }
      setSaveSuccess(true);
      triggerHaptic("success");
      if (selectedLocale !== currentLocale) {
        sharedI18n.setLocaleCookie(selectedLocale);
        window.location.reload();
      }
    } catch {
      setSaveError(t("userProfile.profile.saveError"));
      triggerHaptic("error");
    } finally {
      setIsSaving(false);
    }
  }, [name, selectedLocale, currentLocale, user, onProfileUpdate, client, t]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsx(
      SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsx(UserIcon, { className: "h-5 w-5 text-white" }),
          title: t("userProfile.profile.title"),
          subtitle: t("userProfile.profile.subtitle"),
          gradient: "from-blue-500 via-indigo-500 to-violet-500"
        },
        children: /* @__PURE__ */ jsxs(BaseForm, { onSubmit: handleSave, submitLabel: t("userProfile.profile.saveButton"), showFooter: false, children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-3 pb-4", children: [
            /* @__PURE__ */ jsxs(
              "button",
              {
                type: "button",
                onClick: () => fileInputRef.current?.click(),
                disabled: isUploadingAvatar,
                className: "group relative",
                children: [
                  /* @__PURE__ */ jsx(
                    Avatar,
                    {
                      src: avatarPreview ?? void 0,
                      initials: user?.name?.slice(0, 2).toUpperCase() ?? user?.email?.slice(0, 2).toUpperCase(),
                      alt: user?.name ?? "Profile",
                      className: "h-20 w-20 text-2xl"
                    }
                  ),
                  /* @__PURE__ */ jsx("div", { className: "absolute inset-0 flex items-center justify-center rounded-full bg-black/0 transition group-hover:bg-black/40", children: isUploadingAvatar ? /* @__PURE__ */ jsx(InlineSpinner, {}) : /* @__PURE__ */ jsx(CameraIcon, { className: "h-6 w-6 text-white opacity-0 transition group-hover:opacity-100" }) })
                ]
              }
            ),
            /* @__PURE__ */ jsx(
              "input",
              {
                ref: fileInputRef,
                type: "file",
                accept: "image/jpeg,image/png,image/webp",
                onChange: handleAvatarChange,
                className: "hidden"
              }
            ),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-500 dark:text-slate-400", children: t("userProfile.profile.avatarHint") })
          ] }),
          /* @__PURE__ */ jsx(
            Input,
            {
              label: t("userProfile.profile.nameLabel"),
              value: name,
              onChange: (event) => setName(event.target.value),
              disabled: isSaving,
              autoComplete: "name"
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              label: t("userProfile.profile.emailLabel"),
              type: "email",
              value: user?.email ?? "",
              readOnly: true,
              disabled: true,
              autoComplete: "email"
            }
          ),
          saveError && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", children: saveError }),
          saveSuccess && /* @__PURE__ */ jsx("p", { className: "text-sm text-green-600 dark:text-green-400", children: t("userProfile.profile.saveSuccess") }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "submit",
              color: "ios-glass-blue",
              fullWidth: true,
              loading: isSaving,
              disabled: isSaving,
              children: t("userProfile.profile.saveButton")
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxs(
      SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsx(GlobeAltIcon, { className: "h-5 w-5 text-white" }),
          title: t("userProfile.profile.languageTitle"),
          subtitle: t("userProfile.profile.languageSubtitle"),
          gradient: "from-lime-400 via-emerald-500 to-green-600"
        },
        children: [
          /* @__PURE__ */ jsx("div", { className: "grid grid-cols-3 gap-2", children: sharedI18n.SUPPORTED_LOCALES.map((code) => {
            const meta = sharedI18n.LANGUAGE_META[code];
            const checked = selectedLocale === code;
            return /* @__PURE__ */ jsxs(
              "button",
              {
                type: "button",
                onClick: () => {
                  setSelectedLocale(code);
                  triggerHaptic("light");
                },
                className: `group relative flex flex-col items-center justify-center rounded-xl border px-2 py-2.5 backdrop-blur-xl shadow-[inset_0_1px_0_rgba(255,255,255,0.9),0_10px_22px_-16px_rgba(15,23,42,0.45)] dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.18),0_10px_22px_-16px_rgba(0,0,0,0.75)] transition ${checked ? "border-indigo-400/80 bg-gradient-to-br from-indigo-100/85 via-white/80 to-sky-100/75 dark:border-indigo-300/70 dark:bg-[linear-gradient(140deg,rgba(99,102,241,0.32)_0%,rgba(30,41,59,0.72)_100%)]" : "border-white/55 bg-gradient-to-br from-white/82 via-white/66 to-slate-100/62 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:hover:bg-[linear-gradient(140deg,rgba(51,65,85,0.76)_0%,rgba(30,41,59,0.68)_100%)]"}`,
                children: [
                  /* @__PURE__ */ jsx("span", { className: "text-lg leading-5", children: meta.flag }),
                  /* @__PURE__ */ jsx("span", { className: `mt-1.5 text-xs font-semibold ${checked ? "text-slate-900 dark:text-indigo-100" : "text-slate-700 dark:text-slate-100"}`, children: meta.nativeName }),
                  checked && /* @__PURE__ */ jsx(CheckCircleIcon, { className: "absolute right-1 top-1 h-3.5 w-3.5 text-indigo-600 dark:text-indigo-300" })
                ]
              },
              code
            );
          }) }),
          selectedLocale !== currentLocale && /* @__PURE__ */ jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              color: "ios-glass-blue",
              fullWidth: true,
              loading: isSaving,
              disabled: isSaving,
              onClick: handleSave,
              children: t("userProfile.profile.saveButton")
            }
          ) })
        ]
      }
    )
  ] });
}
function SecurityTabContent() {
  const t = useTranslations("windsock");
  const { client, user, refresh } = useAuth();
  const [showMfaSetup, setShowMfaSetup] = useState(false);
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [passwordError, setPasswordError] = useState(null);
  const [passwordSuccess, setPasswordSuccess] = useState(false);
  const [isSavingPassword, setIsSavingPassword] = useState(false);
  const handleMfaSetupSuccess = useCallback(() => {
    setShowMfaSetup(false);
    refresh();
  }, [refresh]);
  const handleChangePassword = useCallback(async () => {
    setPasswordError(null);
    setPasswordSuccess(false);
    if (!currentPassword) {
      setPasswordError(t("userProfile.security.errorCurrentRequired"));
      return;
    }
    if (!newPassword) {
      setPasswordError(t("userProfile.security.errorNewRequired"));
      return;
    }
    if (newPassword !== confirmPassword) {
      setPasswordError(t("userProfile.security.errorPasswordMismatch"));
      return;
    }
    setIsSavingPassword(true);
    triggerHaptic("light");
    try {
      const result = await client.changePassword(currentPassword, newPassword);
      if (!result.success) {
        setPasswordError(result.error ?? t("userProfile.security.errorSaveFailed"));
        triggerHaptic("error");
        return;
      }
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
      setPasswordSuccess(true);
      triggerHaptic("success");
    } catch {
      setPasswordError(t("userProfile.security.errorSaveFailed"));
      triggerHaptic("error");
    } finally {
      setIsSavingPassword(false);
    }
  }, [currentPassword, newPassword, confirmPassword, client, t]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    showMfaSetup ? /* @__PURE__ */ jsx(
      MfaSetup,
      {
        onSuccess: handleMfaSetupSuccess,
        onCancel: () => setShowMfaSetup(false)
      }
    ) : /* @__PURE__ */ jsx(
      MfaManage,
      {
        mfaEnabled: user?.mfaEnabled ?? false,
        enrolledMethods: user?.mfaEnabled ? [{ type: "totp", label: t("userProfile.security.mfaTotpLabel") }] : [],
        onEnroll: () => setShowMfaSetup(true)
      }
    ),
    /* @__PURE__ */ jsx(
      SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsx(UserIcon, { className: "h-5 w-5 text-white" }),
          title: t("userProfile.security.changePasswordTitle"),
          subtitle: t("userProfile.security.changePasswordSubtitle"),
          gradient: "from-blue-500 via-sky-500 to-cyan-500"
        },
        children: /* @__PURE__ */ jsxs(BaseForm, { onSubmit: handleChangePassword, submitLabel: t("userProfile.security.changePasswordButton"), showFooter: false, children: [
          /* @__PURE__ */ jsx(
            PasswordInput,
            {
              label: t("userProfile.security.currentPasswordLabel"),
              value: currentPassword,
              onChange: (event) => setCurrentPassword(event.target.value),
              disabled: isSavingPassword,
              autoComplete: "current-password"
            }
          ),
          /* @__PURE__ */ jsx(
            PasswordInput,
            {
              label: t("userProfile.security.newPasswordLabel"),
              value: newPassword,
              onChange: (event) => setNewPassword(event.target.value),
              disabled: isSavingPassword,
              autoComplete: "new-password"
            }
          ),
          /* @__PURE__ */ jsx(PasswordStrengthMeter, { password: newPassword }),
          /* @__PURE__ */ jsx(
            PasswordInput,
            {
              label: t("userProfile.security.confirmPasswordLabel"),
              value: confirmPassword,
              onChange: (event) => setConfirmPassword(event.target.value),
              disabled: isSavingPassword,
              autoComplete: "new-password"
            }
          ),
          passwordError && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 dark:text-red-400", children: passwordError }),
          passwordSuccess && /* @__PURE__ */ jsx("p", { className: "text-sm text-green-600 dark:text-green-400", children: t("userProfile.security.changePasswordSuccess") }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "submit",
              color: "ios-glass-blue",
              fullWidth: true,
              loading: isSavingPassword,
              disabled: isSavingPassword,
              children: t("userProfile.security.changePasswordButton")
            }
          )
        ] })
      }
    )
  ] });
}
function SessionsTabContent() {
  const t = useTranslations("windsock");
  const format = useFormatter();
  const { client } = useAuth();
  const [sessions, setSessions] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [revokingId, setRevokingId] = useState(null);
  useEffect(() => {
    let cancelled = false;
    const fetchSessions = async () => {
      setIsLoading(true);
      try {
        const rawSessions = await client.getSessions();
        if (!cancelled) {
          setSessions(rawSessions.map((session) => ({
            id: session.id,
            device: session.userAgent ?? "Unknown",
            location: session.ipAddress ?? "Unknown",
            lastActive: typeof session.createdAt === "string" ? session.createdAt : session.createdAt.toISOString(),
            current: false
          })));
        }
      } catch {
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    };
    fetchSessions();
    return () => {
      cancelled = true;
    };
  }, [client]);
  const handleRevoke = useCallback(async (sessionId) => {
    setRevokingId(sessionId);
    triggerHaptic("medium");
    try {
      await client.revokeSession(sessionId);
      setSessions((previous) => previous.filter((s) => s.id !== sessionId));
      triggerHaptic("success");
    } catch {
      triggerHaptic("error");
    } finally {
      setRevokingId(null);
    }
  }, [client]);
  return /* @__PURE__ */ jsx(
    SectionCard,
    {
      header: {
        icon: /* @__PURE__ */ jsx(ComputerDesktopIcon, { className: "h-5 w-5 text-white" }),
        title: t("userProfile.sessions.title"),
        subtitle: t("userProfile.sessions.subtitle"),
        gradient: "from-teal-500 via-cyan-500 to-sky-500"
      },
      padded: false,
      children: isLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-2 p-8 text-sm text-slate-500 dark:text-slate-400", children: [
        /* @__PURE__ */ jsx(InlineSpinner, {}),
        /* @__PURE__ */ jsx("span", { children: t("userProfile.sessions.loading") })
      ] }) : sessions.length === 0 ? /* @__PURE__ */ jsx("p", { className: "p-6 text-center text-sm text-slate-500 dark:text-slate-400", children: t("userProfile.sessions.empty") }) : /* @__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 liquid-divider", children: [
          /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400", children: t("userProfile.sessions.columnDevice") }),
          /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400", children: t("userProfile.sessions.columnLocation") }),
          /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400", children: t("userProfile.sessions.columnLastActive") }),
          /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400", children: t("userProfile.sessions.columnAction") })
        ] }) }),
        /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-gray-200/60 dark:divide-white/10", children: sessions.map((session) => /* @__PURE__ */ jsxs("tr", { children: [
          /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-slate-900 dark:text-white", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            session.device,
            session.current && /* @__PURE__ */ jsx(Badge, { color: "green", children: t("userProfile.sessions.currentBadge") })
          ] }) }),
          /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-slate-500 dark:text-slate-400", children: session.location }),
          /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-slate-500 dark:text-slate-400", children: format.relativeTime(new Date(session.lastActive)) }),
          /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-right", children: !session.current && /* @__PURE__ */ jsx(
            Button,
            {
              size: "sm",
              color: "ios-glass-red",
              onClick: () => handleRevoke(session.id),
              loading: revokingId === session.id,
              disabled: revokingId !== null,
              children: t("userProfile.sessions.revokeButton")
            }
          ) })
        ] }, session.id)) })
      ] }) })
    }
  );
}
function LinkedAccountsTabContent() {
  const t = useTranslations("windsock");
  const { client } = useAuth();
  const [accounts, setAccounts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [actioningProvider, setActioningProvider] = useState(null);
  useEffect(() => {
    let cancelled = false;
    const fetchAccounts = async () => {
      setIsLoading(true);
      try {
        const rawAccounts = await client.getLinkedAccounts();
        if (!cancelled) {
          setAccounts(rawAccounts.map((account) => ({
            provider: account.provider,
            providerUserId: account.providerAccountId,
            connected: true
          })));
        }
      } catch {
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    };
    fetchAccounts();
    return () => {
      cancelled = true;
    };
  }, [client]);
  const handleDisconnect = useCallback(async (provider) => {
    setActioningProvider(provider);
    triggerHaptic("medium");
    try {
      await client.disconnectProvider(provider);
      setAccounts((previous) => previous.filter((a) => a.provider !== provider));
      triggerHaptic("success");
    } catch {
      triggerHaptic("error");
    } finally {
      setActioningProvider(null);
    }
  }, [client]);
  const providerInitials = (provider) => provider.slice(0, 2).toUpperCase();
  return /* @__PURE__ */ jsx(
    SectionCard,
    {
      header: {
        icon: /* @__PURE__ */ jsx(LinkIcon, { className: "h-5 w-5 text-white" }),
        title: t("userProfile.linkedAccounts.title"),
        subtitle: t("userProfile.linkedAccounts.subtitle"),
        gradient: "from-violet-500 via-purple-500 to-pink-500"
      },
      padded: false,
      children: isLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-2 p-8 text-sm text-slate-500 dark:text-slate-400", children: [
        /* @__PURE__ */ jsx(InlineSpinner, {}),
        /* @__PURE__ */ jsx("span", { children: t("userProfile.linkedAccounts.loading") })
      ] }) : accounts.length === 0 ? /* @__PURE__ */ jsx("p", { className: "p-6 text-center text-sm text-slate-500 dark:text-slate-400", children: t("userProfile.linkedAccounts.empty") }) : /* @__PURE__ */ jsx(ListCard, { children: accounts.map((account) => /* @__PURE__ */ jsx(
        ListCardItem,
        {
          leading: /* @__PURE__ */ jsx(
            Avatar,
            {
              src: account.logoUrl,
              initials: providerInitials(account.provider),
              alt: account.provider
            }
          ),
          trailing: /* @__PURE__ */ jsx(
            Button,
            {
              size: "sm",
              color: "ios-glass-red",
              onClick: () => handleDisconnect(account.provider),
              loading: actioningProvider === account.provider,
              disabled: actioningProvider !== null,
              children: t("userProfile.linkedAccounts.disconnectButton")
            }
          ),
          children: /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium capitalize text-slate-900 dark:text-white", children: account.provider }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-500 dark:text-slate-400", children: t("userProfile.linkedAccounts.connectedLabel") })
          ] })
        },
        account.provider
      )) })
    }
  );
}
function UserProfile({
  defaultTab = "profile",
  tabs = ALL_TABS,
  onSignOut: _onSignOut,
  onProfileUpdate
}) {
  const t = useTranslations("windsock");
  const { status } = useAuth();
  const [activeTab, setActiveTab] = useState(
    tabs.includes(defaultTab) ? defaultTab : tabs[0] ?? "profile"
  );
  if (status === "loading") {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-12", children: /* @__PURE__ */ jsx(InlineSpinner, {}) });
  }
  if (status !== "authenticated") {
    return null;
  }
  const segments = tabs.map((tab) => ({
    value: tab,
    label: t(`userProfile.tabs.${tab}`)
  }));
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    tabs.length > 1 && /* @__PURE__ */ jsx(
      SegmentedControl,
      {
        segments,
        value: activeTab,
        onChange: (value) => setActiveTab(value),
        fullWidth: true
      }
    ),
    activeTab === "profile" && /* @__PURE__ */ jsx(ProfileTabContent, { onProfileUpdate }),
    activeTab === "security" && /* @__PURE__ */ jsx(SecurityTabContent, {}),
    activeTab === "sessions" && /* @__PURE__ */ jsx(SessionsTabContent, {}),
    activeTab === "linked-accounts" && /* @__PURE__ */ jsx(LinkedAccountsTabContent, {})
  ] });
}

export { LinkedAccountsTabContent, MfaManage, MfaSetup, ProfileTabContent, SecurityTabContent, SessionsTabContent, UserProfile };
//# sourceMappingURL=chunk-WS3IJFPW.mjs.map
//# sourceMappingURL=chunk-WS3IJFPW.mjs.map