'use client';

import Link from 'next/link';
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
  type RefObject,
} from 'react';
import { createPortal } from 'react-dom';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { pagerItems } from '@/features/snippets/model';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  getBusinessSettings,
  getExchangeRateHistory,
  getExchangeRateLog,
  getProfile,
  setAutomaticExchangeRates,
  updateBusinessSettings,
  updateProfile,
} from '../api.client';
import type {
  BusinessSettings,
  ExchangeRateFrequency,
  ExchangeRateHistoryEntry,
  ExchangeRateLogEntry,
  ExchangeRateUpdates,
  NotificationProfile,
  UpdateBusinessSettingsBody,
} from '../types';
import { formatPreview, timezoneOptions } from './accountDefaultsZones';
import { CompanyHolidaysPanel } from './CompanyHolidaysPanel';
import { NotificationProfilesPanel } from './NotificationProfilesPanel';
import {
  DialogHead,
  DrawerForm,
  InfoLabel,
  SetDialog,
  SetTabs,
  SettingsForm,
  SettingsFormsProvider,
  SuField,
  TabPanel,
  useHashTab,
} from './settings-ui';
import './account-defaults.css';

/**
 * Settings > Account Management > Account Defaults
 * Design source: settings-account-defaults.php (04-11-2026 pack).
 * Visible design tabs: General | User Defaults | Notification Profiles | Currency | Feature Releases
 * (same order as the live design). Feature Releases toggles save immediately (account lateReleases
 * via PATCH /business/settings; per-user releaseEmails via PATCH /me/profile). Notification
 * profiles are saved with the account.
 * Company Holidays is still reachable via #holidays (Sequences links here) but not in the
 * design tab bar.
 * Wired: GET/PATCH /business/settings for company details, timezone, fiscal year,
 * currency (including extra currencies), and User Defaults (language, region format, email font).
 */

const DESIGN_TABS = [
  { id: 'general', label: 'General' },
  { id: 'user-defaults', label: 'User Defaults' },
  { id: 'notification-profiles', label: 'Notification Profiles' },
  { id: 'currency', label: 'Currency' },
  { id: 'feature-releases', label: 'Feature Releases' },
];

/** Includes hash-only Company Holidays for Sequences deep links. */
const TABS = [...DESIGN_TABS, { id: 'holidays', label: 'Company Holidays' }];

const FISCAL = [
  'January - December',
  'February - January',
  'March - February',
  'April - March',
  'May - April',
  'June - May',
  'July - June',
  'August - July',
  'September - August',
  'October - September',
  'November - October',
  'December - November',
];

const INDUSTRIES = [
  'Accounting',
  'Advertising & Marketing',
  'Automotive',
  'Banking & Financial Services',
  'Computer Software',
  'Consulting',
  'E-commerce',
  'Education',
  'Healthcare',
  'Hospitality',
  'Information Technology',
  'Insurance',
  'Logistics & Supply Chain',
  'Manufacturing',
  'Media & Publishing',
  'Non-profit',
  'Real Estate',
  'Retail',
  'Telecommunications',
  'Travel & Tourism',
  'Other',
];

/** Matches Profile / API `LANGUAGES` + `REGION_FORMATS`. */
const LANGUAGES: [BusinessSettings['defaultLanguage'], string][] = [
  ['en', 'English'],
  ['hi', 'Hindi'],
  ['es', 'Español'],
  ['fr', 'Français'],
  ['de', 'Deutsch'],
];

/** value → label. QA #377: the preview is built from today's date (formatPreview). */
const REGION_FORMATS: [BusinessSettings['defaultRegionFormat'], string][] = [
  ['us', 'United States'],
  ['uk', 'United Kingdom'],
  ['in', 'India'],
  ['de', 'Germany'],
];

const FONTS: [BusinessSettings['defaultEmailFont'], string][] = [
  ['Sans Serif', 'Arial, Helvetica, sans-serif'],
  ['Serif', 'Georgia, serif'],
  ['Arial', 'Arial, sans-serif'],
  ['Georgia', 'Georgia, serif'],
  ['Tahoma', 'Tahoma, sans-serif'],
  ['Verdana', 'Verdana, sans-serif'],
  ['Courier New', '"Courier New", monospace'],
];

const SIZES = [9, 10, 11, 12, 13, 14, 16, 18] as const;

/** View history drawer: rows per page (matches design pager; history cap is 50). */
const FX_HIST_PAGE_SIZE = 10;

/** code → [name, symbol] */
const CURRENCY_LIST: Record<string, [string, string]> = {
  USD: ['US Dollar', '$'],
  INR: ['Indian Rupee', '₹'],
  EUR: ['Euro', '€'],
  GBP: ['British Pound', '£'],
  AED: ['UAE Dirham', 'AED'],
  SGD: ['Singapore Dollar', 'S$'],
  AUD: ['Australian Dollar', 'A$'],
  JPY: ['Japanese Yen', '¥'],
  CAD: ['Canadian Dollar', 'C$'],
};

type CurrencyFormat = '1,234.56' | '1.234,56' | '1 234,56';

type ExtraCurrency = {
  code: string;
  rate: number;
  format: string;
  updated: string;
};

const currencyFormat = (value: string): CurrencyFormat =>
  value === '1.234,56' || value === '1 234,56' ? value : '1,234.56';

const currencyLabel = (code: string) => {
  const [name, symbol] = CURRENCY_LIST[code] ?? [code, ''];
  return `${name} (${code}) ${symbol}`.trim();
};

/** Compact US date like the design (e.g. 11/20/2026). */
const curUpdatedDate = (isoOrEmpty: string) => {
  if (!isoOrEmpty) return '';
  const d = new Date(isoOrEmpty);
  if (Number.isNaN(d.getTime())) return isoOrEmpty;
  return d.toLocaleDateString('en-US');
};

/**
 * Portaled Actions menu (PHP `#currency .dropdown__menu`). Fixed + body portal so
 * `.set-table-card` overflow does not clip it; `right: auto` avoids global `.dropdown__menu`
 * stretch (`right: 0` + `left`).
 */
function CurActionsMenu({
  open,
  anchorRef,
  children,
}: {
  open: boolean;
  anchorRef: RefObject<HTMLButtonElement | null>;
  children: ReactNode;
}) {
  const [place, setPlace] = useState<CSSProperties | undefined>();

  useLayoutEffect(() => {
    if (!open) {
      setPlace(undefined);
      return;
    }
    const position = () => {
      const btn = anchorRef.current?.getBoundingClientRect();
      if (!btn) return;
      const width = 220;
      const left = Math.min(Math.max(8, btn.left), window.innerWidth - width - 8);
      setPlace({
        position: 'fixed',
        top: btn.bottom + 4,
        left,
        right: 'auto',
        width,
        zIndex: 1100,
      });
    };
    position();
    window.addEventListener('scroll', position, true);
    window.addEventListener('resize', position);
    return () => {
      window.removeEventListener('scroll', position, true);
      window.removeEventListener('resize', position);
    };
  }, [open, anchorRef]);

  if (!open || !place || typeof document === 'undefined') return null;

  return createPortal(
    <div
      className="dropdown__menu cur-actions-menu"
      role="menu"
      data-cur-actions-menu=""
      style={place}
    >
      {children}
    </div>,
    document.body,
  );
}

const sampleAmount = (code: string, pattern = '1,234.56') => {
  try {
    const n = 123456.78;
    if (pattern === '1.234,56') {
      return `${CURRENCY_LIST[code]?.[1] ?? ''}${n
        .toFixed(2)
        .replace('.', ',')
        .replace(/\B(?=(\d{3})+(?!\d))/g, '.')}`;
    }
    if (pattern === '1 234,56') {
      return `${CURRENCY_LIST[code]?.[1] ?? ''}${n
        .toFixed(2)
        .replace('.', ',')
        .replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}`;
    }
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: code }).format(n);
  } catch {
    return `${code} 123,456.78`;
  }
};

const field = (form: HTMLFormElement, name: string) =>
  (form.elements.namedItem(name) as HTMLInputElement | HTMLSelectElement | null)?.value ?? '';
const textOrNull = (v: string) => (v.trim() ? v.trim() : null);
const stopEvent = (e: React.SyntheticEvent) => e.stopPropagation();

const FREQUENCY_LABEL: Record<ExchangeRateFrequency, string> = {
  monthly: 'Monthly',
  quarterly: 'Quarterly',
  yearly: 'Yearly',
};

/** YYYY-MM-DD → MM/DD/YYYY, as the HubSpot-style status line shows it. */
const usDate = (day: string) => {
  const [y, m, d] = day.split('-');
  return `${m}/${d}/${y}`;
};

/** An ISO time in the viewer's zone, e.g. 11/20/2026, 4:47 PM. */
const whenText = (iso: string) =>
  new Date(iso).toLocaleString('en-US', {
    month: '2-digit',
    day: '2-digit',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });

/** A rate as typed: no trailing zeros, up to 8 decimals. */
const rateText = (rate: number | null) => (rate === null ? '—' : String(Number(rate.toFixed(8))));

export function AccountDefaultsSettingsView() {
  const me = useCurrentUser();
  const toast = useToast();
  const [tab, setTab] = useHashTab(TABS);
  const [openDefaults, setOpenDefaults] = useState(0);
  const isAdmin = me.role === 'admin';

  const [settings, setSettings] = useState<BusinessSettings | null>(null);
  const updatedAt = useRef<string | undefined>(undefined);
  const tzInput = useRef<HTMLInputElement>(null);

  const [formatKey, setFormatKey] = useState<BusinessSettings['defaultRegionFormat']>('us');
  const [fontName, setFontName] = useState<BusinessSettings['defaultEmailFont']>('Sans Serif');
  const [fontSize, setFontSize] = useState(11);
  const [fontColor, setFontColor] = useState('#444444');

  const [fx, setFx] = useState<ExchangeRateUpdates | null>(null);
  const fxOn = fx?.enabled ?? false;
  const [fxFreqOpen, setFxFreqOpen] = useState(false);
  const [fxOffOpen, setFxOffOpen] = useState(false);
  const [fxHistoryOpen, setFxHistoryOpen] = useState(false);
  const [fxHistPage, setFxHistPage] = useState(1);
  const [fxHistRows, setFxHistRows] = useState<ExchangeRateHistoryEntry[] | null>(null);
  const [fxHistTotalPages, setFxHistTotalPages] = useState(0);
  const [fxHistLoading, setFxHistLoading] = useState(false);
  const [extras, setExtras] = useState<ExtraCurrency[]>([]);
  const [addOpen, setAddOpen] = useState(false);
  const [addCurrencyCode, setAddCurrencyCode] = useState('');
  const [editOpen, setEditOpen] = useState(false);
  const [logOpen, setLogOpen] = useState(false);
  const [logRows, setLogRows] = useState<ExchangeRateLogEntry[] | null>(null);
  const [logCode, setLogCode] = useState('');
  const [logDate, setLogDate] = useState('');
  const [editTarget, setEditTarget] = useState<'company' | string>('company');
  const [companyFormat, setCompanyFormat] = useState<CurrencyFormat>('1,234.56');
  const [profiles, setProfiles] = useState<NotificationProfile[]>([]);
  const [curActionsOpen, setCurActionsOpen] = useState<string | null>(null);
  const curActionsAnchorRef = useRef<HTMLButtonElement | null>(null);
  const [archiveTarget, setArchiveTarget] = useState<ExtraCurrency | null>(null);
  const [setCompanyTarget, setSetCompanyTarget] = useState<ExtraCurrency | null>(null);
  const [curHistoryOpen, setCurHistoryOpen] = useState(false);
  const [curHistoryCode, setCurHistoryCode] = useState('');
  const [curHistoryRows, setCurHistoryRows] = useState<ExchangeRateLogEntry[] | null>(null);
  const [releaseEmails, setReleaseEmails] = useState(true);
  const [frBusy, setFrBusy] = useState<'late' | 'emails' | null>(null);
  const profileUpdatedAt = useRef<string | undefined>(undefined);

  useEffect(() => {
    getBusinessSettings().then(
      (s) => {
        updatedAt.current = s.updatedAt;
        setSettings(s);
        setFormatKey(s.defaultRegionFormat);
        setFontName(s.defaultEmailFont);
        setFontSize(s.defaultEmailFontSize);
        setFontColor(s.defaultEmailFontColor);
        setProfiles(s.notificationProfiles ?? []);
        setFx(s.exchangeRateUpdates ?? null);
        setExtras(
          (s.extraCurrencies ?? []).map((c) => ({
            code: c.code,
            rate: c.rate,
            format: c.format,
            updated: c.updatedAt ? curUpdatedDate(c.updatedAt) : '',
          })),
        );
      },
      (err) => toast(errorText(err), 'danger'),
    );
    getProfile().then(
      (p) => {
        profileUpdatedAt.current = p.updatedAt;
        setReleaseEmails(p.preferences.releaseEmails !== false);
      },
      () => {
        /* Profile load failure shouldn't block Account Defaults; checkbox keeps default on. */
      },
    );
  }, [toast]);

  const save = useCallback(
    async (body: UpdateBusinessSettingsBody) => {
      try {
        const s = await updateBusinessSettings({ ...body, updatedAt: updatedAt.current });
        updatedAt.current = s.updatedAt;
        setSettings(s);
        setProfiles(s.notificationProfiles ?? []);
        setFx(s.exchangeRateUpdates ?? null);
        setExtras(
          (s.extraCurrencies ?? []).map((c) => ({
            code: c.code,
            rate: c.rate,
            format: c.format,
            updated: c.updatedAt ? curUpdatedDate(c.updatedAt) : '',
          })),
        );
      } catch (err) {
        toast(
          isApiError(err) && err.isConflict
            ? 'These settings changed somewhere else. Reload the page to see the latest values.'
            : errorText(err),
          'danger',
        );
        return false;
      }
    },
    [toast],
  );

  const saveGeneral = useCallback(
    (form: HTMLFormElement) => {
      // Design shows Account name + Company name; API only stores one `name`.
      // Keep the company field aligned so Save does not freeze a fake value.
      const accountName = field(form, 'account_name').trim();
      const companyInput = form.elements.namedItem('company_name');
      if (companyInput instanceof HTMLInputElement) companyInput.value = accountName;

      return save({
        name: accountName,
        timezone: field(form, 'timezone'),
        fiscalYearStartMonth: Math.min(
          12,
          Math.max(1, FISCAL.indexOf(field(form, 'fiscal_year')) + 1),
        ),
        domain: textOrNull(field(form, 'company_domain')),
        addressLine1: textOrNull(field(form, 'address')),
        addressLine2: textOrNull(field(form, 'address2')),
        city: textOrNull(field(form, 'city')),
        state: textOrNull(field(form, 'state')),
        postalCode: textOrNull(field(form, 'zip')),
        country: textOrNull(field(form, 'country')),
        industry: textOrNull(field(form, 'industry')),
      });
    },
    [save],
  );

  const saveUserDefaults = useCallback(
    (form: HTMLFormElement) =>
      save({
        defaultLanguage: field(form, 'language') as BusinessSettings['defaultLanguage'],
        defaultRegionFormat: field(form, 'format') as BusinessSettings['defaultRegionFormat'],
        defaultEmailFont: field(form, 'email_font') as BusinessSettings['defaultEmailFont'],
        defaultEmailFontSize: Number(field(form, 'email_size')),
        defaultEmailFontColor: field(form, 'email_color').toUpperCase(),
      }),
    [save],
  );

  // QA #377: every IANA zone, labelled with its offset today (DST-aware).
  const savedZone = settings?.timezone;
  const timezones = useMemo(() => timezoneOptions(new Date(), savedZone), [savedZone]);
  const [timezone, setTimezone] = useState('');
  useEffect(() => {
    if (savedZone) setTimezone(savedZone);
  }, [savedZone]);
  const [fiscalMonth, setFiscalMonth] = useState(1);
  useEffect(() => {
    const month = settings?.fiscalYearStartMonth;
    if (month) setFiscalMonth(month);
  }, [settings?.fiscalYearStartMonth]);

  const fontStack = FONTS.find(([n]) => n === fontName)?.[1] ?? FONTS[0]![1];
  const formatExample = formatPreview(formatKey, new Date(), timezone || undefined);

  const resetUserDefaultsPreview = useCallback(() => {
    if (!settings) return;
    setFormatKey(settings.defaultRegionFormat);
    setFontName(settings.defaultEmailFont);
    setFontSize(settings.defaultEmailFontSize);
    setFontColor(settings.defaultEmailFontColor);
  }, [settings]);
  const usedCodes = useMemo(
    () => new Set([settings?.currency, ...extras.map((e) => e.code)].filter(Boolean) as string[]),
    [settings?.currency, extras],
  );
  const addCurrencyOptions = useMemo(
    () =>
      Object.entries(CURRENCY_LIST)
        .filter(([code]) => !usedCodes.has(code))
        .map(([code, [name, symbol]]) => ({
          value: code,
          label: `${name} (${code}) ${symbol}`,
        })),
    [usedCodes],
  );
  const currencyCount = 1 + extras.length;

  const openEdit = (code: 'company' | string) => {
    setEditTarget(code);
    setEditOpen(true);
  };

  /** Feature Releases › Gradual Releases (account-wide). Saves on toggle; PHP toast copy. */
  const onLateReleasesChange = async (checked: boolean) => {
    if (!isAdmin || frBusy) return;
    const prev = settings?.lateReleases === true;
    setSettings((s) => (s ? { ...s, lateReleases: checked } : s));
    setFrBusy('late');
    const ok = await save({ lateReleases: checked });
    setFrBusy(null);
    if (ok === false) {
      setSettings((s) => (s ? { ...s, lateReleases: prev } : s));
      return;
    }
    toast(
      checked
        ? 'Your account will now be placed at the end of gradual releases.'
        : 'Your account will no longer be placed at the end of gradual releases.',
      'success',
    );
  };

  /** Feature Releases › Email Notifications (current user only). Saves on toggle; PHP toast copy. */
  const onReleaseEmailsChange = async (checked: boolean) => {
    if (frBusy) return;
    const prev = releaseEmails;
    setReleaseEmails(checked);
    setFrBusy('emails');
    try {
      const next = await updateProfile({
        preferences: { releaseEmails: checked },
        updatedAt: profileUpdatedAt.current,
      });
      profileUpdatedAt.current = next.updatedAt;
      setReleaseEmails(next.preferences.releaseEmails !== false);
      toast(
        checked
          ? 'You have subscribed to weekly product update emails.'
          : 'You have unsubscribed to weekly product update emails.',
        'success',
      );
    } catch (err) {
      setReleaseEmails(prev);
      toast(errorText(err), 'danger');
    } finally {
      setFrBusy(null);
    }
  };

  const openCurrencyHistory = (code: string) => {
    setCurActionsOpen(null);
    setCurHistoryCode(code);
    setCurHistoryRows(null);
    setCurHistoryOpen(true);
    void getExchangeRateLog({ code })
      .then(setCurHistoryRows)
      .catch((err: unknown) => {
        toast(errorText(err), 'danger');
        setCurHistoryRows([]);
      });
  };

  const confirmArchiveCurrency = async () => {
    if (!archiveTarget) return;
    const code = archiveTarget.code;
    const next = extras.filter((c) => c.code !== code);
    const ok = await save({
      extraCurrencies: next.map((c) => ({
        code: c.code,
        rate: c.rate,
        format: currencyFormat(c.format),
        updatedAt: new Date().toISOString(),
      })),
    });
    if (ok === false) return;
    setArchiveTarget(null);
    toast(`${currencyLabel(code)} archived`, 'info');
  };

  /** Promote an extra currency to company currency; invert rates so 1 new-company stays consistent. */
  const confirmSetCompanyCurrency = async () => {
    if (!setCompanyTarget || !settings) return;
    const nextCode = setCompanyTarget.code;
    const nextRate = setCompanyTarget.rate;
    if (!Number.isFinite(nextRate) || nextRate <= 0) {
      toast('Exchange rate must be greater than zero', 'danger');
      return;
    }
    const oldCode = settings.currency;
    const inverted = Number((1 / nextRate).toFixed(8));
    const rest = extras
      .filter((c) => c.code !== nextCode)
      .map((c) => ({
        code: c.code,
        rate: Number((c.rate / nextRate).toFixed(8)),
        format: currencyFormat(c.format),
        updatedAt: new Date().toISOString(),
      }));
    const ok = await save({
      currency: nextCode,
      extraCurrencies: [
        {
          code: oldCode,
          rate: inverted,
          format: companyFormat,
          updatedAt: new Date().toISOString(),
        },
        ...rest,
      ],
    });
    if (ok === false) return;
    setCompanyFormat(currencyFormat(setCompanyTarget.format));
    setSetCompanyTarget(null);
    toast(`${currencyLabel(nextCode)} is now the company currency`, 'success');
  };

  useEffect(() => {
    if (!curActionsOpen) return;
    const onDoc = (e: MouseEvent) => {
      const t = e.target as Element | null;
      if (t?.closest?.('.cur-row-actions') || t?.closest?.('[data-cur-actions-menu]')) return;
      setCurActionsOpen(null);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setCurActionsOpen(null);
    };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [curActionsOpen]);

  /**
   * Turns automatic updates on or off, or changes the frequency. The server also moves the
   * business's update time, so the settings are read again: the next save must not be stale.
   */
  const applyFx = useCallback(
    async (body: { enabled: boolean; frequency: ExchangeRateFrequency }) => {
      try {
        const next = await setAutomaticExchangeRates(body);
        const s = await getBusinessSettings();
        updatedAt.current = s.updatedAt;
        setSettings(s);
        setFx(next);
        setExtras(
          (s.extraCurrencies ?? []).map((c) => ({
            code: c.code,
            rate: c.rate,
            format: c.format,
            updated: c.updatedAt ? curUpdatedDate(c.updatedAt) : '',
          })),
        );
        return next;
      } catch (err) {
        toast(errorText(err), 'danger');
        return null;
      }
    },
    [toast],
  );

  const loadLog = useCallback(
    async (code: string, date: string) => {
      try {
        setLogRows(await getExchangeRateLog({ code: code || undefined, date: date || undefined }));
      } catch (err) {
        toast(errorText(err), 'danger');
        setLogRows([]);
      }
    },
    [toast],
  );

  const loadFxHistory = useCallback(
    async (page: number) => {
      setFxHistLoading(true);
      try {
        const res = await getExchangeRateHistory({ page, limit: FX_HIST_PAGE_SIZE });
        setFxHistRows(res.items);
        setFxHistPage(res.page);
        setFxHistTotalPages(res.totalPages);
      } catch (err) {
        toast(errorText(err), 'danger');
        setFxHistRows([]);
        setFxHistTotalPages(0);
      } finally {
        setFxHistLoading(false);
      }
    },
    [toast],
  );

  const openFxHistory = () => {
    setFxHistRows(null);
    setFxHistPage(1);
    setFxHistoryOpen(true);
    void loadFxHistory(1);
  };

  const openLog = () => {
    const code = logCode || settings?.currency || '';
    setLogCode(code);
    setLogRows(null);
    setLogOpen(true);
    void loadLog(code, logDate);
  };

  const logCurrencyOptions = useMemo(() => {
    const codes = [settings?.currency, ...extras.map((e) => e.code)].filter(
      (c): c is string => !!c,
    );
    return [...new Set(codes)].map((code) => ({
      value: code,
      label: currencyLabel(code),
    }));
  }, [settings?.currency, extras]);

  const editRow =
    editTarget === 'company' ? null : (extras.find((e) => e.code === editTarget) ?? null);

  const header = (
    <>
      <header className="set-head">
        <h1 className="set-head__title">Account Defaults</h1>
      </header>
      <SetTabs
        label="Account defaults"
        tabs={DESIGN_TABS}
        active={tab}
        onSelect={setTab}
        boxed
        className="ad-tabs"
      />
    </>
  );

  if (!settings) {
    return (
      <>
        {header}
        <p className="crm-text-muted">Loading account settings…</p>
      </>
    );
  }

  return (
    <SettingsFormsProvider>
      {header}

      {/* ============================================================ GENERAL */}
      <TabPanel id="general" active={tab}>
        <p className="set-intro">These defaults will be applied to the entire account.</p>

        <SettingsForm
          className="set-stack"
          onSave={saveGeneral}
          onReset={() => {
            // a hidden input keeps its value on form.reset(), so put the saved zone back
            if (tzInput.current) tzInput.current.value = settings.timezone;
            setTimezone(settings.timezone);
            setFiscalMonth(settings.fiscalYearStartMonth);
          }}
          readOnly={!isAdmin}
        >
          <div className="field">
            <InfoLabel
              htmlFor="ad-name"
              text="Account name"
              tip="The name shown in the account menu and when you switch between accounts."
            />
            <input
              className="input"
              id="ad-name"
              name="account_name"
              defaultValue={settings.name}
              required
              maxLength={100}
            />
            <p className="field__error">Enter an account name</p>
          </div>

          <div className="field">
            <InfoLabel
              htmlFor="ad-tz"
              text="Time zone"
              tip="Used for reports, scheduled emails, workflows and anywhere a user has not set their own time zone."
            />
            {/* typing in the zone search box is not an unsaved change */}
            <div onInput={stopEvent} onChange={stopEvent}>
              <CustomSelect
                id="ad-tz"
                placeholder="Time zone"
                searchPlaceholder="Search time zones"
                value={timezone}
                options={timezones}
                disabled={!isAdmin}
                menuMinWidth={320}
                onChange={(v) => {
                  if (!v || v === timezone) return;
                  setTimezone(v);
                  // the form tracks unsaved changes from native input events
                  const input = tzInput.current;
                  if (input) {
                    input.value = v;
                    input.dispatchEvent(new Event('input', { bubbles: true }));
                  }
                }}
              />
            </div>
            <input ref={tzInput} type="hidden" name="timezone" defaultValue={settings.timezone} />
          </div>

          <div className="field">
            <InfoLabel
              htmlFor="ad-fy"
              text="Fiscal year"
              tip="Sets the start month for fiscal-quarter and fiscal-year date ranges in reports and forecasts."
            />
            <select
              className="input"
              id="ad-fy"
              name="fiscal_year"
              value={FISCAL[fiscalMonth - 1] ?? FISCAL[0]}
              disabled={!isAdmin}
              onChange={(e) => setFiscalMonth(FISCAL.indexOf(e.target.value) + 1)}
            >
              {FISCAL.map((f) => (
                <option key={f} value={f}>
                  {f}
                </option>
              ))}
            </select>
          </div>

          <div className="set-block">
            <h2 className="set-block__title">Company Information</h2>
            <p className="set-block__sub">
              This information will be used as a default where needed. If you&apos;re looking to
              update your company information for billing, visit{' '}
              <Link className="link" href="/settings/billing">
                Account &amp; Billing
              </Link>
              .
            </p>
          </div>

          <div className="field">
            <label className="field__label" htmlFor="co-name">
              Company name
            </label>
            <input
              className="input"
              id="co-name"
              name="company_name"
              defaultValue={settings.name}
              maxLength={100}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="co-domain">
              Company domain
            </label>
            <input
              className="input"
              id="co-domain"
              name="company_domain"
              defaultValue={settings.domain ?? ''}
              placeholder="yourcompany.com"
              // Settings audit: checked before saving, like the API's #506 rule. A pasted
              // https://www.acme.com/about is fine: the API keeps only the host.
              pattern="^(https?:\/\/)?([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}(:\d+)?(\/\S*)?$"
              maxLength={191}
              aria-describedby="co-domain-error"
            />
            <p className="field__error" id="co-domain-error">
              Enter a domain like yourcompany.com
            </p>
          </div>
          <div className="field">
            <label className="field__label" htmlFor="co-addr">
              Company address
            </label>
            <input
              className="input"
              id="co-addr"
              name="address"
              defaultValue={settings.addressLine1 ?? ''}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="co-addr2">
              Company address line 2
            </label>
            <input
              className="input"
              id="co-addr2"
              name="address2"
              defaultValue={settings.addressLine2 ?? ''}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="co-city">
              City
            </label>
            <input className="input" id="co-city" name="city" defaultValue={settings.city ?? ''} />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="co-state">
              State
            </label>
            <input
              className="input"
              id="co-state"
              name="state"
              defaultValue={settings.state ?? ''}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="co-zip">
              Zip
            </label>
            <input
              className="input"
              id="co-zip"
              name="zip"
              defaultValue={settings.postalCode ?? ''}
              maxLength={20}
              pattern="[A-Za-z0-9][A-Za-z0-9 \-]{0,18}[A-Za-z0-9]?"
              title="Enter a valid ZIP code"
              autoComplete="postal-code"
              aria-describedby="co-zip-error"
            />
            <p className="field__error" id="co-zip-error">
              Enter a valid ZIP code
            </p>
          </div>
          <div className="field">
            <label className="field__label" htmlFor="co-country">
              Country
            </label>
            <input
              className="input"
              id="co-country"
              name="country"
              defaultValue={settings.country ?? ''}
              maxLength={100}
              pattern="[A-Za-z][A-Za-z .'\-]{0,98}"
              title="Enter a valid country name"
              autoComplete="country-name"
              aria-describedby="co-country-error"
            />
            <p className="field__error" id="co-country-error">
              Enter a valid country name
            </p>
          </div>
          <div className="field">
            <InfoLabel
              htmlFor="co-industry"
              text="Industry"
              tip="Helps tailor templates, benchmarks and recommendations to your business."
            />
            <select
              className="input"
              id="co-industry"
              name="industry"
              defaultValue={settings.industry ?? ''}
            >
              <option value="">Select an industry</option>
              {settings.industry && !INDUSTRIES.includes(settings.industry) ? (
                <option value={settings.industry}>{settings.industry}</option>
              ) : null}
              {INDUSTRIES.map((name) => (
                <option key={name} value={name}>
                  {name}
                </option>
              ))}
            </select>
          </div>
        </SettingsForm>
      </TabPanel>

      {/* ====================================================== USER DEFAULTS */}
      <TabPanel id="user-defaults" active={tab}>
        <p className="set-intro">
          Set defaults for users in your account. To add or edit user permissions go to{' '}
          <Link className="link" href="/settings/users">
            Users &amp; Teams
          </Link>
          .
        </p>

        <SettingsForm
          className="set-stack"
          onSave={saveUserDefaults}
          onReset={resetUserDefaultsPreview}
          readOnly={!isAdmin}
        >
          {/* Design always shows this notice (settings-account-defaults.php User Defaults). */}
          <p className="crm-border crm-p-3 crm-rounded-3 crm-w-100">
            To edit these settings, you must be an authorized user.
          </p>

          <div className="set-block">
            <h2 className="set-block__title">New user defaults</h2>
            <p className="set-block__sub">
              Set defaults for users added to your account. They can update this in user
              preferences.
            </p>
          </div>

          <div className="field">
            <InfoLabel
              htmlFor="ud-lang"
              text="Language"
              tip="The interface language new users start with."
            />
            <select
              className="input"
              id="ud-lang"
              name="language"
              defaultValue={settings.defaultLanguage}
            >
              {LANGUAGES.map(([value, label]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </select>
          </div>
          <br />
          <div className="field">
            <InfoLabel
              htmlFor="ud-format"
              text="Date and number format"
              tip="How dates and numbers are displayed for new users."
            />
            <p className="field__help set-format-preview" data-format-preview>
              Format: {formatExample}
            </p>
            <select
              className="input"
              id="ud-format"
              name="format"
              defaultValue={settings.defaultRegionFormat}
              data-format-select=""
              onChange={(e) =>
                setFormatKey(e.target.value as BusinessSettings['defaultRegionFormat'])
              }
            >
              {REGION_FORMATS.map(([value, label]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </select>
          </div>

          <div className="set-block">
            <h2 className="set-block__title">Notifications</h2>
            <p className="set-block__sub">
              Set notification defaults for all users in your account. They can update this in user
              preferences.
            </p>
            {/* Sheet 23 Nov: opens the account's default notifications (all users not in a
                preset profile), not the signed-in user's own Notifications page. */}
            <button
              type="button"
              className="link crm-fw-semibold crm-d-inline-block crm-mt-3"
              disabled={!isAdmin}
              onClick={() => {
                setTab('notification-profiles');
                setOpenDefaults((n) => n + 1);
              }}
            >
              Manage account defaults
            </button>
            <p className="set-block__sub">
              Set up the default notifications for all users in your account who are not included in
              a profile.
            </p>
          </div>

          <div className="set-block">
            <h2 className="set-block__title">Email</h2>
            <p className="set-block__sub">
              This default will apply to outgoing emails from the CRM and Inbox email editors for
              all users of this account.
            </p>
          </div>
          <div className="field">
            <span className="field__label">Font</span>
            <div className="font-row">
              <select
                className="input"
                name="email_font"
                aria-label="Font"
                data-font-family=""
                defaultValue={settings.defaultEmailFont}
                onChange={(e) =>
                  setFontName(e.target.value as BusinessSettings['defaultEmailFont'])
                }
              >
                {FONTS.map(([name, stack]) => (
                  <option key={name} value={name} data-stack={stack}>
                    {name}
                  </option>
                ))}
              </select>
              <select
                className="input font-row__size"
                name="email_size"
                aria-label="Font size"
                data-font-size=""
                defaultValue={settings.defaultEmailFontSize}
                onChange={(e) => setFontSize(Number(e.target.value))}
              >
                {SIZES.map((s) => (
                  <option key={s} value={s}>
                    {s} pt
                  </option>
                ))}
              </select>
              <input
                type="color"
                className="font-row__color"
                name="email_color"
                defaultValue={settings.defaultEmailFontColor}
                aria-label="Font color"
                data-font-color=""
                onChange={(e) => setFontColor(e.target.value)}
              />
            </div>
            <p
              className="font-preview"
              data-font-preview=""
              style={{ fontFamily: fontStack, fontSize: `${fontSize}pt`, color: fontColor }}
            >
              Hi Penelope, thanks for your time today. Here is the proposal we discussed.
            </p>
          </div>
        </SettingsForm>
      </TabPanel>

      {/* =========================================================== CURRENCY */}
      {/* ============================================ NOTIFICATION PROFILES */}
      <TabPanel id="notification-profiles" active={tab}>
        <NotificationProfilesPanel
          isAdmin={isAdmin}
          profiles={profiles}
          currentUserName={me.user.name}
          onSave={async (next) => (await save({ notificationProfiles: next })) !== false}
          openAccountDefaults={openDefaults}
        />
      </TabPanel>

      <TabPanel id="currency" active={tab}>
        <p className="set-intro">These defaults will be used for deals and properties.</p>
        {!isAdmin ? (
          <p className="crm-border crm-p-3 crm-rounded-3 crm-w-100 crm-mb-3">
            To edit these settings, you must be an authorized user.
          </p>
        ) : null}

        <div className="card set-card fx-card">
          <div>
            <p className="crm-fw-semibold">
              Schedule automatic exchange rate updates.{' '}
              <button
                type="button"
                className="link"
                onClick={() =>
                  toast(
                    'Each currency takes the rate of the first day of the chosen period. Updates run within a few days of that date.',
                    'info',
                  )
                }
              >
                Learn more
              </button>
            </p>
            {fxOn && fx?.nextUpdateOn ? (
              <p className="crm-text-body-secondary crm-mt-2" data-fx-status="">
                Frequency: {FREQUENCY_LABEL[fx.frequency]} | Update status: Next update on{' '}
                {usDate(fx.nextUpdateOn)}
              </p>
            ) : !fxOn ? (
              <p className="crm-text-body-secondary crm-mt-2" data-fx-status="">
                Automatic exchange rate updates are turned off.
              </p>
            ) : null}
            {fxOn && fx && fx.manualCurrencies.length > 0 ? (
              <p className="field__help crm-mt-1">
                Update by hand (not covered by the rate source): {fx.manualCurrencies.join(', ')}
              </p>
            ) : null}
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm crm-mt-2"
              onClick={openFxHistory}
            >
              View history
            </button>
          </div>
          <div className="crm-d-flex crm-align-items-center crm-gap-2">
            {fxOn && isAdmin ? (
              <button
                type="button"
                className="icon-btn icon-btn--ghost"
                aria-label="Edit update frequency"
                title="Edit frequency"
                onClick={() => setFxFreqOpen(true)}
              >
                <CrmIcon name="pencil" className="iconSize-16" />
              </button>
            ) : null}
            <label className="switch-labeled">
              <span data-switch-text="">{fxOn ? 'ON' : 'OFF'}</span>
              <span className="switch">
                <input
                  type="checkbox"
                  data-fx-toggle=""
                  aria-label="Schedule automatic exchange rate updates"
                  checked={fxOn}
                  disabled={!isAdmin}
                  onChange={(e) => (e.target.checked ? setFxFreqOpen(true) : setFxOffOpen(true))}
                />
                <span className="switch__track" />
              </span>
            </label>
          </div>
        </div>

        <div className="set-card__head">
          <h2 className="set-block__title">All Currencies</h2>
          <div className="set-head__actions crm-align-items-center">
            <span className="crm-text-body-secondary crm-fs-7">
              Currencies used: <span data-currency-count="">{currencyCount}</span> of 200
            </span>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={openLog}
            >
              Exchange rate log
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={!isAdmin}
              onClick={() => {
                setAddCurrencyCode('');
                setAddOpen(true);
              }}
            >
              Add Currency
            </button>
          </div>
        </div>

        <div className="alert alert--info fx-alert-banner crm-rounded-3 crm-p-3 crm-my-3 crm-d-flex crm-align-items-center crm-flex-wrap crm-gap-1">
          <span>
            Open records (including deals) use these exchange rates. Closed records use the
            exchange rate at the time of closing.
          </span>
          <a
            href="https://knowledge.hubspot.com/account-management/automatic-exchange-rate-updates#understand-automatic-updates-to-exchange-rates"
            target="_blank"
            rel="noopener noreferrer"
            className="link crm-fw-semibold crm-d-inline-flex crm-align-items-center crm-gap-1 crm-nowrap"
          >
            <span>Learn more</span>
            <CrmIcon name="external" className="iconSize-14" />
          </a>
        </div>

        <div className="card set-table-card">
          <table className="set-table cur-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Exchange rate</th>
                <th>Format</th>
                <th>Last updated</th>
              </tr>
            </thead>
            <tbody data-currency-rows="">
              <tr data-code={settings.currency} data-is-company="true">
                <td>
                  <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2">
                    <span className="crm-fw-semibold">{currencyLabel(settings.currency)}</span>
                    {isAdmin ? (
                      <div
                        className={cn(
                          'cur-row-actions',
                          curActionsOpen === 'company' && 'is-open',
                        )}
                      >
                        <div className="dropdown" data-dropdown="">
                          <button
                            type="button"
                            className="btn-crm btn-crm--outline btn-crm--xs crm-rounded-pill"
                            aria-haspopup="true"
                            aria-expanded={curActionsOpen === 'company'}
                            onClick={(e) => {
                              curActionsAnchorRef.current = e.currentTarget;
                              setCurActionsOpen((cur) => (cur === 'company' ? null : 'company'));
                            }}
                          >
                            Actions <CrmIcon name="chevron-down" className="iconSize-12" />
                          </button>
                        </div>
                      </div>
                    ) : null}
                  </div>
                </td>
                <td>
                  <span className="badge-company-currency">Company Currency</span>
                </td>
                <td className="crm-fw-semibold">
                  {sampleAmount(settings.currency, companyFormat)}
                </td>
                <td className="crm-text-body-secondary">
                  {curUpdatedDate(settings.updatedAt) || '—'}
                  <br />
                  <span className="crm-text-body-secondary crm-fs-8">
                    CRM UI
                    <br />
                    <span className="crm-d-flex crm-gap-1 crm-align-items-center">
                      by <CrmIcon name="user" className="iconSize-14" /> {me.user.name}
                    </span>
                  </span>
                </td>
              </tr>
              {extras.map((row) => (
                <tr key={row.code} data-code={row.code} data-is-company="false">
                  <td>
                    <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2">
                      <span className="crm-fw-semibold">{currencyLabel(row.code)}</span>
                      {isAdmin ? (
                        <div
                          className={cn(
                            'cur-row-actions',
                            curActionsOpen === row.code && 'is-open',
                          )}
                        >
                          <div className="dropdown" data-dropdown="">
                            <button
                              type="button"
                              className="btn-crm btn-crm--outline btn-crm--xs crm-rounded-pill"
                              aria-haspopup="true"
                              aria-expanded={curActionsOpen === row.code}
                              onClick={(e) => {
                                curActionsAnchorRef.current = e.currentTarget;
                                setCurActionsOpen((cur) => (cur === row.code ? null : row.code));
                              }}
                            >
                              Actions <CrmIcon name="chevron-down" className="iconSize-12" />
                            </button>
                          </div>
                          <button
                            type="button"
                            className="btn-crm btn-crm--outline btn-crm--xs crm-rounded-pill"
                            onClick={() => {
                              setCurActionsOpen(null);
                              setArchiveTarget(row);
                            }}
                          >
                            Archive
                          </button>
                        </div>
                      ) : null}
                    </div>
                  </td>
                  <td>{row.rate}</td>
                  <td className="crm-fw-semibold">{sampleAmount(row.code, row.format)}</td>
                  <td className="crm-text-body-secondary">
                    {row.updated || '—'}
                    <br />
                    <span className="crm-text-body-secondary crm-fs-8">
                      {fxOn ? 'HubSpot Exchange Rate Updates' : 'CRM UI'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <CurActionsMenu open={curActionsOpen !== null} anchorRef={curActionsAnchorRef}>
          {curActionsOpen === 'company' ? (
            <>
              <button
                type="button"
                className="dropdown__item"
                role="menuitem"
                onClick={() => openCurrencyHistory(settings.currency)}
              >
                View currency history
              </button>
              <button
                type="button"
                className="dropdown__item"
                role="menuitem"
                onClick={() => {
                  setCurActionsOpen(null);
                  openEdit('company');
                }}
              >
                Edit company currency
              </button>
            </>
          ) : curActionsOpen ? (
            <>
              <button
                type="button"
                className="dropdown__item"
                role="menuitem"
                onClick={() => openCurrencyHistory(curActionsOpen)}
              >
                View currency history
              </button>
              <button
                type="button"
                className="dropdown__item"
                role="menuitem"
                onClick={() => {
                  const row = extras.find((r) => r.code === curActionsOpen);
                  setCurActionsOpen(null);
                  if (row) setSetCompanyTarget(row);
                }}
              >
                Set as company currency
              </button>
            </>
          ) : null}
        </CurActionsMenu>
      </TabPanel>

      {/* ============================================ FEATURE RELEASES */}
      <TabPanel id="feature-releases" active={tab}>
        <p className="set-intro">Set defaults related to Feature Releases.</p>

        {/*
          Instant save on toggle (no Cancel/Save bar) — same as PHP settings-account-defaults.js.
          Gradual releases: PATCH /business/settings (admin). Emails: PATCH /me/profile (any user).
        */}
        <form id="fr-settings-form" noValidate onSubmit={(e) => e.preventDefault()}>
          <div className="set-block set-block--wide">
            <h2 className="set-block__title">Gradual Releases</h2>
            <p className="set-block__sub">
              When new features and tools are released, you can opt in to get them at the end of the
              gradual release. This gives you more time to test changes and prepare users. Upcoming
              release dates can be found on the Product Updates page.
            </p>
            <label className="check-row">
              <span className="check">
                <input
                  type="checkbox"
                  name="late_releases"
                  id="fr-late-releases"
                  checked={settings?.lateReleases === true}
                  disabled={!isAdmin || frBusy === 'late' || !settings}
                  onChange={(e) => void onLateReleasesChange(e.target.checked)}
                />
                <span className="check__box" aria-hidden="true" />
              </span>
              <span>Put this account at the end of gradual feature releases</span>
            </label>
            <p className="field__help check-row__note">
              Note: Opting into this setting will <strong>only</strong> apply to all future
              releases. Changes to this preference apply to the entire account.
            </p>
          </div>

          <div className="set-block set-block--wide">
            <h2 className="set-block__title">Email Notifications</h2>
            <p className="set-block__sub">
              Get weekly emails about the latest product updates. Changes to this preference will
              only apply to you.
            </p>
            <label className="check-row">
              <span className="check">
                <input
                  type="checkbox"
                  name="release_emails"
                  id="fr-release-emails"
                  checked={releaseEmails}
                  disabled={frBusy === 'emails'}
                  onChange={(e) => void onReleaseEmailsChange(e.target.checked)}
                />
                <span className="check__box" aria-hidden="true" />
              </span>
              <span>Turn on email notifications</span>
            </label>
          </div>
        </form>
      </TabPanel>

      {/* ============================================== COMPANY HOLIDAYS */}
      <TabPanel id="holidays" active={tab}>
        <CompanyHolidaysPanel isAdmin={isAdmin} />
      </TabPanel>

      {/* Add currency — centred modal (PHP #currency-dialog), not a side panel */}
      <DrawerForm
        id="currency-dialog"
        title="Add currency"
        open={addOpen}
        onClose={() => {
          setAddOpen(false);
          setAddCurrencyCode('');
        }}
        drawer={false}
        submitLabel="Add currency"
        success="Currency added"
        onSave={async (data) => {
          const code = String(data.get('code') || '').trim();
          const rate = Number(data.get('rate'));
          if (!code) {
            toast('Select a currency', 'danger');
            return false;
          }
          if (!Number.isFinite(rate) || rate <= 0) return false;
          if (usedCodes.has(code)) {
            toast(`${code} is already added`, 'danger');
            return false;
          }
          const ok = await save({
            extraCurrencies: [
              ...extras.map((c) => ({
                code: c.code,
                rate: c.rate,
                format: currencyFormat(c.format),
                updatedAt: new Date().toISOString(),
              })),
              {
                code,
                rate,
                format: '1,234.56' as const,
                updatedAt: new Date().toISOString(),
              },
            ],
          });
          if (ok === false) return false;
          setAddCurrencyCode('');
          return `${code} added`;
        }}
      >
        <div className="field">
          <InfoLabel
            htmlFor="cur-code"
            text="Currency"
            tip="Select a currency to add to your account"
          />
          {/* Inline (not portal): portaled menus sit under <dialog> top-layer and look detached. */}
          <CustomSelect
            id="cur-code"
            className="crm-w-100"
            placeholder="Select a currency"
            searchPlaceholder="Search"
            value={addCurrencyCode}
            options={addCurrencyOptions}
            onChange={setAddCurrencyCode}
            searchable
            menuActions={false}
            menuMinWidth={280}
          />
          <input type="hidden" name="code" value={addCurrencyCode} required />
        </div>
        <div className="field">
          <label className="field__label" htmlFor="cur-rate">
            Exchange rate
          </label>
          <input
            className="input"
            id="cur-rate"
            name="rate"
            type="number"
            step="any"
            min={0}
            required
            placeholder="e.g. 0.012"
          />
          <p className="field__help">1 {settings.currency} = ? of the new currency</p>
          <p className="field__error">Enter an exchange rate</p>
        </div>
      </DrawerForm>

      {/* Edit currency / company currency */}
      <DrawerForm
        key={`${editTarget}-${settings.currency}-${editRow?.rate ?? ''}-${companyFormat}`}
        id="cur-edit-dialog"
        title="Edit currency"
        open={editOpen}
        onClose={() => setEditOpen(false)}
        keep
        success="Currency updated"
        onSave={async (data) => {
          const format = currencyFormat(String(data.get('format') || '1,234.56'));
          if (editTarget === 'company') {
            setCompanyFormat(format);
            return `${settings.currency} updated`;
          }
          const rate = Number(data.get('rate'));
          if (!Number.isFinite(rate) || rate <= 0) return false;
          const ok = await save({
            extraCurrencies: extras.map((row) => ({
              code: row.code,
              rate: row.code === editTarget ? rate : row.rate,
              format: row.code === editTarget ? format : currencyFormat(row.format),
              updatedAt: new Date().toISOString(),
            })),
          });
          if (ok === false) return false;
          return `${editTarget} updated`;
        }}
      >
        <p className="crm-fw-semibold crm-mb-3" data-ce-name="">
          {editTarget === 'company' ? currencyLabel(settings.currency) : currencyLabel(editTarget)}
        </p>
        <SuField
          label="Exchange rate"
          htmlFor="ce-rate"
          help={`1 ${settings.currency} = ? of this currency. The company currency is always 1.`}
          error="This field is required"
        >
          <input
            className="input"
            id="ce-rate"
            name="rate"
            type="number"
            step="any"
            min={0}
            required
            disabled={editTarget === 'company'}
            defaultValue={editTarget === 'company' ? 1 : (editRow?.rate ?? '')}
          />
        </SuField>
        <SuField
          label="Number format"
          htmlFor="ce-format"
          help="Used when amounts in this currency are shown."
          error="This field is required"
        >
          <select
            className="input"
            id="ce-format"
            name="format"
            defaultValue={
              editTarget === 'company' ? companyFormat : (editRow?.format ?? '1,234.56')
            }
          >
            <option value="1,234.56">1,234.56</option>
            <option value="1.234,56">1.234,56</option>
            <option value="1 234,56">1 234,56</option>
          </select>
        </SuField>
      </DrawerForm>

      {/* Exchange rate log — centred modal matching PHP #ratelog-dialog */}
      <SetDialog
        id="ratelog-dialog"
        open={logOpen}
        onClose={() => setLogOpen(false)}
        labelledBy="rl-title"
      >
        <div>
          <DialogHead id="rl-title" title="Exchange rate log" onClose={() => setLogOpen(false)} />
          <div className="set-modal__body">
            <div className="field">
              <label className="field__label set-label" htmlFor="rl-company-currency">
                Current company currency
              </label>
              <input
                type="text"
                className="input crm-w-100"
                id="rl-company-currency"
                value={settings ? currencyLabel(settings.currency) : ''}
                disabled
                readOnly
              />
            </div>
            <div className="field">
              <label className="field__label set-label" htmlFor="rl-currency">
                Select currency
              </label>
              <CustomSelect
                id="rl-currency"
                className="crm-w-100"
                placeholder="Select currency"
                searchPlaceholder="Search"
                value={logCode}
                options={logCurrencyOptions}
                onChange={setLogCode}
                searchable
                menuActions={false}
              />
            </div>
            <div className="field">
              <label className="field__label set-label" htmlFor="rl-date">
                Select date
              </label>
              <div className="crm-date-input-wrap">
                <span className="crm-date-input-icon" aria-hidden>
                  <CrmIcon name="calendar" className="iconSize-16" />
                </span>
                <input
                  id="rl-date"
                  className="input crm-date-input"
                  type="date"
                  value={logDate}
                  onChange={(e) => setLogDate(e.target.value)}
                />
              </div>
            </div>
            <div className="crm-mt-1">
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                onClick={() => void loadLog(logCode, logDate)}
              >
                <span>Search log</span>
                <CrmIcon name="search" className="iconSize-14" />
              </button>
            </div>

            <div className="ratelog-results-wrap" hidden={logRows === null}>
              <table className="ratelog-results-table">
                <thead>
                  <tr>
                    <th>Exchange Rate</th>
                    <th>Updated On</th>
                  </tr>
                </thead>
                <tbody>
                  {logRows === null ? null : logRows.length === 0 ? (
                    <tr>
                      <td colSpan={2} className="crm-text-muted">
                        No rate changes found.
                      </td>
                    </tr>
                  ) : (
                    logRows.map((row) => {
                      const company = settings?.currency ?? '';
                      const rateLine =
                        row.code === company
                          ? `1 ${company} = 1 ${company} (Company currency)`
                          : `1 ${company} = ${rateText(row.newRate)} ${row.code}`;
                      const sourceLabel =
                        row.source === 'automatic'
                          ? 'HubSpot Exchange Rate Updates'
                          : 'CRM UI';
                      return (
                        <tr key={row.id}>
                          <td>{rateLine}</td>
                          <td>
                            <div>
                              {/^\d{4}-\d{2}-\d{2}$/.test(row.effectiveOn)
                                ? usDate(row.effectiveOn)
                                : whenText(row.at).split(',')[0]}
                            </div>
                            <div className="crm-text-muted">{sourceLabel}</div>
                            <div className="crm-text-muted crm-d-flex crm-align-items-center crm-gap-1">
                              <span>by</span>
                              <span className="user-avatar-mini" aria-hidden>
                                <CrmIcon name="user" className="iconSize-10" />
                              </span>
                              <span>{row.changedBy || '—'}</span>
                            </div>
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </SetDialog>

      {/* Automatic exchange rate updates: turn on, or change the frequency */}
      <DrawerForm
        key={`fx-freq-${fxFreqOpen}`}
        id="fx-freq-dialog"
        title="Update Exchange Rate Frequency"
        open={fxFreqOpen}
        onClose={() => setFxFreqOpen(false)}
        drawer={false}
        keep
        submitLabel="Update"
        onSave={async (data) => {
          const frequency = String(data.get('frequency') || 'monthly') as ExchangeRateFrequency;
          const next = await applyFx({ enabled: true, frequency });
          if (!next) return false;
          return fxOn
            ? 'Update frequency changed'
            : `Automatic exchange rate updates on (${FREQUENCY_LABEL[frequency].toLowerCase()})`;
        }}
      >
        <p className="field__help crm-mb-3">
          Each currency takes the rate of the first day of the chosen period. The next update date
          moves to match the new frequency.
        </p>
        <fieldset>
          <legend className="field__label crm-mb-2">
            Choose the frequency for updating exchange rates
          </legend>
          {(['monthly', 'quarterly', 'yearly'] as const).map((f) => (
            <label key={f} className="crm-d-flex crm-gap-2 crm-align-items-center crm-mb-2">
              <input
                type="radio"
                name="frequency"
                value={f}
                defaultChecked={(fx?.frequency ?? 'monthly') === f}
              />
              <span>{FREQUENCY_LABEL[f]}</span>
            </label>
          ))}
        </fieldset>
      </DrawerForm>

      {/* Automatic exchange rate updates: turn off (typed confirmation, as HubSpot asks) */}
      <DrawerForm
        key={`fx-off-${fxOffOpen}`}
        id="fx-off-dialog"
        title="Turn off automatic exchange rate updates?"
        open={fxOffOpen}
        onClose={() => setFxOffOpen(false)}
        drawer={false}
        submitLabel="Remove automatic updates"
        onSave={async (data) => {
          if (String(data.get('confirm') || '').trim() !== 'Confirm') {
            toast('Type Confirm to turn the updates off', 'danger');
            return false;
          }
          const next = await applyFx({ enabled: false, frequency: fx?.frequency ?? 'monthly' });
          return next ? 'Automatic exchange rate updates turned off' : false;
        }}
      >
        <p className="field__help crm-mb-3">
          No new exchange rates are fetched after this. The rates already set stay as they are.
        </p>
        <SuField label='Type "Confirm"' htmlFor="fx-confirm" error="Type Confirm to continue">
          <input className="input" id="fx-confirm" name="confirm" autoComplete="off" required />
        </SuField>
      </DrawerForm>

      {/* Automatic exchange rate updates: history (paginated) */}
      <SetDialog
        id="fx-history-drawer"
        open={fxHistoryOpen}
        onClose={() => setFxHistoryOpen(false)}
        drawer
        labelledBy="fx-hist-title"
      >
        <div>
          <DialogHead
            id="fx-hist-title"
            title="Exchange Rate Updates History"
            onClose={() => setFxHistoryOpen(false)}
          />
          <div className="set-modal__body">
            <div className="card set-table-card">
              <table className="set-table su-table">
                <thead>
                  <tr>
                    <th>Status</th>
                    <th>Updated on</th>
                  </tr>
                </thead>
                <tbody>
                  {fxHistRows === null || fxHistLoading ? (
                    <tr>
                      <td colSpan={2} className="crm-text-body-secondary">
                        Loading…
                      </td>
                    </tr>
                  ) : fxHistRows.length === 0 ? (
                    <tr>
                      <td colSpan={2} className="crm-text-body-secondary">
                        No updates yet.
                      </td>
                    </tr>
                  ) : (
                    fxHistRows.map((h) => (
                      <tr key={h.id}>
                        <td>{h.message}</td>
                        <td>
                          {whenText(h.at)}
                          <br />
                          <span className="crm-text-body-secondary">by {h.by}</span>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            {fxHistRows !== null ? (
              <nav className="crm-pager crm-mt-4" aria-label="History pagination">
                <button
                  type="button"
                  className="crm-pager__btn crm-pager__btn--step"
                  disabled={fxHistPage <= 1 || fxHistLoading}
                  aria-label="Previous page"
                  onClick={() => void loadFxHistory(fxHistPage - 1)}
                >
                  <span aria-hidden>‹</span>
                  <span>Prev</span>
                </button>
                <span className="crm-pager__nums">
                  {pagerItems(fxHistPage, Math.max(1, fxHistTotalPages)).map((item, i) =>
                    item === 'dots' ? (
                      <span key={`d-${i}`} className="crm-pager__gap">
                        …
                      </span>
                    ) : (
                      <button
                        key={item}
                        type="button"
                        className="crm-pager__btn crm-pager__btn--num"
                        aria-current={item === fxHistPage ? 'page' : undefined}
                        disabled={
                          item === fxHistPage ||
                          fxHistLoading ||
                          fxHistTotalPages === 0
                        }
                        onClick={() => void loadFxHistory(item)}
                      >
                        {item}
                      </button>
                    ),
                  )}
                </span>
                <button
                  type="button"
                  className="crm-pager__btn crm-pager__btn--step"
                  disabled={
                    fxHistTotalPages === 0 ||
                    fxHistPage >= fxHistTotalPages ||
                    fxHistLoading
                  }
                  aria-label="Next page"
                  onClick={() => void loadFxHistory(fxHistPage + 1)}
                >
                  <span>Next</span>
                  <span aria-hidden>›</span>
                </button>
              </nav>
            ) : null}
          </div>
          <div className="set-modal__foot">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => setFxHistoryOpen(false)}
            >
              Done
            </button>
          </div>
        </div>
      </SetDialog>

      {/* Per-currency history (All Currencies › View currency history) */}
      <SetDialog
        id="cur-history-drawer"
        open={curHistoryOpen}
        onClose={() => setCurHistoryOpen(false)}
        drawer
        labelledBy="cur-history-title"
      >
        <div>
          <DialogHead
            id="cur-history-title"
            title={`${currencyLabel(curHistoryCode)} history`}
            onClose={() => setCurHistoryOpen(false)}
          />
          <div className="set-modal__body">
            <div className="card set-table-card">
              <table className="set-table">
                <thead>
                  <tr>
                    <th>Currency status</th>
                    <th>Updated on</th>
                  </tr>
                </thead>
                <tbody>
                  {curHistoryRows === null ? (
                    <tr>
                      <td colSpan={2} className="crm-text-body-secondary">
                        Loading…
                      </td>
                    </tr>
                  ) : curHistoryRows.length === 0 ? (
                    <tr>
                      <td colSpan={2} className="crm-text-body-secondary">
                        No history yet.
                      </td>
                    </tr>
                  ) : (
                    curHistoryRows.map((row) => (
                      <tr key={row.id}>
                        <td>
                          {row.oldRate === null
                            ? `Rate set to ${rateText(row.newRate)}`
                            : `Rate changed from ${rateText(row.oldRate)} to ${rateText(row.newRate)}`}
                        </td>
                        <td>
                          {/^\d{4}-\d{2}-\d{2}$/.test(row.effectiveOn)
                            ? usDate(row.effectiveOn)
                            : whenText(row.at).split(',')[0]}
                          <br />
                          <span className="crm-text-muted">
                            {row.source === 'automatic'
                              ? 'HubSpot Exchange Rate Updates'
                              : `by ${row.changedBy || '—'}`}
                          </span>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </SetDialog>

      {/* Archive currency confirm */}
      <SetDialog
        id="archive-currency-dialog"
        open={!!archiveTarget}
        onClose={() => setArchiveTarget(null)}
        labelledBy="archive-dialog-title"
      >
        <div>
          <DialogHead
            id="archive-dialog-title"
            title={`Archive ${archiveTarget ? currencyLabel(archiveTarget.code) : ''}?`}
            onClose={() => setArchiveTarget(null)}
          />
          <div className="set-modal__body">
            <p className="crm-text-body crm-m-0">
              Archiving a currency will remove it as an option on new deals. Existing deals will keep
              any archived currencies.
            </p>
          </div>
          <div className="set-modal__foot crm-d-flex crm-gap-2">
            <button
              type="button"
              className="btn-crm btn-crm--danger"
              onClick={() => void confirmArchiveCurrency()}
            >
              Archive currency
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setArchiveTarget(null)}
            >
              Cancel
            </button>
          </div>
        </div>
      </SetDialog>

      {/* Set as company currency confirm */}
      <SetDialog
        id="set-company-currency-dialog"
        open={!!setCompanyTarget}
        onClose={() => setSetCompanyTarget(null)}
        labelledBy="scc-title"
      >
        <div>
          <DialogHead
            id="scc-title"
            title="Set as company currency"
            onClose={() => setSetCompanyTarget(null)}
          />
          <div className="set-modal__body">
            <p className="crm-text-body crm-mb-4">
              This will update your company currency to{' '}
              <span className="crm-fw-medium">
                {setCompanyTarget ? currencyLabel(setCompanyTarget.code) : ''}
              </span>
              . Updating your company currency will update your exchange rates accordingly, except
              for deals that are already in a closed stage.
            </p>
            <div className="crm-d-flex crm-flex-column crm-gap-2 crm-mb-2 crm-text-body">
              <div>
                <strong>Company currency:</strong>{' '}
                {setCompanyTarget ? currencyLabel(setCompanyTarget.code) : ''}
              </div>
              <div>
                <strong>Format:</strong>{' '}
                {setCompanyTarget
                  ? sampleAmount(setCompanyTarget.code, setCompanyTarget.format)
                  : ''}
              </div>
            </div>
          </div>
          <div className="set-modal__foot crm-d-flex crm-gap-2">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => void confirmSetCompanyCurrency()}
            >
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setSetCompanyTarget(null)}
            >
              Cancel
            </button>
          </div>
        </div>
      </SetDialog>
    </SettingsFormsProvider>
  );
}
