"use client";
'use strict';

var chunkJSNRCYSO_js = require('./chunk-JSNRCYSO.js');
var chunkI2NZGVBG_js = require('./chunk-I2NZGVBG.js');
var chunkUZ3CMNUJ_js = require('./chunk-UZ3CMNUJ.js');
var chunkYXN2K77G_js = require('./chunk-YXN2K77G.js');
var react = require('react');
var outline = require('@heroicons/react/24/outline');
var client = require('@datatechsolutions/windsock/client');
var jsxRuntime = require('react/jsx-runtime');
var solid = require('@heroicons/react/20/solid');
var sharedI18n = require('@datatechsolutions/shared-domain/i18n');

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var sharedI18n__namespace = /*#__PURE__*/_interopNamespace(sharedI18n);

function MfaSetup({
  onSuccess,
  onCancel,
  enforcement = "optional",
  onGenerateSecret,
  onVerifySetup
}) {
  const t = chunkYXN2K77G_js.useTranslations("windsock");
  const { client: client$1 } = 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] = react.useState(0);
  const [selectedMethod, setSelectedMethod] = react.useState("totp");
  const [qrCodeUri, setQrCodeUri] = react.useState("");
  const [secret, setSecret] = react.useState("");
  const [verifyCode, setVerifyCode] = react.useState("");
  const [verifyError, setVerifyError] = react.useState(null);
  const [backupCodes, setBackupCodes] = react.useState([]);
  const [savedBackupCodes, setSavedBackupCodes] = react.useState(false);
  const [isLoading, setIsLoading] = react.useState(false);
  const handleStepChange = react.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$1.generateMfaSecret();
            setSecret(result.secret);
            setQrCodeUri(result.qrCode);
            setBackupCodes(result.backupCodes);
          }
        } catch {
          return;
        } finally {
          setIsLoading(false);
        }
      }
      chunkUZ3CMNUJ_js.triggerHaptic("light");
      setCurrentStep(step);
    },
    [currentStep, onGenerateSecret, client$1]
  );
  const handleMethodSelect = react.useCallback((method) => {
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    setSelectedMethod(method);
  }, []);
  const handleVerifyComplete = react.useCallback(
    async (code) => {
      setVerifyError(null);
      setIsLoading(true);
      try {
        if (onVerifySetup) {
          const result = await onVerifySetup(code);
          if (result.success) {
            chunkUZ3CMNUJ_js.triggerHaptic("success");
            if (result.backupCodes?.length) {
              setBackupCodes(result.backupCodes);
            }
            setCurrentStep(3);
          } else {
            chunkUZ3CMNUJ_js.triggerHaptic("error");
            setVerifyError(t("mfa.setup.errorInvalidCode"));
          }
        } else {
          const result = await client$1.verifyMfaSetup(code);
          if (result.success) {
            chunkUZ3CMNUJ_js.triggerHaptic("success");
            setCurrentStep(3);
          } else {
            chunkUZ3CMNUJ_js.triggerHaptic("error");
            setVerifyError(t("mfa.setup.errorInvalidCode"));
          }
        }
      } catch {
        chunkUZ3CMNUJ_js.triggerHaptic("error");
        setVerifyError(t("mfa.setup.errorVerificationFailed"));
      } finally {
        setIsLoading(false);
      }
    },
    [onVerifySetup, client$1, t]
  );
  const handleSubmit = react.useCallback(() => {
    chunkUZ3CMNUJ_js.triggerHaptic("success");
    onSuccess?.();
  }, [onSuccess]);
  const handleCancel = react.useCallback(() => {
    chunkUZ3CMNUJ_js.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__ */ jsxRuntime.jsxs(
    chunkI2NZGVBG_js.StepFormPage,
    {
      title: t("mfa.setup.title"),
      subtitle: enforcement === "required" ? t("mfa.setup.subtitleRequired") : t("mfa.setup.subtitleOptional"),
      label: t("mfa.setup.label"),
      icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsx(
          chunkI2NZGVBG_js.OptionGrid,
          {
            icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsx("div", { className: "space-y-4", children: isLoading ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-center py-8", children: /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.Spinner, {}) }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
          qrCodeUri && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl bg-white p-4", children: /* @__PURE__ */ jsxRuntime.jsx(
            "img",
            {
              src: qrCodeUri,
              alt: t("mfa.setup.qrCodeAlt"),
              className: "h-48 w-48"
            }
          ) }) }),
          secret && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "text-center", children: [
            /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mb-1", children: t("mfa.setup.manualSecretLabel") }),
            /* @__PURE__ */ jsxRuntime.jsx("code", { className: "font-mono text-sm font-medium text-gray-900 dark:text-white tracking-widest", children: secret })
          ] })
        ] }) }),
        currentStep === 2 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkJSNRCYSO_js.OtpInput,
            {
              value: verifyCode,
              onChange: setVerifyCode,
              onComplete: handleVerifyComplete,
              error: verifyError ?? void 0,
              disabled: isLoading,
              autoFocus: true
            }
          ),
          isLoading && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.Spinner, {}) })
        ] }),
        currentStep === 3 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkJSNRCYSO_js.BackupCodeGrid,
            {
              codes: backupCodes,
              revealed: true
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.FormCheckbox,
            {
              label: t("mfa.setup.backupCodesSavedConfirm"),
              checked: savedBackupCodes,
              onChange: setSavedBackupCodes
            }
          )
        ] })
      ]
    }
  );
}
function MfaManage({
  mfaEnabled,
  enrolledMethods = [],
  onEnroll,
  onDisable,
  onRegenerateBackupCodes
}) {
  const t = chunkYXN2K77G_js.useTranslations("windsock");
  const format = chunkYXN2K77G_js.useFormatter();
  const { client: client$1 } = client.useAuth();
  const [isBackupSheetOpen, setIsBackupSheetOpen] = react.useState(false);
  const [newBackupCodes, setNewBackupCodes] = react.useState([]);
  const [isRegenerating, setIsRegenerating] = react.useState(false);
  const [isConfirmDisableOpen, setIsConfirmDisableOpen] = react.useState(false);
  const [disablePassword, setDisablePassword] = react.useState("");
  const [disableError, setDisableError] = react.useState(null);
  const [isDisabling, setIsDisabling] = react.useState(false);
  const handleOpenBackupSheet = react.useCallback(async () => {
    chunkUZ3CMNUJ_js.triggerHaptic("medium");
    setIsRegenerating(true);
    try {
      const codes = onRegenerateBackupCodes ? await onRegenerateBackupCodes() : await client$1.regenerateBackupCodes();
      setNewBackupCodes(codes);
      setIsBackupSheetOpen(true);
    } catch {
    } finally {
      setIsRegenerating(false);
    }
  }, [onRegenerateBackupCodes, client$1]);
  const handleCloseBackupSheet = react.useCallback(() => {
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    setIsBackupSheetOpen(false);
    setNewBackupCodes([]);
  }, []);
  const handleRequestDisable = react.useCallback(() => {
    chunkUZ3CMNUJ_js.triggerHaptic("warning");
    setDisablePassword("");
    setDisableError(null);
    setIsConfirmDisableOpen(true);
  }, []);
  const handleConfirmDisable = react.useCallback(async () => {
    if (!disablePassword.trim()) {
      setDisableError(t("mfa.manage.disablePasswordRequired"));
      chunkUZ3CMNUJ_js.triggerHaptic("error");
      return;
    }
    setDisableError(null);
    setIsDisabling(true);
    chunkUZ3CMNUJ_js.triggerHaptic("medium");
    try {
      if (onDisable) {
        onDisable();
      } else {
        const result = await client$1.disableMfa(disablePassword);
        if (!result.success) {
          setDisableError(result.error ?? t("mfa.manage.disableError"));
          chunkUZ3CMNUJ_js.triggerHaptic("error");
          return;
        }
      }
      setIsConfirmDisableOpen(false);
      chunkUZ3CMNUJ_js.triggerHaptic("success");
    } catch {
      setDisableError(t("mfa.manage.disableError"));
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setIsDisabling(false);
    }
  }, [disablePassword, onDisable, client$1, t]);
  const handleCancelDisable = react.useCallback(() => {
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    setIsConfirmDisableOpen(false);
    setDisablePassword("");
    setDisableError(null);
  }, []);
  const handleEnroll = react.useCallback(() => {
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    onEnroll?.();
  }, [onEnroll]);
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.StatusBadge, { status: "active", label: t("mfa.manage.statusEnabled"), size: "sm" }) : /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.StatusBadge, { status: "inactive", label: t("mfa.manage.statusDisabled"), size: "sm" })
        },
        padded: false,
        children: !mfaEnabled ? (
          /* MFA not enabled — show empty state with enable CTA */
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "p-4 sm:p-6", children: /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.EmptyState,
            {
              message: t("mfa.manage.emptyStateMessage"),
              description: t("mfa.manage.emptyStateDescription"),
              icon: solid.ShieldExclamationIcon,
              action: {
                label: t("mfa.manage.enableButton"),
                onClick: handleEnroll
              },
              variant: "card"
            }
          ) })
        ) : (
          /* MFA enabled — show enrolled methods list + action buttons */
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
            enrolledMethods.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.ListCard, { children: enrolledMethods.map((method, index) => /* @__PURE__ */ jsxRuntime.jsxs(
              chunkI2NZGVBG_js.ListCardItem,
              {
                leading: /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx(outline.ShieldCheckIcon, { className: "h-5 w-5 text-white" }) }),
                trailing: /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.StatusBadge, { status: "active", label: t("mfa.manage.methodStatusActive"), size: "sm" }),
                children: [
                  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: method.label }),
                  method.createdAt && /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:gap-3", children: [
              onEnroll && /* @__PURE__ */ jsxRuntime.jsxs(
                chunkI2NZGVBG_js.Button,
                {
                  color: "ios-glass-blue",
                  onClick: handleEnroll,
                  className: "flex-1",
                  children: [
                    /* @__PURE__ */ jsxRuntime.jsx(outline.PlusIcon, { className: "h-4 w-4 mr-1.5" }),
                    t("mfa.manage.addMethodButton")
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntime.jsxs(
                chunkI2NZGVBG_js.Button,
                {
                  outline: true,
                  onClick: handleOpenBackupSheet,
                  loading: isRegenerating,
                  disabled: isRegenerating,
                  className: "flex-1",
                  children: [
                    /* @__PURE__ */ jsxRuntime.jsx(outline.ArrowPathIcon, { className: "h-4 w-4 mr-1.5" }),
                    t("mfa.manage.regenerateBackupCodesButton")
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntime.jsx(
                chunkI2NZGVBG_js.Button,
                {
                  color: "ios-glass-red",
                  onClick: handleRequestDisable,
                  className: "flex-1",
                  children: t("mfa.manage.disableMfaButton")
                }
              )
            ] })
          ] })
        )
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.Sheet,
      {
        open: isBackupSheetOpen,
        onClose: handleCloseBackupSheet,
        title: t("mfa.manage.backupCodesSheetTitle"),
        side: "bottom",
        size: "md",
        children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
          /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("mfa.manage.backupCodesSheetDescription") }),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkJSNRCYSO_js.BackupCodeGrid,
            {
              codes: newBackupCodes,
              revealed: true
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Button,
            {
              color: "ios-glass-blue",
              fullWidth: true,
              onClick: handleCloseBackupSheet,
              children: t("mfa.manage.backupCodesDoneButton")
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.Sheet,
      {
        open: isConfirmDisableOpen,
        onClose: handleCancelDisable,
        title: t("mfa.manage.confirmDisableTitle"),
        side: "bottom",
        size: "md",
        children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 p-4 sm:p-6", children: [
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-xl bg-ios-red shadow-sm", children: /* @__PURE__ */ jsxRuntime.jsx(solid.ShieldExclamationIcon, { className: "h-5 w-5 text-white" }) }),
            /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("mfa.manage.confirmDisableDescription") })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.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__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-600 dark:text-red-400", role: "alert", children: disableError }),
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-3", children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              chunkI2NZGVBG_js.Button,
              {
                outline: true,
                onClick: handleCancelDisable,
                disabled: isDisabling,
                className: "flex-1",
                children: t("mfa.manage.confirmDisableCancelLabel")
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(
              chunkI2NZGVBG_js.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 = chunkYXN2K77G_js.useTranslations("windsock");
  const currentLocale = chunkYXN2K77G_js.useLocale();
  const { user, client: client$1 } = client.useAuth();
  const [name, setName] = react.useState(user?.name ?? "");
  const [avatarPreview, setAvatarPreview] = react.useState(user?.image ?? null);
  const [isUploadingAvatar, setIsUploadingAvatar] = react.useState(false);
  const fileInputRef = react.useRef(null);
  const [selectedLocale, setSelectedLocale] = react.useState(currentLocale);
  const [isSaving, setIsSaving] = react.useState(false);
  const [saveError, setSaveError] = react.useState(null);
  const [saveSuccess, setSaveSuccess] = react.useState(false);
  const handleAvatarChange = react.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);
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    try {
      const uploadResult = await client$1.uploadFile(file, "avatars");
      if (!uploadResult.success || !uploadResult.key) {
        throw new Error(uploadResult.error ?? "Upload failed");
      }
      const updateResult = await client$1.updateProfile({ image: uploadResult.key });
      if (!updateResult.success) {
        throw new Error(updateResult.error ?? "Profile update failed");
      }
      chunkUZ3CMNUJ_js.triggerHaptic("success");
    } catch (error) {
      setSaveError(error instanceof Error ? error.message : "Upload failed");
      setAvatarPreview(user?.image ?? null);
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setIsUploadingAvatar(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  }, [client$1, user, t]);
  const handleSave = react.useCallback(async () => {
    setSaveError(null);
    setSaveSuccess(false);
    setIsSaving(true);
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    try {
      if (onProfileUpdate) {
        await onProfileUpdate({ name, email: user?.email ?? "", locale: selectedLocale });
      } else {
        const result = await client$1.updateProfile({ name, locale: selectedLocale });
        if (!result.success) {
          throw new Error(result.error);
        }
      }
      setSaveSuccess(true);
      chunkUZ3CMNUJ_js.triggerHaptic("success");
      if (selectedLocale !== currentLocale) {
        sharedI18n__namespace.setLocaleCookie(selectedLocale);
        window.location.reload();
      }
    } catch {
      setSaveError(t("userProfile.profile.saveError"));
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setIsSaving(false);
    }
  }, [name, selectedLocale, currentLocale, user, onProfileUpdate, client$1, t]);
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsxs(chunkI2NZGVBG_js.BaseForm, { onSubmit: handleSave, submitLabel: t("userProfile.profile.saveButton"), showFooter: false, children: [
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center gap-3 pb-4", children: [
            /* @__PURE__ */ jsxRuntime.jsxs(
              "button",
              {
                type: "button",
                onClick: () => fileInputRef.current?.click(),
                disabled: isUploadingAvatar,
                className: "group relative",
                children: [
                  /* @__PURE__ */ jsxRuntime.jsx(
                    chunkI2NZGVBG_js.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__ */ jsxRuntime.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__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.InlineSpinner, {}) : /* @__PURE__ */ jsxRuntime.jsx(outline.CameraIcon, { className: "h-6 w-6 text-white opacity-0 transition group-hover:opacity-100" }) })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(
              "input",
              {
                ref: fileInputRef,
                type: "file",
                accept: "image/jpeg,image/png,image/webp",
                onChange: handleAvatarChange,
                className: "hidden"
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: t("userProfile.profile.avatarHint") })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Input,
            {
              label: t("userProfile.profile.nameLabel"),
              value: name,
              onChange: (event) => setName(event.target.value),
              disabled: isSaving,
              autoComplete: "name"
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Input,
            {
              label: t("userProfile.profile.emailLabel"),
              type: "email",
              value: user?.email ?? "",
              readOnly: true,
              disabled: true,
              autoComplete: "email"
            }
          ),
          saveError && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-600 dark:text-red-400", children: saveError }),
          saveSuccess && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-green-600 dark:text-green-400", children: t("userProfile.profile.saveSuccess") }),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Button,
            {
              type: "submit",
              color: "ios-glass-blue",
              fullWidth: true,
              loading: isSaving,
              disabled: isSaving,
              children: t("userProfile.profile.saveButton")
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsxs(
      chunkI2NZGVBG_js.SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsx("div", { className: "grid grid-cols-3 gap-2", children: sharedI18n__namespace.SUPPORTED_LOCALES.map((code) => {
            const meta = sharedI18n__namespace.LANGUAGE_META[code];
            const checked = selectedLocale === code;
            return /* @__PURE__ */ jsxRuntime.jsxs(
              "button",
              {
                type: "button",
                onClick: () => {
                  setSelectedLocale(code);
                  chunkUZ3CMNUJ_js.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__ */ jsxRuntime.jsx("span", { className: "text-lg leading-5", children: meta.flag }),
                  /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx(outline.CheckCircleIcon, { className: "absolute right-1 top-1 h-3.5 w-3.5 text-indigo-600 dark:text-indigo-300" })
                ]
              },
              code
            );
          }) }),
          selectedLocale !== currentLocale && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Button,
            {
              type: "button",
              color: "ios-glass-blue",
              fullWidth: true,
              loading: isSaving,
              disabled: isSaving,
              onClick: handleSave,
              children: t("userProfile.profile.saveButton")
            }
          ) })
        ]
      }
    )
  ] });
}
function SecurityTabContent() {
  const t = chunkYXN2K77G_js.useTranslations("windsock");
  const { client: client$1, user, refresh } = client.useAuth();
  const [showMfaSetup, setShowMfaSetup] = react.useState(false);
  const [currentPassword, setCurrentPassword] = react.useState("");
  const [newPassword, setNewPassword] = react.useState("");
  const [confirmPassword, setConfirmPassword] = react.useState("");
  const [passwordError, setPasswordError] = react.useState(null);
  const [passwordSuccess, setPasswordSuccess] = react.useState(false);
  const [isSavingPassword, setIsSavingPassword] = react.useState(false);
  const handleMfaSetupSuccess = react.useCallback(() => {
    setShowMfaSetup(false);
    refresh();
  }, [refresh]);
  const handleChangePassword = react.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);
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    try {
      const result = await client$1.changePassword(currentPassword, newPassword);
      if (!result.success) {
        setPasswordError(result.error ?? t("userProfile.security.errorSaveFailed"));
        chunkUZ3CMNUJ_js.triggerHaptic("error");
        return;
      }
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
      setPasswordSuccess(true);
      chunkUZ3CMNUJ_js.triggerHaptic("success");
    } catch {
      setPasswordError(t("userProfile.security.errorSaveFailed"));
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setIsSavingPassword(false);
    }
  }, [currentPassword, newPassword, confirmPassword, client$1, t]);
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
    showMfaSetup ? /* @__PURE__ */ jsxRuntime.jsx(
      MfaSetup,
      {
        onSuccess: handleMfaSetupSuccess,
        onCancel: () => setShowMfaSetup(false)
      }
    ) : /* @__PURE__ */ jsxRuntime.jsx(
      MfaManage,
      {
        mfaEnabled: user?.mfaEnabled ?? false,
        enrolledMethods: user?.mfaEnabled ? [{ type: "totp", label: t("userProfile.security.mfaTotpLabel") }] : [],
        onEnroll: () => setShowMfaSetup(true)
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.SectionCard,
      {
        header: {
          icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsxs(chunkI2NZGVBG_js.BaseForm, { onSubmit: handleChangePassword, submitLabel: t("userProfile.security.changePasswordButton"), showFooter: false, children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.PasswordInput,
            {
              label: t("userProfile.security.currentPasswordLabel"),
              value: currentPassword,
              onChange: (event) => setCurrentPassword(event.target.value),
              disabled: isSavingPassword,
              autoComplete: "current-password"
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.PasswordInput,
            {
              label: t("userProfile.security.newPasswordLabel"),
              value: newPassword,
              onChange: (event) => setNewPassword(event.target.value),
              disabled: isSavingPassword,
              autoComplete: "new-password"
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(chunkJSNRCYSO_js.PasswordStrengthMeter, { password: newPassword }),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.PasswordInput,
            {
              label: t("userProfile.security.confirmPasswordLabel"),
              value: confirmPassword,
              onChange: (event) => setConfirmPassword(event.target.value),
              disabled: isSavingPassword,
              autoComplete: "new-password"
            }
          ),
          passwordError && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-600 dark:text-red-400", children: passwordError }),
          passwordSuccess && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-green-600 dark:text-green-400", children: t("userProfile.security.changePasswordSuccess") }),
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Button,
            {
              type: "submit",
              color: "ios-glass-blue",
              fullWidth: true,
              loading: isSavingPassword,
              disabled: isSavingPassword,
              children: t("userProfile.security.changePasswordButton")
            }
          )
        ] })
      }
    )
  ] });
}
function SessionsTabContent() {
  const t = chunkYXN2K77G_js.useTranslations("windsock");
  const format = chunkYXN2K77G_js.useFormatter();
  const { client: client$1 } = client.useAuth();
  const [sessions, setSessions] = react.useState([]);
  const [isLoading, setIsLoading] = react.useState(true);
  const [revokingId, setRevokingId] = react.useState(null);
  react.useEffect(() => {
    let cancelled = false;
    const fetchSessions = async () => {
      setIsLoading(true);
      try {
        const rawSessions = await client$1.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$1]);
  const handleRevoke = react.useCallback(async (sessionId) => {
    setRevokingId(sessionId);
    chunkUZ3CMNUJ_js.triggerHaptic("medium");
    try {
      await client$1.revokeSession(sessionId);
      setSessions((previous) => previous.filter((s) => s.id !== sessionId));
      chunkUZ3CMNUJ_js.triggerHaptic("success");
    } catch {
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setRevokingId(null);
    }
  }, [client$1]);
  return /* @__PURE__ */ jsxRuntime.jsx(
    chunkI2NZGVBG_js.SectionCard,
    {
      header: {
        icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-center gap-2 p-8 text-sm text-gray-500 dark:text-gray-400", children: [
        /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.InlineSpinner, {}),
        /* @__PURE__ */ jsxRuntime.jsx("span", { children: t("userProfile.sessions.loading") })
      ] }) : sessions.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "p-6 text-center text-sm text-gray-500 dark:text-gray-400", children: t("userProfile.sessions.empty") }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxRuntime.jsxs("table", { className: "w-full text-sm", children: [
        /* @__PURE__ */ jsxRuntime.jsx("thead", { children: /* @__PURE__ */ jsxRuntime.jsxs("tr", { className: "border-b border-gray-200/60 dark:border-white/10", children: [
          /* @__PURE__ */ jsxRuntime.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("userProfile.sessions.columnDevice") }),
          /* @__PURE__ */ jsxRuntime.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("userProfile.sessions.columnLocation") }),
          /* @__PURE__ */ jsxRuntime.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("userProfile.sessions.columnLastActive") }),
          /* @__PURE__ */ jsxRuntime.jsx("th", { className: "px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: t("userProfile.sessions.columnAction") })
        ] }) }),
        /* @__PURE__ */ jsxRuntime.jsx("tbody", { className: "divide-y divide-gray-200/60 dark:divide-white/10", children: sessions.map((session) => /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntime.jsx("td", { className: "px-4 py-3 text-gray-900 dark:text-white", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
            session.device,
            session.current && /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.Badge, { color: "green", children: t("userProfile.sessions.currentBadge") })
          ] }) }),
          /* @__PURE__ */ jsxRuntime.jsx("td", { className: "px-4 py-3 text-gray-500 dark:text-gray-400", children: session.location }),
          /* @__PURE__ */ jsxRuntime.jsx("td", { className: "px-4 py-3 text-gray-500 dark:text-gray-400", children: format.relativeTime(new Date(session.lastActive)) }),
          /* @__PURE__ */ jsxRuntime.jsx("td", { className: "px-4 py-3 text-right", children: !session.current && /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.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 = chunkYXN2K77G_js.useTranslations("windsock");
  const { client: client$1 } = client.useAuth();
  const [accounts, setAccounts] = react.useState([]);
  const [isLoading, setIsLoading] = react.useState(true);
  const [actioningProvider, setActioningProvider] = react.useState(null);
  react.useEffect(() => {
    let cancelled = false;
    const fetchAccounts = async () => {
      setIsLoading(true);
      try {
        const rawAccounts = await client$1.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$1]);
  const handleDisconnect = react.useCallback(async (provider) => {
    setActioningProvider(provider);
    chunkUZ3CMNUJ_js.triggerHaptic("medium");
    try {
      await client$1.disconnectProvider(provider);
      setAccounts((previous) => previous.filter((a) => a.provider !== provider));
      chunkUZ3CMNUJ_js.triggerHaptic("success");
    } catch {
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setActioningProvider(null);
    }
  }, [client$1]);
  const providerInitials = (provider) => provider.slice(0, 2).toUpperCase();
  return /* @__PURE__ */ jsxRuntime.jsx(
    chunkI2NZGVBG_js.SectionCard,
    {
      header: {
        icon: /* @__PURE__ */ jsxRuntime.jsx(outline.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__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-center gap-2 p-8 text-sm text-gray-500 dark:text-gray-400", children: [
        /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.InlineSpinner, {}),
        /* @__PURE__ */ jsxRuntime.jsx("span", { children: t("userProfile.linkedAccounts.loading") })
      ] }) : accounts.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "p-6 text-center text-sm text-gray-500 dark:text-gray-400", children: t("userProfile.linkedAccounts.empty") }) : /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.ListCard, { children: accounts.map((account) => /* @__PURE__ */ jsxRuntime.jsx(
        chunkI2NZGVBG_js.ListCardItem,
        {
          leading: /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Avatar,
            {
              src: account.logoUrl,
              initials: providerInitials(account.provider),
              alt: account.provider
            }
          ),
          trailing: /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.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__ */ jsxRuntime.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium capitalize text-gray-900 dark:text-white", children: account.provider }),
            /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: t("userProfile.linkedAccounts.connectedLabel") })
          ] })
        },
        account.provider
      )) })
    }
  );
}
function UserProfile({
  defaultTab = "profile",
  tabs = ALL_TABS,
  onSignOut: _onSignOut,
  onProfileUpdate
}) {
  const t = chunkYXN2K77G_js.useTranslations("windsock");
  const { status } = client.useAuth();
  const [activeTab, setActiveTab] = react.useState(
    tabs.includes(defaultTab) ? defaultTab : tabs[0] ?? "profile"
  );
  if (status === "loading") {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-center py-12", children: /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.InlineSpinner, {}) });
  }
  if (status !== "authenticated") {
    return null;
  }
  const segments = tabs.map((tab) => ({
    value: tab,
    label: t(`userProfile.tabs.${tab}`)
  }));
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
    tabs.length > 1 && /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.SegmentedControl,
      {
        segments,
        value: activeTab,
        onChange: (value) => setActiveTab(value),
        fullWidth: true
      }
    ),
    activeTab === "profile" && /* @__PURE__ */ jsxRuntime.jsx(ProfileTabContent, { onProfileUpdate }),
    activeTab === "security" && /* @__PURE__ */ jsxRuntime.jsx(SecurityTabContent, {}),
    activeTab === "sessions" && /* @__PURE__ */ jsxRuntime.jsx(SessionsTabContent, {}),
    activeTab === "linked-accounts" && /* @__PURE__ */ jsxRuntime.jsx(LinkedAccountsTabContent, {})
  ] });
}

exports.LinkedAccountsTabContent = LinkedAccountsTabContent;
exports.MfaManage = MfaManage;
exports.MfaSetup = MfaSetup;
exports.ProfileTabContent = ProfileTabContent;
exports.SecurityTabContent = SecurityTabContent;
exports.SessionsTabContent = SessionsTabContent;
exports.UserProfile = UserProfile;
//# sourceMappingURL=chunk-AOUUZ52N.js.map
//# sourceMappingURL=chunk-AOUUZ52N.js.map