"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, AtSign, Bell, CircleCheckBig, Forward, LogOut, Mail, MailPlus, Menu, MoreVertical, Palette, PanelRightClose, Pencil, Search, ShieldCheck, Trash2, UserRoundPlus, Users, WalletCards, X } from "lucide-react";
import { CSSProperties, FormEvent, type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { api, setTenantAdminMailboxEmail } from "@/lib/api";
import { isLoginThemeName, loginThemes } from "@/lib/login-theme";
import { optimizeBrandingUpload } from "@/lib/image-optimization";
import { resolveProductTierLabelKey } from "@/lib/product-tier-labels";
import { useRuntimeBranding } from "@/lib/runtime-branding";
import { resolveBrandDomainFromHost, siteConfig } from "@/lib/site-config";
import type { DistributionList, Domain, LicenseStatusConfig, Mailbox } from "@/lib/types";
import { BrandLogo } from "./brand-logo";
import { LoginDesigner, type LoginDesignerDraft } from "./login-designer";

type ScopeFilter = "all" | "over_quota" | "inactive_6m" | "postmaster" | "two_factor";
type AdminView = "accounts" | "distribution_lists" | "login_designer" | "information";
type MailboxAccountStatus = "active" | "locked" | "closed";
type CustomerAdminVariant = "zimphony" | "mailmali";

const TENANT_ADMIN_SESSION_KEY = "zimphony.tenantAdminSession";
const INACTIVE_ACCOUNT_DAYS = 90;
const PRODUCT_WEBSITE = "https://www.zimphony.com";
const PRODUCT_SUPPORT_EMAIL = "support@zimphony.com";
const MAILBOX_ACCOUNT_STATUSES: Array<{ value: MailboxAccountStatus; label: string; description: string; tone: "emerald" | "amber" | "red" }> = [
  { value: "active", label: "Active", description: "Mailbox can sign in and receive mail normally.", tone: "emerald" },
  { value: "locked", label: "Locked", description: "User login is disabled, but new mail delivery continues, often used if an account is compromised.", tone: "amber" },
  { value: "closed", label: "Closed", description: "Disabled login and bouncing messages; addresses are removed from distribution lists as a soft-delete step.", tone: "red" },
];

type SavedTenantAdminSession = {
  adminToken: string;
  adminEmail: string;
};

function readSavedTenantAdminSession(): SavedTenantAdminSession | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = window.sessionStorage.getItem(TENANT_ADMIN_SESSION_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as Partial<SavedTenantAdminSession>;
    const adminToken = String(parsed.adminToken || "").trim();
    const adminEmail = String(parsed.adminEmail || "").trim();
    if (!adminToken || !adminEmail) return null;
    return { adminToken, adminEmail };
  } catch {
    return null;
  }
}

function saveTenantAdminSession(session: SavedTenantAdminSession) {
  if (typeof window === "undefined") return;
  window.sessionStorage.setItem(TENANT_ADMIN_SESSION_KEY, JSON.stringify(session));
}

function clearTenantAdminSession() {
  if (typeof window === "undefined") return;
  window.sessionStorage.removeItem(TENANT_ADMIN_SESSION_KEY);
}

export function CustomerAdmin({ variant = "zimphony" }: { variant?: CustomerAdminVariant }) {
  const queryClient = useQueryClient();
  const isMailMaliAdmin = variant === "mailmali";
  const [activeView, setActiveView] = useState<AdminView>("accounts");
  const [adminSidebarOpen, setAdminSidebarOpen] = useState(false);
  const [adminToken, setAdminToken] = useState("");
  const [adminEmail, setAdminEmail] = useState("");
  const [sessionChecked, setSessionChecked] = useState(false);
  const [adminPassword, setAdminPassword] = useState("");
  const [twoFactorChallenge, setTwoFactorChallenge] = useState<{ token: string; expiresIn: number } | null>(null);
  const [twoFactorCode, setTwoFactorCode] = useState("");
  const [brandLogoFile, setBrandLogoFile] = useState<File | null>(null);
  const [brandNameDraft, setBrandNameDraft] = useState("");
  const [brandTaglineDraft, setBrandTaglineDraft] = useState("");
  const [loginDesignerDraft, setLoginDesignerDraft] = useState<LoginDesignerDraft>({ mode: "theme", theme: "mint", landscapeOnly: false, template: "panel-left", backgroundColor: "#def8f1", gradientColor: "#bdf1e4", brandNameColor: loginThemes.mint.heading, taglineColor: loginThemes.mint.body, supportingTextColor: loginThemes.mint.supporting, boxTransparency: 5 });
  const [loginBackgroundFile, setLoginBackgroundFile] = useState<File | null>(null);
  const [brandEditorOpen, setBrandEditorOpen] = useState(false);
  const [hostBrandDomain, setHostBrandDomain] = useState("");
  const [selectedDomainId, setSelectedDomainId] = useState("");
  const [localPart, setLocalPart] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [quotaMb, setQuotaMb] = useState(0);
  const [createMailboxPassword, setCreateMailboxPassword] = useState("");
  const [createMailboxConfirmPassword, setCreateMailboxConfirmPassword] = useState("");
  const [createMailboxOpen, setCreateMailboxOpen] = useState(false);
  const [createMailboxValidationError, setCreateMailboxValidationError] = useState("");
  const [dlSearch, setDlSearch] = useState("");
  const [dlLocalPart, setDlLocalPart] = useState("");
  const [dlDisplayName, setDlDisplayName] = useState("");
  const [dlSelectedEmail, setDlSelectedEmail] = useState("");
  const [dlMemberEmail, setDlMemberEmail] = useState("");
  const [addMemberListEmail, setAddMemberListEmail] = useState("");
  const [membersListEmail, setMembersListEmail] = useState("");
  const [createDistributionListOpen, setCreateDistributionListOpen] = useState(false);
  const [deleteDistributionListEmail, setDeleteDistributionListEmail] = useState("");
  const [createDistributionListValidationError, setCreateDistributionListValidationError] = useState("");
  const [search, setSearch] = useState("");
  const [scope, setScope] = useState<ScopeFilter>("all");
  const [pageSize, setPageSize] = useState(25);
  const [pageIndex, setPageIndex] = useState(1);
  const [selectedMailboxId, setSelectedMailboxId] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [notice, setNotice] = useState("");
  const [passwordModalMailboxId, setPasswordModalMailboxId] = useState("");
  const [deleteModalMailboxId, setDeleteModalMailboxId] = useState("");
  const [mailboxActionMenuId, setMailboxActionMenuId] = useState("");
  const [renameMailboxId, setRenameMailboxId] = useState("");
  const [displayNameMailboxId, setDisplayNameMailboxId] = useState("");
  const [statusMailboxId, setStatusMailboxId] = useState("");
  const [aliasMailboxId, setAliasMailboxId] = useState("");
  const [forwardMailboxId, setForwardMailboxId] = useState("");
  const [renameLocalPart, setRenameLocalPart] = useState("");
  const [mailboxDisplayNameDraft, setMailboxDisplayNameDraft] = useState("");
  const [mailboxStatusDraft, setMailboxStatusDraft] = useState<MailboxAccountStatus>("active");
  const [aliasEmail, setAliasEmail] = useState("");
  const [forwardAddressesText, setForwardAddressesText] = useState("");
  const [forwardKeepLocalCopy, setForwardKeepLocalCopy] = useState(true);

  const isSignedIn = Boolean(adminToken.trim() && adminEmail.trim());

  function clearTenantAdminQueryCache() {
    queryClient.removeQueries({ queryKey: ["tenant-admin-me"] });
    queryClient.removeQueries({ queryKey: ["tenant-admin-organization"] });
    queryClient.removeQueries({ queryKey: ["tenant-admin-domains"] });
    queryClient.removeQueries({ queryKey: ["tenant-admin-mailboxes"] });
    queryClient.removeQueries({ queryKey: ["tenant-admin-distribution-lists"] });
  }

  function applyAdminSession(token: string, email: string) {
    const nextToken = token.trim();
    const nextEmail = email.trim();
    setAdminToken(nextToken);
    setAdminEmail(nextEmail);
    setTenantAdminMailboxEmail(nextEmail);
    saveTenantAdminSession({ adminToken: nextToken, adminEmail: nextEmail });
  }

  useEffect(() => {
    setTenantAdminMailboxEmail(adminEmail);
  }, [adminEmail]);

  useEffect(() => {
    setHostBrandDomain(siteConfig.adminBrandDomain || resolveBrandDomainFromHost(window.location.hostname));
    const savedSession = readSavedTenantAdminSession();
    if (savedSession) {
      setAdminToken(savedSession.adminToken);
      setAdminEmail(savedSession.adminEmail);
      setTenantAdminMailboxEmail(savedSession.adminEmail);
    }
    setSessionChecked(true);
  }, []);

  const me = useQuery({
    queryKey: ["tenant-admin-me", adminToken, adminEmail],
    queryFn: () => api.tenantAdminMe(adminToken),
    enabled: isSignedIn,
    staleTime: 30_000,
  });
  const organization = useQuery({
    queryKey: ["tenant-admin-organization", adminToken, adminEmail],
    queryFn: () => api.tenantAdminOrganization(adminToken),
    enabled: isSignedIn,
    staleTime: 30_000,
  });
  const domains = useQuery({
    queryKey: ["tenant-admin-domains", adminToken, adminEmail],
    queryFn: () => api.tenantAdminDomains(adminToken),
    enabled: isSignedIn,
    staleTime: 30_000,
  });
  const runtimeConfig = useQuery({
    queryKey: ["tenant-admin-runtime-config", adminToken, adminEmail],
    queryFn: () => api.config(),
    enabled: isSignedIn,
    staleTime: 30_000,
  });
  const mailboxes = useQuery({
    queryKey: ["tenant-admin-mailboxes", adminToken, adminEmail],
    queryFn: () => api.tenantAdminMailboxes(adminToken),
    enabled: isSignedIn,
    staleTime: 0,
    refetchOnMount: "always",
    refetchOnWindowFocus: true,
  });
  const distributionLists = useQuery({
    queryKey: ["tenant-admin-distribution-lists", adminToken, adminEmail],
    queryFn: () => api.tenantAdminDistributionLists(adminToken),
    enabled: isSignedIn,
    staleTime: 15_000,
  });
  const organizationBrandDomain = String(organization.data?.organization.primary_domain || "").trim().toLowerCase();
  const configuredAdminBrandDomain = String(siteConfig.adminBrandDomain || "").trim().toLowerCase();
  const brandDomain = String(configuredAdminBrandDomain || organizationBrandDomain || hostBrandDomain || "").trim().toLowerCase();
  const branding = useRuntimeBranding(brandDomain);
  const brandingCacheDomains = useMemo(
    () => Array.from(new Set([brandDomain, organizationBrandDomain, hostBrandDomain.trim().toLowerCase()].filter(Boolean))),
    [brandDomain, hostBrandDomain, organizationBrandDomain],
  );

  useEffect(() => {
    if (brandEditorOpen) return;
    setBrandNameDraft(branding.name || "");
    setBrandTaglineDraft(branding.tagline || "");
    const loginThemeName = isLoginThemeName(branding.loginTheme) ? branding.loginTheme : "mint";
    const loginTheme = loginThemes[loginThemeName];
    setLoginDesignerDraft({ mode: branding.loginDesignMode, theme: loginThemeName, landscapeOnly: Boolean(branding.loginLandscapeOnly), template: branding.loginTemplate, backgroundColor: branding.loginBackgroundColor, gradientColor: branding.loginGradientColor, brandNameColor: branding.loginBrandNameColor || loginTheme.heading, taglineColor: branding.loginTaglineColor || loginTheme.body, supportingTextColor: branding.loginSupportingTextColor || loginTheme.supporting, boxTransparency: branding.loginBoxTransparency });
  }, [brandEditorOpen, branding.loginBackgroundColor, branding.loginBoxTransparency, branding.loginBrandNameColor, branding.loginDesignMode, branding.loginGradientColor, branding.loginLandscapeOnly, branding.loginSupportingTextColor, branding.loginTaglineColor, branding.loginTemplate, branding.loginTheme, branding.name, branding.tagline]);

  const allMailboxes = (mailboxes.data?.mailboxes as Mailbox[] | undefined) ?? [];
  const allDomains = (domains.data?.domains as Domain[] | undefined) ?? [];
  const allDistributionLists = (distributionLists.data?.distribution_lists as DistributionList[] | undefined) ?? [];

  useEffect(() => {
    if (!selectedDomainId && allDomains[0]) {
      setSelectedDomainId(allDomains[0].id);
    }
  }, [allDomains, selectedDomainId]);

  useEffect(() => {
    if (selectedMailboxId && allMailboxes.some((mailbox) => mailbox.id === selectedMailboxId)) {
      return;
    }
    if (allMailboxes[0]) {
      setSelectedMailboxId(allMailboxes[0].id);
    }
  }, [allMailboxes, selectedMailboxId]);

  useEffect(() => {
    if (dlSelectedEmail && allDistributionLists.some((item) => item.name === dlSelectedEmail)) {
      return;
    }
    if (allDistributionLists[0]) {
      setDlSelectedEmail(allDistributionLists[0].name);
    }
  }, [allDistributionLists, dlSelectedEmail]);

  const visibleMailboxes = useMemo(() => {
    const term = search.trim().toLowerCase();
    return allMailboxes.filter((mailbox) => {
      const quotaPercent = Number(mailbox.quota_percent ?? 0);
      const lastLoginDays = Number(mailbox.last_login_days ?? -1);
      const accountStatus = mailbox.account_status || mailbox.status || "";
      const statusLabel = formatMailboxAccountStatus(accountStatus);
      const matchesSearch =
        !term ||
        mailbox.email.toLowerCase().includes(term) ||
        (mailbox.display_name || "").toLowerCase().includes(term) ||
        (mailbox.local_part || "").toLowerCase().includes(term) ||
        accountStatus.toLowerCase().includes(term) ||
        statusLabel.toLowerCase().includes(term);
      if (!matchesSearch) return false;
      if (scope === "over_quota") return quotaPercent >= 90;
      if (scope === "inactive_6m") return lastLoginDays < 0 || lastLoginDays >= INACTIVE_ACCOUNT_DAYS;
      if (scope === "postmaster") return mailbox.role === "postmaster" || mailbox.is_postmaster;
      if (scope === "two_factor") return Boolean(mailbox.two_factor_enabled);
      return true;
    });
  }, [allMailboxes, scope, search]);

  const pageSizeOptions = [25, 50, 75, 100];
  const mailboxPageCount = Math.max(1, Math.ceil(visibleMailboxes.length / pageSize));
  const currentPage = Math.min(pageIndex, mailboxPageCount);
  const pagedMailboxes = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return visibleMailboxes.slice(start, start + pageSize);
  }, [currentPage, pageSize, visibleMailboxes]);

  const visibleDistributionLists = useMemo(() => {
    const term = dlSearch.trim().toLowerCase();
    return allDistributionLists.filter((list) => {
      if (!term) return true;
      return (
        list.name.toLowerCase().includes(term) ||
        (list.display_name || "").toLowerCase().includes(term) ||
        list.members.some((member) => member.toLowerCase().includes(term))
      );
    });
  }, [allDistributionLists, dlSearch]);

  const selectedDistributionList = useMemo(
    () => allDistributionLists.find((item) => item.name === dlSelectedEmail) || visibleDistributionLists[0] || null,
    [allDistributionLists, dlSelectedEmail, visibleDistributionLists],
  );
  const addMemberDistributionList = useMemo(() => allDistributionLists.find((item) => item.name === addMemberListEmail) || null, [allDistributionLists, addMemberListEmail]);
  const membersDistributionList = useMemo(() => allDistributionLists.find((item) => item.name === membersListEmail) || null, [allDistributionLists, membersListEmail]);
  const deleteDistributionListTarget = useMemo(() => allDistributionLists.find((item) => item.name === deleteDistributionListEmail) || null, [allDistributionLists, deleteDistributionListEmail]);
  const selectedDomain = useMemo(() => allDomains.find((domain) => domain.id === selectedDomainId) || allDomains[0] || null, [allDomains, selectedDomainId]);

  useEffect(() => {
    setNewPassword("");
    setConfirmPassword("");
  }, [selectedMailboxId]);

  useEffect(() => {
    if (!passwordModalMailboxId) {
      setNewPassword("");
      setConfirmPassword("");
    }
  }, [passwordModalMailboxId]);

  useEffect(() => {
    if (!selectedMailboxId && passwordModalMailboxId) {
      setPasswordModalMailboxId("");
    }
  }, [passwordModalMailboxId, selectedMailboxId]);

  useEffect(() => {
    setPageIndex(1);
  }, [pageSize, scope, search]);

  useEffect(() => {
    if (pageIndex > mailboxPageCount) {
      setPageIndex(mailboxPageCount);
    }
  }, [mailboxPageCount, pageIndex]);

  const summary = useMemo(() => {
    const quotaOver = allMailboxes.filter((mailbox) => Number(mailbox.quota_percent ?? 0) >= 90);
    const inactive = allMailboxes.filter((mailbox) => Number(mailbox.last_login_days ?? -1) < 0 || Number(mailbox.last_login_days ?? -1) >= INACTIVE_ACCOUNT_DAYS);
    const postmasters = allMailboxes.filter((mailbox) => mailbox.role === "postmaster" || mailbox.is_postmaster);
    const twoFactor = allMailboxes.filter((mailbox) => mailbox.two_factor_enabled);
    const closed = allMailboxes.filter((mailbox) => normalizeMailboxAccountStatus(mailbox.account_status || mailbox.status) === "closed");
    return {
      total: allMailboxes.length,
      quotaOver: quotaOver.length,
      inactive: inactive.length,
      postmasters: postmasters.length,
      twoFactor: twoFactor.length,
      closed: closed.length,
    };
  }, [allMailboxes]);

  const adminLogin = useMutation({
    mutationFn: (payload: { email: string; password: string }) => api.tenantAdminLogin(payload),
    onMutate: () => {
      setNotice("");
      setCreateDistributionListValidationError("");
      clearTenantAdminQueryCache();
    },
    onSuccess: async (data) => {
      if (data.two_factor_required && data.challenge_token) {
        setTwoFactorChallenge({ token: data.challenge_token, expiresIn: data.challenge_expires_in });
        setTwoFactorCode("");
        setNotice("");
        return;
      }
      applyAdminSession(data.admin_token, data.email);
      setAdminPassword("");
      setTwoFactorChallenge(null);
      setTwoFactorCode("");
      setNotice("Admin access granted");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-me", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-organization", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-domains", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-distribution-lists", data.admin_token, data.email] });
    },
  });

  const verifyAdminTwoFactor = useMutation({
    mutationFn: (payload: { challenge_token: string; code: string }) => api.tenantAdminLoginTwoFactor(payload),
    onMutate: () => {
      setNotice("");
      setCreateDistributionListValidationError("");
      clearTenantAdminQueryCache();
    },
    onSuccess: async (data) => {
      applyAdminSession(data.admin_token, data.email);
      setAdminPassword("");
      setTwoFactorChallenge(null);
      setTwoFactorCode("");
      setNotice("Admin access granted");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-me", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-organization", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-domains", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", data.admin_token] });
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-distribution-lists", data.admin_token, data.email] });
    },
  });

  const adminLogout = useMutation({
    mutationFn: () => api.logout(),
    onSettled: () => {
      setAdminToken("");
      setAdminEmail("");
      clearTenantAdminSession();
      setAdminPassword("");
      setTwoFactorChallenge(null);
      setTwoFactorCode("");
      setTenantAdminMailboxEmail("");
      setNotice("");
      setDlSelectedEmail("");
      setDlLocalPart("");
      setDlDisplayName("");
      setDlMemberEmail("");
      setAddMemberListEmail("");
      setMembersListEmail("");
      setCreateMailboxValidationError("");
      setCreateDistributionListValidationError("");
      adminLogin.reset();
      verifyAdminTwoFactor.reset();
      clearTenantAdminQueryCache();
    },
  });
  const uploadBrandLogo = useMutation({
    mutationFn: async (file: File) => api.tenantAdminUploadBrandLogo(adminToken, await optimizeBrandingUpload(file, "logo"), `${branding.name} logo`, brandDomain),
    onSuccess: async (data) => {
      setBrandLogoFile(null);
      setNotice("Brand logo updated");
      for (const domain of brandingCacheDomains) {
        queryClient.setQueryData(["app-branding", domain], data);
      }
      await queryClient.invalidateQueries({ queryKey: ["app-branding", brandDomain] });
    },
  });
  const uploadLoginBackground = useMutation({
    mutationFn: async (file: File) => api.tenantAdminUploadLoginBackground(adminToken, await optimizeBrandingUpload(file, "background"), brandDomain),
    onSuccess: async (data) => {
      setLoginBackgroundFile(null);
      for (const domain of brandingCacheDomains) queryClient.setQueryData(["app-branding", domain], data);
      await queryClient.invalidateQueries({ queryKey: ["app-branding", brandDomain] });
    },
  });
  const updateBranding = useMutation({
    mutationFn: (payload: { name: string; tagline: string; login_theme: string; login_landscape_only: boolean; login_design_mode?: "theme" | "custom"; login_template?: "panel-left" | "panel-right" | "centered" | "split"; login_background_color?: string; login_gradient_color?: string; login_brand_name_color?: string; login_tagline_color?: string; login_supporting_text_color?: string; login_box_transparency?: number }) => api.tenantAdminUpdateBranding(adminToken, { ...payload, domain: brandDomain }),
    onSuccess: async (data, payload) => {
      const nextBranding = {
        ...data.branding,
        name: payload.name,
        tagline: payload.tagline,
        login_theme: payload.login_theme,
        login_landscape_only: payload.login_landscape_only,
        login_design_mode: payload.login_design_mode,
        login_template: payload.login_template,
        login_background_color: payload.login_background_color,
        login_gradient_color: payload.login_gradient_color,
        login_brand_name_color: payload.login_brand_name_color,
        login_tagline_color: payload.login_tagline_color,
        login_supporting_text_color: payload.login_supporting_text_color,
        login_box_transparency: payload.login_box_transparency,
      };
      const nextData = { ...data, branding: nextBranding };
      setNotice("Branding updated");
      for (const domain of brandingCacheDomains) {
        queryClient.setQueryData(["app-branding", domain], (current: { branding?: typeof nextBranding } | undefined) => ({
          ...(current || {}),
          ...nextData,
          branding: {
            ...(current?.branding || {}),
            ...nextBranding,
          },
        }));
      }
      await queryClient.invalidateQueries({ queryKey: ["app-branding", brandDomain] });
    },
  });

  const createMailbox = useMutation({
    mutationFn: (payload: { domain_id: string; local_part: string; display_name?: string; quota_mb?: number; password: string }) =>
      api.tenantAdminCreateMailbox(adminToken, payload),
    onMutate: () => {
      setNotice("");
      setCreateMailboxValidationError("");
    },
    onSuccess: async (data) => {
      setNotice("Mailbox added");
      setLocalPart("");
      setDisplayName("");
      setQuotaMb(0);
      setCreateMailboxPassword("");
      setCreateMailboxConfirmPassword("");
      setCreateMailboxValidationError("");
      setCreateMailboxOpen(false);
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
      const created = data.mailbox;
      if (created?.id) {
        setSelectedMailboxId(created.id);
      }
    },
  });

  const deleteMailbox = useMutation({
    mutationFn: (mailboxId: string) => api.tenantAdminDeleteMailbox(adminToken, mailboxId),
    onSuccess: async () => {
      setNotice("Mailbox deleted");
      setSelectedMailboxId("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const updateMailboxPassword = useMutation({
    mutationFn: ({ mailboxId, password }: { mailboxId: string; password: string }) =>
      api.tenantAdminUpdateMailboxPassword(adminToken, mailboxId, { password }),
    onSuccess: async () => {
      setNotice("Password updated");
      setNewPassword("");
      setConfirmPassword("");
      setPasswordModalMailboxId("");
    },
  });

  const renameMailboxMutation = useMutation({
    mutationFn: ({ mailboxId, localPart }: { mailboxId: string; localPart: string }) =>
      api.tenantAdminRenameMailbox(adminToken, mailboxId, { local_part: localPart }),
    onSuccess: async (data) => {
      setNotice("Mailbox renamed");
      setRenameMailboxId("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
      if (data.mailbox?.id) setSelectedMailboxId(data.mailbox.id);
    },
  });

  const updateMailboxDisplayName = useMutation({
    mutationFn: ({ mailboxId, displayName }: { mailboxId: string; displayName: string }) =>
      api.tenantAdminUpdateMailbox(adminToken, mailboxId, { display_name: displayName }),
    onSuccess: async () => {
      setNotice("Display name updated");
      setDisplayNameMailboxId("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const updateMailboxStatus = useMutation({
    mutationFn: ({ mailboxId, status }: { mailboxId: string; status: MailboxAccountStatus }) =>
      api.tenantAdminUpdateMailbox(adminToken, mailboxId, { status }),
    onSuccess: async () => {
      setNotice("Account status updated");
      setStatusMailboxId("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const addMailboxAlias = useMutation({
    mutationFn: ({ mailboxId, alias }: { mailboxId: string; alias: string }) =>
      api.tenantAdminAddMailboxAlias(adminToken, mailboxId, { alias }),
    onSuccess: async () => {
      setNotice("Alias added");
      setAliasEmail("");
      setAliasMailboxId("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const removeMailboxAlias = useMutation({
    mutationFn: ({ mailboxId, alias }: { mailboxId: string; alias: string }) =>
      api.tenantAdminRemoveMailboxAlias(adminToken, mailboxId, alias),
    onSuccess: async () => {
      setNotice("Alias removed");
      setAliasMailboxId("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const updateMailboxForwarding = useMutation({
    mutationFn: ({ mailboxId, addresses, keepLocalCopy }: { mailboxId: string; addresses: string[]; keepLocalCopy: boolean }) =>
      api.tenantAdminUpdateMailboxForwarding(adminToken, mailboxId, { addresses, keep_local_copy: keepLocalCopy }),
    onSuccess: async () => {
      setNotice("Forwarding updated");
      setForwardMailboxId("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const disableMailboxTwoFactor = useMutation({
    mutationFn: (mailboxId: string) => api.tenantAdminDisableMailboxTwoFactor(adminToken, mailboxId),
    onSuccess: async () => {
      setNotice("2FA disabled for this mailbox");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const updateMailboxTwoFactorRequired = useMutation({
    mutationFn: ({ mailboxId, required }: { mailboxId: string; required: boolean }) =>
      api.tenantAdminUpdateMailboxTwoFactorRequired(adminToken, mailboxId, { required }),
    onSuccess: async (_data, variables) => {
      setNotice(variables.required ? "2FA required for this mailbox" : "2FA requirement removed");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const requestDisableMailboxTwoFactor = (mailbox: Mailbox) => {
    const confirmed = window.confirm(`Disable 2FA for ${mailbox.email}? Use this only when the user cannot access their authenticator app.`);
    if (!confirmed) return;
    setSelectedMailboxId(mailbox.id);
    disableMailboxTwoFactor.mutate(mailbox.id);
  };

  const updateMailboxRole = useMutation({
    mutationFn: ({ mailboxId, role }: { mailboxId: string; role: string }) =>
      api.tenantAdminUpdateMailboxRole(adminToken, mailboxId, { role }),
    onSuccess: async () => {
      setNotice("Role updated");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-mailboxes", adminToken] });
    },
  });

  const createDistributionList = useMutation({
    mutationFn: (payload: { domain_id: string; local_part: string; display_name?: string }) =>
      api.tenantAdminCreateDistributionList(adminToken, payload),
    onSuccess: async (data) => {
      setNotice("Distribution list added");
      setCreateDistributionListValidationError("");
      setDlLocalPart("");
      setDlDisplayName("");
      const created = data.distribution_list;
      if (created?.name) {
        setDlSelectedEmail(created.name);
        queryClient.setQueryData<{ distribution_lists: DistributionList[] }>(["tenant-admin-distribution-lists", adminToken, adminEmail], (current) => {
          const existing = current?.distribution_lists ?? [];
          const nextLists = [created, ...existing.filter((item) => item.name !== created.name)];
          nextLists.sort((left, right) => left.name.localeCompare(right.name));
          return { distribution_lists: nextLists };
        });
      }
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-distribution-lists", adminToken, adminEmail] });
      setCreateDistributionListOpen(false);
    },
  });

  const deleteDistributionList = useMutation({
    mutationFn: (email: string) => api.tenantAdminDeleteDistributionList(adminToken, email),
    onSuccess: async () => {
      setNotice("Distribution list deleted");
      setDlSelectedEmail("");
      setDeleteDistributionListEmail("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-distribution-lists", adminToken, adminEmail] });
    },
  });

  const addDistributionListMember = useMutation({
    mutationFn: ({ email, memberEmail }: { email: string; memberEmail: string }) =>
      api.tenantAdminAddDistributionListMember(adminToken, email, memberEmail),
    onSuccess: async (data) => {
      setNotice("Distribution list member added");
      setDlMemberEmail("");
      const updated = data.distribution_list;
      if (updated?.name) {
        setDlSelectedEmail(updated.name);
      }
      setAddMemberListEmail("");
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-distribution-lists", adminToken, adminEmail] });
    },
  });

  const removeDistributionListMember = useMutation({
    mutationFn: ({ email, memberEmail }: { email: string; memberEmail: string }) =>
      api.tenantAdminRemoveDistributionListMember(adminToken, email, memberEmail),
    onSuccess: async (data) => {
      setNotice("Distribution list member removed");
      const updated = data.distribution_list;
      if (updated?.name) {
        setDlSelectedEmail(updated.name);
      }
      await queryClient.invalidateQueries({ queryKey: ["tenant-admin-distribution-lists", adminToken, adminEmail] });
    },
  });

  useEffect(() => {
    setCreateDistributionListValidationError("");
    createDistributionList.reset();
    deleteDistributionList.reset();
    addDistributionListMember.reset();
    removeDistributionListMember.reset();
  }, [adminToken, adminEmail]);

  const mailboxError = mailboxes.error instanceof Error ? mailboxes.error.message : "";
  const authError = me.error instanceof Error ? me.error.message : "";
  const loginError = adminLogin.error instanceof Error ? adminLogin.error.message : "";
  const twoFactorError = verifyAdminTwoFactor.error instanceof Error ? verifyAdminTwoFactor.error.message : "";
  const passwordValidationError = newPassword ? validatePassword(newPassword) : "";
  const passwordMismatchError = confirmPassword && newPassword !== confirmPassword ? "Passwords do not match" : "";
  const passwordError = passwordValidationError || passwordMismatchError;
  const createMailboxPasswordValidationError = createMailboxPassword ? validatePassword(createMailboxPassword) : "";
  const createMailboxPasswordMismatchError = createMailboxConfirmPassword && createMailboxPassword !== createMailboxConfirmPassword ? "Passwords do not match" : "";
  const createMailboxPasswordError = createMailboxPasswordValidationError || createMailboxPasswordMismatchError;
  const selectedDomainName = selectedDomain?.domain_name || organization.data?.organization.primary_domain || "";
  const createMailboxLocalPartError = localPart ? validateEmailLocalPart(localPart) : "";
  const createMailboxEmail = selectedDomainName && localPart.trim() ? `${localPart.trim().toLowerCase()}@${selectedDomainName.trim().toLowerCase()}` : "";
  const createMailboxDuplicateError =
    createMailboxEmail && allMailboxes.some((mailbox) => mailbox.email.trim().toLowerCase() === createMailboxEmail)
      ? "This mailbox already exists."
      : "";
  const passwordModalMailboxes = allMailboxes.filter((mailbox) => mailbox.id === passwordModalMailboxId);
  const deleteModalMailboxes = allMailboxes.filter((mailbox) => mailbox.id === deleteModalMailboxId);
  const renameMailbox = allMailboxes.find((mailbox) => mailbox.id === renameMailboxId) || null;
  const displayNameMailbox = allMailboxes.find((mailbox) => mailbox.id === displayNameMailboxId) || null;
  const statusMailbox = allMailboxes.find((mailbox) => mailbox.id === statusMailboxId) || null;
  const aliasMailbox = allMailboxes.find((mailbox) => mailbox.id === aliasMailboxId) || null;
  const forwardMailbox = allMailboxes.find((mailbox) => mailbox.id === forwardMailboxId) || null;
  const mailboxDisplayNameError = mailboxDisplayNameDraft.trim() ? "" : "Display name is required.";
  const renameLocalPartError = renameLocalPart ? validateEmailLocalPart(renameLocalPart) : "";
  const renameSelfError =
    renameMailbox && renameLocalPart.trim().toLowerCase() === (renameMailbox.local_part || renameMailbox.email.split("@", 1)[0] || "").trim().toLowerCase()
      ? "New mailbox email must be different from the current email."
      : "";
  const aliasEmailError = aliasEmail ? validateEmailAddress(aliasEmail) : "";
  const aliasSelfError = aliasMailbox && aliasEmail.trim().toLowerCase() === aliasMailbox.email.trim().toLowerCase()
    ? "Alias cannot be the same as mailbox email."
    : "";
  const forwardAddresses = parseAddressList(forwardAddressesText);
  const forwardAddressError = forwardAddressesText.trim()
    ? forwardAddresses.find((address) => validateEmailAddress(address))
      ? "Enter valid forwarding email addresses."
      : ""
    : "";
  const forwardSelfError = forwardMailbox && forwardAddresses.includes(forwardMailbox.email.trim().toLowerCase())
    ? "A mailbox cannot forward mail to itself."
    : "";
  const forwardPermissionError = forwardMailbox && !forwardMailbox.forward_allowed && forwardAddresses.length
    ? "This mailbox does not have permission to use mail forwarding."
    : "";
  const dlCreateDomainId = selectedDomainId || allDomains[0]?.id || "";
  const distributionListError =
    distributionLists.error instanceof Error
      ? distributionLists.error.message
      : createDistributionListOpen && createDistributionList.error instanceof Error
        ? createDistributionList.error.message
        : deleteDistributionList.error instanceof Error
          ? deleteDistributionList.error.message
          : addDistributionListMember.error instanceof Error
            ? addDistributionListMember.error.message
            : removeDistributionListMember.error instanceof Error
              ? removeDistributionListMember.error.message
              : "";
  const canSavePassword = Boolean(passwordModalMailboxId && newPassword && confirmPassword && !passwordError && !updateMailboxPassword.isPending);
  const canCreateMailbox = !createMailbox.isPending;
  const adminHelpText = runtimeConfig.data?.admin_help_text?.trim() || siteConfig.adminHelpText;
  const brandEditorBusy = updateBranding.isPending || uploadBrandLogo.isPending;

  useEffect(() => {
    if (!renameMailbox) return;
    setRenameLocalPart(renameMailbox.local_part || renameMailbox.email.split("@", 1)[0] || "");
  }, [renameMailbox]);

  useEffect(() => {
    if (!displayNameMailbox) return;
    setMailboxDisplayNameDraft(displayNameMailbox.display_name || "");
  }, [displayNameMailbox]);

  useEffect(() => {
    if (!statusMailbox) return;
    const status = normalizeMailboxAccountStatus(statusMailbox.account_status || statusMailbox.status || "active");
    setMailboxStatusDraft(status);
  }, [statusMailbox]);

  useEffect(() => {
    if (!aliasMailbox) return;
    setAliasEmail("");
  }, [aliasMailbox]);

  useEffect(() => {
    if (!forwardMailbox) return;
    setForwardAddressesText((forwardMailbox.forward_addresses || []).join(", "));
    setForwardKeepLocalCopy(forwardMailbox.forward_keep_local_copy ?? true);
  }, [forwardMailbox]);

  function openBrandEditor() {
    setBrandNameDraft(branding.name || "");
    setBrandTaglineDraft(branding.tagline || "");
    setBrandLogoFile(null);
    setBrandEditorOpen(true);
  }

  async function saveBrandEditor() {
    const nextName = brandNameDraft.trim();
    const nextTagline = brandTaglineDraft.trim();
    if (!nextName || brandEditorBusy) return;
    const brandingChanged =
      nextName !== (branding.name || "") ||
      nextTagline !== (branding.tagline || "");
    try {
      if (brandingChanged) {
        await updateBranding.mutateAsync({ name: nextName, tagline: nextTagline, login_theme: loginDesignerDraft.theme, login_landscape_only: loginDesignerDraft.landscapeOnly, login_design_mode: loginDesignerDraft.mode, login_template: loginDesignerDraft.template, login_background_color: loginDesignerDraft.backgroundColor, login_gradient_color: loginDesignerDraft.gradientColor, login_brand_name_color: loginDesignerDraft.brandNameColor, login_tagline_color: loginDesignerDraft.taglineColor, login_supporting_text_color: loginDesignerDraft.supportingTextColor, login_box_transparency: loginDesignerDraft.boxTransparency });
      }
      if (brandLogoFile) {
        await uploadBrandLogo.mutateAsync(brandLogoFile);
      }
      setBrandEditorOpen(false);
    } catch {
      // Mutation errors are rendered inside the modal.
    }
  }

  async function saveLoginDesigner() {
    if (updateBranding.isPending || uploadLoginBackground.isPending) return;
    try {
      await updateBranding.mutateAsync({ name: branding.name, tagline: branding.tagline, login_theme: loginDesignerDraft.theme, login_landscape_only: loginDesignerDraft.landscapeOnly, login_design_mode: loginDesignerDraft.mode, login_template: loginDesignerDraft.template, login_background_color: loginDesignerDraft.backgroundColor, login_gradient_color: loginDesignerDraft.gradientColor, login_brand_name_color: loginDesignerDraft.brandNameColor, login_tagline_color: loginDesignerDraft.taglineColor, login_supporting_text_color: loginDesignerDraft.supportingTextColor, login_box_transparency: loginDesignerDraft.boxTransparency });
      if (loginBackgroundFile) await uploadLoginBackground.mutateAsync(loginBackgroundFile);
      setNotice("Login design updated");
    } catch {
      // Mutation errors are shown in the designer.
    }
  }

  if (!isSignedIn) {
    if (!sessionChecked) {
      return (
        <main className="grid min-h-screen place-items-center bg-[#eef3f8] px-4 py-8" style={{ "--accent": "#2d49c8" } as CSSProperties}>
          <div className="rounded-xl border border-slate-200 bg-white px-5 py-4 text-sm font-black text-slate-600 shadow-soft">
            Loading admin workspace...
          </div>
        </main>
      );
    }

    return (
      <main className="relative min-h-[100dvh] overflow-x-hidden bg-[#eaf2fb] px-3 py-3 sm:px-5 sm:py-5 lg:grid lg:place-items-center lg:px-8 lg:py-7" style={{ "--accent": "#2d49c8" } as CSSProperties}>
        <section className="relative mx-auto w-full max-w-[1080px] overflow-hidden rounded-xl bg-[#dcecff] shadow-[18px_18px_0_rgba(22,32,58,0.82)] lg:min-h-[min(634px,calc(100dvh-3.5rem))]">
          <div
            aria-hidden="true"
            className="absolute inset-0 bg-no-repeat"
            style={{ backgroundImage: "url('/admin-login-workspace.webp')", backgroundPosition: "right bottom", backgroundSize: "92% auto" }}
          />
          <div className="relative z-10 grid min-h-[calc(100dvh-1.5rem)] content-start gap-5 px-5 py-7 sm:min-h-[calc(100dvh-2.5rem)] sm:px-10 sm:py-8 lg:min-h-[min(634px,calc(100dvh-3.5rem))] lg:grid-cols-[318px_minmax(0,1fr)] lg:content-normal lg:items-center lg:gap-[78px] lg:px-16 lg:py-12">
            <form
              onSubmit={(event: FormEvent<HTMLFormElement>) => {
                event.preventDefault();
                if (twoFactorChallenge) {
                  verifyAdminTwoFactor.mutate({ challenge_token: twoFactorChallenge.token, code: twoFactorCode });
                  return;
                }
                if (adminLogin.isPending) {
                  return;
                }
                const email = adminEmail.trim();
                if (!email || !adminPassword) {
                  setNotice("Enter both email and password.");
                  return;
                }
                setNotice("");
                adminLogin.mutate({ email, password: adminPassword });
              }}
              className="order-2 grid w-full max-w-[318px] justify-self-center gap-4 rounded-[42px] bg-white px-7 py-6 shadow-[0_12px_26px_rgba(22,32,58,0.22)] sm:px-8 sm:py-7 lg:order-1 lg:justify-self-start lg:gap-5 lg:py-8"
            >
              <div className="grid justify-items-center gap-3 text-center">
                <div className="grid h-[88px] w-[88px] place-items-center rounded-full bg-[#eef5ff] p-3 sm:h-[96px] sm:w-[96px] lg:h-[112px] lg:w-[112px] lg:p-4">
                  <BrandLogo size="lg" centered brandDomain={brandDomain} className="[&>div:first-child]:!h-full [&>div:first-child]:!w-full" />
                </div>
                <div className="grid gap-1">
                  <span className="mx-auto w-fit rounded-full bg-cyan-50 px-3 py-1 text-xs font-black uppercase tracking-[0.18em] text-cyan-700">
                  Domain Level
                  </span>
                  <h2 className="text-xl font-black leading-tight text-slate-950">{twoFactorChallenge ? "Two-factor check" : "Admin sign in"}</h2>
                  <p className="text-xs leading-5 text-slate-600">
                  {twoFactorChallenge ? "Enter your code." : "Use your postmaster mailbox."}
                  </p>
                </div>
              </div>

              {!twoFactorChallenge ? (
                <div className="grid gap-3">
                  <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
                    Email
                    <input value={adminEmail} onChange={(event) => setAdminEmail(event.target.value)} className="field h-11 px-3" placeholder="postmaster@example.com" required />
                  </label>
                  <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
                    Password
                    <input value={adminPassword} onChange={(event) => setAdminPassword(event.target.value)} type="password" className="field h-11 px-3" placeholder="Password" required />
                  </label>
                </div>
              ) : (
                <div className="grid gap-3 rounded-lg border border-slate-200 bg-slate-50 p-4">
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5 rounded-full bg-white p-2 text-emerald-700 shadow-sm">
                      <ShieldCheck size={16} />
                    </div>
                    <div>
                      <strong className="block text-sm font-black text-slate-900">Two-factor code</strong>
                      <p className="mt-1 text-sm leading-6 text-slate-500">This postmaster mailbox requires an extra verification step before admin access is granted.</p>
                    </div>
                  </div>
                  <label className="grid gap-2 text-sm font-semibold text-slate-700">
                    Code
                    <input
                      autoFocus
                      className="field h-12 px-4 tracking-[0.24em]"
                      inputMode="numeric"
                      autoComplete="one-time-code"
                      value={twoFactorCode}
                      onChange={(event) => setTwoFactorCode(event.target.value.replace(/\D/g, "").slice(0, 10))}
                      placeholder="123456"
                      required
                    />
                  </label>
                </div>
              )}

              {loginError ? <p className="rounded-lg border border-rose-100 bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">{loginError}</p> : null}
              {twoFactorError ? <p className="rounded-lg border border-rose-100 bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">{twoFactorError}</p> : null}
              {notice && !loginError && !twoFactorError ? <p className="rounded-lg border border-emerald-100 bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">{notice}</p> : null}

              <div className="grid gap-3">
                <button className="theme-button h-11 w-full" disabled={adminLogin.isPending || verifyAdminTwoFactor.isPending}>
                  {twoFactorChallenge ? (verifyAdminTwoFactor.isPending ? "Verifying..." : "Sign in") : adminLogin.isPending ? "Signing in..." : "Open console"}
                </button>
                {twoFactorChallenge ? (
                  <button
                    type="button"
                    onClick={() => {
                      setTwoFactorChallenge(null);
                      setTwoFactorCode("");
                    }}
                    className="theme-button-soft h-11 w-full"
                  >
                    Back
                  </button>
                ) : null}
              </div>
            </form>

            <aside className="order-1 grid content-start gap-3 lg:order-2 lg:self-start lg:gap-4 lg:pt-6">
              <div className="mx-auto w-full max-w-[475px] text-center lg:mx-0 lg:text-left">
                <h1 className="text-balance text-3xl font-black leading-[1.04] text-[#16203a] sm:text-4xl lg:whitespace-nowrap lg:text-[2.65rem]">Admin access.</h1>
                <p className="mt-3 max-w-[39rem] text-sm font-medium leading-6 text-[#203f92] sm:text-base lg:mt-4">Manage mailboxes and distribution lists.</p>
                <p className="mt-2 max-w-[36rem] text-sm leading-5 text-[#365fa3]">{branding.name}{branding.tagline ? ` - ${branding.tagline}` : ""}</p>
              </div>
              <div className="mx-auto inline-flex w-fit items-center gap-2 rounded-full bg-white px-3.5 py-2 text-xs font-black text-[#2440be] shadow-[0_3px_10px_rgba(22,32,58,0.16)] lg:mx-0">
                <span className="h-2 w-2 rounded-full bg-[#2d49c8]" />
                Admin workspace
              </div>
            </aside>
          </div>
        </section>
      </main>
    );
  }

  return (
    <main className="min-h-[100dvh] bg-[#eef3f8] xl:h-[100dvh] xl:overflow-hidden" style={{ "--accent": "#1d6fd8" } as CSSProperties}>
      <div className="grid min-h-[100dvh] grid-cols-1 xl:h-full xl:min-h-0 xl:grid-cols-[300px_minmax(0,1fr)] xl:overflow-hidden">
        {adminSidebarOpen ? (
          <button
            type="button"
            aria-label="Close admin menu"
            className="fixed inset-0 z-[70] bg-slate-950/35 backdrop-blur-[1px] xl:hidden"
            onClick={() => setAdminSidebarOpen(false)}
          />
        ) : null}
        <aside
          className={`fixed inset-y-0 left-0 z-[80] min-h-0 w-[300px] max-w-[86vw] transform overflow-auto bg-[linear-gradient(180deg,#2750f0_0%,#2748dd_52%,#2139ba_100%)] px-4 py-4 text-white shadow-xl transition-transform duration-200 ease-out sm:px-5 xl:static xl:z-auto xl:w-auto xl:max-w-none xl:translate-x-0 xl:px-6 xl:py-5 ${
            adminSidebarOpen ? "translate-x-0" : "-translate-x-full"
          }`}
        >
          <div className="mb-4 grid gap-3 xl:mb-8 xl:block">
            <button
              type="button"
              onClick={openBrandEditor}
              className="w-full rounded-xl bg-transparent p-0 text-left transition focus:outline-none focus:ring-2 focus:ring-white/55"
              aria-label="Edit brand logo, name, and tagline"
              title="Edit brand logo, name, and tagline"
            >
              <BrandLogo size="sm" subtitle={branding.tagline || siteConfig.adminSubtitle} dark brandDomain={brandDomain} />
            </button>
            <div className="rounded-xl bg-white/8 p-3 ring-1 ring-white/14 backdrop-blur-sm xl:mt-6 xl:rounded-2xl xl:p-4">
              <div className="flex items-center gap-3">
                <div className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-white/20 text-base font-black xl:h-12 xl:w-12 xl:text-lg">{(adminEmail || "P").slice(0, 1).toUpperCase()}</div>
                <div className="min-w-0">
                  <p className="truncate text-base font-black">{adminEmail || "Postmaster"}</p>
                  <p className="truncate text-sm text-white/72">{selectedDomain?.domain_name || organization.data?.organization.primary_domain || siteConfig.adminSubtitle}</p>
                </div>
              </div>
            </div>
          </div>

          <div className="mb-6">
            <p className="text-sm font-black uppercase tracking-[0.16em] text-white/62">Main menu</p>
            <div className="mt-3 grid gap-2 xl:grid-cols-1">
              <SidebarNavItem
                active={activeView === "accounts"}
                label={isMailMaliAdmin ? "Mailboxes" : "Accounts"}
                meta={`${summary.total}`}
                onClick={() => {
                  setActiveView("accounts");
                  setAdminSidebarOpen(false);
                }}
              />
              <SidebarNavItem
                active={activeView === "distribution_lists"}
                label="Distribution lists"
                meta={`${allDistributionLists.length}`}
                onClick={() => {
                  setActiveView("distribution_lists");
                  setAdminSidebarOpen(false);
                }}
              />
              <SidebarNavItem
                active={activeView === "login_designer"}
                label={isMailMaliAdmin ? "Login page design" : "Login Designer"}
                onClick={() => {
                  setActiveView("login_designer");
                  setAdminSidebarOpen(false);
                }}
              />
              <SidebarNavItem
                active={activeView === "information"}
                label={isMailMaliAdmin ? "Subscription & Billing" : "Product Information"}
                onClick={() => {
                  setActiveView("information");
                  setAdminSidebarOpen(false);
                }}
              />
            </div>
            <div className="mt-4 border-t border-white/18 pt-4">
              <button
                type="button"
                onClick={() => {
                  setAdminSidebarOpen(false);
                  adminLogout.mutate();
                }}
                className="flex w-full items-center justify-center gap-2 rounded-xl bg-white/10 px-4 py-3 text-sm font-bold text-white ring-1 ring-white/14 transition hover:bg-white/16"
              >
                <LogOut size={15} />
                Logout
              </button>
            </div>
          </div>
        </aside>

        <section className="grid min-h-[70dvh] min-w-0 grid-rows-[auto_1fr] border-r border-slate-200/80 bg-[#f5f7fb] xl:min-h-0 xl:overflow-hidden">
          <header className="border-b border-slate-200 bg-white px-3 py-3 shadow-[0_1px_0_rgba(23,32,51,0.04)] sm:px-5">
            <div className="flex flex-col gap-3">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <div className="flex min-w-0 flex-1 flex-wrap items-center gap-3 lg:gap-6">
                  <button
                    type="button"
                    onClick={() => setAdminSidebarOpen(true)}
                    className="icon-button h-10 w-10 xl:hidden"
                    aria-label="Open admin menu"
                  >
                    <Menu size={18} />
                  </button>
                  <p className="whitespace-nowrap text-base font-black text-slate-900">{adminHelpText}</p>
                  {activeView !== "information" && activeView !== "login_designer" ? (
                    <div className="relative min-w-0 flex-1 basis-full sm:basis-[360px] lg:min-w-[360px] xl:min-w-[560px]">
                      <Search className="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={17} />
                      <input
                        value={activeView === "accounts" ? search : dlSearch}
                        onChange={(event) => (activeView === "accounts" ? setSearch(event.target.value) : setDlSearch(event.target.value))}
                        className="field h-11 w-full rounded-none border-slate-200 pl-11"
                        placeholder={activeView === "accounts" ? "Search Account" : "Search distribution lists"}
                      />
                    </div>
                  ) : null}
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  <AlertIcon
                    icon={<Bell size={16} />}
                    count={summary.quotaOver || 0}
                    tone="warning"
                    labelText="> 90%"
                    label={`${summary.quotaOver || 0} account${summary.quotaOver === 1 ? "" : "s"} over 90% quota`}
                    tooltipTitle="Quota warning"
                    tooltipText={`${summary.quotaOver || 0} mailbox${summary.quotaOver === 1 ? "" : "es"} are using 90% or more of their quota.`}
                  />
                  <AlertIcon
                    icon={<Mail size={16} />}
                    count={summary.inactive || 0}
                    tone="info"
                    labelText="Inactive"
                    label={`${summary.inactive || 0} inactive account${summary.inactive === 1 ? "" : "s"}`}
                    tooltipTitle="Inactive accounts"
                    tooltipText={`${summary.inactive || 0} mailbox${summary.inactive === 1 ? "" : "es"} have never logged in or have been inactive for ${INACTIVE_ACCOUNT_DAYS} days.`}
                  />
                  <AlertIcon
                    icon={<UserRoundPlus size={16} />}
                    count={summary.postmasters || 0}
                    tone="success"
                    labelText="Postmaster"
                    label={`${summary.postmasters || 0} postmaster account${summary.postmasters === 1 ? "" : "s"}`}
                    tooltipTitle="Postmasters"
                    tooltipText={`${summary.postmasters || 0} mailbox${summary.postmasters === 1 ? "" : "es"} can administer this domain.`}
                  />
                  <AlertIcon
                    icon={<CircleCheckBig size={16} />}
                    count={summary.twoFactor || 0}
                    tone="secure"
                    labelText="2FA"
                    label={`${summary.twoFactor || 0} account${summary.twoFactor === 1 ? "" : "s"} with 2FA enabled`}
                    tooltipTitle="Two-factor authentication"
                    tooltipText={`${summary.twoFactor || 0} mailbox${summary.twoFactor === 1 ? "" : "es"} have two-factor authentication enabled.`}
                  />
                  {summary.closed ? (
                    <AlertIcon
                      icon={<X size={16} />}
                      count={summary.closed}
                      tone="danger"
                      labelText="Closed"
                      label={`${summary.closed} closed account${summary.closed === 1 ? "" : "s"}`}
                      tooltipTitle="Closed accounts"
                      tooltipText={`${summary.closed} mailbox${summary.closed === 1 ? "" : "es"} are closed and excluded from ${isMailMaliAdmin ? "mailbox seat" : "mailbox license"} count.`}
                    />
                  ) : null}
                </div>
              </div>
              {activeView === "login_designer" ? (
                <div className="flex items-center gap-3 py-1"><Palette size={19} className="text-[var(--accent)]" /><p className="text-lg font-black text-slate-950">{isMailMaliAdmin ? "Login page design" : "Login Designer"}</p></div>
              ) : activeView === "information" ? (
                <div className="flex flex-col gap-3 rounded-2xl border border-slate-200 bg-[#f8fafc] px-4 py-4">
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="text-xl font-black text-slate-950 sm:text-2xl">{isMailMaliAdmin ? "Subscription & Billing" : "Product Information"}</p>
                      <p className="mt-1 text-sm font-medium text-slate-600 sm:text-lg">
                        {isMailMaliAdmin ? "Service plan, mailbox seats, renewal, payment, and support details." : "Product, support, and current installation details."}
                      </p>
                    </div>
                    <div className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-500">
                      {isMailMaliAdmin ? "Service" : "Product"} <span className="font-black text-slate-950">{isMailMaliAdmin ? "Mail Mali" : "Zimphony Webmail"}</span>
                    </div>
                  </div>
                </div>
              ) : activeView === "accounts" ? (
                <>
                  <div className="flex flex-col gap-3 rounded-2xl border border-slate-200 bg-[#f8fafc] px-4 py-4">
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="text-xl font-black text-slate-950 sm:text-2xl">{isMailMaliAdmin ? "Mailbox(es)" : "Email Account(s)"} {visibleMailboxes.length}</p>
                        <p className="mt-1 truncate text-sm font-medium text-slate-600 sm:text-lg">Domain {selectedDomain?.domain_name || organization.data?.organization.primary_domain || "—"}</p>
                      </div>
                    </div>
                    <div className="flex flex-wrap items-center justify-end gap-3">
                      <div className="flex flex-wrap items-center gap-2">
                        <div className="flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-600">
                          <span>Rows</span>
                          <select
                            value={pageSize}
                            onChange={(event) => setPageSize(Number(event.target.value))}
                            className="min-w-[5rem] bg-transparent text-sm font-black text-slate-900 outline-none"
                            aria-label="Rows per page"
                          >
                            {pageSizeOptions.map((option) => (
                              <option key={option} value={option}>
                                {option}
                              </option>
                            ))}
                          </select>
                        </div>
                        <button
                          type="button"
                          onClick={() => {
                            setCreateMailboxValidationError("");
                            createMailbox.reset();
                            setCreateMailboxOpen(true);
                          }}
                          className="theme-button h-10 px-4 text-sm"
                        >
                          <MailPlus size={15} />
                          Add mailbox
                        </button>
                      </div>
                    </div>
                  </div>
                </>
              ) : (
                <div className="flex flex-col gap-3 rounded-2xl border border-slate-200 bg-[#f8fafc] px-4 py-4">
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="text-xl font-black text-slate-950 sm:text-2xl">Distribution list(s) {visibleDistributionLists.length}</p>
                      <p className="mt-1 truncate text-sm font-medium text-slate-600 sm:text-lg">Manage lists for {selectedDomain?.domain_name || organization.data?.organization.primary_domain || "—"}</p>
                    </div>
                    <div className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-500">
                      Selected <span className="font-black text-slate-950">{selectedDistributionList ? 1 : 0}</span> list
                    </div>
                  </div>
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div className="rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-600">
                      Create, delete, and member changes are applied directly to distribution lists.
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        setDlSelectedEmail("");
                        setDlLocalPart("");
                        setDlDisplayName("");
                        setCreateDistributionListValidationError("");
                        createDistributionList.reset();
                        setCreateDistributionListOpen(true);
                      }}
                      className="theme-button h-10 px-4 text-sm"
                    >
                      <MailPlus size={15} />
                      Add distribution list
                    </button>
                  </div>
                </div>
              )}
            </div>
          </header>

          <div className="min-h-0 overflow-auto px-3 py-3 sm:px-4 sm:py-4">
            {!isMailMaliAdmin && runtimeConfig.data?.license?.hard_block ? <InlineNotice tone="error">{runtimeConfig.data.license.message || "Product activation is required."}</InlineNotice> : null}
            {!isMailMaliAdmin && !runtimeConfig.data?.license?.hard_block && runtimeConfig.data?.license?.admin_warning ? <InlineNotice tone="warning">{runtimeConfig.data.license.message || "License status requires administrator attention."}</InlineNotice> : null}
            {notice ? <InlineNotice tone="info">{notice}</InlineNotice> : null}
            {authError ? <InlineNotice tone="error">{authError}</InlineNotice> : null}
            {mailboxError ? <InlineNotice tone="error">{mailboxError}</InlineNotice> : null}
            {distributionListError ? <InlineNotice tone="error">{distributionListError}</InlineNotice> : null}
            {activeView === "login_designer" ? (
              <LoginDesigner
                draft={loginDesignerDraft}
                backgroundUrl={branding.loginBackgroundUrl}
                selectedFileName={loginBackgroundFile?.name || ""}
                busy={updateBranding.isPending || uploadLoginBackground.isPending}
                error={(updateBranding.error instanceof Error ? updateBranding.error.message : "") || (uploadLoginBackground.error instanceof Error ? uploadLoginBackground.error.message : "")}
                onChange={setLoginDesignerDraft}
                onFileChange={setLoginBackgroundFile}
                onSave={() => void saveLoginDesigner()}
              />
            ) : activeView === "information" ? (
              <AdminProductInfoPanel
                variant={variant}
                product={runtimeConfig.data?.product}
                organizationName={organization.data?.organization.name || ""}
                primaryDomain={organization.data?.organization.primary_domain || selectedDomain?.domain_name || ""}
                selectedDomainName={selectedDomain?.domain_name || ""}
                adminEmail={adminEmail}
                mailboxCount={allMailboxes.length}
                distributionListCount={allDistributionLists.length}
                nativeConfigured={Boolean(runtimeConfig.data?.native_zimbra_configured)}
                calendarConfigured={Boolean(runtimeConfig.data?.calendar_configured)}
                driveConfigured={Boolean(runtimeConfig.data?.drive_configured)}
                imapsyncConfigured={Boolean(runtimeConfig.data?.imapsync_configured)}
                billingConfigured={Boolean(runtimeConfig.data?.billing_configured)}
                license={runtimeConfig.data?.license}
              />
            ) : activeView === "accounts" ? (
              <div className="min-h-[360px] overflow-x-auto rounded-2xl border border-slate-200 bg-white shadow-soft">
                <div className="min-w-[1280px]">
                  <div className="grid grid-cols-[52px_minmax(220px,1.55fr)_minmax(180px,1.1fr)_140px_130px_140px_120px_130px] items-center gap-4 border-b border-slate-200 bg-slate-50 px-4 py-3 text-sm font-black text-slate-700">
                    <span className="flex items-center justify-center" title="Postmaster">
                      <UserRoundPlus size={15} />
                    </span>
                    <span>Email</span>
                    <span>Name</span>
                    <span>Quota</span>
                    <span>2FA Enabled</span>
                    <span>Last login</span>
                    <span>Status</span>
                    <span className="text-right">Actions</span>
                  </div>
                  <div className="grid gap-0">
                    {pagedMailboxes.map((mailbox) => (
                      <MailboxRow
                        key={mailbox.id}
                        mailbox={mailbox}
                        selected={mailbox.id === selectedMailboxId}
                        busy={updateMailboxRole.isPending || updateMailboxTwoFactorRequired.isPending}
                        isLastPostmaster={summary.postmasters <= 1 && isMailboxPostmaster(mailbox)}
                        menuOpen={mailboxActionMenuId === mailbox.id}
                        onSelect={() => setSelectedMailboxId(mailbox.id)}
                        onToggleMenu={() => setMailboxActionMenuId((current) => current === mailbox.id ? "" : mailbox.id)}
                        onCloseMenu={() => setMailboxActionMenuId("")}
                        onRename={() => {
                          setSelectedMailboxId(mailbox.id);
                          renameMailboxMutation.reset();
                          setRenameMailboxId(mailbox.id);
                          setMailboxActionMenuId("");
                        }}
                        onEditDisplayName={() => {
                          setSelectedMailboxId(mailbox.id);
                          updateMailboxDisplayName.reset();
                          setDisplayNameMailboxId(mailbox.id);
                          setMailboxActionMenuId("");
                        }}
                        onStatus={() => {
                          setSelectedMailboxId(mailbox.id);
                          updateMailboxStatus.reset();
                          setStatusMailboxId(mailbox.id);
                          setMailboxActionMenuId("");
                        }}
                        onAlias={() => {
                          setSelectedMailboxId(mailbox.id);
                          addMailboxAlias.reset();
                          removeMailboxAlias.reset();
                          setAliasMailboxId(mailbox.id);
                          setMailboxActionMenuId("");
                        }}
                        onForward={() => {
                          setSelectedMailboxId(mailbox.id);
                          updateMailboxForwarding.reset();
                          setForwardMailboxId(mailbox.id);
                          setMailboxActionMenuId("");
                        }}
                        onReset={() => {
                          setSelectedMailboxId(mailbox.id);
                          setPasswordModalMailboxId(mailbox.id);
                          setMailboxActionMenuId("");
                        }}
                        onDisableTwoFactor={() => requestDisableMailboxTwoFactor(mailbox)}
                        onToggleTwoFactorRequired={() => {
                          setSelectedMailboxId(mailbox.id);
                          updateMailboxTwoFactorRequired.mutate({ mailboxId: mailbox.id, required: !mailbox.two_factor_required });
                        }}
                        onTogglePostmaster={() => {
                          const nextIsPostmaster = !isMailboxPostmaster(mailbox);
                          if (!nextIsPostmaster && summary.postmasters <= 1) {
                            setNotice("At least one postmaster must remain assigned.");
                            return;
                          }
                          updateMailboxRole.mutate({ mailboxId: mailbox.id, role: nextIsPostmaster ? "postmaster" : "mailbox" });
                        }}
                        onDelete={() => {
                          setDeleteModalMailboxId(mailbox.id);
                          setMailboxActionMenuId("");
                        }}
                      />
                    ))}
                    {!visibleMailboxes.length ? (
                      <div className="rounded-xl border border-dashed border-slate-300 bg-slate-50 px-4 py-10 text-center text-sm font-semibold text-slate-500">
                        No accounts match the current search or filter.
                      </div>
                    ) : null}
                    {visibleMailboxes.length ? (
                      <div className="flex flex-wrap items-center justify-between gap-3 border-t border-slate-200 bg-slate-50 px-4 py-3 text-sm font-semibold text-slate-600">
                        <p>
                          Showing {Math.min((currentPage - 1) * pageSize + 1, visibleMailboxes.length)}-
                          {Math.min(currentPage * pageSize, visibleMailboxes.length)} of {visibleMailboxes.length}
                        </p>
                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            onClick={() => setPageIndex((value) => Math.max(1, value - 1))}
                            className="theme-button-soft h-9 px-3 text-xs disabled:opacity-50"
                            disabled={currentPage <= 1}
                          >
                            Prev
                          </button>
                          <span className="rounded-full border border-slate-200 bg-white px-3 py-1 text-xs font-black uppercase tracking-[0.12em] text-slate-500">
                            Page {currentPage} of {mailboxPageCount}
                          </span>
                          <button
                            type="button"
                            onClick={() => setPageIndex((value) => Math.min(mailboxPageCount, value + 1))}
                            className="theme-button-soft h-9 px-3 text-xs disabled:opacity-50"
                            disabled={currentPage >= mailboxPageCount}
                          >
                            Next
                          </button>
                        </div>
                      </div>
                    ) : null}
                  </div>
                </div>
              </div>
            ) : (
              <div className="overflow-x-auto rounded-2xl border border-slate-200 bg-white shadow-soft">
                <div className="min-w-[940px]">
                  <div className="grid grid-cols-[minmax(260px,1.55fr)_minmax(160px,0.9fr)_110px_330px] items-center gap-4 border-b border-slate-200 bg-slate-50 px-4 py-3 text-sm font-black text-slate-700">
                    <span>Email</span>
                    <span>Name</span>
                    <span>Members</span>
                    <span className="text-right">Actions</span>
                  </div>
                  <div className="grid gap-0">
                    {visibleDistributionLists.map((list) => (
                      <DistributionListRow
                        key={list.name}
                        distributionList={list}
                        selected={list.name === dlSelectedEmail}
                        onSelect={() => {
                          setDlSelectedEmail(list.name);
                        }}
                        onAddMember={() => {
                          setDlSelectedEmail(list.name);
                          setDlMemberEmail("");
                          setAddMemberListEmail(list.name);
                        }}
                        onShowMembers={() => {
                          setDlSelectedEmail(list.name);
                          setMembersListEmail(list.name);
                        }}
                        onDelete={() => {
                          setDlSelectedEmail(list.name);
                          setDeleteDistributionListEmail(list.name);
                        }}
                      />
                    ))}
                    {!visibleDistributionLists.length ? (
                      <div className="rounded-xl border border-dashed border-slate-300 bg-slate-50 px-4 py-10 text-center text-sm font-semibold text-slate-500">
                        No distribution lists match the current search.
                      </div>
                    ) : null}
                  </div>
                </div>
              </div>
            )}
          </div>
        </section>

      </div>
      {passwordModalMailboxId ? (
        <PasswordDialog
          mailboxes={passwordModalMailboxes}
          password={newPassword}
          confirmPassword={confirmPassword}
          error={passwordError}
          busy={updateMailboxPassword.isPending}
          canSubmit={canSavePassword}
          onPasswordChange={setNewPassword}
          onConfirmPasswordChange={setConfirmPassword}
          onClose={() => setPasswordModalMailboxId("")}
          onSubmit={() => {
            const mailboxId = passwordModalMailboxId;
            if (!mailboxId) return;
            updateMailboxPassword.mutate(
              { mailboxId, password: newPassword },
              { onSuccess: () => setPasswordModalMailboxId("") },
            );
          }}
        />
      ) : null}
      {renameMailbox ? (
        <MailboxRenameDialog
          mailbox={renameMailbox}
          localPart={renameLocalPart}
          error={renameLocalPartError || renameSelfError || (renameMailboxMutation.error instanceof Error ? renameMailboxMutation.error.message : "")}
          busy={renameMailboxMutation.isPending}
          canSubmit={!!renameLocalPart.trim() && !renameLocalPartError && !renameSelfError}
          onLocalPartChange={(value) => {
            renameMailboxMutation.reset();
            setRenameLocalPart(value);
          }}
          onClose={() => setRenameMailboxId("")}
          onSubmit={() => {
            if (renameLocalPartError || renameSelfError || !renameLocalPart.trim()) return;
            renameMailboxMutation.mutate({ mailboxId: renameMailbox.id, localPart: renameLocalPart.trim().toLowerCase() });
          }}
        />
      ) : null}
      {displayNameMailbox ? (
        <MailboxDisplayNameDialog
          mailbox={displayNameMailbox}
          displayName={mailboxDisplayNameDraft}
          error={mailboxDisplayNameError || (updateMailboxDisplayName.error instanceof Error ? updateMailboxDisplayName.error.message : "")}
          busy={updateMailboxDisplayName.isPending}
          onDisplayNameChange={setMailboxDisplayNameDraft}
          onClose={() => setDisplayNameMailboxId("")}
          onSubmit={() => {
            if (mailboxDisplayNameError) return;
            updateMailboxDisplayName.mutate({ mailboxId: displayNameMailbox.id, displayName: mailboxDisplayNameDraft.trim() });
          }}
        />
      ) : null}
      {statusMailbox ? (
        <MailboxStatusDialog
          mailbox={statusMailbox}
          status={mailboxStatusDraft}
          error={updateMailboxStatus.error instanceof Error ? updateMailboxStatus.error.message : ""}
          busy={updateMailboxStatus.isPending}
          onStatusChange={setMailboxStatusDraft}
          onClose={() => setStatusMailboxId("")}
          onSubmit={() => {
            updateMailboxStatus.mutate({ mailboxId: statusMailbox.id, status: mailboxStatusDraft });
          }}
        />
      ) : null}
      {aliasMailbox ? (
        <MailboxAliasDialog
          mailbox={aliasMailbox}
          aliasEmail={aliasEmail}
          error={aliasEmailError || aliasSelfError || (addMailboxAlias.error instanceof Error ? addMailboxAlias.error.message : removeMailboxAlias.error instanceof Error ? removeMailboxAlias.error.message : "")}
          busy={addMailboxAlias.isPending || removeMailboxAlias.isPending}
          canSubmit={!!aliasEmail.trim() && !aliasEmailError && !aliasSelfError}
          onAliasEmailChange={(value) => {
            addMailboxAlias.reset();
            removeMailboxAlias.reset();
            setAliasEmail(value);
          }}
          onClose={() => setAliasMailboxId("")}
          onAddAlias={() => {
            if (aliasEmailError || aliasSelfError || !aliasEmail.trim()) return;
            addMailboxAlias.mutate({ mailboxId: aliasMailbox.id, alias: aliasEmail.trim().toLowerCase() });
          }}
          onRemoveAlias={(alias) => removeMailboxAlias.mutate({ mailboxId: aliasMailbox.id, alias })}
        />
      ) : null}
      {forwardMailbox ? (
        <MailboxForwardDialog
          mailbox={forwardMailbox}
          addressesText={forwardAddressesText}
          keepLocalCopy={forwardKeepLocalCopy}
          error={forwardAddressError || forwardSelfError || forwardPermissionError || (updateMailboxForwarding.error instanceof Error ? updateMailboxForwarding.error.message : "")}
          busy={updateMailboxForwarding.isPending}
          onAddressesTextChange={setForwardAddressesText}
          onKeepLocalCopyChange={setForwardKeepLocalCopy}
          onClose={() => setForwardMailboxId("")}
          onSubmit={() => {
            if (forwardAddressError || forwardSelfError || forwardPermissionError) return;
            updateMailboxForwarding.mutate({ mailboxId: forwardMailbox.id, addresses: forwardAddresses, keepLocalCopy: forwardKeepLocalCopy });
          }}
        />
      ) : null}
      {deleteModalMailboxId ? (
        <ConfirmDialog
          title="Delete mailbox"
          message={`Delete "${deleteModalMailboxes[0]?.email || "this mailbox"}"? All mailbox data will be permanently removed and cannot be recovered.`}
          confirmLabel="Delete mailbox"
          tone="danger"
          busy={deleteMailbox.isPending}
          onClose={() => setDeleteModalMailboxId("")}
          onConfirm={() => {
            const mailboxId = deleteModalMailboxId;
            if (!mailboxId) return;
            deleteMailbox.mutate(mailboxId, { onSuccess: () => setDeleteModalMailboxId("") });
          }}
        />
      ) : null}
      {deleteDistributionListEmail ? (
        <ConfirmDialog
          title="Delete distribution list"
          message={`Delete "${deleteDistributionListTarget?.name || deleteDistributionListEmail}"? The list address and its member list will be removed.`}
          confirmLabel="Delete distribution list"
          tone="danger"
          busy={deleteDistributionList.isPending}
          onClose={() => {
            if (deleteDistributionList.isPending) return;
            setDeleteDistributionListEmail("");
          }}
          onConfirm={() => {
            const email = deleteDistributionListEmail;
            if (!email) return;
            deleteDistributionList.mutate(email);
          }}
        />
      ) : null}
      {createMailboxOpen ? (
        <CreateMailboxDialog
          domainName={selectedDomainName}
          localPart={localPart}
          displayName={displayName}
          password={createMailboxPassword}
          confirmPassword={createMailboxConfirmPassword}
          localPartError={createMailboxLocalPartError}
          passwordError={createMailboxPasswordError}
          error={
            createMailboxValidationError ||
            createMailboxLocalPartError ||
            createMailboxDuplicateError ||
            normalizeCreateMailboxError(createMailbox.error instanceof Error ? createMailbox.error.message : "")
          }
          busy={createMailbox.isPending}
          canSubmit={canCreateMailbox}
          onClose={() => {
            if (createMailbox.isPending) return;
            setCreateMailboxValidationError("");
            createMailbox.reset();
            setCreateMailboxOpen(false);
          }}
          onLocalPartChange={(value) => {
            setCreateMailboxValidationError("");
            createMailbox.reset();
            setLocalPart(value);
          }}
          onDisplayNameChange={setDisplayName}
          onPasswordChange={(value) => {
            setCreateMailboxValidationError("");
            createMailbox.reset();
            setCreateMailboxPassword(value);
          }}
          onConfirmPasswordChange={(value) => {
            setCreateMailboxValidationError("");
            createMailbox.reset();
            setCreateMailboxConfirmPassword(value);
          }}
          onSubmit={() => {
            if (createMailbox.isPending) return;
            if (!selectedDomainId || !selectedDomainName) {
              setCreateMailboxValidationError("No domain is available for this tenant.");
              return;
            }
            if (!localPart.trim()) {
              setCreateMailboxValidationError("Enter an email address.");
              return;
            }
            if (createMailboxLocalPartError) {
              setCreateMailboxValidationError(createMailboxLocalPartError);
              return;
            }
            if (createMailboxDuplicateError) {
              setCreateMailboxValidationError(createMailboxDuplicateError);
              return;
            }
            if (!createMailboxPassword) {
              setCreateMailboxValidationError("Enter a password.");
              return;
            }
            if (!createMailboxConfirmPassword) {
              setCreateMailboxValidationError("Confirm the password.");
              return;
            }
            if (createMailboxPasswordError) {
              setCreateMailboxValidationError(createMailboxPasswordError);
              return;
            }
            createMailbox.mutate({
              domain_id: selectedDomainId,
              local_part: localPart.trim(),
              display_name: displayName.trim(),
              quota_mb: quotaMb,
              password: createMailboxPassword,
            });
          }}
        />
      ) : null}
      {createDistributionListOpen ? (
        <CreateDistributionListDialog
          domainName={selectedDomain?.domain_name || allDomains[0]?.domain_name || ""}
          localPart={dlLocalPart}
          displayName={dlDisplayName}
          error={createDistributionListValidationError || (createDistributionList.error instanceof Error ? createDistributionList.error.message : "")}
          busy={createDistributionList.isPending}
          canSubmit={!createDistributionList.isPending}
          onClose={() => {
            if (createDistributionList.isPending) return;
            setCreateDistributionListValidationError("");
            createDistributionList.reset();
            setCreateDistributionListOpen(false);
          }}
          onLocalPartChange={(value) => {
            setCreateDistributionListValidationError("");
            createDistributionList.reset();
            setDlLocalPart(value);
          }}
          onDisplayNameChange={setDlDisplayName}
          onSubmit={() => {
            if (!dlCreateDomainId) {
              setCreateDistributionListValidationError("No domain is available for this tenant.");
              return;
            }
            if (!dlLocalPart.trim()) {
              setCreateDistributionListValidationError("Enter a distribution list address.");
              return;
            }
            createDistributionList.mutate({
              domain_id: dlCreateDomainId,
              local_part: dlLocalPart.trim(),
              display_name: dlDisplayName.trim(),
            });
          }}
        />
      ) : null}
      {addMemberDistributionList ? (
        <AddDistributionListMemberDialog
          distributionList={addMemberDistributionList}
          memberEmail={dlMemberEmail}
          busy={addDistributionListMember.isPending}
          onMemberEmailChange={setDlMemberEmail}
          onClose={() => {
            if (addDistributionListMember.isPending) return;
            setAddMemberListEmail("");
            setDlMemberEmail("");
          }}
          onSubmit={() => {
            if (!dlMemberEmail.trim()) return;
            addDistributionListMember.mutate({ email: addMemberDistributionList.name, memberEmail: dlMemberEmail.trim() });
          }}
        />
      ) : null}
      {membersDistributionList ? (
        <DistributionListMembersDialog
          distributionList={membersDistributionList}
          busy={removeDistributionListMember.isPending}
          onClose={() => {
            if (removeDistributionListMember.isPending) return;
            setMembersListEmail("");
          }}
          onRemoveMember={(member) => removeDistributionListMember.mutate({ email: membersDistributionList.name, memberEmail: member })}
        />
      ) : null}
      {brandEditorOpen ? (
        <BrandEditorDialog
          brandDomain={brandDomain}
          brandName={brandNameDraft}
          brandTagline={brandTaglineDraft}
          selectedLogoFileName={brandLogoFile?.name || ""}
          busy={brandEditorBusy}
          brandError={updateBranding.error instanceof Error ? updateBranding.error.message : ""}
          logoError={uploadBrandLogo.error instanceof Error ? uploadBrandLogo.error.message : ""}
          canSubmit={Boolean(brandNameDraft.trim()) && !brandEditorBusy}
          onClose={() => {
            if (brandEditorBusy) return;
            setBrandEditorOpen(false);
            setBrandLogoFile(null);
          }}
          onBrandNameChange={setBrandNameDraft}
          onBrandTaglineChange={setBrandTaglineDraft}
          onLogoFileChange={setBrandLogoFile}
          onSubmit={() => void saveBrandEditor()}
        />
      ) : null}
    </main>
  );
}

function BrandEditorDialog({
  brandDomain,
  brandName,
  brandTagline,
  selectedLogoFileName,
  busy,
  brandError,
  logoError,
  canSubmit,
  onClose,
  onBrandNameChange,
  onBrandTaglineChange,
  onLogoFileChange,
  onSubmit,
}: {
  brandDomain: string;
  brandName: string;
  brandTagline: string;
  selectedLogoFileName: string;
  busy: boolean;
  brandError: string;
  logoError: string;
  canSubmit: boolean;
  onClose: () => void;
  onBrandNameChange: (value: string) => void;
  onBrandTaglineChange: (value: string) => void;
  onLogoFileChange: (file: File | null) => void;
  onSubmit: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-xl rounded-xl border border-slate-200 bg-white p-6 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-5 flex items-start justify-between gap-4">
          <div className="min-w-0">
            <p className="text-xs font-black uppercase tracking-[0.14em] text-[var(--accent)]">Branding</p>
            <h3 className="mt-1 text-xl font-black text-slate-950">Edit brand</h3>
            <p className="mt-2 text-sm leading-6 text-slate-600">Update the logo, brand name, and tagline for {brandDomain || "this tenant"}.</p>
          </div>
          <button type="button" onClick={onClose} className="icon-button h-10 w-10" aria-label="Close brand editor" disabled={busy}>
            <X size={16} />
          </button>
        </div>

        <form
          className="grid gap-4"
          onSubmit={(event: FormEvent<HTMLFormElement>) => {
            event.preventDefault();
            if (!canSubmit) return;
            onSubmit();
          }}
        >
          <div className="rounded-lg border border-slate-200 bg-slate-50 p-3">
            <BrandLogo size="sm" subtitle={brandTagline || siteConfig.adminSubtitle} brandDomain={brandDomain} brandName={brandName || undefined} />
          </div>

          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Brand name
            <input value={brandName} onChange={(event) => onBrandNameChange(event.target.value)} className="field h-11 px-3" placeholder="Zimphony Webmail" required />
          </label>

          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Tagline
            <input value={brandTagline} onChange={(event) => onBrandTaglineChange(event.target.value)} className="field h-11 px-3" placeholder="Business email that grows with you" />
          </label>

          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Logo
            <input
              type="file"
              accept="image/png,image/jpeg,image/webp,image/svg+xml,image/gif"
              onChange={(event) => onLogoFileChange(event.target.files?.[0] || null)}
              className="block w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-2 file:text-sm file:font-bold file:text-slate-700"
            />
            <span className="text-xs font-semibold text-slate-500">{selectedLogoFileName || "PNG, JPG, WEBP, SVG, GIF up to 5 MB."}</span>
          </label>

          {brandError ? <InlineNotice tone="error">{brandError}</InlineNotice> : null}
          {logoError ? <InlineNotice tone="error">{logoError}</InlineNotice> : null}

          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose} className="theme-button-soft h-10 px-4 text-sm" disabled={busy}>
              Cancel
            </button>
            <button type="submit" className="theme-button h-10 px-4 text-sm" disabled={!canSubmit}>
              {busy ? "Saving..." : "Save brand"}
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}

function CreateMailboxDialog({
  domainName,
  localPart,
  displayName,
  password,
  confirmPassword,
  localPartError,
  passwordError,
  error,
  busy,
  canSubmit,
  onClose,
  onLocalPartChange,
  onDisplayNameChange,
  onPasswordChange,
  onConfirmPasswordChange,
  onSubmit,
}: {
  domainName: string;
  localPart: string;
  displayName: string;
  password: string;
  confirmPassword: string;
  localPartError: string;
  passwordError: string;
  error: string;
  busy: boolean;
  canSubmit: boolean;
  onClose: () => void;
  onLocalPartChange: (value: string) => void;
  onDisplayNameChange: (value: string) => void;
  onPasswordChange: (value: string) => void;
  onConfirmPasswordChange: (value: string) => void;
  onSubmit: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-2xl rounded-xl border border-slate-200 bg-white p-7 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-6 flex items-start justify-between gap-4">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.14em] text-[var(--accent)]">Mailbox</p>
            <h3 className="mt-1 text-2xl font-black text-slate-950">Add mailbox</h3>
            <p className="mt-2 text-sm leading-6 text-slate-600">Create a mailbox under <span className="font-black text-slate-950">@{domainName || "selected-domain"}</span> and set its password now.</p>
          </div>
          <button type="button" onClick={onClose} className="icon-button h-10 w-10" aria-label="Close add mailbox dialog">
            <X size={16} />
          </button>
        </div>
        <form
          noValidate
          className="grid gap-5"
          onSubmit={(event) => {
            event.preventDefault();
            if (!canSubmit) return;
            onSubmit();
          }}
        >
          <div className="rounded-2xl border border-slate-200 bg-slate-50/70 p-4">
            <p className="text-[11px] font-black uppercase tracking-[0.14em] text-slate-500">Mailbox identity</p>
            <div className="mt-3 grid gap-4 md:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]">
              <label className="grid gap-2 text-sm font-semibold text-slate-700">
                Email address
                <div className={`grid grid-cols-[minmax(0,1fr)_auto] overflow-hidden rounded-xl border bg-white ${localPartError ? "border-rose-300 ring-2 ring-rose-100" : "border-slate-200"}`}>
                  <input
                    value={localPart}
                    onChange={(event) => onLocalPartChange(event.target.value.replace(/\s+/g, ""))}
                    className="h-12 min-w-0 px-4 outline-none"
                    placeholder="sales"
                    required
                    aria-invalid={Boolean(localPartError)}
                  />
                  <div className="grid place-items-center border-l border-slate-200 px-4 text-sm font-black text-slate-600">@{domainName || "selected-domain"}</div>
                </div>
                <span className="text-xs font-semibold text-slate-500">Use only the part before @{domainName || "selected-domain"}.</span>
              </label>
              <label className="grid gap-2 text-sm font-semibold text-slate-700">
                Display name
                <input value={displayName} onChange={(event) => onDisplayNameChange(event.target.value)} className="field h-12 px-4" placeholder="Sales team" />
              </label>
            </div>
          </div>
          <div className="rounded-2xl border border-slate-200 bg-slate-50/70 p-4">
            <p className="text-[11px] font-black uppercase tracking-[0.14em] text-slate-500">Password</p>
            <div className="mt-3 grid gap-4 md:grid-cols-2">
              <label className="grid gap-2 text-sm font-semibold text-slate-700">
                Password
                <input value={password} onChange={(event) => onPasswordChange(event.target.value)} type="password" className="field h-12 px-4" placeholder="Create password" required aria-invalid={Boolean(passwordError)} />
              </label>
              <label className="grid gap-2 text-sm font-semibold text-slate-700">
                Confirm password
                <input value={confirmPassword} onChange={(event) => onConfirmPasswordChange(event.target.value)} type="password" className="field h-12 px-4" placeholder="Confirm password" required aria-invalid={Boolean(passwordError)} />
              </label>
            </div>
            <div className="mt-4 rounded-xl border border-slate-200 bg-white px-4 py-3 text-xs font-semibold text-slate-600">
              Password rule: 8-16 characters with at least 1 lowercase, 1 uppercase, and 1 number.
            </div>
          </div>
          {error ? <InlineNotice tone="error">{error}</InlineNotice> : null}
          <div className="flex justify-end gap-2 border-t border-slate-200 pt-1">
            <button type="button" onClick={onClose} className="h-11 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700">
              Cancel
            </button>
            <button type="submit" className="theme-button h-11 px-5 text-sm disabled:opacity-50" disabled={!canSubmit || busy}>
              <MailPlus size={15} />
              {busy ? "Creating..." : "Create mailbox"}
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}

function CreateDistributionListDialog({
  domainName,
  localPart,
  displayName,
  error,
  busy,
  canSubmit,
  onClose,
  onLocalPartChange,
  onDisplayNameChange,
  onSubmit,
}: {
  domainName: string;
  localPart: string;
  displayName: string;
  error: string;
  busy: boolean;
  canSubmit: boolean;
  onClose: () => void;
  onLocalPartChange: (value: string) => void;
  onDisplayNameChange: (value: string) => void;
  onSubmit: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-xl rounded-[28px] border border-slate-200 bg-white p-7 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-6 flex items-start justify-between gap-4">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.14em] text-[var(--accent)]">Distribution list</p>
            <h3 className="mt-1 text-2xl font-black text-slate-950">Add distribution list</h3>
            <p className="mt-2 text-sm leading-6 text-slate-600">
              Create a shared list under <span className="font-black text-slate-950">@{domainName || "selected-domain"}</span>.
            </p>
          </div>
          <button type="button" onClick={onClose} className="icon-button h-10 w-10" aria-label="Close add distribution list dialog" disabled={busy}>
            <X size={16} />
          </button>
        </div>
        <form
          className="grid gap-5"
          onSubmit={(event) => {
            event.preventDefault();
            if (!canSubmit) return;
            onSubmit();
          }}
        >
          <div className="rounded-2xl border border-slate-200 bg-slate-50/70 p-4">
            <p className="text-[11px] font-black uppercase tracking-[0.14em] text-slate-500">List identity</p>
            <div className="mt-3 grid gap-4">
              <label className="grid gap-2 text-sm font-semibold text-slate-700">
                Email address
                <div className="grid grid-cols-[minmax(0,1fr)_auto] overflow-hidden rounded-xl border border-slate-200 bg-white">
                  <input value={localPart} onChange={(event) => onLocalPartChange(event.target.value.replace(/\s+/g, ""))} className="h-12 min-w-0 px-4 outline-none" placeholder="team" disabled={busy} autoFocus />
                  <div className="grid place-items-center border-l border-slate-200 px-4 text-sm font-black text-slate-600">@{domainName || "selected-domain"}</div>
                </div>
              </label>
              <label className="grid gap-2 text-sm font-semibold text-slate-700">
                Display name
                <input value={displayName} onChange={(event) => onDisplayNameChange(event.target.value)} className="field h-12 px-4" placeholder="Team announcements" disabled={busy} />
              </label>
            </div>
          </div>
          {error ? <InlineNotice tone="error">{error}</InlineNotice> : null}
          <div className="flex justify-end gap-2 border-t border-slate-200 pt-1">
            <button type="button" onClick={onClose} className="h-11 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700" disabled={busy}>
              Cancel
            </button>
            <button type="submit" className="theme-button h-11 px-5 text-sm disabled:opacity-50" disabled={!canSubmit || busy}>
              <MailPlus size={15} />
              {busy ? "Creating..." : "Create distribution list"}
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}

function AddDistributionListMemberDialog({
  distributionList,
  memberEmail,
  busy,
  onMemberEmailChange,
  onClose,
  onSubmit,
}: {
  distributionList: DistributionList;
  memberEmail: string;
  busy: boolean;
  onMemberEmailChange: (value: string) => void;
  onClose: () => void;
  onSubmit: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-lg rounded-[28px] border border-slate-200 bg-white p-7 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-6 flex items-start justify-between gap-4">
          <div className="min-w-0">
            <p className="text-xs font-black uppercase tracking-[0.14em] text-[var(--accent)]">Distribution list</p>
            <h3 className="mt-1 text-2xl font-black text-slate-950">Add member</h3>
            <p className="mt-2 break-all text-sm font-semibold leading-6 text-slate-600">{distributionList.name}</p>
          </div>
          <button type="button" onClick={onClose} className="icon-button h-10 w-10" aria-label="Close add member dialog" disabled={busy}>
            <X size={16} />
          </button>
        </div>
        <form
          className="grid gap-5"
          onSubmit={(event) => {
            event.preventDefault();
            if (!memberEmail.trim() || busy) return;
            onSubmit();
          }}
        >
          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Member email
            <input value={memberEmail} onChange={(event) => onMemberEmailChange(event.target.value.trim())} className="field h-12 px-4" placeholder="member@example.com" disabled={busy} autoFocus />
          </label>
          <div className="flex justify-end gap-2 border-t border-slate-200 pt-1">
            <button type="button" onClick={onClose} className="h-11 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700" disabled={busy}>
              Cancel
            </button>
            <button type="submit" className="theme-button h-11 px-5 text-sm disabled:opacity-50" disabled={!memberEmail.trim() || busy}>
              <UserRoundPlus size={15} />
              {busy ? "Adding..." : "Add member"}
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}

function DistributionListMembersDialog({
  distributionList,
  busy,
  onClose,
  onRemoveMember,
}: {
  distributionList: DistributionList;
  busy: boolean;
  onClose: () => void;
  onRemoveMember: (member: string) => void;
}) {
  const members = distributionList.members || [];

  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-2xl rounded-[28px] border border-slate-200 bg-white p-7 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-6 flex items-start justify-between gap-4">
          <div className="min-w-0">
            <p className="text-xs font-black uppercase tracking-[0.14em] text-[var(--accent)]">Members</p>
            <h3 className="mt-1 text-2xl font-black text-slate-950">Distribution list members</h3>
            <p className="mt-2 break-all text-sm font-semibold leading-6 text-slate-600">{distributionList.name}</p>
          </div>
          <button type="button" onClick={onClose} className="icon-button h-10 w-10" aria-label="Close members dialog" disabled={busy}>
            <X size={16} />
          </button>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50/70 p-4">
          <div className="mb-3 flex items-center justify-between gap-3">
            <p className="text-sm font-black text-slate-950">Members</p>
            <Badge>{members.length} members</Badge>
          </div>
          {members.length ? (
            <div className="grid max-h-[46vh] gap-2 overflow-auto pr-1">
              {members.map((member) => (
                <div key={member} className="flex items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-3 py-2.5">
                  <span className="min-w-0 truncate text-sm font-semibold text-slate-700">{member}</span>
                  <button type="button" onClick={() => onRemoveMember(member)} className="theme-button-soft h-8 px-3 text-xs text-rose-600" disabled={busy}>
                    <Trash2 size={13} />
                    Remove
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <div className="rounded-xl border border-dashed border-slate-300 bg-white px-4 py-8 text-center text-sm font-semibold text-slate-500">No members yet.</div>
          )}
        </div>
        <div className="mt-5 flex justify-end border-t border-slate-200 pt-4">
          <button type="button" onClick={onClose} className="h-11 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700" disabled={busy}>
            Close
          </button>
        </div>
      </section>
    </div>
  );
}

function SidebarNavItem({ label, meta, active = false, onClick }: { label: string; meta?: string; active?: boolean; onClick?: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`flex items-center justify-between rounded-xl px-4 py-3 text-left text-sm font-bold transition ${
        active ? "bg-white/14 text-white ring-1 ring-white/18" : "bg-white/6 text-white/82 ring-1 ring-white/10 hover:bg-white/10"
      }`}
    >
      <span>{label}</span>
      {meta ? <span className={`rounded-full px-2 py-0.5 text-[11px] font-black ${active ? "bg-white text-[#2440be]" : "bg-white/12 text-white/80"}`}>{meta}</span> : null}
    </button>
  );
}

function AdminProductInfoPanel({
  variant = "zimphony",
  product,
  organizationName,
  primaryDomain,
  selectedDomainName,
  adminEmail,
  mailboxCount,
  distributionListCount,
  nativeConfigured,
  calendarConfigured,
  driveConfigured,
  imapsyncConfigured,
  billingConfigured,
  license,
}: {
  variant?: CustomerAdminVariant;
  product?: {
    name?: string;
    edition?: string;
    tier?: string;
    source_sku?: string;
    providers?: Record<string, string>;
  };
  organizationName: string;
  primaryDomain: string;
  selectedDomainName: string;
  adminEmail: string;
  mailboxCount: number;
  distributionListCount: number;
  nativeConfigured: boolean;
  calendarConfigured: boolean;
  driveConfigured: boolean;
  imapsyncConfigured: boolean;
  billingConfigured: boolean;
  license?: LicenseStatusConfig;
}) {
  const isMailMaliAdmin = variant === "mailmali";
  if (isMailMaliAdmin) {
    return (
      <div className="grid gap-4">
        <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.16em] text-[var(--accent)]">Subscription & Billing</p>
              <h2 className="mt-2 text-2xl font-black text-slate-950">Mail Mali service plan</h2>
              <p className="mt-1 text-sm font-semibold text-slate-600">Manage mailbox seats, renewal, payment, and customer support for this domain.</p>
            </div>
            <Badge tone="emerald">Service active</Badge>
          </div>
          <div className="mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
            <AdminInfoRow label="Organization" value={organizationName || "Unknown"} />
            <AdminInfoRow label="Primary domain" value={primaryDomain || "Unknown"} />
            <AdminInfoRow label="Selected domain" value={selectedDomainName || primaryDomain || "Unknown"} />
            <AdminInfoRow label="Signed-in admin" value={adminEmail || "Unknown"} />
            <AdminInfoRow label="Mailbox seats used" value={`${mailboxCount}`} />
            <AdminInfoRow label="Distribution lists" value={`${distributionListCount}`} />
          </div>
        </section>

        <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Order & Payment</p>
              <h3 className="mt-2 text-xl font-black text-slate-950">Mailbox seats and renewal</h3>
              <p className="mt-1 text-sm font-semibold leading-6 text-slate-600">
                The full mailbox management workspace is available here. Seat ordering and payment actions will be connected to your subscription provider soon.
              </p>
            </div>
            <WalletCards className="text-slate-400" size={24} />
          </div>
          <div className="mt-4 flex flex-wrap gap-3">
            <button type="button" className="theme-button h-10 px-4 text-sm" disabled>
              Order more mailbox seats
            </button>
            <button type="button" className="theme-button-soft h-10 px-4 text-sm" disabled>
              Open payment
            </button>
          </div>
          <p className="mt-3 text-xs font-semibold text-slate-500">Payment setup is being connected.</p>
        </section>

        <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
          <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Service status</p>
          <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            <AdminStatusPill label="Mailbox management" enabled={true} />
            <AdminStatusPill label="Login page design" enabled={true} />
            <AdminStatusPill label="Mail migration" enabled={imapsyncConfigured} />
            <AdminStatusPill label="Subscription billing" enabled={billingConfigured} />
          </div>
        </section>

        <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
          <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Support</p>
          <p className="mt-2 text-sm font-semibold leading-6 text-slate-600">Contact Mail Mali support for service plan, renewal, payment, or mailbox seat changes that are not yet self-service.</p>
        </section>
      </div>
    );
  }
  const productName = product?.name || "Zimphony Webmail";
  const tierLabel = formatAdminProductTierLabel(product?.tier, product?.edition);
  const sourceSku = formatAdminSourceSkuLabel(product?.source_sku, product?.tier);
  const mailProvider = formatProviderLabel(product?.providers?.mail || "zimbra");
  const calendarProvider = formatProviderLabel(product?.providers?.calendar || "none");
  const taskProvider = product?.providers?.task ? formatProviderLabel(product.providers.task) : calendarProvider;
  const driveProvider = formatProviderLabel(product?.providers?.drive || "none");
  const freeTier = (product?.tier || "").toLowerCase() === "free" || license?.required === false;
  const deploymentsLabel = freeTier
    ? "License server not required"
    : license?.allowed_deployments
      ? `${license.deployment_count ?? 0} / ${license.allowed_deployments}`
      : license?.deployment_count != null
        ? `${license.deployment_count}`
        : "Not checked";
  const supportUpgradeLabel = freeTier ? "Not included" : license?.support_upgrade_active === false ? "Expired or inactive" : "Active";
  const activationLabel = license?.activation_required === false ? "Not required" : license?.activated ? "Activated" : license?.activation_status === "activation_grace" ? "Grace period" : license?.activation_blocked || license?.hard_block ? "Blocked" : "Required";
  const activationBlocked = Boolean(license?.activation_blocked || license?.hard_block);
  const licenseAttention = Boolean(!activationBlocked && license?.admin_warning);

  return (
    <div className="grid gap-4">
      <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.16em] text-[var(--accent)]">Product Information</p>
            <h2 className="mt-2 text-2xl font-black text-slate-950">{productName}</h2>
            <p className="mt-1 text-sm font-semibold text-slate-600">Customer admin console for the current installation.</p>
          </div>
          <Badge tone="emerald">{tierLabel}</Badge>
        </div>
        <div className="mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          <AdminInfoRow label="Product Website" value="www.zimphony.com" href={PRODUCT_WEBSITE} />
          <AdminInfoRow label="Support email" value={PRODUCT_SUPPORT_EMAIL} href={`mailto:${PRODUCT_SUPPORT_EMAIL}`} />
          <AdminInfoRow label="Edition" value={tierLabel} />
          <AdminInfoRow label="Source SKU" value={sourceSku} />
          <AdminInfoRow label="Mail provider" value={mailProvider} />
          <AdminInfoRow label="Calendar provider" value={calendarProvider} />
          <AdminInfoRow label="Task provider" value={taskProvider} />
          <AdminInfoRow label="Drive provider" value={driveProvider} />
        </div>
      </section>

      <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
        <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Installation</p>
        <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          <AdminInfoRow label="Organization" value={organizationName || "Unknown"} />
          <AdminInfoRow label="Primary domain" value={primaryDomain || "Unknown"} />
          <AdminInfoRow label="Selected domain" value={selectedDomainName || primaryDomain || "Unknown"} />
          <AdminInfoRow label="Signed-in admin" value={adminEmail || "Unknown"} />
          <AdminInfoRow label="Mailboxes" value={`${mailboxCount}`} />
          <AdminInfoRow label="Distribution lists" value={`${distributionListCount}`} />
        </div>
      </section>

      <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
        <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Service status</p>
        <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
          <AdminStatusPill label="Native Mail Server" enabled={nativeConfigured} />
          <AdminStatusPill label="Calendar" enabled={calendarConfigured} />
          <AdminStatusPill label="Drive" enabled={driveConfigured} />
          <AdminStatusPill label="Migration" enabled={imapsyncConfigured} />
          <AdminStatusPill label="Billing" enabled={billingConfigured} />
        </div>
      </section>

      <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
        {activationBlocked ? (
          <div className="mb-4 flex items-start gap-3 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-red-800">
            <AlertTriangle className="mt-0.5 shrink-0" size={18} />
            <div className="min-w-0">
              <p className="text-sm font-black">Activation blocked</p>
              <p className="mt-1 text-sm font-semibold leading-6">{license?.message || "License key was not found. Update the license key and restart the backend."}</p>
              {license?.last_error ? <p className="mt-1 break-words text-xs font-black text-red-700">Last error: {license.last_error}</p> : null}
            </div>
          </div>
        ) : null}
        {licenseAttention ? (
          <div className="mb-4 flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-amber-800">
            <AlertTriangle className="mt-0.5 shrink-0" size={18} />
            <div className="min-w-0">
              <p className="text-sm font-black">License attention required</p>
              <p className="mt-1 text-sm font-semibold leading-6">{license?.message || "License status requires administrator attention."}</p>
            </div>
          </div>
        ) : null}
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">License status</p>
            <p className="mt-2 text-sm font-semibold leading-6 text-slate-600">{license?.message || "License status has not been checked yet."}</p>
          </div>
          {activationBlocked ? <Badge tone="red">Activation blocked</Badge> : <AdminStatusPill label={license?.required ? "License check" : "Free edition"} enabled={!license?.admin_warning} />}
        </div>
        <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          <AdminInfoRow label="Status" value={license?.status || "Unknown"} />
          <AdminInfoRow label="Activation" value={activationLabel} tone={activationBlocked ? "red" : license?.activation_status === "activation_grace" ? "amber" : "default"} />
          <AdminInfoRow label="Grace until" value={license?.activation_grace_until ? new Date(license.activation_grace_until).toLocaleString() : "None"} />
          <AdminInfoRow label="License model" value={license?.license_model || (license?.required ? "Unknown" : "Free")} />
          <AdminInfoRow label="Deployments" value={deploymentsLabel} />
          <AdminInfoRow label="Mailboxes" value={`${license?.active_mailboxes ?? mailboxCount}${license?.mailbox_quota ? ` / ${license.mailbox_quota}` : ""}`} />
          <AdminInfoRow label="Support & upgrade" value={supportUpgradeLabel} />
          <AdminInfoRow label="Server" value={license?.server_reachable ? "Reachable" : license?.cache_used ? "Cached" : "Not checked"} />
          <AdminInfoRow label="License server" value={freeTier ? "Not required" : license?.server_url || "Not configured"} />
          <AdminInfoRow label="Last checked" value={license?.checked_at ? new Date(license.checked_at).toLocaleString() : "Not checked"} />
          <AdminInfoRow label="Last error" value={license?.last_error || "None"} tone={license?.last_error ? "red" : "default"} />
          <AdminInfoRow label="Over deployment" value={license?.over_deployment ? "Yes" : "No"} tone={license?.over_deployment ? "amber" : "default"} />
          <AdminInfoRow label="Over quota" value={license?.over_quota ? "Yes" : "No"} tone={license?.over_quota ? "amber" : "default"} />
        </div>
      </section>
    </div>
  );
}

function AdminInfoRow({ label, value, href, tone = "default" }: { label: string; value: string; href?: string; tone?: "default" | "red" | "amber" }) {
  const toneClasses =
    tone === "red"
      ? "border-red-200 bg-red-50 text-red-800"
      : tone === "amber"
        ? "border-amber-200 bg-amber-50 text-amber-800"
        : "border-slate-200 bg-slate-50 text-slate-950";
  const content = href ? (
    <a className="truncate font-black text-[var(--accent)] underline-offset-4 hover:underline" href={href} target={href.startsWith("mailto:") ? undefined : "_blank"} rel={href.startsWith("mailto:") ? undefined : "noreferrer"}>
      {value}
    </a>
  ) : (
    <p className={tone === "default" ? "truncate font-black text-slate-950" : "truncate font-black"}>{value}</p>
  );
  return (
    <div className={`min-w-0 rounded-xl border px-4 py-3 ${toneClasses}`}>
      <p className={`text-xs font-black uppercase tracking-[0.12em] ${tone === "default" ? "text-slate-500" : ""}`}>{label}</p>
      <div className="mt-1 min-w-0 text-sm">{content}</div>
    </div>
  );
}

function AdminStatusPill({ label, enabled }: { label: string; enabled: boolean }) {
  return (
    <div className={`rounded-xl border px-4 py-3 ${enabled ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-slate-200 bg-slate-50 text-slate-500"}`}>
      <p className="text-xs font-black uppercase tracking-[0.12em]">{label}</p>
      <p className="mt-1 text-sm font-black">{enabled ? "Configured" : "Not configured"}</p>
    </div>
  );
}

function formatAdminProductTierLabel(tier?: string, edition?: string) {
  const labelKey = resolveProductTierLabelKey(tier, edition);
  if (labelKey === "productTier.freeEdition") return "Free Edition";
  if (labelKey === "productTier.zimbraNative") return "Native Mail Server";
  if (labelKey === "productTier.googleConnect") return "Google-Connect";
  return "Shared Webmail";
}

function formatAdminSourceSkuLabel(sourceSku?: string, tier?: string) {
  const normalized = (sourceSku || "").trim().toLowerCase().replace(/[-\s]+/g, "_");
  if (normalized === "full_source") return "Packaged deployment";
  if (normalized === "encoded_unlimited") return "Encoded package";
  if (normalized === "encoded_per_mailbox") return "Encoded per-mailbox package";
  if (!normalized) {
    const normalizedTier = (tier || "").trim().toLowerCase().replace(/[-\s]+/g, "_");
    return normalizedTier === "zimbra_native" || normalizedTier === "google_connect" ? "Packaged deployment" : "Encoded package";
  }
  return normalized.replace(/_/g, " ");
}

function formatProviderLabel(value?: string) {
  const normalized = (value || "").trim().toLowerCase();
  if (!normalized || normalized === "none") return "none";
  if (normalized === "zimbra" || normalized === "native_zimbra") return "Mail Server";
  if (normalized === "google") return "Google";
  return "Provider";
}

function normalizeMailboxAccountStatus(value?: string): MailboxAccountStatus {
  const normalized = (value || "").trim().toLowerCase();
  if (normalized === "locked" || normalized === "closed") return normalized;
  return "active";
}

function mailboxAccountStatusTone(value?: string): "emerald" | "amber" | "red" {
  return MAILBOX_ACCOUNT_STATUSES.find((item) => item.value === normalizeMailboxAccountStatus(value))?.tone || "emerald";
}

function formatMailboxAccountStatus(value?: string) {
  const status = normalizeMailboxAccountStatus(value);
  return MAILBOX_ACCOUNT_STATUSES.find((item) => item.value === status)?.label || "Active";
}

function AlertIcon({
  icon,
  count,
  tone,
  labelText,
  label,
  tooltipTitle,
  tooltipText,
}: {
  icon: ReactNode;
  count: number;
  tone: "danger" | "warning" | "info" | "success" | "secure";
  labelText: string;
  label: string;
  tooltipTitle: string;
  tooltipText: string;
}) {
  const toneClassName = {
    danger: "border-rose-200 bg-rose-50 text-rose-700 hover:border-rose-300 hover:bg-rose-100",
    warning: "border-orange-200 bg-orange-50 text-orange-700 hover:border-orange-300 hover:bg-orange-100",
    info: "border-sky-200 bg-sky-50 text-sky-700 hover:border-sky-300 hover:bg-sky-100",
    success: "border-emerald-200 bg-emerald-50 text-emerald-700 hover:border-emerald-300 hover:bg-emerald-100",
    secure: "border-indigo-200 bg-indigo-50 text-indigo-700 hover:border-indigo-300 hover:bg-indigo-100",
  }[tone];
  const countClassName = {
    danger: "bg-rose-600 text-white",
    warning: "bg-orange-600 text-white",
    info: "bg-sky-600 text-white",
    success: "bg-emerald-600 text-white",
    secure: "bg-indigo-600 text-white",
  }[tone];

  return (
    <button
      type="button"
      className={`group relative inline-flex h-10 items-center gap-2 rounded-full border px-3 text-sm font-black transition focus:outline-none focus:ring-2 focus:ring-[color-mix(in_srgb,var(--accent)_24%,white)] ${toneClassName}`}
      aria-label={label}
    >
      <span className="grid h-5 w-5 place-items-center">{icon}</span>
      <span className="hidden sm:inline">{labelText}</span>
      <span className={`grid h-5 min-w-5 place-items-center rounded-full px-1.5 text-[10px] font-black ${countClassName}`}>
        {count}
      </span>
      <span className="pointer-events-none absolute right-0 top-[calc(100%+0.65rem)] z-20 hidden w-64 rounded-lg border border-slate-200 bg-white p-3 text-left shadow-soft group-hover:block group-focus-visible:block">
        <span className="block text-xs font-black uppercase tracking-[0.12em] text-slate-500">{tooltipTitle}</span>
        <span className="mt-1 block text-sm font-semibold leading-5 text-slate-700">{tooltipText}</span>
      </span>
    </button>
  );
}

function InlineNotice({ tone, children }: { tone: "info" | "error" | "warning"; children: ReactNode }) {
  if (tone === "error") {
    return <div className="mb-3 rounded-xl border border-rose-100 bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">{children}</div>;
  }
  if (tone === "warning") {
    return <div className="mb-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800">{children}</div>;
  }

  return (
    <div className="mb-3 rounded-xl border border-[color-mix(in_srgb,var(--accent)_20%,white)] bg-[color-mix(in_srgb,var(--accent)_8%,white)] px-4 py-3 text-sm font-semibold text-[var(--accent)]">
      {children}
    </div>
  );
}

function ScopeChip({ active, label, onClick }: { active: boolean; label: string; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`rounded-full border px-3 py-2 text-xs font-black uppercase tracking-[0.12em] transition ${
        active
          ? "border-[color-mix(in_srgb,var(--accent)_35%,white)] bg-[color-mix(in_srgb,var(--accent)_10%,white)] text-[var(--accent)]"
          : "border-slate-200 bg-white text-slate-500 hover:border-[color-mix(in_srgb,var(--accent)_18%,white)] hover:text-slate-800"
      }`}
    >
      {label}
    </button>
  );
}

function Badge({ children, tone = "slate" }: { children: ReactNode; tone?: "slate" | "emerald" | "amber" | "red" }) {
  const classes =
    tone === "emerald"
      ? "border-emerald-200 bg-emerald-50 text-emerald-700"
      : tone === "amber"
        ? "border-amber-200 bg-amber-50 text-amber-700"
      : tone === "red"
        ? "border-red-200 bg-red-50 text-red-700"
      : "border-slate-200 bg-white text-slate-500";
  return <span className={`inline-flex items-center rounded-full border px-2.5 py-1 text-[10px] font-black uppercase tracking-[0.12em] ${classes}`}>{children}</span>;
}

function FeaturePill({ label, value, dark = false }: { label: string; value: string; dark?: boolean }) {
  return (
    <div className={dark ? "rounded-xl border border-white/18 bg-white/12 px-4 py-3 backdrop-blur-[1px]" : "rounded-xl border border-slate-200 bg-white px-4 py-3"}>
      <p className={dark ? "text-[11px] font-black uppercase tracking-[0.14em] text-emerald-50/85" : "text-[11px] font-black uppercase tracking-[0.14em] text-slate-500"}>{label}</p>
      <p className={dark ? "mt-1 text-sm font-semibold text-white" : "mt-1 text-sm font-semibold text-slate-900"}>{value}</p>
    </div>
  );
}

function MailboxRow({
  mailbox,
  selected,
  busy,
  isLastPostmaster,
  menuOpen,
  onSelect,
  onToggleMenu,
  onCloseMenu,
  onRename,
  onEditDisplayName,
  onStatus,
  onAlias,
  onForward,
  onReset,
  onDisableTwoFactor,
  onToggleTwoFactorRequired,
  onTogglePostmaster,
  onDelete,
}: {
  mailbox: Mailbox;
  selected: boolean;
  busy: boolean;
  isLastPostmaster: boolean;
  menuOpen: boolean;
  onSelect: () => void;
  onToggleMenu: () => void;
  onCloseMenu: () => void;
  onRename: () => void;
  onEditDisplayName: () => void;
  onStatus: () => void;
  onAlias: () => void;
  onForward: () => void;
  onReset: () => void;
  onDisableTwoFactor: () => void;
  onToggleTwoFactorRequired: () => void;
  onTogglePostmaster: () => void;
  onDelete: () => void;
}) {
  const quota = getMailboxQuota(mailbox);
  const lastLogin = formatLastLogin(mailbox.last_login_at || "", Number(mailbox.last_login_days ?? -1));
  const mailboxPostmaster = isMailboxPostmaster(mailbox);
  const aliasCount = (mailbox.aliases || []).filter(Boolean).length;
  const forwardCount = (mailbox.forward_addresses || []).filter(Boolean).length;
  const twoFactorRequired = Boolean(mailbox.two_factor_required);
  const actionMenuButtonRef = useRef<HTMLButtonElement | null>(null);
  const [menuPosition, setMenuPosition] = useState<CSSProperties>({});
  const postmasterTitle = mailboxPostmaster
    ? (isLastPostmaster ? "Cannot unset the last postmaster" : "Unset postmaster")
    : "Set postmaster";
  const updateMenuPosition = () => {
    const button = actionMenuButtonRef.current;
    if (!button || typeof window === "undefined") return;
    const rect = button.getBoundingClientRect();
    const menuWidth = 240;
    const menuHeight = 412;
    const gap = 8;
    const left = Math.max(12, Math.min(window.innerWidth - menuWidth - 12, rect.right - menuWidth));
    const opensUp = rect.bottom + gap + menuHeight > window.innerHeight && rect.top - gap - menuHeight > 12;
    const top = opensUp ? rect.top - gap - menuHeight : Math.min(rect.bottom + gap, window.innerHeight - 12);
    setMenuPosition({ top, left });
  };

  useEffect(() => {
    if (!menuOpen) return;
    updateMenuPosition();
    const close = () => onCloseMenu();
    window.addEventListener("resize", close);
    window.addEventListener("scroll", close, true);
    return () => {
      window.removeEventListener("resize", close);
      window.removeEventListener("scroll", close, true);
    };
  }, [menuOpen, onCloseMenu]);

  return (
    <div
      role="button"
      tabIndex={0}
      onClick={onSelect}
      onKeyDown={(event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          onSelect();
        }
      }}
      className={`border-b border-slate-200 px-4 py-3 text-left transition last:border-b-0 ${
        selected
          ? "bg-[color-mix(in_srgb,var(--accent)_8%,white)]"
            : "bg-white hover:bg-slate-50"
      }`}
    >
      <div className="grid grid-cols-[52px_minmax(220px,1.55fr)_minmax(180px,1.1fr)_140px_130px_140px_120px_130px] items-center gap-4">
        <div className="flex items-center">
          <button
            type="button"
            onClick={(event) => {
              event.stopPropagation();
              onTogglePostmaster();
            }}
            disabled={busy || isLastPostmaster}
            className={`inline-flex h-5 w-5 items-center justify-center rounded border transition ${
              mailboxPostmaster ? "border-[color-mix(in_srgb,var(--accent)_35%,white)] bg-[var(--accent)] text-white" : "border-slate-300 bg-white text-transparent"
            }`}
            aria-label={`${postmasterTitle} for ${mailbox.email}`}
            aria-pressed={mailboxPostmaster}
            title={postmasterTitle}
          >
            <svg viewBox="0 0 16 16" className="h-3 w-3" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M3.5 8.3 6.5 11l6-7" />
            </svg>
          </button>
        </div>
        <div className="flex min-w-0 items-start gap-3">
          <div className="min-w-0">
            <p className="truncate text-sm font-black text-slate-950">{mailbox.email}</p>
          </div>
        </div>
        <div className="min-w-0">
          <p className="truncate text-sm font-semibold text-slate-700">{mailbox.display_name || "—"}</p>
        </div>
        <div className="grid gap-1">
          <div className="h-2 overflow-hidden rounded-full bg-slate-200">
            <div className="h-full rounded-full bg-[var(--accent)]" style={{ width: `${Math.min(quota.percent, 100)}%` }} />
          </div>
          <div className="text-[11px] font-semibold text-slate-500">{quota.summaryCompact}</div>
        </div>
        <div className="flex items-center">
          <div className="flex flex-wrap items-center gap-1.5">
            {mailbox.two_factor_enabled ? (
              <button
                type="button"
                onClick={(event) => {
                  event.stopPropagation();
                  onDisableTwoFactor();
                }}
                className="inline-flex h-7 items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2.5 text-xs font-black text-emerald-700 transition hover:border-rose-200 hover:bg-rose-50 hover:text-rose-700 focus:outline-none focus:ring-2 focus:ring-rose-200"
                title="Click to disable 2FA for this account"
                aria-label={`Click to disable 2FA for ${mailbox.email}`}
              >
                <CircleCheckBig size={14} />
                Enabled
              </button>
            ) : twoFactorRequired ? (
              <span className="inline-flex h-7 items-center gap-1 rounded-full border border-indigo-200 bg-indigo-50 px-2.5 text-xs font-black text-indigo-700" title="2FA is required for this mailbox">
                <ShieldCheck size={13} />
                Required
              </span>
            ) : (
              <span className="text-sm font-semibold text-slate-300" aria-label="2FA disabled">
                —
              </span>
            )}
          </div>
        </div>
        <div className="text-sm font-semibold text-slate-700">
          {lastLogin}
        </div>
        <div className="flex items-center">
          <Badge tone={mailboxAccountStatusTone(mailbox.account_status || mailbox.status)}>
            {formatMailboxAccountStatus(mailbox.account_status || mailbox.status)}
          </Badge>
        </div>
        <div className="relative flex items-center justify-end">
          <button
            ref={actionMenuButtonRef}
            type="button"
            onClick={(event) => {
              event.stopPropagation();
              updateMenuPosition();
              onToggleMenu();
            }}
            onBlur={(event) => {
              if (!event.currentTarget.parentElement?.contains(event.relatedTarget as Node | null)) onCloseMenu();
            }}
            className="inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-[color-mix(in_srgb,var(--accent)_24%,white)] bg-[color-mix(in_srgb,var(--accent)_7%,white)] px-3 text-sm font-black text-[var(--accent)] shadow-[0_1px_2px_rgba(15,23,42,0.05)] transition hover:border-[color-mix(in_srgb,var(--accent)_38%,white)] hover:bg-[color-mix(in_srgb,var(--accent)_12%,white)] hover:text-[var(--accent)] focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2"
            aria-label={`Open actions for ${mailbox.email}`}
            aria-expanded={menuOpen}
          >
            <span className="grid h-6 w-6 place-items-center rounded-md bg-[var(--accent)] text-white">
              <MoreVertical size={15} />
            </span>
            More
          </button>
          {menuOpen ? (
            <div
              className="fixed z-[10020] w-60 overflow-hidden rounded-lg border border-slate-200 bg-white py-1.5 text-sm font-semibold text-slate-700 shadow-lg"
              style={menuPosition}
              onClick={(event) => event.stopPropagation()}
              onBlur={(event) => {
                if (!event.currentTarget.contains(event.relatedTarget as Node | null)) onCloseMenu();
              }}
            >
              <MailboxActionMenuItem icon={<Pencil size={15} />} label="Edit display name" onClick={onEditDisplayName} />
              <MailboxActionMenuItem icon={<AtSign size={15} />} label="Rename email" onClick={onRename} />
              <MailboxActionMenuItem icon={<AlertTriangle size={15} />} label="Account status" onClick={onStatus} />
              <MailboxActionMenuItem
                icon={<AtSign size={15} />}
                label="Alias"
                active={aliasCount > 0}
                indicator={aliasCount > 0 ? `${aliasCount}` : ""}
                indicatorLabel={aliasCount > 0 ? `${aliasCount} aliases configured` : ""}
                onClick={onAlias}
              />
              <MailboxActionMenuItem
                icon={<Forward size={15} />}
                label="Forward"
                active={forwardCount > 0}
                indicator={forwardCount > 0 ? "On" : ""}
                indicatorLabel={forwardCount > 0 ? `${forwardCount} forwarding addresses configured` : ""}
                onClick={onForward}
              />
              <MailboxActionMenuItem icon={<UserRoundPlus size={15} />} label={mailboxPostmaster ? "Unset postmaster" : "Set postmaster"} disabled={busy || isLastPostmaster} onClick={onTogglePostmaster} />
              <MailboxActionMenuItem
                icon={<ShieldCheck size={15} />}
                label={twoFactorRequired ? "Do not require 2FA" : "Require 2FA"}
                active={twoFactorRequired}
                indicator={twoFactorRequired ? "Required" : ""}
                indicatorLabel={twoFactorRequired ? "2FA is required for this mailbox" : ""}
                disabled={busy}
                onClick={onToggleTwoFactorRequired}
              />
              {mailbox.two_factor_enabled ? <MailboxActionMenuItem icon={<CircleCheckBig size={15} />} label="Disable 2FA" onClick={onDisableTwoFactor} /> : null}
              <MailboxActionMenuItem icon={<Pencil size={15} />} label="Password" onClick={onReset} />
              <MailboxActionMenuItem icon={<Trash2 size={15} />} label="Delete" tone="danger" onClick={onDelete} />
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}

function MailboxActionMenuItem({
  icon,
  label,
  tone = "default",
  disabled = false,
  active = false,
  indicator = "",
  indicatorLabel = "",
  onClick,
}: {
  icon: ReactNode;
  label: string;
  tone?: "default" | "danger";
  disabled?: boolean;
  active?: boolean;
  indicator?: string;
  indicatorLabel?: string;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      disabled={disabled}
      onMouseDown={(event) => event.preventDefault()}
      onClick={onClick}
      className={`flex h-11 w-full items-center gap-3 px-3.5 text-left transition disabled:cursor-not-allowed disabled:text-slate-300 ${
        tone === "danger"
          ? "text-rose-600 hover:bg-rose-50"
          : active
            ? "bg-[color-mix(in_srgb,var(--accent)_7%,white)] text-slate-950 hover:bg-[color-mix(in_srgb,var(--accent)_10%,white)]"
            : "hover:bg-slate-50 hover:text-slate-950"
      }`}
    >
      <span
        className={`grid h-7 w-7 place-items-center rounded-md ${
          active ? "bg-[var(--accent)] text-white" : "bg-slate-100 text-current"
        }`}
      >
        {icon}
      </span>
      <span className="min-w-0 flex-1 truncate">{label}</span>
      {indicator ? (
        <span
          className="shrink-0 rounded-full border border-[color-mix(in_srgb,var(--accent)_22%,white)] bg-white px-2 py-0.5 text-[11px] font-black text-[var(--accent)]"
          aria-label={indicatorLabel || indicator}
        >
          {indicator}
        </span>
      ) : null}
    </button>
  );
}

function DistributionListRow({
  distributionList,
  selected,
  onSelect,
  onAddMember,
  onShowMembers,
  onDelete,
}: {
  distributionList: DistributionList;
  selected: boolean;
  onSelect: () => void;
  onAddMember: () => void;
  onShowMembers: () => void;
  onDelete: () => void;
}) {
  return (
    <div
      role="button"
      tabIndex={0}
      onClick={onSelect}
      onKeyDown={(event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          onSelect();
        }
      }}
      className={`grid grid-cols-[minmax(260px,1.55fr)_minmax(160px,0.9fr)_110px_330px] items-center gap-4 border-b border-slate-200 px-4 py-3 text-left transition last:border-b-0 ${
        selected ? "bg-[color-mix(in_srgb,var(--accent)_6%,white)]" : "hover:bg-slate-50/90"
      }`}
    >
      <div className="min-w-0">
        <p className="truncate text-sm font-black text-slate-950">{distributionList.name}</p>
        <p className="mt-1 truncate text-xs font-semibold text-slate-500">Distribution list</p>
      </div>
      <p className="truncate text-sm font-semibold text-slate-600">{distributionList.display_name || "No display name"}</p>
      <div>
        <Badge>{distributionList.member_count} members</Badge>
      </div>
      <div className="flex justify-end gap-2">
        <button
          type="button"
          onClick={(event) => {
            event.stopPropagation();
            onShowMembers();
          }}
          className="theme-button-soft h-9 px-3 text-xs"
        >
          <Users size={14} />
          Members
        </button>
        <button
          type="button"
          onClick={(event) => {
            event.stopPropagation();
            onAddMember();
          }}
          className="theme-button h-9 px-3 text-xs"
        >
          <UserRoundPlus size={14} />
          Add member
        </button>
        <button
          type="button"
          onClick={(event) => {
            event.stopPropagation();
            onDelete();
          }}
          className="theme-button-soft h-9 px-3 text-xs text-rose-600"
        >
          <Trash2 size={14} />
          Delete
        </button>
      </div>
    </div>
  );
}

function PasswordDialog({
  mailboxes,
  password,
  confirmPassword,
  error,
  busy,
  canSubmit,
  onPasswordChange,
  onConfirmPasswordChange,
  onClose,
  onSubmit,
}: {
  mailboxes: Mailbox[];
  password: string;
  confirmPassword: string;
  error: string;
  busy: boolean;
  canSubmit: boolean;
  onPasswordChange: (value: string) => void;
  onConfirmPasswordChange: (value: string) => void;
  onClose: () => void;
  onSubmit: () => void;
}) {
  const isBulk = mailboxes.length > 1;
  const firstMailbox = mailboxes[0];

  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-lg rounded-xl border border-slate-200 bg-white p-5 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-4">
          <p className="text-xs font-black uppercase text-slate-500">Password</p>
          <h3 className="mt-1 text-lg font-black text-slate-950">{isBulk ? `Update password for ${mailboxes.length} mailboxes` : "Update mailbox password"}</h3>
          <p className="mt-3 text-sm leading-6 text-slate-600">
            {isBulk ? "The new password will be applied to every selected mailbox immediately." : `Set a new password for ${firstMailbox?.email || "this mailbox"}.`}
          </p>
        </div>
        <div className="mb-4 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
          <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-500">{isBulk ? "Selected mailboxes" : "Mailbox"}</p>
          {isBulk ? (
            <div className="mt-2 grid gap-1">
              {mailboxes.slice(0, 4).map((mailbox) => (
                <p key={mailbox.id} className="truncate text-sm font-semibold text-slate-700">{mailbox.email}</p>
              ))}
              {mailboxes.length > 4 ? <p className="text-sm font-semibold text-slate-500">+{mailboxes.length - 4} more</p> : null}
            </div>
          ) : (
            <div className="mt-2">
              <p className="text-sm font-black text-slate-950">{firstMailbox?.email || "—"}</p>
              <p className="mt-1 text-xs font-semibold text-slate-500">{firstMailbox?.display_name || "—"}</p>
            </div>
          )}
        </div>
        <form
          className="grid gap-3"
          onSubmit={(event) => {
            event.preventDefault();
            if (!canSubmit) return;
            onSubmit();
          }}
        >
          <div className="grid gap-3 sm:grid-cols-2">
            <input value={password} onChange={(event) => onPasswordChange(event.target.value)} type="password" className="field h-11" placeholder="New password" />
            <input value={confirmPassword} onChange={(event) => onConfirmPasswordChange(event.target.value)} type="password" className="field h-11" placeholder="Confirm password" />
          </div>
          <p className="text-xs font-semibold text-slate-500">Password must be 8-16 characters and include uppercase, lowercase, and a number.</p>
          {error ? <p className="text-sm font-bold text-rose-600">{error}</p> : null}
          <div className="flex justify-end gap-2">
            <button type="button" onClick={onClose} className="h-10 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700">
              Cancel
            </button>
            <button type="submit" disabled={!canSubmit || busy} className="theme-button h-10 px-4 text-sm disabled:opacity-50">
              {busy ? "Saving..." : "Update password"}
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}

function MailboxRenameDialog({
  mailbox,
  localPart,
  error,
  busy,
  canSubmit,
  onLocalPartChange,
  onClose,
  onSubmit,
}: {
  mailbox: Mailbox;
  localPart: string;
  error: string;
  busy: boolean;
  canSubmit: boolean;
  onLocalPartChange: (value: string) => void;
  onClose: () => void;
  onSubmit: () => void;
}) {
  const domain = mailbox.email.includes("@") ? mailbox.email.split("@").pop() || "" : "";
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-lg rounded-xl border border-slate-200 bg-white p-5 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-4">
          <p className="text-xs font-black uppercase text-slate-500">Rename</p>
          <h3 className="mt-1 text-lg font-black text-slate-950">Rename mailbox</h3>
          <p className="mt-3 text-sm leading-6 text-slate-600">Change the mailbox address for {mailbox.email}.</p>
        </div>
        <form className="grid gap-3" onSubmit={(event) => { event.preventDefault(); if (!busy) onSubmit(); }}>
          <label className="grid gap-1 text-sm font-bold text-slate-700">
            New email
            <div className="grid grid-cols-[minmax(0,1fr)_auto] overflow-hidden rounded-lg border border-slate-200 bg-white focus-within:ring-2 focus-within:ring-[var(--accent)]">
              <input value={localPart} onChange={(event) => onLocalPartChange(event.target.value)} className="h-11 min-w-0 px-3 outline-none" placeholder="name" />
              <span className="grid h-11 place-items-center border-l border-slate-200 bg-slate-50 px-3 text-sm font-black text-slate-500">@{domain}</span>
            </div>
          </label>
          {error ? <p className="text-sm font-bold text-rose-600">{error}</p> : null}
          <DialogActions busy={busy} submitLabel="Rename mailbox" busyLabel="Renaming..." onClose={onClose} disabled={!canSubmit} />
        </form>
      </section>
    </div>
  );
}

function MailboxDisplayNameDialog({
  mailbox,
  displayName,
  error,
  busy,
  onDisplayNameChange,
  onClose,
  onSubmit,
}: {
  mailbox: Mailbox;
  displayName: string;
  error: string;
  busy: boolean;
  onDisplayNameChange: (value: string) => void;
  onClose: () => void;
  onSubmit: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-lg rounded-xl border border-slate-200 bg-white p-5 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-4">
          <p className="text-xs font-black uppercase text-slate-500">Display name</p>
          <h3 className="mt-1 text-lg font-black text-slate-950">Edit display name</h3>
          <p className="mt-3 text-sm leading-6 text-slate-600">Change the name shown for {mailbox.email}. The mailbox address will not change.</p>
        </div>
        <form className="grid gap-3" onSubmit={(event) => { event.preventDefault(); if (!busy) onSubmit(); }}>
          <label className="grid gap-1 text-sm font-bold text-slate-700">
            Display name
            <input
              value={displayName}
              onChange={(event) => onDisplayNameChange(event.target.value)}
              className="field h-11"
              placeholder="Full name"
              autoFocus
            />
          </label>
          {error ? <p className="text-sm font-bold text-rose-600">{error}</p> : null}
          <DialogActions busy={busy} submitLabel="Save display name" busyLabel="Saving..." onClose={onClose} disabled={!displayName.trim() || Boolean(error)} />
        </form>
      </section>
    </div>
  );
}

function MailboxStatusDialog({
  mailbox,
  status,
  error,
  busy,
  onStatusChange,
  onClose,
  onSubmit,
}: {
  mailbox: Mailbox;
  status: MailboxAccountStatus;
  error: string;
  busy: boolean;
  onStatusChange: (value: MailboxAccountStatus) => void;
  onClose: () => void;
  onSubmit: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-xl rounded-xl border border-slate-200 bg-white p-5 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-4">
          <p className="text-xs font-black uppercase text-slate-500">Account status</p>
          <h3 className="mt-1 text-lg font-black text-slate-950">Change account status</h3>
          <p className="mt-3 text-sm leading-6 text-slate-600">Set account status for {mailbox.email}.</p>
        </div>
        <form className="grid gap-4" onSubmit={(event) => { event.preventDefault(); if (!busy) onSubmit(); }}>
          <div className="grid gap-2">
            {MAILBOX_ACCOUNT_STATUSES.map((item) => {
              const selected = status === item.value;
              return (
                <button
                  key={item.value}
                  type="button"
                  onClick={() => onStatusChange(item.value)}
                  className={`flex items-start justify-between gap-4 rounded-lg border px-4 py-3 text-left transition ${
                    selected
                      ? "border-[color-mix(in_srgb,var(--accent)_36%,white)] bg-[color-mix(in_srgb,var(--accent)_8%,white)]"
                      : "border-slate-200 bg-white hover:bg-slate-50"
                  }`}
                  aria-pressed={selected}
                >
                  <span className="min-w-0">
                    <span className="block text-sm font-black text-slate-950">{item.label}</span>
                    <span className="mt-1 block text-sm font-semibold leading-5 text-slate-600">{item.description}</span>
                  </span>
                  <Badge tone={item.tone}>{item.label}</Badge>
                </button>
              );
            })}
          </div>
          {error ? <p className="text-sm font-bold text-rose-600">{error}</p> : null}
          <DialogActions busy={busy} submitLabel="Save status" busyLabel="Saving..." onClose={onClose} />
        </form>
      </section>
    </div>
  );
}

function MailboxAliasDialog({
  mailbox,
  aliasEmail,
  error,
  busy,
  canSubmit,
  onAliasEmailChange,
  onClose,
  onAddAlias,
  onRemoveAlias,
}: {
  mailbox: Mailbox;
  aliasEmail: string;
  error: string;
  busy: boolean;
  canSubmit: boolean;
  onAliasEmailChange: (value: string) => void;
  onClose: () => void;
  onAddAlias: () => void;
  onRemoveAlias: (alias: string) => void;
}) {
  const aliases = mailbox.aliases || [];
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-lg rounded-xl border border-slate-200 bg-white p-5 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-4">
          <p className="text-xs font-black uppercase text-slate-500">Alias</p>
          <h3 className="mt-1 text-lg font-black text-slate-950">Mailbox aliases</h3>
          <p className="mt-3 text-sm leading-6 text-slate-600">Manage alternate addresses for {mailbox.email}.</p>
        </div>
        <div className="mb-4 grid gap-2 rounded-xl border border-slate-200 bg-slate-50 p-3">
          {aliases.length ? aliases.map((alias) => (
            <div key={alias} className="flex items-center justify-between gap-3 rounded-lg bg-white px-3 py-2">
              <span className="min-w-0 truncate text-sm font-semibold text-slate-700">{alias}</span>
              <button type="button" disabled={busy} onClick={() => onRemoveAlias(alias)} className="text-xs font-black text-rose-600 disabled:opacity-50">Remove</button>
            </div>
          )) : <p className="text-sm font-semibold text-slate-500">No aliases yet.</p>}
        </div>
        <form className="grid gap-3" onSubmit={(event) => { event.preventDefault(); if (!busy) onAddAlias(); }}>
          <input value={aliasEmail} onChange={(event) => onAliasEmailChange(event.target.value)} className="field h-11" placeholder="alias@example.com" />
          {error ? <p className="text-sm font-bold text-rose-600">{error}</p> : null}
          <DialogActions busy={busy} submitLabel="Add alias" busyLabel="Saving..." onClose={onClose} disabled={!canSubmit} />
        </form>
      </section>
    </div>
  );
}

function MailboxForwardDialog({
  mailbox,
  addressesText,
  keepLocalCopy,
  error,
  busy,
  onAddressesTextChange,
  onKeepLocalCopyChange,
  onClose,
  onSubmit,
}: {
  mailbox: Mailbox;
  addressesText: string;
  keepLocalCopy: boolean;
  error: string;
  busy: boolean;
  onAddressesTextChange: (value: string) => void;
  onKeepLocalCopyChange: (value: boolean) => void;
  onClose: () => void;
  onSubmit: () => void;
}) {
  const forwardingAllowed = mailbox.forward_allowed !== false;
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-lg rounded-xl border border-slate-200 bg-white p-5 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-4">
          <p className="text-xs font-black uppercase text-slate-500">Forward</p>
          <h3 className="mt-1 text-lg font-black text-slate-950">Mail forwarding</h3>
          <p className="mt-3 text-sm leading-6 text-slate-600">Set forwarding for {mailbox.email}. Permission is checked on save.</p>
        </div>
        {!mailbox.forward_allowed ? <InlineNotice tone="warning">This mailbox does not have permission to use forwarding.</InlineNotice> : null}
        <form className="mt-3 grid gap-3" onSubmit={(event) => { event.preventDefault(); if (!busy && forwardingAllowed) onSubmit(); }}>
          <textarea
            value={addressesText}
            onChange={(event) => onAddressesTextChange(event.target.value)}
            className="field min-h-28 py-3 disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-400"
            placeholder="forward@example.com, archive@example.com"
            disabled={!forwardingAllowed || busy}
          />
          <label className="flex items-center gap-2 text-sm font-semibold text-slate-700">
            <input
              type="checkbox"
              checked={keepLocalCopy}
              onChange={(event) => onKeepLocalCopyChange(event.target.checked)}
              className="h-4 w-4 rounded border-slate-300 text-[var(--accent)] disabled:cursor-not-allowed disabled:opacity-50"
              disabled={!forwardingAllowed || busy}
            />
            Keep a copy in this mailbox
          </label>
          <p className="text-xs font-semibold text-slate-500">Leave the address field empty to turn forwarding off.</p>
          {error ? <p className="text-sm font-bold text-rose-600">{error}</p> : null}
          <DialogActions busy={busy} submitLabel="Save forwarding" busyLabel="Saving..." onClose={onClose} disabled={!forwardingAllowed || Boolean(error)} />
        </form>
      </section>
    </div>
  );
}

function DialogActions({ busy, submitLabel, busyLabel, disabled, onClose }: { busy: boolean; submitLabel: string; busyLabel: string; disabled?: boolean; onClose: () => void }) {
  return (
    <div className="flex justify-end gap-2">
      <button type="button" onClick={onClose} className="h-10 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700">
        Cancel
      </button>
      <button type="submit" disabled={disabled || busy} className="theme-button h-10 px-4 text-sm disabled:opacity-50">
        {busy ? busyLabel : submitLabel}
      </button>
    </div>
  );
}

function ConfirmDialog({
  title,
  message,
  confirmLabel,
  tone = "default",
  busy,
  onClose,
  onConfirm,
}: {
  title: string;
  message: string;
  confirmLabel: string;
  tone?: "default" | "danger";
  busy: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  return (
    <div className="fixed inset-0 z-[10000] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <section className="w-full max-w-md rounded-xl border border-slate-200 bg-white p-5 shadow-soft" onClick={(event) => event.stopPropagation()}>
        <div className="mb-4">
          <p className="text-xs font-black uppercase text-slate-500">Confirm</p>
          <h3 className="mt-1 text-lg font-black text-slate-950">{title}</h3>
          <p className="mt-3 text-sm leading-6 text-slate-600">{message}</p>
        </div>
        <div className="flex justify-end gap-2">
          <button type="button" onClick={onClose} className="h-10 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700">
            Cancel
          </button>
          <button
            type="button"
            onClick={onConfirm}
            disabled={busy}
            className={`h-10 rounded-lg px-4 font-bold text-white disabled:opacity-50 ${tone === "danger" ? "bg-rose-600 hover:bg-rose-700" : "theme-button"}`}
          >
            {busy ? "Working..." : confirmLabel}
          </button>
        </div>
      </section>
    </div>
  );
}

function getMailboxQuota(mailbox: Mailbox) {
  const usedKb = Number(mailbox.quota_used_kb || 0);
  const limitKb = Number(mailbox.quota_limit_kb || 0) || Number(mailbox.quota_mb || 0) * 1024;
  const rawPercent = Number(mailbox.quota_percent || 0);
  const available = limitKb > 0;
  const percent = available ? Math.max(0, Math.min(100, rawPercent || (usedKb / limitKb) * 100)) : 0;
  const usedLabel = formatStorage(usedKb);
  const limitLabel = available ? formatStorage(limitKb) : "—";
  const percentLabel = available ? `${percent.toFixed(0)}%` : "ข้อมูลไม่เพียงพอ";
  return {
    available,
    usedKb,
    limitKb,
    percent,
    usedLabel,
    limitLabel,
    percentLabel,
    summary: available ? `${usedLabel} of ${limitLabel}` : "ข้อมูลโควต้ายังไม่เพียงพอที่จะแสดง",
    summaryCompact: available ? `${percentLabel} · ${usedLabel} of ${limitLabel}` : "ข้อมูลไม่เพียงพอ",
  };
}

function isMailboxPostmaster(mailbox: Mailbox) {
  return mailbox.role === "postmaster" || Boolean(mailbox.is_postmaster);
}

function formatStorage(kb: number) {
  if (!kb || kb <= 0) return "0 KB";
  if (kb < 1024) return `${kb} KB`;
  const mb = kb / 1024;
  if (mb < 1024) return `${mb.toFixed(mb >= 100 ? 0 : 1)} MB`;
  const gb = mb / 1024;
  return `${gb.toFixed(gb >= 100 ? 0 : 1)} GB`;
}

function formatLastLogin(iso: string, days: number) {
  if (days < 0 && !iso) return "Never logged in";
  if (days < 1) return "Today";
  if (days === 1) return "1 day ago";
  if (days < 7) return `${days} days ago`;
  if (days < 30) return `${Math.round(days / 7)} weeks ago`;
  if (days < 365) return `${Math.round(days / 30)} months ago`;
  return `${Math.round(days / 365)} years ago`;
}

function validateEmailLocalPart(value: string) {
  const localPart = value.trim().toLowerCase();
  if (!localPart) return "";
  if (localPart.includes("@")) {
    return "Enter only the part before @.";
  }
  if (localPart.startsWith(".") || localPart.endsWith(".") || localPart.includes("..")) {
    return "Email address format is invalid.";
  }
  if (!/^[a-z0-9._%+-]+$/.test(localPart)) {
    return "Email address can use letters, numbers, dots, underscores, percent signs, plus signs, and hyphens only.";
  }
  return "";
}

function validateEmailAddress(value: string) {
  const email = value.trim().toLowerCase();
  if (!email) return "";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    return "Email address format is invalid.";
  }
  const [localPart] = email.split("@", 1);
  return validateEmailLocalPart(localPart);
}

function parseAddressList(value: string) {
  return value
    .split(/[\n,;]+/)
    .map((item) => item.trim().toLowerCase())
    .filter(Boolean);
}

function normalizeCreateMailboxError(message: string) {
  const text = message.trim();
  if (!text) return "";
  const lower = text.toLowerCase();
  if (lower.includes("already exists") || lower.includes("account exists") || lower.includes("mailbox exists") || lower.includes("account_exists")) {
    return "This mailbox already exists.";
  }
  if (lower.includes("invalid") && (lower.includes("email") || lower.includes("account") || lower.includes("local_part"))) {
    return "Email address format is invalid.";
  }
  return text;
}

function validatePassword(password: string) {
  if (!password) return "";
  if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,16}$/.test(password)) {
    return "Password must be 8-16 characters and include uppercase, lowercase, and a number";
  }
  return "";
}
