"use client";

import { AtSign, Bell, CheckCircle2, ExternalLink, Globe2, Mail, ShieldCheck, WalletCards } from "lucide-react";
import type { CSSProperties } from "react";
import { useEffect, useMemo, useState } from "react";
import {
  buildMailMaliHostnameRecordFallback,
  buildMockMailMaliAddonOrderUrl,
  fetchMailMaliCustomHostnames,
  fetchMailMaliMailboxes,
  fetchMailMaliQuota,
  getMailMaliBapReadonlyConfig,
  getMockMailMaliDomainAdminData,
  isMailMaliServiceRestorePending,
  mailMaliAccountDataUnavailableMessage,
  mockMailMaliServiceScenarios,
  type MailMaliCustomHostnameResponse,
  type MailMaliCustomHostnameStatus,
  type MailMaliMailboxAccountSummary,
  type MailMaliMockServiceScenario,
  type MailMaliPlanCode,
  type MailMaliPlanQuotaRow,
  type MailMaliQuotaResponse,
  type MailMaliQuarantineAction,
  type MailMaliQuarantinedMessageSummary,
  type MailMaliServiceStatus,
} from "@/lib/mail-mali-bap-client";
import { adminFlavorConfig } from "@/lib/product-flavor";

function formatServiceStatus(status: MailMaliServiceStatus) {
  return status
    .split("_")
    .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))
    .join(" ");
}

function serviceStatusMessage(status: MailMaliServiceStatus, days = 30) {
  if (status === "renewal_due_60_days" || status === "renewal_due_30_days" || status === "renewal_due_7_days") {
    return `Your email service plan renews in ${days} days.`;
  }
  if (status === "past_due") {
    return "Your service renewal is past due. Please complete payment to continue using the service.";
  }
  if (status === "grace_period") {
    return "Your service renewal is past due. Please complete payment to keep using the service without interruption.";
  }
  if (status === "payment_pending") {
    return "Your additional mailbox order is pending payment.";
  }
  if (status === "payment_failed") {
    return "Payment failed. Update payment or try again.";
  }
  if (status === "suspended") {
    return "Email service for this domain is temporarily suspended because renewal payment has not been completed.";
  }
  if (isMailMaliServiceRestorePending(status)) {
    return "Your email service restore is pending. Service access will resume after processing is complete.";
  }
  if (status === "cancelled") {
    return "This email service has been cancelled.";
  }
  if (status === "terminated") {
    return "This email service has ended. Contact support for next steps.";
  }
  return "Your email service is active.";
}

function formatHostnameStatus(status: MailMaliCustomHostnameStatus | undefined) {
  if (!status) return "Checking";
  return status
    .split("_")
    .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))
    .join(" ");
}

function hostnameStatusClass(status: MailMaliCustomHostnameStatus | "ok" | "missing" | "mismatch" | undefined) {
  if (status === "active" || status === "ok") return "bg-emerald-50 text-emerald-700 ring-emerald-100";
  if (status === "checking" || status === "pending") return "bg-blue-50 text-blue-700 ring-blue-100";
  if (status === "failed" || status === "missing" || status === "mismatch") return "bg-rose-50 text-rose-700 ring-rose-100";
  return "bg-amber-50 text-amber-700 ring-amber-100";
}

function safeHttpUrl(value?: string | null) {
  if (!value) return "";
  try {
    const url = new URL(value);
    return url.protocol === "http:" || url.protocol === "https:" ? url.toString() : "";
  } catch {
    return "";
  }
}

function serviceAllowsMailboxCreate(status: MailMaliServiceStatus) {
  return status !== "past_due" && status !== "payment_failed" && status !== "suspended" && status !== "cancelled" && status !== "terminated";
}

function serviceAllowsMailProtectionActions(status: MailMaliServiceStatus) {
  return status !== "suspended" && status !== "cancelled" && status !== "terminated";
}

function planCreateMessage(plan: MailMaliPlanQuotaRow, serviceStatus: MailMaliServiceStatus, days: number) {
  if (!serviceAllowsMailboxCreate(serviceStatus)) {
    return serviceStatusMessage(serviceStatus, days);
  }
  if (plan.available <= 0) {
    return `You have used all paid ${plan.display_name} mailboxes.`;
  }
  return "Ready to create. Provisioning integration will be connected later.";
}

export function MailMaliDomainAdmin() {
  const [selectedScenario, setSelectedScenario] = useState<MailMaliMockServiceScenario>("renewal_due_30_days");
  const mockDomainAdminData = useMemo(() => getMockMailMaliDomainAdminData(selectedScenario), [selectedScenario]);
  const readonlyConfig = useMemo(() => getMailMaliBapReadonlyConfig(), []);
  const [apiQuota, setApiQuota] = useState<MailMaliQuotaResponse | null>(null);
  const [apiMailboxes, setApiMailboxes] = useState<MailMaliMailboxAccountSummary[] | null>(null);
  const [apiCustomHostnames, setApiCustomHostnames] = useState<MailMaliCustomHostnameResponse | null>(null);
  const [accountDataError, setAccountDataError] = useState("");
  const [accountDataLoading, setAccountDataLoading] = useState(false);
  const quota = apiQuota ?? mockDomainAdminData.quota;
  const mailboxes = apiMailboxes ?? mockDomainAdminData.mailboxes;
  const customHostnames = apiCustomHostnames ?? mockDomainAdminData.customHostnames;
  const { addonOrders, quarantinedMessages: initialQuarantinedMessages, security } = mockDomainAdminData;
  const [localPart, setLocalPart] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [selectedPlanCode, setSelectedPlanCode] = useState<MailMaliPlanCode>("starter");
  const [mockCreateState, setMockCreateState] = useState("");
  const [quarantinedMessages, setQuarantinedMessages] = useState<MailMaliQuarantinedMessageSummary[]>(initialQuarantinedMessages);
  const [pendingQuarantineAction, setPendingQuarantineAction] = useState<{ message: MailMaliQuarantinedMessageSummary; action: MailMaliQuarantineAction } | null>(null);
  const [quarantineActionNotice, setQuarantineActionNotice] = useState("");
  const activeOrder = addonOrders.find((order) => order.payment_status === "pending");
  const selectedPlan = quota.plans.find((plan) => plan.plan_code === selectedPlanCode) ?? quota.plans[0];
  const quotaTotal = quota.plans.reduce(
    (total, plan) => ({
      paid: total.paid + plan.paid,
      used: total.used + plan.used,
      reserved: total.reserved + plan.reserved,
      available: total.available + plan.available,
    }),
    { paid: 0, used: 0, reserved: 0, available: 0 },
  );
  const renewalDays = quota.service_status === "renewal_due_60_days" ? 60 : quota.service_status === "renewal_due_7_days" ? 7 : 30;
  const showServiceBanner = quota.service_status !== "active" || security.dns_status === "action_needed" || Boolean(activeOrder);
  const selectedPlanOrderUrl = selectedPlan ? buildMockMailMaliAddonOrderUrl(quota.domain, selectedPlan.plan_code) : "";
  const selectedPlanPaymentUrl = selectedPlan?.payment_url || selectedPlanOrderUrl;
  const createBlockedByService = !serviceAllowsMailboxCreate(quota.service_status);
  const createBlockedByQuota = Boolean(selectedPlan && selectedPlan.available <= 0);
  const createReady = Boolean(selectedPlan && !createBlockedByService && !createBlockedByQuota && localPart.trim() && displayName.trim());
  const createGateMessage = selectedPlan ? planCreateMessage(selectedPlan, quota.service_status, renewalDays) : "Select a service plan.";
  const mailProtectionActionsEnabled = serviceAllowsMailProtectionActions(quota.service_status);
  const visibleQuarantineCount = quarantinedMessages.filter((message) => message.status === "held").length;

  useEffect(() => {
    if (!readonlyConfig.enabled) {
      setAccountDataError("");
      setAccountDataLoading(false);
      setApiQuota(null);
      setApiMailboxes(null);
      setApiCustomHostnames(null);
      return;
    }

    let cancelled = false;
    setAccountDataLoading(true);
    setAccountDataError("");

    Promise.all([
      fetchMailMaliQuota(mockDomainAdminData.quota.domain, readonlyConfig),
      fetchMailMaliMailboxes(mockDomainAdminData.quota.domain, readonlyConfig),
      fetchMailMaliCustomHostnames(mockDomainAdminData.quota.domain, readonlyConfig),
    ])
      .then(([quotaResponse, mailboxResponse, hostnameResponse]) => {
        if (cancelled) return;
        setApiQuota(quotaResponse);
        setApiMailboxes(mailboxResponse);
        setApiCustomHostnames(hostnameResponse);
      })
      .catch(() => {
        if (cancelled) return;
        setApiQuota(null);
        setApiMailboxes(null);
        setApiCustomHostnames(null);
        setAccountDataError(mailMaliAccountDataUnavailableMessage);
      })
      .finally(() => {
        if (!cancelled) setAccountDataLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [mockDomainAdminData.quota.domain, readonlyConfig]);

  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">
        <aside className="bg-[linear-gradient(180deg,#2750f0_0%,#2748dd_52%,#2139ba_100%)] px-5 py-5 text-white xl:min-h-0 xl:overflow-auto xl:px-6">
          <div className="grid gap-6">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.18em] text-white/65">Domain admin</p>
              <h1 className="mt-2 text-2xl font-black">Mail Mali</h1>
              <p className="mt-2 text-sm leading-6 text-white/72">English-only admin for hosted email service operations.</p>
            </div>
            <div className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/15">
              <p className="text-sm font-black">{quota.domain}</p>
              <p className="mt-1 text-xs font-semibold text-white/65">Hosted SaaS domain</p>
            </div>
            <nav className="grid gap-2 text-sm font-bold" aria-label="Mail Mali admin sections">
              {[
                "Service status",
                "Mailbox quota by plan",
                "Mailboxes",
                "Mail protection",
                "Custom hostnames",
                "Google Connect",
              ].map((item) => (
                <span key={item} className="rounded-xl bg-white/10 px-4 py-3 ring-1 ring-white/10">
                  {item}
                </span>
              ))}
            </nav>
          </div>
        </aside>

        <section className="grid min-h-0 grid-rows-[auto_1fr] bg-[#f5f7fb]">
          <header className="border-b border-slate-200 bg-white px-4 py-4 shadow-[0_1px_0_rgba(23,32,51,0.04)] sm:px-6">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Mail Mali domain admin</p>
                <h2 className="mt-1 text-2xl font-black text-slate-950">Admin workspace foundation</h2>
                <p className="mt-1 text-sm font-medium text-slate-600">Existing admin layout direction with Mail Mali service modules.</p>
              </div>
              <span className="rounded-full bg-emerald-50 px-4 py-2 text-sm font-black text-emerald-700 ring-1 ring-emerald-100">
                {adminFlavorConfig.deploymentModel === "hosted_saas" ? "Hosted SaaS" : "Package"}
              </span>
            </div>
          </header>

          <div className="min-h-0 overflow-auto px-4 py-4 sm:px-6">
            <section className="mb-4 rounded-2xl border border-blue-100 bg-blue-50 p-4 shadow-soft">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.14em] text-blue-700">Mock scenario</p>
                  <p className="mt-1 text-sm font-semibold text-blue-900">Dev-only local selector for service lifecycle UI states. It does not call external services.</p>
                </div>
                <label className="grid min-w-[240px] gap-1 text-sm font-black text-blue-900">
                  Service lifecycle state
                  <select
                    value={selectedScenario}
                    onChange={(event) => {
                      setSelectedScenario(event.target.value as MailMaliMockServiceScenario);
                      setMockCreateState("");
                    }}
                    className="h-10 rounded-xl border border-blue-200 bg-white px-3 text-sm font-bold text-slate-900 outline-none focus:ring-2 focus:ring-blue-300"
                  >
                    {mockMailMaliServiceScenarios.map((scenario) => (
                      <option key={scenario.value} value={scenario.value}>{scenario.label}</option>
                    ))}
                  </select>
                </label>
              </div>
            </section>

            {showServiceBanner ? (
              <section className="mb-4 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900 shadow-soft">
                <div className="flex items-start gap-3">
                  <Bell className="mt-0.5 shrink-0" size={18} />
                  <div className="grid gap-1">
                    <p className="font-black">Service status: {formatServiceStatus(quota.service_status)}</p>
                    <p className="font-semibold">{serviceStatusMessage(quota.service_status, renewalDays)}</p>
                    {activeOrder ? <p>Your additional mailbox order is pending payment.</p> : null}
                    {security.dns_status === "action_needed" ? <p>Please review your domain DNS settings to keep email delivery working properly.</p> : null}
                  </div>
                </div>
              </section>
            ) : null}

            {accountDataError ? (
              <section className="mb-4 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm font-semibold text-amber-900 shadow-soft">
                {accountDataError}
              </section>
            ) : null}

            {accountDataLoading ? (
              <section className="mb-4 rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm font-semibold text-blue-900 shadow-soft">
                Loading account data from the read-only service endpoint.
              </section>
            ) : null}

            <div className="grid gap-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(340px,0.6fr)]">
              <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.14em] text-slate-500">Mailbox quota by plan</p>
                    <h3 className="mt-2 text-xl font-black text-slate-950">Paid mailbox seats</h3>
                    <p className="mt-1 text-sm leading-6 text-slate-600">
                      {quotaTotal.used} of {quotaTotal.paid} paid mailbox seats are used. {quotaTotal.reserved} reserved. Data shape follows the BAP contract with local mock data only.
                    </p>
                  </div>
                  <WalletCards className="text-[var(--accent)]" size={24} />
                </div>
                <div className="mt-5 overflow-hidden rounded-xl border border-slate-200">
                  <table className="w-full min-w-[760px] text-left text-sm">
                    <thead className="bg-slate-50 text-xs font-black uppercase tracking-[0.12em] text-slate-500">
                      <tr>
                        <th className="px-4 py-3">Service plan</th>
                        <th className="px-4 py-3 text-right">Paid</th>
                        <th className="px-4 py-3 text-right">Used</th>
                        <th className="px-4 py-3 text-right">Reserved</th>
                        <th className="px-4 py-3 text-right">Available</th>
                        <th className="px-4 py-3">Storage</th>
                        <th className="px-4 py-3">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {quota.plans.map((row) => (
                        <tr key={row.plan_id}>
                          <td className="px-4 py-3">
                            <span className="font-black text-slate-950">{row.display_name}</span>
                            <span className="mt-1 block text-xs font-semibold text-slate-500">{row.annual_price_thb.toLocaleString("en-US")} THB/year</span>
                          </td>
                          <td className="px-4 py-3 text-right font-semibold text-slate-700">{row.paid}</td>
                          <td className="px-4 py-3 text-right font-semibold text-slate-700">{row.used}</td>
                          <td className="px-4 py-3 text-right font-semibold text-slate-700">{row.reserved}</td>
                          <td className="px-4 py-3 text-right font-black text-slate-950">{row.available}</td>
                          <td className="px-4 py-3 font-semibold text-slate-600">{row.storage_gb} GB each</td>
                          <td className="px-4 py-3">
                            {row.available > 0 ? (
                              <span className="rounded-full bg-emerald-50 px-3 py-1 text-xs font-black text-emerald-700 ring-1 ring-emerald-100">Create allowed</span>
                            ) : (
                              <span className="rounded-full bg-amber-50 px-3 py-1 text-xs font-black text-amber-700 ring-1 ring-amber-100">Order more</span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <p className="mt-3 text-xs font-semibold text-slate-500">Quota version {quota.quota_version} · Generated {quota.generated_at}</p>
              </section>

              <div className="grid gap-4">
                <SummaryCard title="Service status" icon={Bell} body={serviceStatusMessage(quota.service_status, renewalDays)} meta={`Renewal date ${quota.plans[0]?.renewal_date ?? "—"}`} />
                <SummaryCard title="Mail protection" icon={ShieldCheck} body={`Mail protection is ${security.mail_protection_status}. ${visibleQuarantineCount} quarantined messages need review.`} meta={`DNS status: ${security.dns_status.replace(/_/g, " ")}`} />
                <SummaryCard title="Custom hostnames" icon={Globe2} body={`${customHostnames.hostnames.length} hostname${customHostnames.hostnames.length === 1 ? "" : "s"} configured for this domain.`} meta={`Status generated ${customHostnames.generated_at}`} />
                <SummaryCard title="Google Connect" icon={AtSign} body={`Google Connect status: ${security.google_connect_status.replace(/_/g, " ")}.`} meta="Connected service controls will use BAP state later." />
              </div>
            </div>

            <section className="mt-4 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.14em] text-slate-500">Custom hostnames</p>
                  <h3 className="mt-2 text-xl font-black text-slate-950">Hostname setup and status</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-600">
                    Read-only status is used when enabled. Setup guidance remains non-mutating and uses safe DNS record metadata only.
                  </p>
                </div>
                <Globe2 className="text-[var(--accent)]" size={24} />
              </div>
              <div className="mt-5 grid gap-4 lg:grid-cols-2">
                {customHostnames.hostnames.map((hostname) => {
                  const setupUrl = safeHttpUrl(hostname.setup_url);
                  const targetCname = hostname.target_cname ?? hostname.target_hostname ?? "mail.mailmali.com";
                  const records = hostname.records?.length ? hostname.records : buildMailMaliHostnameRecordFallback(hostname.hostname, targetCname);
                  const setupStatus = hostname.setup_status ?? hostname.status;
                  return (
                  <article key={hostname.hostname} className="rounded-xl border border-slate-200 bg-slate-50 p-4">
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="truncate text-base font-black text-slate-950">{hostname.hostname}</p>
                        <p className="mt-1 text-sm font-semibold text-slate-600">Target: {targetCname}</p>
                      </div>
                      <span className={`rounded-full px-3 py-1 text-xs font-black ring-1 ${hostnameStatusClass(setupStatus)}`}>
                        {formatHostnameStatus(setupStatus)}
                      </span>
                    </div>
                    <div className="mt-4 grid gap-2 sm:grid-cols-2">
                      <div className="rounded-lg bg-white p-3 ring-1 ring-slate-200">
                        <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-500">DNS status</p>
                        <p className="mt-1 text-sm font-black text-slate-950">{(hostname.dns_status ?? "checking").replace(/_/g, " ")}</p>
                      </div>
                      <div className="rounded-lg bg-white p-3 ring-1 ring-slate-200">
                        <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-500">HTTPS status</p>
                        <p className="mt-1 text-sm font-black text-slate-950">{(hostname.ssl_status ?? "checking").replace(/_/g, " ")}</p>
                      </div>
                    </div>
                    {hostname.customer_message_en ? <p className="mt-4 rounded-lg border border-blue-100 bg-blue-50 p-3 text-sm font-semibold text-blue-900">{hostname.customer_message_en}</p> : null}
                    <div className="mt-4 overflow-hidden rounded-lg border border-slate-200 bg-white">
                      <table className="w-full min-w-[520px] text-left text-sm">
                        <thead className="bg-slate-50 text-xs font-black uppercase tracking-[0.12em] text-slate-500">
                          <tr>
                            <th className="px-3 py-2">Type</th>
                            <th className="px-3 py-2">Name</th>
                            <th className="px-3 py-2">Target</th>
                            <th className="px-3 py-2">Status</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                          {records.map((record) => (
                            <tr key={`${hostname.hostname}-${record.type}-${record.name}`}>
                              <td className="px-3 py-2 font-black text-slate-800">{record.type}</td>
                              <td className="px-3 py-2 font-semibold text-slate-700">{record.name}</td>
                              <td className="px-3 py-2 font-mono text-xs text-slate-600">{record.value}</td>
                              <td className="px-3 py-2">
                                <span className={`rounded-full px-2 py-1 text-xs font-black ring-1 ${hostnameStatusClass(record.status)}`}>
                                  {record.status.replace(/_/g, " ")}
                                </span>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                    <div className="mt-4 flex flex-wrap items-center justify-between gap-3 text-xs font-semibold text-slate-500">
                      <span>Last checked: {hostname.last_checked_at || "Not checked yet"}</span>
                      {setupUrl ? (
                        <a className="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-black text-slate-700" href={setupUrl} target="_blank" rel="noreferrer">
                          Setup details <ExternalLink size={14} />
                        </a>
                      ) : null}
                    </div>
                  </article>
                  );
                })}
              </div>
              <p className="mt-3 text-xs font-semibold text-slate-500">Hostname status generated {customHostnames.generated_at}</p>
            </section>

            <section className="mt-4 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.14em] text-slate-500">Mail protection</p>
                  <h3 className="mt-2 text-xl font-black text-slate-950">Spam quarantine</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-600">Safe metadata only. Message body content is not shown in this mock shell.</p>
                </div>
                <span className="rounded-full bg-blue-50 px-4 py-2 text-sm font-black text-blue-700 ring-1 ring-blue-100">Mail safety status: {security.mail_protection_status}</span>
              </div>
              <div className="mt-4 grid gap-3 md:grid-cols-3">
                <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
                  <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-500">Quarantined messages</p>
                  <p className="mt-2 text-2xl font-black text-slate-950">{visibleQuarantineCount}</p>
                </div>
                <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
                  <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-500">Mail routing</p>
                  <p className="mt-2 text-sm font-black text-slate-950">{security.dns_status.replace(/_/g, " ")}</p>
                </div>
                <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
                  <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-500">Actions</p>
                  <p className="mt-2 text-sm font-black text-slate-950">{mailProtectionActionsEnabled ? "Mock actions available" : "Actions disabled"}</p>
                </div>
              </div>
              {!mailProtectionActionsEnabled ? <p className="mt-4 rounded-xl border border-amber-200 bg-amber-50 p-3 text-sm font-bold text-amber-900">{serviceStatusMessage(quota.service_status, renewalDays)}</p> : null}
              {quarantineActionNotice ? <p className="mt-4 rounded-xl border border-emerald-200 bg-emerald-50 p-3 text-sm font-bold text-emerald-800">{quarantineActionNotice}</p> : null}
              <div className="mt-5 overflow-hidden rounded-xl border border-slate-200">
                <table className="w-full min-w-[860px] text-left text-sm">
                  <thead className="bg-slate-50 text-xs font-black uppercase tracking-[0.12em] text-slate-500">
                    <tr>
                      <th className="px-4 py-3">Recipient</th>
                      <th className="px-4 py-3">Sender</th>
                      <th className="px-4 py-3">Subject</th>
                      <th className="px-4 py-3">Received</th>
                      <th className="px-4 py-3">Category</th>
                      <th className="px-4 py-3">Score</th>
                      <th className="px-4 py-3">Status</th>
                      <th className="px-4 py-3 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {quarantinedMessages.map((message) => {
                      const actionDisabled = !mailProtectionActionsEnabled || message.status !== "held";
                      return (
                        <tr key={message.message_id}>
                          <td className="px-4 py-3 font-semibold text-slate-700">{message.recipient}</td>
                          <td className="px-4 py-3 font-semibold text-slate-700">{message.sender}</td>
                          <td className="px-4 py-3 font-black text-slate-950">{message.subject}</td>
                          <td className="px-4 py-3 font-semibold text-slate-600">{message.received_at}</td>
                          <td className="px-4 py-3"><span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-black text-slate-700">{message.category}</span></td>
                          <td className="px-4 py-3 font-semibold text-slate-700">{message.score.toFixed(1)} · {message.severity}</td>
                          <td className="px-4 py-3 font-semibold text-slate-700">{message.status.replace(/_/g, " ")}</td>
                          <td className="px-4 py-3">
                            <div className="flex justify-end gap-2">
                              <button type="button" className="rounded-lg border border-slate-200 px-3 py-2 text-xs font-black text-slate-700 disabled:opacity-45" disabled={actionDisabled || !message.allowed_actions.includes("release_message")} onClick={() => setPendingQuarantineAction({ message, action: "release_message" })}>
                                Release
                              </button>
                              <button type="button" className="rounded-lg border border-rose-200 px-3 py-2 text-xs font-black text-rose-700 disabled:opacity-45" disabled={actionDisabled || !message.allowed_actions.includes("delete_message")} onClick={() => setPendingQuarantineAction({ message, action: "delete_message" })}>
                                Delete
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </section>

            {pendingQuarantineAction ? (
              <div className="fixed inset-0 z-50 grid place-items-center bg-slate-950/40 p-4">
                <section className="w-full max-w-md rounded-2xl bg-white p-5 shadow-2xl">
                  <p className="text-xs font-black uppercase tracking-[0.14em] text-slate-500">Confirm mock action</p>
                  <h3 className="mt-2 text-xl font-black text-slate-950">{pendingQuarantineAction.action === "release_message" ? "Release message" : "Delete message"}</h3>
                  <p className="mt-2 text-sm leading-6 text-slate-600">This records a local mock action only. No external service is called.</p>
                  <p className="mt-3 rounded-xl bg-slate-50 p-3 text-sm font-semibold text-slate-700">{pendingQuarantineAction.message.subject}</p>
                  <div className="mt-5 flex justify-end gap-2">
                    <button type="button" className="rounded-xl border border-slate-200 px-4 py-2 text-sm font-black text-slate-700" onClick={() => setPendingQuarantineAction(null)}>
                      Cancel
                    </button>
                    <button
                      type="button"
                      className="rounded-xl bg-slate-950 px-4 py-2 text-sm font-black text-white"
                      onClick={() => {
                        const nextStatus = pendingQuarantineAction.action === "release_message" ? "release_recorded" : "delete_recorded";
                        setQuarantinedMessages((messages) => messages.map((message) => message.message_id === pendingQuarantineAction.message.message_id ? { ...message, status: nextStatus, allowed_actions: [] } : message));
                        setQuarantineActionNotice(`Mock action recorded for ${pendingQuarantineAction.message.subject}.`);
                        setPendingQuarantineAction(null);
                      }}
                    >
                      Confirm
                    </button>
                  </div>
                </section>
              </div>
            ) : null}

            <section className="mt-4 rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.14em] text-slate-500">Mailboxes</p>
                  <h3 className="mt-2 text-xl font-black text-slate-950">Domain mailboxes</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-600">Mailbox rows use typed BAP-aligned mock summaries. Create actions remain placeholders only.</p>
                </div>
                <Mail className="text-[var(--accent)]" size={24} />
              </div>
              <div className="mt-5 grid gap-3 md:grid-cols-3">
                {mailboxes.map((mailbox) => (
                  <article key={mailbox.mailbox_id} className="rounded-xl border border-slate-200 bg-slate-50 p-4">
                    <div className="flex items-start justify-between gap-2">
                      <div className="min-w-0">
                        <p className="truncate text-sm font-black text-slate-950">{mailbox.email}</p>
                        <p className="mt-1 truncate text-sm font-semibold text-slate-600">{mailbox.display_name}</p>
                      </div>
                      <CheckCircle2 className="shrink-0 text-emerald-600" size={18} />
                    </div>
                    <div className="mt-4 flex flex-wrap gap-2">
                      <span className="rounded-full bg-white px-3 py-1 text-xs font-black text-slate-700 ring-1 ring-slate-200">{mailbox.plan_display_name}</span>
                      <span className="rounded-full bg-emerald-50 px-3 py-1 text-xs font-black text-emerald-700 ring-1 ring-emerald-100">{mailbox.status}</span>
                    </div>
                    <p className="mt-3 text-xs font-semibold text-slate-500">
                      {mailbox.storage_used_gb ?? 0} GB used of {mailbox.storage_gb} GB
                    </p>
                  </article>
                ))}
              </div>
            </section>

            <section className="mt-4 rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.14em] text-slate-500">Create mailbox</p>
                  <h3 className="mt-2 text-xl font-black text-slate-950">Plan-specific quota gate</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-600">This form uses local mock data only. Provisioning integration will be connected later.</p>
                </div>
                <Mail className="text-[var(--accent)]" size={24} />
              </div>
              <form
                className="mt-5 grid gap-4 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]"
                onSubmit={(event) => {
                  event.preventDefault();
                  if (!createReady) return;
                  setMockCreateState(`Ready to create ${localPart.trim()}@example.com as a ${selectedPlan.display_name} mailbox. Provisioning integration will be connected later.`);
                }}
              >
                <div className="grid gap-4 rounded-xl border border-slate-200 bg-slate-50 p-4">
                  <label className="grid gap-2 text-sm font-bold text-slate-700">
                    Email address/localpart
                    <div className="grid grid-cols-[minmax(0,1fr)_auto] overflow-hidden rounded-xl border border-slate-200 bg-white focus-within:ring-2 focus-within:ring-[var(--accent)]">
                      <input value={localPart} onChange={(event) => setLocalPart(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">@example.com</span>
                    </div>
                  </label>
                  <label className="grid gap-2 text-sm font-bold text-slate-700">
                    Display name
                    <input value={displayName} onChange={(event) => setDisplayName(event.target.value)} className="field h-11" placeholder="Full name" />
                  </label>
                  <div className="rounded-xl border border-slate-200 bg-white p-3 text-sm font-semibold text-slate-600">
                    <p className="font-black text-slate-950">{createGateMessage}</p>
                    {mockCreateState ? <p className="mt-2 text-emerald-700">{mockCreateState}</p> : null}
                    {createBlockedByService ? <p className="mt-2">Complete the service or payment action before creating a mailbox.</p> : null}
                    {createBlockedByQuota && selectedPlan && selectedPlanPaymentUrl ? (
                      <a className="mt-3 inline-flex rounded-xl bg-slate-950 px-4 py-2 text-sm font-black text-white" href={selectedPlanPaymentUrl} target="_blank" rel="noreferrer">
                        Order more {selectedPlan.display_name} mailboxes
                      </a>
                    ) : null}
                    {createBlockedByQuota && selectedPlan && !selectedPlanPaymentUrl ? <p className="mt-2">Contact your account team to add more mailbox seats.</p> : null}
                  </div>
                  <button type="submit" className="theme-button h-11" disabled={!createReady}>
                    Create mailbox
                  </button>
                </div>

                <fieldset className="grid gap-3">
                  <legend className="sr-only">Mailbox plan selector</legend>
                  {quota.plans.map((plan) => {
                    const selected = selectedPlanCode === plan.plan_code;
                    const planBlocked = plan.available <= 0 || createBlockedByService;
                    return (
                      <button
                        key={plan.plan_id}
                        type="button"
                        onClick={() => {
                          setSelectedPlanCode(plan.plan_code);
                          setMockCreateState("");
                        }}
                        className={`rounded-xl border p-4 text-left transition ${selected ? "border-[var(--accent)] bg-blue-50" : "border-slate-200 bg-white hover:bg-slate-50"}`}
                        aria-pressed={selected}
                      >
                        <div className="flex flex-wrap items-start justify-between gap-3">
                          <div>
                            <p className="text-base font-black text-slate-950">{plan.display_name}</p>
                            <p className="mt-1 text-sm font-semibold text-slate-600">{plan.storage_gb} GB storage · {plan.annual_price_thb.toLocaleString("en-US")} THB/year</p>
                          </div>
                          <span className={`rounded-full px-3 py-1 text-xs font-black ${planBlocked ? "bg-amber-50 text-amber-700 ring-1 ring-amber-100" : "bg-emerald-50 text-emerald-700 ring-1 ring-emerald-100"}`}>
                            {plan.available} available
                          </span>
                        </div>
                        <p className="mt-3 text-sm font-semibold text-slate-500">
                          Paid {plan.paid} · Used {plan.used} · Reserved {plan.reserved}
                        </p>
                      </button>
                    );
                  })}
                </fieldset>
              </form>
            </section>
          </div>
        </section>
      </div>
    </main>
  );
}

function SummaryCard({ title, body, meta, icon: Icon }: { title: string; body: string; meta: string; icon: typeof Bell }) {
  return (
    <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
      <div className="flex items-start gap-3">
        <span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-blue-50 text-[var(--accent)]">
          <Icon size={18} />
        </span>
        <div>
          <h3 className="text-base font-black text-slate-950">{title}</h3>
          <p className="mt-1 text-sm leading-6 text-slate-600">{body}</p>
          <p className="mt-2 text-xs font-bold uppercase tracking-[0.12em] text-slate-400">{meta}</p>
        </div>
      </div>
    </section>
  );
}
