'use client';

import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { logout } from '@/features/auth/api.client';
import { signOutExtension } from '@/features/extension/bridge';
import {
  closeBillingAccount,
  getBillingAccount,
  type BillingAccount,
  type BillingLimit,
  type BillingTransaction,
  type BillingTransactionKind,
} from '@/features/settings/api.client';
import {
  spreadsheetFile,
  SPREADSHEET_MIME,
  type SpreadsheetFormat,
} from '@/lib/export/spreadsheet';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { BillingDateRangePicker, type BillingDateRange } from './BillingDateRangePicker';
import { useHashTab } from './settings-ui';

const TABS = [
  { id: 'billing-overview', label: 'Overview' },
  { id: 'billing-credits', label: 'CRM Credits' },
  { id: 'billing-contacts', label: 'Marketing Contacts' },
  { id: 'billing-limits', label: 'Other Limits' },
  { id: 'billing-transactions', label: 'Transactions' },
  { id: 'billing-delete', label: 'Delete Account' },
];

const FREE_TOOLS: Array<{ label: string; icon: string }> = [
  { label: 'Free Marketing Tools', icon: 'sparkles' },
  { label: 'Free Content Tools', icon: 'send' },
  { label: 'Free Sales Tools', icon: 'bookmark' },
  { label: 'Free Data Tools', icon: 'chart' },
  { label: 'Free Service Tools', icon: 'check-circle' },
  { label: 'Free Revenue Tools', icon: 'arrow-up' },
];

const FILTERS: Array<{ key: string; label: string; options: string[] }> = [
  { key: 'orders', label: 'Orders', options: ['Issued'] },
  { key: 'invoices', label: 'Invoices', options: ['Paid', 'Open', 'Overdue'] },
  { key: 'payments', label: 'Payments', options: ['Select all', 'Processed', 'Failed'] },
  { key: 'credits', label: 'Credits', options: ['Select all', 'Purchased', 'Used'] },
  { key: 'refunds', label: 'Refunds', options: ['Select all', 'Processed', 'Failed'] },
  { key: 'usage & limits', label: 'Usage & Limits', options: ['Select all', 'Usage'] },
];

const KIND_BY_FILTER: Record<string, BillingTransactionKind> = {
  orders: 'order',
  invoices: 'invoice',
  payments: 'payment',
  credits: 'credit',
  refunds: 'refund',
  'usage & limits': 'usage',
};

const ICONS: Record<string, string> = {
  workflow:
    '<rect x="3" y="3" width="6" height="6" rx="1"/><rect x="15" y="15" width="6" height="6" rx="1"/><path d="M6 9v4a2 2 0 0 0 2 2h7"/>',
  sparkles:
    '<path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M6 18l2.5-2.5M15.5 8.5 18 6"/>',
  send: '<path d="M21 3 10 14"/><path d="m21 3-6.5 18-4.5-7-7-4.5z"/>',
  bookmark: '<path d="M6 4h12a1 1 0 0 1 1 1v16l-7-4-7 4V5a1 1 0 0 1 1-1z"/>',
  chart: '<path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/>',
  'check-circle': '<circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/>',
  'arrow-up': '<path d="M12 19V5M6 11l6-6 6 6"/>',
  'arrow-down': '<path d="M12 5v14M6 13l6 6 6-6"/>',
  info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/>',
  'chevron-down': '<path d="m6 9 6 6 6-6"/>',
  search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
  check: '<path d="m5 12 5 5 9-10"/>',
  external:
    '<path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',
  file: '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/>',
  'id-card':
    '<rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="9" cy="11" r="2"/><path d="M6 16a3 3 0 0 1 6 0M14 10h4M14 14h3"/>',
  list: '<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01"/>',
  x: '<path d="M6 6l12 12M18 6 6 18"/>',
  calendar:
    '<rect x="3.5" y="5" width="17" height="15.5" rx="2"/><path d="M3.5 10h17M8 3v4M16 3v4"/>',
};

function Icon({ name, className = 'iconSize-16' }: { name: string; className?: string }) {
  const inner = ICONS[name];
  if (!inner) return null;
  return (
    <svg
      className={`icon ${className}`}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
      focusable={false}
      dangerouslySetInnerHTML={{ __html: inner }}
    />
  );
}

function money(n: number) {
  return `$${Math.round(n).toLocaleString('en-US')}`;
}

function pct(used: number, limit: number) {
  if (limit <= 0) return 0;
  return Math.min(100, Math.round((used / limit) * 100));
}

function formatCount(n: number) {
  return n.toLocaleString('en-US');
}

function dayOf(iso: string) {
  return iso.slice(0, 10);
}

function inRange(iso: string, range: BillingDateRange) {
  const day = dayOf(iso);
  if (range.from && day < range.from) return false;
  if (range.to && day > range.to) return false;
  return true;
}

function download(name: string, data: Uint8Array, mime: string) {
  const blob = new Blob([data as BlobPart], { type: mime });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = name;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    URL.revokeObjectURL(a.href);
    a.remove();
  }, 200);
}

export function AccountBillingView() {
  const [tab, setTab] = useHashTab(TABS, 'billing-overview');
  const [account, setAccount] = useState<BillingAccount | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [toast, setToast] = useState<string | null>(null);
  const [limitQuery, setLimitQuery] = useState('');
  const [sortKey, setSortKey] = useState<'usage' | 'name'>('usage');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc');
  const [sortOpen, setSortOpen] = useState(false);
  const [txQuery, setTxQuery] = useState('');
  const [txRange, setTxRange] = useState<BillingDateRange>({ from: '', to: '' });
  const [dateOpen, setDateOpen] = useState(false);
  const [openFilter, setOpenFilter] = useState<string | null>(null);
  const [checks, setChecks] = useState<Record<string, string[]>>({});
  const [quickLast12, setQuickLast12] = useState(false);
  const [quickCredits, setQuickCredits] = useState(false);
  const [exportOpen, setExportOpen] = useState(false);
  const [exportRange, setExportRange] = useState<BillingDateRange>({ from: '', to: '' });
  const [exportCalOpen, setExportCalOpen] = useState(false);
  const [exportFormat, setExportFormat] = useState<SpreadsheetFormat>('csv');
  const [deleteOpen, setDeleteOpen] = useState(false);
  const toastTimer = useRef<number | null>(null);
  const exportBtn = useRef<HTMLButtonElement>(null);
  const exportPanel = useRef<HTMLElement>(null);

  useEffect(() => {
    getBillingAccount().then(
      (row) => setAccount(row),
      (err: unknown) => setLoadError(errorText(err)),
    );
  }, []);

  const showToast = (message: string) => {
    setToast(message);
    if (toastTimer.current) window.clearTimeout(toastTimer.current);
    toastTimer.current = window.setTimeout(() => setToast(null), 2600);
  };

  useEffect(() => {
    const close = (event: PointerEvent) => {
      const target = event.target instanceof Element ? event.target : null;
      if (!target) return;
      if (!target.closest('.billing-sort')) setSortOpen(false);
      if (!target.closest('.billing-filter')) {
        setOpenFilter(null);
        setDateOpen(false);
      }
      if (
        exportOpen &&
        exportPanel.current &&
        !exportPanel.current.contains(target) &&
        !exportBtn.current?.contains(target)
      ) {
        setExportOpen(false);
        setExportCalOpen(false);
      }
    };
    document.addEventListener('pointerdown', close, true);
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== 'Escape') return;
      setSortOpen(false);
      setOpenFilter(null);
      setDateOpen(false);
      setExportOpen(false);
      setExportCalOpen(false);
      setDeleteOpen(false);
    };
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('pointerdown', close, true);
      document.removeEventListener('keydown', onKey);
    };
  }, [exportOpen]);

  useEffect(() => {
    if (!exportOpen || !exportBtn.current || !exportPanel.current) return;
    const place = () => {
      const panel = exportPanel.current;
      const trigger = exportBtn.current;
      if (!panel || !trigger) return;
      const rect = trigger.getBoundingClientRect();
      const width = Math.min(panel.offsetWidth || 360, window.innerWidth - 24);
      let left = rect.right - width;
      left = Math.max(12, Math.min(left, window.innerWidth - width - 12));
      let top = rect.bottom + 8;
      const height = panel.offsetHeight || 280;
      if (top + height > window.innerHeight - 12) top = Math.max(12, rect.top - height - 8);
      panel.style.left = `${Math.round(left)}px`;
      panel.style.top = `${Math.round(top)}px`;
    };
    place();
    window.addEventListener('resize', place);
    window.addEventListener('scroll', place, true);
    return () => {
      window.removeEventListener('resize', place);
      window.removeEventListener('scroll', place, true);
    };
  }, [exportOpen, exportCalOpen]);

  const limits = useMemo(() => {
    const rows = (account?.limits ?? []).filter((row) =>
      row.name.toLowerCase().includes(limitQuery.trim().toLowerCase()),
    );
    return [...rows].sort((a, b) => {
      const value = sortKey === 'name' ? a.name.localeCompare(b.name) : a.used - b.used;
      return sortDir === 'asc' ? value : -value;
    });
  }, [account, limitQuery, sortKey, sortDir]);

  const shownTx = useMemo(() => {
    if (!account) return [];
    const q = txQuery.trim().toLowerCase();
    return account.transactions.filter((row) => {
      if (q && !`${row.number} ${row.description} ${row.status}`.toLowerCase().includes(q)) {
        return false;
      }
      if (!inRange(row.occurredAt, txRange)) return false;
      if (quickLast12) {
        const from = new Date();
        from.setMonth(from.getMonth() - 12);
        if (new Date(row.occurredAt) < from) return false;
      }
      if (quickCredits && row.kind !== 'credit' && row.kind !== 'refund') return false;
      const filterKey = Object.keys(KIND_BY_FILTER).find((key) => KIND_BY_FILTER[key] === row.kind);
      const selected = filterKey ? (checks[filterKey] ?? []) : [];
      if (selected.length && !selected.includes(row.status)) return false;
      return true;
    });
  }, [account, txQuery, txRange, checks, quickLast12, quickCredits]);

  const toggleCheck = (filter: string, option: string, options: string[]) => {
    setChecks((cur) => {
      const current = new Set(cur[filter] ?? []);
      if (option === 'Select all') {
        const rest = options.filter((o) => o !== 'Select all');
        const allOn = rest.every((o) => current.has(o));
        return { ...cur, [filter]: allOn ? [] : rest };
      }
      if (current.has(option)) current.delete(option);
      else current.add(option);
      return { ...cur, [filter]: [...current] };
    });
  };

  const exportStatement = () => {
    const rows: Array<Array<string | number>> = [
      ['Number', 'Date', 'Type', 'Status', 'Description', 'Amount'],
    ];
    const list = (account?.transactions ?? []).filter((row) =>
      inRange(row.occurredAt, exportRange),
    );
    if (!list.length) rows.push(['', '', '', '', 'No billing activity', '']);
    else {
      for (const row of list) {
        rows.push([
          row.number,
          new Date(row.occurredAt).toLocaleDateString('en-US', { dateStyle: 'medium' }),
          row.kind,
          row.status,
          row.description,
          row.amount,
        ]);
      }
    }
    const file = spreadsheetFile({ name: 'Account statement', rows }, exportFormat);
    download(`account-statement.${exportFormat}`, file, SPREADSHEET_MIME[exportFormat]);
    setExportOpen(false);
    setExportCalOpen(false);
    showToast('Account statement exported');
  };

  const closeHub = async () => {
    setBusy('close');
    try {
      await closeBillingAccount();
      try {
        await signOutExtension();
      } catch {
        // extension may be missing
      }
      await logout();
      window.location.assign('/login');
    } catch (err) {
      showToast(errorText(err));
      setBusy(null);
    }
  };

  const panel = (id: string, children: ReactNode) => (
    <section className="billing-panel" id={id} role="tabpanel" hidden={tab !== id}>
      {children}
    </section>
  );

  if (loadError) {
    return (
      <div className="billing-page billing-main">
        <header className="set-head">
          <div>
            <h1 className="set-head__title">Account &amp; Billing</h1>
          </div>
        </header>
        <p className="set-intro">{loadError}</p>
      </div>
    );
  }

  const hubId = account?.hubId ?? '—';

  return (
    <div className="billing-page billing-main">
      <header className="set-head">
        <div>
          <h1 className="set-head__title">Account &amp; Billing</h1>
        </div>
      </header>
      <div className="os-tabbar crm-mb-4 billing-tabbar">
        <nav className="os-tabs" aria-label="Account and billing">
          {TABS.map((item) => (
            <button
              key={item.id}
              type="button"
              className={cn('os-tab', tab === item.id && 'is-active')}
              aria-current={tab === item.id ? 'page' : undefined}
              onClick={() => setTab(item.id)}
            >
              {item.label}
            </button>
          ))}
        </nav>
      </div>

      {panel(
        'billing-overview',
        <div className="billing-overview-grid">
          <article className="billing-card billing-subscription">
            <div className="billing-brand">
              <span className="billing-brand-mark">AdMedia</span>
              <strong>AdMedia</strong>
              <span className="billing-hub-id">CRM ID: {hubId}</span>
            </div>
            <p className="billing-muted">Your subscription</p>
            <h2 className="billing-free">
              <span className="billing-orange-mark">
                <Icon name="workflow" />
              </span>
              {account?.plan === 'starter' ? 'Starter' : 'Free'}
            </h2>
            <ul className="billing-tools-list">
              {FREE_TOOLS.map((tool) => (
                <li key={tool.label}>
                  <span className="billing-tool-icon">
                    <Icon name={tool.icon} />
                  </span>
                  <span>{tool.label}</span>
                  <span
                    className="billing-tip"
                    tabIndex={0}
                    title="Included with your current plan"
                    aria-label="Included with your current plan"
                  >
                    <Icon name="info" className="iconSize-16" />
                  </span>
                </li>
              ))}
            </ul>
          </article>
          {/* QA #362: no Starter plan upsell here — this is AdMedia's own CRM. */}
        </div>,
      )}

      {panel(
        'billing-credits',
        <div className="billing-empty-hero">
          <div className="billing-empty-copy">
            {/* QA #362: the balance only; no "Upgrade" heading or credit purchase. */}
            <h2>CRM Credits</h2>
            <p>
              {account?.credits
                ? `You have ${formatCount(account.credits)} CRM Credits.`
                : 'This account has no CRM Credits.'}
            </p>
          </div>
          <div className="billing-illustration billing-credit-art" aria-hidden="true">
            <Icon name="workflow" />
            <Icon name="file" />
            <Icon name="sparkles" />
          </div>
        </div>,
      )}

      {panel(
        'billing-contacts',
        <div className="billing-empty-hero">
          <div className="billing-empty-copy">
            <h2>
              {account?.marketingContacts.enabled
                ? 'Marketing Contacts'
                : "You don't have any Marketing Contacts"}
            </h2>
            {/* QA #362: usage only; no Marketing Hub purchase. */}
            {account?.marketingContacts.enabled ? (
              <p>
                You are using {formatCount(account.marketingContacts.used)} of{' '}
                {formatCount(account.marketingContacts.limit)} Marketing Contacts.
              </p>
            ) : null}
          </div>
          <div className="billing-illustration billing-contact-art" aria-hidden="true">
            <Icon name="id-card" />
            <Icon name="list" />
          </div>
        </div>,
      )}

      {panel(
        'billing-limits',
        <div className="billing-content-card">
          <h2>Other Limits</h2>
          <p>Some features include limits.</p>
          <div className="billing-limits-toolbar">
            <label className="billing-searchbar">
              <Icon name="search" />
              <input
                type="search"
                id="billing-limit-search"
                placeholder="Search limits"
                aria-label="Search limits"
                value={limitQuery}
                onChange={(e) => setLimitQuery(e.target.value)}
              />
            </label>
            <div className="billing-sort">
              <button
                type="button"
                className="billing-sort-trigger"
                aria-expanded={sortOpen}
                onClick={() => setSortOpen((v) => !v)}
              >
                <Icon name="arrow-down" />{' '}
                <span>Sort by: {sortKey === 'name' ? 'Name' : 'Usage'}</span>{' '}
                <Icon name="chevron-down" className="iconSize-14" />
              </button>
              <div className="billing-sort-menu" hidden={!sortOpen}>
                <button
                  type="button"
                  onClick={() => {
                    setSortKey('usage');
                    setSortOpen(false);
                  }}
                >
                  Usage
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setSortKey('name');
                    setSortOpen(false);
                  }}
                >
                  Name
                </button>
                <hr />
                <button
                  type="button"
                  onClick={() => {
                    setSortDir('asc');
                    setSortOpen(false);
                  }}
                >
                  <Icon name="arrow-up" /> Ascending
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setSortDir('desc');
                    setSortOpen(false);
                  }}
                >
                  <Icon name="arrow-down" /> Descending
                </button>
              </div>
            </div>
          </div>
          <div className="billing-limit-grid">
            {limits.map((row: BillingLimit) => (
              <article key={row.key} className="billing-limit-card">
                <div className="billing-limit-head">
                  <strong>{row.name}</strong>
                </div>
                <p>{row.description}</p>
                <strong>
                  {formatCount(row.used)} of {formatCount(row.limit)} emails
                </strong>
                <div className="billing-progress">
                  <span style={{ width: `${pct(row.used, row.limit)}%` }} />
                </div>
                <p className="billing-muted">{pct(row.used, row.limit)}%</p>
                <p className="billing-muted">
                  {row.reset === 'monthly' ? 'Resets Monthly' : 'Does not reset'}
                </p>
              </article>
            ))}
          </div>
        </div>,
      )}

      {panel(
        'billing-transactions',
        <div className="billing-content-card billing-transactions-card">
          <h2>Transactions</h2>
          <div className="billing-transaction-toolbar">
            <label className="billing-searchbar billing-transaction-search">
              <Icon name="search" />
              <input
                type="search"
                placeholder="Search invoices & transactions"
                aria-label="Search invoices and transactions"
                value={txQuery}
                onChange={(e) => setTxQuery(e.target.value)}
              />
            </label>
            <div className="billing-filter" data-filter="date">
              <button
                type="button"
                className="billing-filter-trigger"
                aria-expanded={openFilter === 'date'}
                onClick={() => {
                  const next = openFilter !== 'date';
                  setOpenFilter(next ? 'date' : null);
                  setDateOpen(next);
                }}
              >
                Date range <Icon name="chevron-down" className="iconSize-14" />
              </button>
              <div className="billing-filter-pop billing-date-pop" hidden={openFilter !== 'date'}>
                <div className="cad-date-picker-wrap billing-transaction-date-picker">
                  <BillingDateRangePicker
                    id="billingTransactionDatePicker"
                    fromLabel="Start date"
                    toLabel="End date"
                    value={txRange}
                    onChange={setTxRange}
                    calendarOpen={dateOpen}
                    onCalendarOpenChange={setDateOpen}
                  />
                </div>
              </div>
            </div>
            {FILTERS.map((filter) => (
              <div className="billing-filter" data-filter={filter.key} key={filter.key}>
                <button
                  type="button"
                  className="billing-filter-trigger"
                  aria-expanded={openFilter === filter.key}
                  onClick={() => setOpenFilter((cur) => (cur === filter.key ? null : filter.key))}
                >
                  {filter.label} <Icon name="chevron-down" className="iconSize-14" />
                </button>
                <div
                  className="billing-filter-pop billing-check-pop"
                  hidden={openFilter !== filter.key}
                >
                  {filter.options.map((opt) => (
                    <label key={opt}>
                      <input
                        type="checkbox"
                        value={opt}
                        checked={
                          opt === 'Select all'
                            ? filter.options
                                .filter((o) => o !== 'Select all')
                                .every((o) => (checks[filter.key] ?? []).includes(o))
                            : (checks[filter.key] ?? []).includes(opt)
                        }
                        onChange={() => toggleCheck(filter.key, opt, filter.options)}
                      />{' '}
                      <span>{opt}</span>
                    </label>
                  ))}
                </div>
              </div>
            ))}
          </div>
          <div className="billing-quick-row">
            <div className="billing-quick-filters">
              <strong>Quick filters:</strong>
              <button
                type="button"
                className={cn('billing-quick-pill', quickLast12 && 'is-active')}
                onClick={() => setQuickLast12((v) => !v)}
              >
                Last 12 months
              </button>
              <button
                type="button"
                className={cn('billing-quick-pill', quickCredits && 'is-active')}
                onClick={() => setQuickCredits((v) => !v)}
              >
                Credits &amp; refunds
              </button>
            </div>
            <button
              type="button"
              className="billing-export-trigger"
              ref={exportBtn}
              onClick={() => {
                setExportOpen((v) => !v);
                setExportCalOpen(false);
              }}
            >
              <Icon name="file" className="iconSize-14" /> Export Account Statement
            </button>
          </div>
          {shownTx.length ? (
            <div className="billing-limit-grid">
              {shownTx.map((row: BillingTransaction) => (
                <article key={row.id} className="billing-limit-card">
                  <div className="billing-limit-head">
                    <strong>{row.number}</strong>
                    <span className="billing-pill">{row.status}</span>
                  </div>
                  <p>{row.description}</p>
                  <strong>{money(row.amount)}</strong>
                  <p className="billing-muted">
                    {new Date(row.occurredAt).toLocaleDateString('en-US', { dateStyle: 'medium' })}{' '}
                    · {row.kind}
                  </p>
                </article>
              ))}
            </div>
          ) : (
            <div className="billing-no-activity">
              <div className="billing-empty-icon">
                <Icon name="file" />
                <Icon name="file" />
              </div>
              <strong>No billing activity</strong>
              <p>Transactions will appear here when you&apos;re billed or make a payment.</p>
            </div>
          )}
        </div>,
      )}

      {panel(
        'billing-delete',
        <div className="billing-content-card billing-delete-card">
          <div>
            <h2>Delete Your CRM Account</h2>
            <p>Delete this hub (Hub ID {hubId}) and all content associated with it.</p>
            <p>
              <strong>Please note:</strong> This action will not automatically delete any associated
              CRM user profiles. For more information on deleting users after closing your account,
              please see{' '}
              <a className="billing-feature-link" href="#billing-delete">
                this article <Icon name="external" className="iconSize-14" />
              </a>
            </p>
          </div>
          <button
            type="button"
            className="billing-delete-button"
            onClick={() => setDeleteOpen(true)}
          >
            Delete account
          </button>
        </div>,
      )}

      <div
        className={cn('billing-modal-backdrop', exportOpen && 'is-export-popover')}
        id="billing-export-modal"
        hidden={!exportOpen}
      >
        <section
          className="billing-modal"
          role="dialog"
          aria-modal="true"
          aria-labelledby="billing-export-title"
          ref={exportPanel}
        >
          <button
            type="button"
            className="billing-modal-close"
            aria-label="Close"
            onClick={() => {
              setExportOpen(false);
              setExportCalOpen(false);
            }}
          >
            <Icon name="x" />
          </button>
          <h2 id="billing-export-title">Export Account Statement</h2>
          <label className="billing-modal-label">Date range</label>
          <div className="billing-export-date-picker cad-date-picker-wrap">
            <BillingDateRangePicker
              id="billingExportDatePicker"
              fromLabel="Export start date"
              toLabel="Export end date"
              value={exportRange}
              onChange={setExportRange}
              calendarOpen={exportCalOpen}
              onCalendarOpenChange={setExportCalOpen}
            />
          </div>
          <label className="billing-modal-label">Format</label>
          <div className="billing-format-options">
            {(['csv', 'xls', 'xlsx'] as const).map((fmt) => (
              <label key={fmt}>
                <input
                  type="radio"
                  name="billing-format"
                  value={fmt}
                  checked={exportFormat === fmt}
                  onChange={() => setExportFormat(fmt)}
                />{' '}
                {fmt.toUpperCase()}
              </label>
            ))}
          </div>
          <button
            type="button"
            className="billing-buy billing-export-confirm"
            onClick={exportStatement}
          >
            Export
          </button>
        </section>
      </div>

      <div className="billing-modal-backdrop" hidden={!deleteOpen}>
        <section
          className="billing-modal"
          role="dialog"
          aria-modal="true"
          aria-labelledby="billing-delete-title"
        >
          <button
            type="button"
            className="billing-modal-close"
            aria-label="Close"
            onClick={() => setDeleteOpen(false)}
          >
            <Icon name="x" />
          </button>
          <h2 id="billing-delete-title">Delete account</h2>
          <p>
            This closes hub {hubId} and signs everyone out of it. Records stay archived until they
            are exported or purged.
          </p>
          <div className="billing-modal-actions">
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDeleteOpen(false)}
            >
              Cancel
            </button>
            <button
              type="button"
              className="billing-delete-button"
              disabled={busy === 'close'}
              onClick={() => void closeHub()}
            >
              Confirm
            </button>
          </div>
        </section>
      </div>
      <div className="billing-toast" role="status" aria-live="polite" hidden={!toast}>
        {toast}
      </div>
    </div>
  );
}
