import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { MailGate } from "@/components/mail-gate";
import type { MemberMailboxViewState } from "@/components/mail-members-panel";
import type { MailSetupSection } from "@/components/mail-setup-workspace";
import { requireSessionUser } from "@/lib/auth";
import {
  getAiAssistOverviewByOwnerEmail,
  getManagedMembersByOwnerEmail,
  type MailAiAssistOverview,
  type ManagedMailboxMember
} from "@/lib/mail-automation";
import { getAutoSendOverviewByOwnerEmail, type MailAutoSendOverview } from "@/lib/mail-auto-send";
import {
  getMailBillingCancellationOverviewByOwnerEmail,
  type MailBillingCancellationOverview
} from "@/lib/billing-cancellation";
import type { MailListSortOrder } from "@/lib/mail-layout";
import { plainTextToHtml, sanitizeMailboxHtml } from "@/lib/mail-html";
import { MAIL_QUOTE_INLINE_STYLE } from "@/lib/mail-quote-style";
import { buildMailSignatureComposeContent, getMailSignatureByEmail } from "@/lib/mail-signature";
import {
  getMailAppOverviewByEmail,
  getMailLayoutPreferencesByEmail,
  getMailboxMessageRawSourceByEmail,
  getPreferredNotificationEmailByEmail,
  getRecoveryEmailOverviewByEmail,
  getMailSetupOverviewByEmail,
  shouldShowDkimRotationNoticeByEmail,
  type MailMessageDetail,
  type MailMessageFilter,
  type MailSearchField
} from "@/lib/official-mail";
import { DEFAULT_MAILBOX_PAGE_SIZE, normalizeMailboxPageSize } from "@/lib/mailbox-page-size";
import {
  resolveMailBillingProvider,
  resolvePolarLocalizedPrice,
} from "@/lib/billing-region-server";
import { resolveRequestLocale } from "@/lib/i18n-server";
import { getCachedMailboxMessageTranslationForEmail } from "@/lib/mail-message-translation";
import { countMailBillingSeatsFromManagedMembers, createMailPlanSummary } from "@/lib/mail-billing";
import { hasOperationalBenefitByOwnerEmail } from "@/lib/mail-operational-benefit";
import {
  pickMailBillingHistoryPage,
  pickMailBillingHistoryRangePreset,
  pickMailBillingTab,
  resolveMailBillingHistoryState,
  type MailBillingHistoryState
} from "@/lib/mail-billing-history";
import {
  getMailBillingOwnershipByEmail,
  getMailBillingHistoryByOwnerEmail,
  getMailBillingOverviewByOwnerEmail,
  isTossPaymentsBillingEnabledForEmail,
  type MailBillingHistoryPage,
  type MailBillingOverview
} from "@/lib/toss-pay";
import {
  getPolarBillingOverviewByOwnerEmail,
  getPolarMailPlanBillingStatus,
  type PolarBillingOverview,
} from "@/lib/polar-billing";

type MailPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

type NoticeTone = "error" | "success" | "warning";

function pickParam(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

function pickRawSourceBcc(rawSource: string | null) {
  if (!rawSource) {
    return "";
  }

  const headers = rawSource.split(/\r?\n\r?\n/, 1)[0]?.replace(/\r?\n[\t ]+/g, " ");
  return headers?.match(/^Bcc:\s*(.+)$/im)?.[1]?.trim() ?? "";
}

function pickMessageFilter(value: string | string[] | undefined): MailMessageFilter {
  const picked = pickParam(value);

  if (picked === "unread" || picked === "important" || picked === "attachments") {
    return picked;
  }

  return "all";
}

function pickPositivePage(value: string | string[] | undefined) {
  const picked = Number(pickParam(value) ?? "1");

  if (!Number.isFinite(picked) || picked < 1) {
    return 1;
  }

  return Math.floor(picked);
}

function pickPositiveInteger(value: string | string[] | undefined) {
  const picked = Number(pickParam(value) ?? "");

  if (!Number.isFinite(picked) || picked < 1) {
    return null;
  }

  return Math.floor(picked);
}

function pickSearchField(value: string | string[] | undefined): MailSearchField {
  const picked = pickParam(value);

  if (picked === "correspondent" || picked === "from" || picked === "to" || picked === "subject" || picked === "body") {
    return picked;
  }

  return "all";
}

function pickComposeMode(value: string | string[] | undefined) {
  const picked = pickParam(value);

  if (picked === "reply" || picked === "replyAll" || picked === "forward" || picked === "draft") {
    return picked;
  }

  return "new";
}

function pickSortOrder(value: string | string[] | undefined, fallback: MailListSortOrder): MailListSortOrder {
  const picked = pickParam(value);

  return picked === "oldest" || picked === "latest" ? picked : fallback;
}

function padNumber(value: number) {
  return String(value).padStart(2, "0");
}

function formatComposeFullDate(value: string) {
  const date = new Date(value);
  const weekdays = ["일", "월", "화", "수", "목", "금", "토"];
  const hours = date.getHours();
  const period = hours >= 12 ? "PM" : "AM";
  const hour12 = hours % 12 || 12;

  return `${date.getFullYear()}.${padNumber(date.getMonth() + 1)}.${padNumber(
    date.getDate()
  )} (${weekdays[date.getDay()]}) ${hour12}:${padNumber(date.getMinutes())} ${period}`;
}

function escapeHtml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function prefixedSubject(subject: string, prefix: "Fwd:" | "Re:") {
  const trimmed = subject.trim();

  if (!trimmed) {
    return prefix;
  }

  return trimmed.toLowerCase().startsWith(prefix.toLowerCase()) ? trimmed : `${prefix} ${trimmed}`;
}

function splitAddressList(value: string) {
  return value
    .split(",")
    .map((address) => address.trim())
    .filter(Boolean);
}

function originalMessageHtml(message: MailMessageDetail) {
  return (
    message.bodyHtmlDisplay?.trim() ||
    message.bodyHtml?.trim() ||
    plainTextToHtml(message.bodyText.trim() || message.snippet.trim() || "")
  );
}

function quotedMessageBody(message: MailMessageDetail) {
  return [
    "",
    "",
    "---------- 원본 메일 ----------",
    `보낸사람: ${message.fromName ? `${message.fromName} <${message.fromAddress}>` : message.fromAddress}`,
    `보낸시각: ${formatComposeFullDate(message.receivedAt)}`,
    `제목: ${message.subject}`,
    `받는사람: ${message.toAddresses}`,
    "",
    message.bodyText.trim() || message.snippet.trim() || ""
  ].join("\n");
}

function quotedMessageHtml(message: MailMessageDetail, action: "forward" | "reply" | "replyAll") {
  const sender = message.fromName ? `${message.fromName} <${message.fromAddress}>` : message.fromAddress;
  const bodyHtml = originalMessageHtml(message);
  const replyHeader = `${formatComposeFullDate(message.receivedAt)}, ${sender}님이 작성:`;

  if (action === "forward") {
    return [
      "<p><br></p>",
      "<p><br></p>",
      "<p>---------- 원본 메일 ----------</p>",
      `<p>보낸사람: ${escapeHtml(sender)}</p>`,
      `<p>보낸시각: ${escapeHtml(formatComposeFullDate(message.receivedAt))}</p>`,
      `<p>제목: ${escapeHtml(message.subject)}</p>`,
      `<p>받는사람: ${escapeHtml(message.toAddresses)}</p>`,
      "<p><br></p>",
      `<blockquote style="${MAIL_QUOTE_INLINE_STYLE}">${bodyHtml}</blockquote>`
    ].join("");
  }

  return [
    "<p><br></p>",
    "<p><br></p>",
    `<div>${escapeHtml(replyHeader)}</div>`,
    `<blockquote style="${MAIL_QUOTE_INLINE_STYLE}">${bodyHtml}</blockquote>`
  ].join("");
}

function resolveSourceComposeDefaults(input: {
  bcc: string;
  body: string;
  bodyHtml: string;
  cc: string;
  mode: "draft" | "forward" | "new" | "reply" | "replyAll";
  message: MailMessageDetail | null;
  ownAddresses: string[];
  subject: string;
  to: string;
}) {
  if (input.mode === "new" || !input.message) {
    return {
      bcc: input.bcc,
      body: input.body,
      bodyHtml: input.bodyHtml,
      cc: input.cc,
      subject: input.subject,
      to: input.to
    };
  }

  if (input.mode === "draft") {
    const [toAddresses = "", ccAddresses = ""] = input.message.toAddresses.split(/\s*\/\s*참조:\s*/, 2);

    return {
      bcc: input.bcc,
      body: input.message.bodyText,
      bodyHtml: input.message.bodyHtml ?? "",
      cc: ccAddresses,
      subject: input.message.subject,
      to: toAddresses
    };
  }

  if (input.mode === "forward") {
    return {
      bcc: "",
      body: quotedMessageBody(input.message),
      bodyHtml: quotedMessageHtml(input.message, "forward"),
      cc: "",
      subject: prefixedSubject(input.message.subject, "Fwd:"),
      to: ""
    };
  }

  if (input.mode === "replyAll") {
    const ownAddresses = new Set(input.ownAddresses.map((address) => address.toLowerCase()));
    const recipients = [input.message.fromAddress, ...splitAddressList(input.message.toAddresses)].filter(
      (address, index, array) => {
        const normalized = address.toLowerCase();

        return !ownAddresses.has(normalized) && array.findIndex((item) => item.toLowerCase() === normalized) === index;
      }
    );

    return {
      bcc: "",
      body: quotedMessageBody(input.message),
      bodyHtml: quotedMessageHtml(input.message, "replyAll"),
      cc: recipients.slice(1).join(", "),
      subject: prefixedSubject(input.message.subject, "Re:"),
      to: recipients[0] ?? ""
    };
  }

  return {
    bcc: "",
    body: quotedMessageBody(input.message),
    bodyHtml: quotedMessageHtml(input.message, "reply"),
    cc: "",
    subject: prefixedSubject(input.message.subject, "Re:"),
    to: input.message.fromAddress
  };
}

const noticeMap: Record<string, { tone: NoticeTone; message: string }> = {
  "domain-required": {
    tone: "error",
    message: "도메인과 대표 메일 아이디를 모두 입력해주세요."
  },
  "domain-taken": {
    tone: "error",
    message: "이미 다른 계정에서 사용 중인 도메인입니다."
  },
  "mailbox-taken": {
    tone: "error",
    message: "이미 등록된 대표 메일 주소입니다. 다른 메일 아이디를 사용해주세요."
  },
  "invalid-local-part": {
    tone: "error",
    message: "메일 아이디는 영문 소문자, 숫자, 점(.), 하이픈(-), 밑줄(_)만 사용할 수 있습니다."
  },
  "password-required": {
    tone: "error",
    message: "변경할 비밀번호와 확인 값을 모두 입력해주세요."
  },
  "password-mismatch": {
    tone: "error",
    message: "비밀번호와 확인 값이 서로 다릅니다."
  },
  "security-password-required": {
    tone: "error",
    message: "대표 메일 비밀번호 정보가 없어 다시 저장이 필요합니다. 계정 설정에서 비밀번호를 먼저 등록해주세요."
  },
  "mail-config": {
    tone: "error",
    message: "메일 서버 연결 설정이 누락되어 있습니다. 관리자에게 문의해주세요."
  },
  "mail-auth": {
    tone: "error",
    message: "메일 서버 인증에 실패했습니다. 잠시 후 다시 시도해주세요."
  },
  "mail-domain-exists": {
    tone: "error",
    message: "같은 도메인이 이미 등록되어 있어 자동 연결을 멈췄습니다. 기존 도메인 사용 상태를 먼저 확인해주세요."
  },
  "mail-setup": {
    tone: "error",
    message: "도메인 또는 메일함 생성 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요."
  },
  "dkim-regeneration": {
    tone: "error",
    message: "DKIM 키를 다시 발급하지 못했습니다. 잠시 후 다시 시도하거나 관리자에게 문의해주세요."
  },
  "dkim-usage": {
    tone: "error",
    message: "DKIM 사용 설정을 변경하지 못했습니다. 잠시 후 다시 시도해주세요."
  },
  "verify-pending": {
    tone: "error",
    message:
      "현재 저장된 DNS 값 또는 메일 서버 등록 상태가 일치하지 않습니다. DNS 반영과 메일함 연결 상태를 다시 확인해주세요."
  },
  provisioned: {
    tone: "success",
    message: "대표 메일함 등록이 완료되었습니다. 아래 DNS 값을 복사해 도메인 관리 화면에 입력하세요."
  },
  "dkim-regenerated": {
    tone: "success",
    message: "새 DKIM 키를 발급했습니다. DNS의 DKIM 값을 새 값으로 바꾼 뒤 연결 상태를 확인해주세요."
  },
  "dkim-enabled": {
    tone: "success",
    message: "DKIM 사용을 켰습니다. DNS의 DKIM 값이 정상인지 연결 상태를 확인해주세요."
  },
  "dkim-disabled": {
    tone: "success",
    message: "DKIM 검증을 건너뛰도록 설정했습니다. SPF와 DMARC는 계속 필요합니다."
  },
  "password-updated": {
    tone: "success",
    message: "대표 메일 로그인 비밀번호를 변경했습니다. 외부 연결 전용 비밀번호는 별도로 유지됩니다."
  },
  verified: {
    tone: "success",
    message: "DNS 검증이 완료되었습니다. 이제 메일함에서 바로 송수신을 시작할 수 있습니다."
  },
  "verified-with-warning": {
    tone: "warning",
    message:
      "도메인 연결은 완료됐지만 DKIM 설정이 일치하지 않습니다. 발신 메일이 스팸으로 분류되지 않도록 DKIM 값을 확인해주세요."
  },
  "ai-assist-saved": {
    tone: "success",
    message: "AI 어시스트 브릿지를 저장했습니다. 이제 새 메일 요약과 답장 릴레이가 활성화됩니다."
  },
  "ai-assist-disabled": {
    tone: "success",
    message: "AI 어시스트 브릿지를 비활성화했습니다."
  },
  "auto-send-saved": {
    tone: "success",
    message: "자동발송 예약 설정을 저장했습니다."
  },
  "auto-send-disabled": {
    tone: "success",
    message: "자동발송 예약을 비활성화했습니다."
  },
  "auto-send-invalid": {
    tone: "error",
    message: "자동발송 예약 값이 올바르지 않습니다. 다시 확인해주세요."
  },
  "auto-send-invalid-email": {
    tone: "error",
    message: "자동발송 수신자 이메일 형식이 올바르지 않습니다."
  },
  "auto-send-required": {
    tone: "error",
    message: "예약 활성화에는 수신자와 제목·본문이 포함된 보낼 내용이 필요합니다."
  },
  "auto-send-plan-required": {
    tone: "error",
    message: "자동발송 예약은 성장 플랜에서 사용할 수 있습니다."
  },
  "member-created": {
    tone: "success",
    message: "새 멤버 메일함을 추가했습니다."
  },
  "member-updated": {
    tone: "success",
    message: "멤버 메일함 정보를 수정했습니다."
  },
  "member-deleted": {
    tone: "success",
    message: "멤버 메일함을 삭제했습니다."
  },
  send: {
    tone: "success",
    message: "메일을 발송했습니다."
  },
  "send-queued": {
    tone: "success",
    message: "메일을 발송했습니다."
  },
  "send-individual": {
    tone: "success",
    message: "메일을 개별 발송했습니다."
  },
  "send-individual-queued": {
    tone: "success",
    message: "메일을 개별 발송했습니다."
  },
  draft: {
    tone: "success",
    message: "초안을 저장했습니다."
  },
  refresh: {
    tone: "success",
    message: "메일함을 다시 동기화했습니다."
  },
  "mark-read": {
    tone: "success",
    message: "선택한 메일을 읽음 처리했습니다."
  },
  "mark-unread": {
    tone: "success",
    message: "선택한 메일을 안읽음 처리했습니다."
  },
  "move-trash": {
    tone: "success",
    message: "선택한 메일을 휴지통으로 이동했습니다."
  },
  "move-trash-delete": {
    tone: "success",
    message: "선택한 메일을 휴지통으로 이동하고, 휴지통에 있던 메일은 영구 삭제했습니다."
  },
  "delete-permanent": {
    tone: "success",
    message: "선택한 메일을 영구 삭제했습니다."
  },
  "move-spam": {
    tone: "success",
    message: "선택한 발송자의 모든 메일을 스팸함으로 이동했습니다."
  },
  "move-unspam": {
    tone: "success",
    message: "선택한 메일을 받은메일함으로 이동하고 스팸 분류를 해제했습니다."
  },
  "move-folder": {
    tone: "success",
    message: "선택한 메일을 폴더로 이동했습니다."
  },
  "move-rule": {
    tone: "success",
    message: "앞으로 같은 발신자에게 오는 메일을 선택한 메일함으로 이동합니다."
  },
  "move-rule-existing": {
    tone: "success",
    message: "앞으로 수신되는 메일과 기존 받은 메일을 선택한 메일함으로 이동했습니다."
  },
  "sender-spam": {
    tone: "success",
    message: "해당 발송자를 스팸 자동 분류 대상으로 등록하고 기존 메일을 스팸함으로 이동했습니다."
  },
  "sender-unspam": {
    tone: "success",
    message: "해당 발송자를 스팸 자동 분류 대상에서 해제했습니다."
  },
  "sender-unspam-moved": {
    tone: "success",
    message: "해당 발송자를 스팸 자동 분류 대상에서 해제하고 기존 메일을 선택한 메일함으로 이동했습니다."
  },
  "move-sent-only": {
    tone: "error",
    message: "보낸 메일만 보낸메일함으로 이동할 수 있습니다."
  },
  "continue-move-custom-folder-only": {
    tone: "error",
    message: "계속 이동은 내 메일함을 선택했을 때 설정할 수 있습니다."
  },
  "continue-move-requires-one-sender": {
    tone: "error",
    message: "계속 이동은 같은 발신자의 받은 메일만 선택해 설정할 수 있습니다."
  },
  "move-conflict": {
    tone: "error",
    message: "메일함 상태가 최신이 아니어서 이동에 실패했습니다. 메일함을 다시 동기화한 뒤 다시 시도해주세요."
  },
  "folder-name-required": {
    tone: "error",
    message: "새 메일함 이름을 입력해주세요."
  },
  "folder-name-exists": {
    tone: "error",
    message: "같은 이름의 메일함이 이미 있습니다."
  },
  "mailbox-connected": {
    tone: "success",
    message: "메일함 비밀번호를 저장하고 실동기화를 완료했습니다."
  },
  "compose-required": {
    tone: "error",
    message: "받는 사람(또는 참조/숨은참조), 제목, 본문 또는 첨부 파일을 입력해주세요."
  },
  "free-send-limit-daily": {
    tone: "error",
    message: "무료 플랜 대표 계정은 하루 30건까지 메일을 보낼 수 있습니다."
  },
  "invalid-recipient": {
    tone: "error",
    message: "받는 사람, 참조, 숨은참조에는 올바른 이메일 주소만 입력할 수 있습니다."
  },
  "mailbox-connection-failed": {
    tone: "error",
    message: "메일함 연결 검증에 실패했습니다."
  },
  "mailbox-password-required": {
    tone: "error",
    message: "메일함 비밀번호를 입력해주세요."
  },
  "mailbox-password-must-differ": {
    tone: "error",
    message: "계정 비밀번호는 메일 서버 연결용 비밀번호로 사용할 수 없습니다."
  },
  "ai-assist-config-missing": {
    tone: "error",
    message: "AI 어시스트 시스템 메일 설정이 비어 있습니다."
  },
  "ai-assist-invalid-email": {
    tone: "error",
    message: "알림 수신 주소에는 올바른 이메일만 입력할 수 있습니다."
  },
  "ai-assist-notification-required": {
    tone: "error",
    message: "AI 알림을 받을 이메일 주소를 입력해주세요."
  },
  "ai-assist-plan-required": {
    tone: "error",
    message: "AI 어시스트는 성장 플랜에서만 사용할 수 있습니다. 결제 및 구독에서 성장 플랜을 시작해주세요."
  },
  "member-required": {
    tone: "error",
    message: "멤버 이름, 메일 아이디, 비밀번호를 모두 입력해주세요."
  },
  "member-password-mismatch": {
    tone: "error",
    message: "멤버 메일함 비밀번호와 확인 값이 서로 다릅니다."
  },
  "member-mailbox-taken": {
    tone: "error",
    message: "이미 사용 중인 멤버 메일 주소입니다."
  },
  "member-not-found": {
    tone: "error",
    message: "대상 멤버 메일함을 찾을 수 없습니다."
  },
  "member-management-forbidden": {
    tone: "error",
    message: "멤버 관리는 대표 관리자 계정에서만 접근할 수 있습니다."
  },
  "member-plan-required": {
    tone: "error",
    message: "팀 멤버 추가는 성장플랜 구독 중일 때 가능합니다."
  },
  "member-billing-inactive": {
    tone: "error",
    message: "결제수단이 활성 상태가 아니어서 멤버 추가 결제를 진행할 수 없습니다."
  },
  "member-charge-failed": {
    tone: "error",
    message: "멤버 추가 결제 인증에 실패했습니다. 결제수단 상태를 확인해주세요."
  },
  "member-create-refunded": {
    tone: "error",
    message: "멤버 생성 중 오류가 발생해 방금 결제는 자동으로 취소했습니다."
  },
  "member-charge-refund-failed": {
    tone: "error",
    message: "멤버 생성은 실패했습니다. 결제 취소가 자동 완료되지 않았으므로 결제내역을 바로 확인해주세요."
  },
  "compose-failed": {
    tone: "error",
    message: "메일 처리 중 오류가 발생했습니다."
  },
  "imap-failed": {
    tone: "error",
    message: "IMAP 동기화 중 오류가 발생했습니다."
  },
  "mailbox-auth": {
    tone: "error",
    message: "메일함 인증 정보가 없거나 올바르지 않습니다."
  },
  "send-cooldown-active": {
    tone: "error",
    message: "1분 안에 단건 메일을 10건 연속 발송해 최대 60초 동안 추가 단건 발송이 제한됩니다."
  },
  "refresh-failed": {
    tone: "error",
    message: "메일함 새로고침 중 오류가 발생했습니다."
  },
  "read-failed": {
    tone: "error",
    message: "읽음 상태 변경 중 오류가 발생했습니다."
  },
  "star-failed": {
    tone: "error",
    message: "중요 표시 변경 중 오류가 발생했습니다."
  },
  "move-failed": {
    tone: "error",
    message: "메일 이동 중 오류가 발생했습니다."
  },
  "billing-registration-returned": {
    tone: "success",
    message: "결제수단 등록을 마쳤습니다. 잠시 후 상태가 반영되면 바로 사용할 수 있습니다."
  },
  "billing-registration-failed": {
    tone: "error",
    message: "토스 앱 자동결제 등록이 취소되었거나 실패했습니다."
  },
  "polar-checkout-complete": {
    tone: "success",
    message: "Polar 카드 등록과 성장 플랜 결제가 완료되었습니다. 결제 상태를 반영하고 있습니다."
  },
  "billing-management-forbidden": {
    tone: "error",
    message: "플랜 변경과 결제 관리는 각 도메인의 대표 관리자 계정에서만 가능합니다."
  },
  "sender-spam-failed": {
    tone: "error",
    message: "발송자 스팸 설정 처리 중 오류가 발생했습니다."
  },
  "smtp-failed": {
    tone: "error",
    message: "SMTP 발송 중 오류가 발생했습니다."
  },
  system: {
    tone: "error",
    message: "처리 중 오류가 발생했습니다."
  }
};

const setupSections: MailSetupSection[] = [
  "account",
  "contacts",
  "classification",
  "spam",
  "storage",
  "domain",
  "assistant",
  "integrations",
  "members",
  "billing",
  "language"
];

export default async function MailPage({ searchParams }: MailPageProps) {
  const user = await requireSessionUser();
  const requestHeaders = await headers();
  const locale = await resolveRequestLocale(user.preferredLocale);
  const billingProvider = resolveMailBillingProvider(requestHeaders, user.preferredLocale);
  const polarPrice = resolvePolarLocalizedPrice(requestHeaders, user.preferredLocale);
  const domainSetupAssistanceAvailable = billingProvider === "toss-pay";
  const params = searchParams ? await searchParams : {};
  const folder = pickParam(params.folder) ?? "inbox";
  const panel = pickParam(params.panel);
  const sectionParam = pickParam(params.section);
  const normalizedSectionParam =
    sectionParam === "security" ? "account" : sectionParam === "addresses" ? "members" : sectionParam;
  const requestedView = pickParam(params.view);
  const view = requestedView === "compose" || requestedView === "files" ? requestedView : "list";
  const page = pickPositivePage(params.page);
  const pageSize = normalizeMailboxPageSize(pickParam(params.pageSize));
  const messageFilter = pickMessageFilter(params.tab);
  const searchField = pickSearchField(params.field);
  const searchQuery = pickParam(params.q)?.trim() ?? "";
  const composeSelf = pickParam(params.self) === "1";
  const composeTo = pickParam(params.to) ?? "";
  const composeCc = pickParam(params.cc) ?? "";
  const composeBcc = pickParam(params.bcc) ?? "";
  const composeSubject = pickParam(params.subject) ?? "";
  const composeBody = pickParam(params.body) ?? "";
  const composeBodyHtml = pickParam(params.bodyHtml) ?? "";
  const composeMode = pickComposeMode(params.composeMode);
  const detailParam = pickParam(params.detail);
  const detailView = detailParam === "source" || detailParam === "logs" ? detailParam : "body";
  const billingTab = pickMailBillingTab(params.billingTab);
  const billingHistoryState = resolveMailBillingHistoryState({
    from: pickParam(params.billingFrom),
    page: pickMailBillingHistoryPage(params.billingPage),
    rangePreset: pickMailBillingHistoryRangePreset(params.billingRange),
    to: pickParam(params.billingTo)
  });
  const memberMailboxId = pickPositiveInteger(params.memberMailbox);
  const memberMailboxFolder = pickParam(params.memberFolder) ?? "inbox";
  const memberMailboxPage = pickPositivePage(params.memberPage);
  const memberMailboxMessageId = pickPositiveInteger(params.memberMessage);
  const details = pickParam(params.details);
  const messageParam = pickParam(params.message);
  const messageId = messageParam ? Number(messageParam) : null;
  const success = pickParam(params.success);
  const error = pickParam(params.error);
  const baseNotice = success ? noticeMap[success] : error ? noticeMap[error] : null;
  const currentPanel = !user.mailConfigured
    ? "setup"
    : panel === "setup"
      ? "setup"
      : panel === "auto-send"
        ? "auto-send"
        : "mail";
  const setupSection =
    normalizedSectionParam && setupSections.includes(normalizedSectionParam as MailSetupSection)
      ? (normalizedSectionParam as MailSetupSection)
      : "domain";
  const billingOwnership = await getMailBillingOwnershipByEmail(user.email);
  const canManageBilling = billingOwnership.canManageBilling;
  const billingOwnerEmail = billingOwnership.ownerEmail;
  const usesTossPayments = isTossPaymentsBillingEnabledForEmail(billingOwnerEmail);

  if (
    currentPanel === "setup" &&
    !canManageBilling &&
    (setupSection === "domain" || setupSection === "members" || setupSection === "billing")
  ) {
    redirect(user.mailConfigured ? "/mail?folder=all" : "/mail?panel=setup&section=account");
  }

  const storedLayoutPreferences = await getMailLayoutPreferencesByEmail(user.email);
  const layoutPreferences = {
    ...storedLayoutPreferences,
    sortOrder: pickSortOrder(params.sort, storedLayoutPreferences.sortOrder)
  };

  const [
    mailData,
    setupOverview,
    preferredNotificationEmail,
    recoveryEmailOverview,
    showDkimRotationNotice,
    signatureSettings
  ] = await Promise.all([
    currentPanel === "mail" || user.mailConfigured
      ? getMailAppOverviewByEmail(user.email, {
          folder,
          messageId: Number.isFinite(messageId) ? messageId : null,
          messageFilter,
          sortOrder: layoutPreferences.sortOrder,
          searchField,
          searchQuery,
          page,
          pageSize,
          includeOriginalBodyHtml: view === "compose",
          markMessageRead: currentPanel === "mail" && view !== "compose" && Number.isFinite(messageId)
        })
      : Promise.resolve(null),
    getMailSetupOverviewByEmail(user.email),
    getPreferredNotificationEmailByEmail(user.email),
    getRecoveryEmailOverviewByEmail(user.email),
    shouldShowDkimRotationNoticeByEmail(user.email),
    getMailSignatureByEmail(user.email).catch(() => ({
      enabled: false,
      html: "",
      imageUrl: null,
      imageWidth: 420,
      text: ""
    }))
  ]);
  let managedMembers: ManagedMailboxMember[] = [];
  let aiAssistOverview: MailAiAssistOverview | null = null;
  let autoSendOverview: MailAutoSendOverview | null = null;
  let billingOverview: MailBillingOverview | null = null;
  let polarBillingOverview: PolarBillingOverview | null = null;
  let billingCancellationOverview: MailBillingCancellationOverview | null = null;
  let billingHistoryPage: MailBillingHistoryPage | null = null;
  let memberMailboxView: MemberMailboxViewState | null = null;

  if (setupOverview) {
    const [
      membersResult,
      aiAssistResult,
      autoSendResult,
      billingResult,
      polarBillingResult,
      billingCancellationResult,
      billingHistoryResult
    ] = await Promise.all([
      getManagedMembersByOwnerEmail(billingOwnerEmail).catch(() => []),
      getAiAssistOverviewByOwnerEmail(user.email).catch(() => null),
      getAutoSendOverviewByOwnerEmail(user.email).catch(() => null),
      billingProvider === "toss-pay"
        ? getMailBillingOverviewByOwnerEmail(billingOwnerEmail, {
            recoverRemoteStatus: currentPanel === "setup" && setupSection === "billing"
          }).catch(() => null)
        : Promise.resolve(null),
      billingProvider === "polar"
        ? getPolarBillingOverviewByOwnerEmail(billingOwnerEmail, polarPrice).catch(() => null)
        : Promise.resolve(null),
      billingProvider === "toss-pay" && currentPanel === "setup" && setupSection === "billing"
        ? getMailBillingCancellationOverviewByOwnerEmail(billingOwnerEmail).catch(() => null)
        : Promise.resolve(null),
      billingProvider === "toss-pay" && currentPanel === "setup" && setupSection === "billing" && billingTab === "history"
        ? getMailBillingHistoryByOwnerEmail(billingOwnerEmail, {
            from: billingHistoryState.from,
            page: billingHistoryState.page,
            rangePreset: billingHistoryState.rangePreset,
            to: billingHistoryState.to
          }).catch(() => null)
        : Promise.resolve(null)
    ]);

    managedMembers = membersResult;
    aiAssistOverview = aiAssistResult;
    autoSendOverview = autoSendResult;
    billingOverview = billingResult;
    polarBillingOverview = polarBillingResult;
    billingCancellationOverview = billingCancellationResult;
    billingHistoryPage = billingHistoryResult;
  }

  if (currentPanel === "setup" && setupSection === "members" && memberMailboxId !== null) {
    if (!canManageBilling) {
      redirect(user.mailConfigured ? "/mail?folder=all" : "/mail?panel=setup&section=account");
    }

    const selectedMember = managedMembers.find((member) => member.id === memberMailboxId) ?? null;

    if (!selectedMember) {
      redirect("/mail?panel=setup&section=members&error=member-not-found");
    }

    const selectedMemberMailboxData = await getMailAppOverviewByEmail(selectedMember.email, {
      folder: memberMailboxFolder,
      messageId: memberMailboxMessageId,
      page: memberMailboxPage,
      pageSize: DEFAULT_MAILBOX_PAGE_SIZE,
      sortOrder: layoutPreferences.sortOrder
    });

    memberMailboxView = {
      data: selectedMemberMailboxData,
      folder: memberMailboxFolder,
      member: selectedMember,
      messageId: memberMailboxMessageId,
      page: memberMailboxPage
    };
  }

  const effectiveBillingHistoryState: MailBillingHistoryState = billingHistoryPage
    ? {
        from: billingHistoryPage.from,
        page: billingHistoryPage.page,
        rangePreset: billingHistoryPage.rangePreset,
        to: billingHistoryPage.to
      }
    : billingHistoryState;

  const notice = baseNotice && details ? { ...baseNotice, message: `${baseNotice.message} (${details})` } : baseNotice;
  const draftBcc =
    view === "compose" && composeMode === "draft" && messageId !== null
      ? pickRawSourceBcc(await getMailboxMessageRawSourceByEmail(user.email, messageId).catch(() => null))
      : "";
  const sourceComposeDefaults = resolveSourceComposeDefaults({
    bcc: draftBcc || composeBcc,
    body: composeBody,
    bodyHtml: composeBodyHtml,
    cc: composeCc,
    message: view === "compose" ? (mailData?.selectedMessage ?? null) : null,
    mode: composeMode,
    ownAddresses: [user.email, user.mailbox].filter(Boolean),
    subject: composeSubject,
    to: composeSelf ? user.email : composeTo
  });
  const sanitizedComposeBodyHtml =
    sanitizeMailboxHtml(sourceComposeDefaults.bodyHtml) ??
    (sourceComposeDefaults.body.trim() ? plainTextToHtml(sourceComposeDefaults.body) : "");
  const signatureComposeContent = buildMailSignatureComposeContent(signatureSettings);
  const initialMessageTranslation =
    mailData?.selectedMessage?.direction === "inbound"
      ? await getCachedMailboxMessageTranslationForEmail({
          email: user.email,
          messageId: mailData.selectedMessage.id,
          targetLocale: locale
        }).catch(() => null)
      : null;
  const tossSubscriptionStatus = billingOverview?.subscription?.status ?? null;
  const billingStatus = billingProvider === "polar"
    ? getPolarMailPlanBillingStatus(polarBillingOverview)
    : tossSubscriptionStatus === "active" && !billingOverview?.subscription?.initialPaymentComplete
      ? "pending"
      : tossSubscriptionStatus;
  const planSummary = createMailPlanSummary({
    billingSeatCount:
      polarBillingOverview?.billingSeatCount ??
      billingOverview?.billingSeatCount ??
      countMailBillingSeatsFromManagedMembers(managedMembers.length),
    billingStatus,
    isComplimentary: await hasOperationalBenefitByOwnerEmail(billingOwnerEmail),
    locale,
    localizedPrice:
      billingProvider === "polar" && polarBillingOverview
        ? {
            amount: polarBillingOverview.unitPrice,
            currency: polarBillingOverview.currency,
          }
        : billingProvider === "polar"
          ? polarPrice
          : null,
    seatChargeAmount: billingOverview?.subscription?.seatChargeAmount
  });

  return (
    <div className="mail-workspace min-h-screen bg-[#f6f7fb]">
      <main className="h-screen w-full overflow-hidden">
        <MailGate
          key={user.email}
          currentPanel={currentPanel}
          dkimRegenerated={success === "dkim-regenerated"}
          showDkimRotationNotice={showDkimRotationNotice}
          setupSection={setupSection}
          setupOverview={setupOverview}
          managedMembers={managedMembers}
          memberMailboxView={memberMailboxView}
          aiAssistOverview={aiAssistOverview}
          autoSendOverview={autoSendOverview}
          billingOverview={billingOverview}
          billingProvider={billingProvider}
          usesTossPayments={usesTossPayments}
          polarBillingOverview={polarBillingOverview}
          billingCancellationOverview={billingCancellationOverview}
          billingTab={billingTab}
          billingHistoryPage={billingHistoryPage}
          billingHistoryState={effectiveBillingHistoryState}
          planSummary={planSummary}
          canManageBilling={canManageBilling}
          domainSetupAssistanceAvailable={domainSetupAssistanceAvailable}
          mailConfigured={user.mailConfigured}
          userEmail={user.email}
          userNotificationEmail={preferredNotificationEmail}
          userRecoveryEmail={recoveryEmailOverview.email}
          userRecoveryEmailVerified={recoveryEmailOverview.verified}
          userDisplayName={user.displayName}
          mailbox={user.mailbox}
          companyName={user.companyName}
          domain={user.domain}
          data={mailData}
          initialMessageTranslation={initialMessageTranslation}
          currentFolder={mailData?.currentFolder ?? folder}
          currentView={view}
          composeMode={composeMode}
          sourceDraftMessageId={composeMode === "draft" ? (mailData?.selectedMessage?.id ?? null) : null}
          detailView={detailView}
          detailOpen={view === "compose" || Boolean(messageParam)}
          currentSearchField={searchField}
          currentSearchQuery={searchQuery}
          composeBccDefault={sourceComposeDefaults.bcc}
          composeCcDefault={sourceComposeDefaults.cc}
          composeToDefault={sourceComposeDefaults.to}
          composeSubjectDefault={sourceComposeDefaults.subject}
          composeBodyDefault={sourceComposeDefaults.body}
          composeBodyHtmlDefault={sanitizedComposeBodyHtml}
          composeSignatureHtml={signatureComposeContent.html}
          composeSignatureText={signatureComposeContent.text}
          signatureSettings={signatureSettings}
          layoutPreferences={layoutPreferences}
          notice={notice}
        />
      </main>
    </div>
  );
}
