'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useConfirm } from '@/components/crm/useConfirm';
import { useToast } from '@/components/crm/ToastProvider';
import { listSubscriptionTypes } from '@/features/subscriptions/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  clonePrivacyBanner,
  createPrivacyBanner,
  deletePrivacyBanner,
  getPrivacySettings,
  updatePrivacyBanner,
  updatePrivacySettings,
  type ConsentTexts,
  type CreatePrivacyBannerBody,
  type PrivacyBanner,
  type PrivacyBannerType,
  type PrivacyRequestPage,
  type PrivacySettings,
  type UpdatePrivacySettingsBody,
} from '../api.client';
import { DialogHead, SetDialog, SetTabs, TabPanel, useHashTab } from './settings-ui';

const TABS = [
  { id: 'privacy-setup', label: 'Setup' },
  { id: 'privacy-consent-options', label: 'Consent options' },
  { id: 'privacy-cookies', label: 'Cookies' },
  { id: 'privacy-data-hosting', label: 'Data Hosting' },
  { id: 'privacy-request-manager', label: 'Data request manager' },
];

/** Same rule as the API: a host name, not free text. QA #510. */
/** A banner's type in the domain's banner list (HubSpot: "Cookies enabled, require opt-in"). */
const BANNER_TYPE_LABEL: Record<string, string> = {
  notification: 'Notification only',
  optin: 'Cookies enabled, require opt-in',
  optout: 'Cookies enabled, allow opt-out',
};

const COOKIE_BANNER_DOMAIN = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;

const CONSENT_LANGUAGES = [
  'Dutch',
  'English',
  'English (United Kingdom)',
  'Finnish',
  'French',
  'French (Canada)',
  'German',
  'Greek',
  'Hungarian',
  'Italian',
  'Japanese',
  'Korean',
  'Norwegian',
  'Polish',
  'Portuguese',
  'Portuguese - Brazil',
  'Romanian',
  'Spanish',
  'Swedish',
  'Turkish',
];

const BANNER_LANGUAGES = [
  'English',
  'Spanish',
  'German',
  'Japanese',
  'French',
  'Portuguese - Brazil',
];

const GPC_DEFAULTS: Record<string, string> = {
  English: 'We respect Global Privacy Control signals from your browser.',
  Spanish: 'Respetamos las señales de Control Global de Privacidad de su navegador.',
  German: 'Wir respektieren die Global-Privacy-Control-Signale Ihres Browsers.',
  Japanese: 'お使いのブラウザーからのグローバルプライバシーコントロール信号を尊重します。',
  French: 'Nous respectons les signaux Global Privacy Control de votre navigateur.',
  'Portuguese - Brazil':
    'Respeitamos os sinais do Controle Global de Privacidade do seu navegador.',
};

const HOSTING_OPTIONS = [
  'Australia',
  'United States (East)',
  'Canada',
  'European Union (Germany)',
] as const;

const EU_COUNTRIES = [
  'Austria',
  'Belgium',
  'Bulgaria',
  'Croatia',
  'Cyprus',
  'Czechia',
  'Denmark',
  'Estonia',
  'Finland',
  'France',
  'Germany',
  'Greece',
  'Hungary',
  'Ireland',
  'Italy',
  'Latvia',
  'Lithuania',
  'Luxembourg',
  'Malta',
  'Netherlands',
  'Poland',
  'Portugal',
  'Romania',
  'Slovakia',
  'Slovenia',
  'Spain',
  'Sweden',
];

const COUNTRIES = [
  'Afghanistan',
  'Albania',
  'Algeria',
  'Andorra',
  'Angola',
  'Argentina',
  'Armenia',
  'Australia',
  'Austria',
  'Azerbaijan',
  'Bahrain',
  'Bangladesh',
  'Belgium',
  'Bolivia',
  'Bosnia and Herzegovina',
  'Botswana',
  'Brazil',
  'Bulgaria',
  'Cambodia',
  'Cameroon',
  'Canada',
  'Chile',
  'China',
  'Colombia',
  'Costa Rica',
  'Croatia',
  'Cyprus',
  'Czechia',
  'Denmark',
  'Dominican Republic',
  'Ecuador',
  'Egypt',
  'El Salvador',
  'Estonia',
  'Ethiopia',
  'Finland',
  'France',
  'Georgia',
  'Germany',
  'Ghana',
  'Greece',
  'Guatemala',
  'Honduras',
  'Hong Kong',
  'Hungary',
  'Iceland',
  'India',
  'Indonesia',
  'Iran',
  'Iraq',
  'Ireland',
  'Israel',
  'Italy',
  'Jamaica',
  'Japan',
  'Jordan',
  'Kazakhstan',
  'Kenya',
  'Kuwait',
  'Latvia',
  'Lebanon',
  'Liechtenstein',
  'Lithuania',
  'Luxembourg',
  'Malaysia',
  'Malta',
  'Mexico',
  'Monaco',
  'Mongolia',
  'Montenegro',
  'Morocco',
  'Nepal',
  'Netherlands',
  'New Zealand',
  'Nigeria',
  'North Macedonia',
  'Norway',
  'Oman',
  'Pakistan',
  'Panama',
  'Peru',
  'Philippines',
  'Poland',
  'Portugal',
  'Puerto Rico',
  'Qatar',
  'Romania',
  'Russia',
  'Saudi Arabia',
  'Serbia',
  'Singapore',
  'Slovakia',
  'Slovenia',
  'South Africa',
  'South Korea',
  'Spain',
  'Sri Lanka',
  'Sweden',
  'Switzerland',
  'Taiwan',
  'Thailand',
  'Tunisia',
  'Turkey',
  'Ukraine',
  'United Arab Emirates',
  'United Kingdom',
  'United States',
  'Uruguay',
  'Venezuela',
  'Vietnam',
  'Zimbabwe',
];

const COUNTRY_CODES: Record<string, string> = {
  Portugal: 'PT',
  Austria: 'AT',
  Romania: 'RO',
  Belgium: 'BE',
  France: 'FR',
  Germany: 'DE',
  Spain: 'ES',
  Italy: 'IT',
  Netherlands: 'NL',
  Ireland: 'IE',
  Poland: 'PL',
  Sweden: 'SE',
  Finland: 'FI',
  Denmark: 'DK',
  Greece: 'GR',
  Hungary: 'HU',
  Czechia: 'CZ',
  Slovakia: 'SK',
  Slovenia: 'SI',
  Croatia: 'HR',
  Bulgaria: 'BG',
  Cyprus: 'CY',
  Estonia: 'EE',
  Latvia: 'LV',
  Lithuania: 'LT',
  Luxembourg: 'LU',
  Malta: 'MT',
};

const OTHER_COUNTRIES = COUNTRIES.filter((c) => !EU_COUNTRIES.includes(c));

type ConsentKey = keyof ConsentTexts;

const CONSENT_ITEMS: Array<{
  key: ConsentKey;
  title: string;
  description: string;
  extra?: 'communicate' | 'explicit';
  checkboxKey?: ConsentKey;
}> = [
  {
    key: 'legitimateInterest',
    title: 'Legitimate interest text',
    description:
      'You will need this text when you inform your contacts that your data may be used for direct marketing under legitimate interest.',
  },
  {
    key: 'privacyPolicy',
    title: 'Privacy policy text',
    description:
      'You will need this text to let your privacy policy explain how you collect, use, and protect personal information.',
  },
  {
    key: 'consentToCommunicate',
    title: 'Consent to communicate text',
    description:
      'You will need this text when you ask contacts for permission to receive communications from your business.',
    extra: 'communicate',
    checkboxKey: 'consentToCommunicateCheckbox',
  },
  {
    key: 'explicitConsent',
    title: 'Explicit consent to process data text',
    description:
      'You will need this text when you ask contacts for explicit permission to process their personal data.',
    extra: 'explicit',
    checkboxKey: 'explicitConsentCheckbox',
  },
  {
    key: 'specificConsent',
    title: 'Specific consent to process data text',
    description:
      'You will need this text when you ask contacts for consent to process data for a specific purpose.',
  },
  {
    key: 'implicitConsent',
    title: 'Implicit consent to process data text',
    description:
      'You’ll see this option only when using the Legacy Editor. Use this text when explaining that processing is necessary to deliver the contracted service.',
  },
];

type InfoKey =
  | 'legal-reasons'
  | 'request-page'
  | 'default-banners'
  | 'hosting-change'
  | 'external-domain'
  | 'privacy-toggle-confirm'
  | 'privacy-guide'
  | 'request-help'
  | 'gpc-help'
  | 'inactive-contacts'
  | 'hosting-info';

const INFO_TITLES: Record<InfoKey, string> = {
  'legal-reasons': 'Review legal reasons for storing customer data',
  'request-page': 'Data privacy request page',
  'default-banners': 'Default consent banners',
  'hosting-change': 'Schedule a data migration',
  'external-domain': 'Add external domain',
  'privacy-toggle-confirm': 'Turn on data privacy settings?',
  'privacy-guide': 'Data privacy settings',
  'request-help': 'Data privacy request page',
  'gpc-help': 'Global Privacy Control',
  'inactive-contacts': 'Delete Contacts with no activity',
  'hosting-info': 'Data hosting location',
};

function ChevronDown() {
  return (
    <svg
      className="privacy-svg-chevron"
      viewBox="0 0 16 16"
      width="16"
      height="16"
      aria-hidden="true"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="m4 6 4 4 4-4" />
    </svg>
  );
}

function ExternalIcon() {
  return (
    <svg
      className="privacy-external-icon"
      viewBox="0 0 16 16"
      width="12"
      height="12"
      aria-hidden="true"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M9 3h4v4M13 3 7 9" />
      <path d="M12 9v3a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h3" />
    </svg>
  );
}

function InfoGlyph() {
  return (
    <svg
      className="privacy-info-icon"
      viewBox="0 0 16 16"
      width="14"
      height="14"
      aria-hidden="true"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
    >
      <circle cx="8" cy="8" r="6.2" />
      <path d="M8 7v4M8 4.7h.01" strokeLinecap="round" />
    </svg>
  );
}

function AccordionChevron() {
  return (
    <svg
      className="privacy-chevron-svg"
      viewBox="0 0 16 16"
      width="15"
      height="15"
      aria-hidden="true"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="m6 3 5 5-5 5" />
    </svg>
  );
}

function ActionArrow() {
  return (
    <svg
      className="privacy-action-arrow"
      viewBox="0 0 18 18"
      width="16"
      height="16"
      aria-hidden="true"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M3 9h11M10 5l4 4-4 4" />
    </svg>
  );
}

function EditPencil() {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden="true"
      width="15"
      height="15"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M12 20h9" />
      <path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L8 18l-4 1 1-4Z" />
    </svg>
  );
}

function SearchGlyph() {
  return (
    <svg
      viewBox="0 0 20 20"
      width="16"
      height="16"
      aria-hidden="true"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
    >
      <circle cx="8.8" cy="8.8" r="5.8" />
      <path d="m13.2 13.2 4 4" />
    </svg>
  );
}

function PrivacySwitch({
  checked,
  onChange,
  name,
  label,
}: {
  checked: boolean;
  onChange: (next: boolean) => void;
  name?: string;
  label?: string;
}) {
  return (
    <label className="switch privacy-switch" aria-label={label}>
      <input
        type="checkbox"
        name={name}
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span className="switch__track" />
    </label>
  );
}

function CheckRow({
  checked,
  onChange,
  children,
  disabled,
}: {
  checked: boolean;
  onChange?: (next: boolean) => void;
  children: ReactNode;
  disabled?: boolean;
}) {
  return (
    <label className="check">
      <input
        type="checkbox"
        checked={checked}
        disabled={disabled}
        onChange={onChange ? (e) => onChange(e.target.checked) : undefined}
      />
      <span className="check__box" aria-hidden="true" />
      <span>{children}</span>
    </label>
  );
}

function editorHtml(id: string) {
  return document.getElementById(id)?.innerHTML.trim() ?? '';
}

function PrivacyRichEditor({ id, label, html }: { id: string; label: string; html: string }) {
  const ref = useRef<HTMLDivElement>(null);
  const [linkOpen, setLinkOpen] = useState(false);
  const [linkText, setLinkText] = useState('');
  const [linkUrl, setLinkUrl] = useState('');
  const [linkNewTab, setLinkNewTab] = useState(true);

  useEffect(() => {
    if (ref.current) ref.current.innerHTML = html;
  }, [html]);

  const run = (command: string) => {
    ref.current?.focus();
    document.execCommand(command, false);
  };

  const applyLink = () => {
    const url = linkUrl.trim();
    if (!url) return;
    const text = linkText.trim() || url;
    ref.current?.focus();
    document.execCommand(
      'insertHTML',
      false,
      `<a href="${url.replace(/"/g, '&quot;')}"${linkNewTab ? ' target="_blank" rel="noopener"' : ''}>${text}</a>`,
    );
    setLinkOpen(false);
    setLinkText('');
    setLinkUrl('');
  };

  return (
    <div className="privacy-rich-editor-wrap gm-consent-rich-wrap">
      <div className="gm-consent-activity-editor">
        <div
          id={id}
          ref={ref}
          className="privacy-rich-editor gm-consent-rich-editor acx-editor__area"
          contentEditable
          role="textbox"
          aria-multiline
          aria-label={label}
          suppressContentEditableWarning
        />
        <div className="acx-toolbar privacy-editor-toolbar">
          <button
            type="button"
            aria-label="Bold"
            onMouseDown={(e) => {
              e.preventDefault();
              run('bold');
            }}
          >
            <b>B</b>
          </button>
          <button
            type="button"
            aria-label="Italic"
            onMouseDown={(e) => {
              e.preventDefault();
              run('italic');
            }}
          >
            <i>I</i>
          </button>
          <button
            type="button"
            aria-label="Underline"
            onMouseDown={(e) => {
              e.preventDefault();
              run('underline');
            }}
          >
            <u>U</u>
          </button>
          <span />
          <button
            type="button"
            aria-label="Insert link"
            onMouseDown={(e) => {
              e.preventDefault();
              const selected = window.getSelection()?.toString() ?? '';
              setLinkText(selected);
              setLinkOpen(true);
            }}
          >
            Link
          </button>
        </div>
      </div>
      {linkOpen ? (
        <div className="field" style={{ marginTop: 10 }}>
          <label className="field__label" htmlFor={`${id}-link-text`}>
            Link text
          </label>
          <input
            className="input"
            id={`${id}-link-text`}
            value={linkText}
            onChange={(e) => setLinkText(e.target.value)}
          />
          <label className="field__label" htmlFor={`${id}-link-url`} style={{ marginTop: 8 }}>
            URL
          </label>
          <input
            className="input"
            id={`${id}-link-url`}
            value={linkUrl}
            onChange={(e) => setLinkUrl(e.target.value)}
            placeholder="https://"
          />
          <label className="check" style={{ marginTop: 8 }}>
            <input
              type="checkbox"
              checked={linkNewTab}
              onChange={(e) => setLinkNewTab(e.target.checked)}
            />
            <span className="check__box" aria-hidden="true" />
            <span>Open in new tab</span>
          </label>
          <div className="privacy-drawer-foot" style={{ padding: '10px 0 0', border: 0 }}>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={() => setLinkOpen(false)}
            >
              Cancel
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              onClick={applyLink}
            >
              Apply
            </button>
          </div>
        </div>
      ) : null}
    </div>
  );
}

function emptyBanner() {
  return {
    name: '',
    urlPath: '',
    countries: [] as string[],
    gpc: false,
    gpcText: GPC_DEFAULTS.English,
    gpcLanguage: '',
    deactivateCookies: false,
    allowAllCookies: false,
    bannerType: '' as PrivacyBannerType | '',
    optByCategory: false,
    analyticsCookies: true,
    advertisingCookies: true,
    language: '',
    customizeOpen: false,
  };
}

export function PrivacySettingsView() {
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const [tab, setTab] = useHashTab(TABS, 'privacy-setup');
  const [settings, setSettings] = useState<PrivacySettings | null>(null);
  const [enabled, setEnabled] = useState(false);
  const [languageMenu, setLanguageMenu] = useState(false);
  const [languageQuery, setLanguageQuery] = useState('');
  const [editedKeys, setEditedKeys] = useState<Set<ConsentKey>>(new Set());
  const [openAccordions, setOpenAccordions] = useState<Record<string, boolean>>({});
  const [subscriptionNames, setSubscriptionNames] = useState<string[]>([
    'Marketing Information',
    'Product updates',
    'Newsletter',
    'Events & webinars',
  ]);
  const [editItem, setEditItem] = useState<(typeof CONSENT_ITEMS)[number] | null>(null);
  const [infoKey, setInfoKey] = useState<InfoKey | null>(null);
  const [legalText, setLegalText] = useState('');
  const [requestPage, setRequestPage] = useState<PrivacyRequestPage>({
    heading: 'Data privacy request',
    intro: 'Use this form to request a copy of your data or ask us to delete it.',
    email: '',
    access: true,
    delete: true,
    export: true,
  });
  const [showDefault, setShowDefault] = useState(true);
  const [includePreferences, setIncludePreferences] = useState(true);
  // Add external domains (design: "+ Add another domain"): one field per new domain.
  const [externalDomainDrafts, setExternalDomainDrafts] = useState<string[]>(['']);
  const [domainSearch, setDomainSearch] = useState('');
  const [hostingDraft, setHostingDraft] = useState('');
  const [inactiveDaysDraft, setInactiveDaysDraft] = useState(365);
  const [editingBannerId, setEditingBannerId] = useState<string | null>(null);
  // HubSpot Cookies › a domain › Consent Banners: the domain whose banners are shown, and the
  // domain a new banner is made for.
  const [domainView, setDomainView] = useState<string | null>(null);
  const [bannerDomain, setBannerDomain] = useState<string | null>(null);
  const [bannerSearch, setBannerSearch] = useState('');
  const [cloneSource, setCloneSource] = useState<PrivacyBanner | null>(null);
  const [cloneTargets, setCloneTargets] = useState<string[]>([]);
  const [bannerOpen, setBannerOpen] = useState(false);
  const [bannerStep, setBannerStep] = useState(0);
  const [banner, setBanner] = useState(emptyBanner);
  const [countryMenu, setCountryMenu] = useState(false);
  const [countryQuery, setCountryQuery] = useState('');
  const [gpcLangMenu, setGpcLangMenu] = useState(false);
  const [gpcLangQuery, setGpcLangQuery] = useState('');
  const [bannerLangMenu, setBannerLangMenu] = useState(false);
  const [bannerLangQuery, setBannerLangQuery] = useState('');
  const [saving, setSaving] = useState(false);

  const apply = useCallback((next: PrivacySettings) => {
    setSettings(next);
    setEnabled(next.enabled);
    setLegalText(next.legalReasonText);
    setRequestPage({ ...next.requestPage, email: next.requestPage.email ?? '' });
    setShowDefault(next.defaultBanners.showDefault);
    setIncludePreferences(next.defaultBanners.includePreferences);
    setInactiveDaysDraft(next.inactiveDays);
  }, []);

  useEffect(() => {
    let cancelled = false;
    getPrivacySettings()
      .then((row) => {
        if (!cancelled) apply(row);
      })
      .catch((error) => {
        if (!cancelled) toast(errorText(error), 'danger');
      });
    listSubscriptionTypes(true)
      .then((types) => {
        const names = types.filter((t) => t.active).map((t) => t.name);
        if (!cancelled && names.length) setSubscriptionNames(names);
      })
      .catch(() => undefined);
    return () => {
      cancelled = true;
    };
  }, [apply, toast]);

  const patch = useCallback(
    async (body: UpdatePrivacySettingsBody, success?: string) => {
      setSaving(true);
      try {
        apply(await updatePrivacySettings(body));
        if (success) toast(success, 'success');
        return true;
      } catch (error) {
        toast(errorText(error), 'danger');
        return false;
      } finally {
        setSaving(false);
      }
    },
    [apply, toast],
  );

  const texts = useMemo(() => {
    const language = settings?.consentLanguage ?? 'English';
    return settings?.consentTextsByLanguage[language] ?? settings?.consentTextsByLanguage.English;
  }, [settings]);

  const externalDomains = settings?.externalDomains ?? [];
  const connectedDomain = externalDomains[0] || settings?.trackingDomain || null;
  const hasBanners = (settings?.banners.length ?? 0) > 0;
  const asDrawer = infoKey === 'hosting-change' || infoKey === 'inactive-contacts';

  // QA #531: removing a cookie banner domain is not undoable, so confirm first.
  const removeExternalDomain = async (domain: string) => {
    const confirmed = await confirm({
      title: 'Remove cookie banner domain?',
      message: `${domain} will no longer show a cookie banner, and its consent banners are deleted.`,
      confirmLabel: 'Remove',
      danger: true,
    });
    if (!confirmed) return;
    await patch(
      { externalDomains: externalDomains.filter((d) => d !== domain) },
      'External domain removed',
    );
  };

  const openInfo = (key: InfoKey) => {
    if (settings) {
      setLegalText(settings.legalReasonText);
      setRequestPage({ ...settings.requestPage, email: settings.requestPage.email ?? '' });
      setShowDefault(settings.defaultBanners.showDefault);
      setIncludePreferences(settings.defaultBanners.includePreferences);
      setExternalDomainDrafts(['']);
      setHostingDraft('');
      setInactiveDaysDraft(settings.inactiveDays);
    }
    setInfoKey(key);
  };

  const closeInfo = () => {
    if (infoKey === 'privacy-toggle-confirm' && !settings?.enabled) setEnabled(false);
    setInfoKey(null);
  };

  const saveInfo = async () => {
    if (!infoKey) return;
    if (infoKey === 'privacy-toggle-confirm') {
      const ok = await patch({ enabled: true }, 'Data privacy settings enabled');
      if (!ok) setEnabled(false);
      setInfoKey(null);
      return;
    }
    if (infoKey === 'inactive-contacts') {
      if (!inactiveDaysDraft || inactiveDaysDraft < 1) return;
      await patch({ inactiveDays: inactiveDaysDraft }, 'Inactive contact criteria saved');
      setInfoKey(null);
      return;
    }
    if (infoKey === 'hosting-change') {
      if (!hostingDraft) return;
      await patch(
        {
          hostingLocation: hostingDraft as NonNullable<
            UpdatePrivacySettingsBody['hostingLocation']
          >,
        },
        'Data migration scheduled',
      );
      setInfoKey(null);
      return;
    }
    if (infoKey === 'request-page') {
      await patch(
        { requestPage: { ...requestPage, email: requestPage.email?.trim() || null } },
        'Data privacy request page saved',
      );
      setInfoKey(null);
      return;
    }
    if (infoKey === 'legal-reasons') {
      await patch({ legalReasonText: legalText }, 'Legal reason text saved');
      setInfoKey(null);
      return;
    }
    if (infoKey === 'external-domain') {
      const typed = externalDomainDrafts.map((d) => d.trim().toLowerCase()).filter(Boolean);
      if (!typed.length) return;
      const bad = typed.find((d) => !COOKIE_BANNER_DOMAIN.test(d));
      if (bad) {
        toast(`${bad} isn't a domain. Enter one like www.example.com`, 'danger');
        return;
      }
      const added = typed.filter((d, i) => typed.indexOf(d) === i && !externalDomains.includes(d));
      if (!added.length) {
        toast('Those domains are already added', 'info');
        return;
      }
      await patch(
        { externalDomains: [...externalDomains, ...added] },
        added.length === 1 ? 'External domain added' : `${added.length} external domains added`,
      );
      setInfoKey(null);
      return;
    }
    if (infoKey === 'default-banners') {
      await patch(
        { defaultBanners: { showDefault, includePreferences } },
        'Default banner settings saved',
      );
      setInfoKey(null);
      return;
    }
    toast('Privacy settings saved', 'success');
    setInfoKey(null);
  };

  const saveLabel =
    infoKey === 'hosting-change'
      ? 'Schedule data migration'
      : infoKey === 'privacy-toggle-confirm'
        ? 'Yes, turn on data privacy settings'
        : infoKey === 'external-domain'
          ? 'Add external domains'
          : 'Save';

  const openBanner = (row?: PrivacyBanner) => {
    setEditingBannerId(row?.id ?? null);
    setBannerDomain(row ? row.domain : domainView);
    setBanner(
      row
        ? {
            name: row.name,
            urlPath: row.urlPath,
            countries: row.countries,
            gpc: row.gpc,
            gpcText: row.gpcText || GPC_DEFAULTS.English,
            gpcLanguage: row.gpcLanguage ?? '',
            deactivateCookies: row.deactivateCookies,
            allowAllCookies: row.allowAllCookies,
            bannerType: row.bannerType,
            optByCategory: row.optByCategory,
            analyticsCookies: row.analyticsCookies,
            advertisingCookies: row.advertisingCookies,
            language: row.language,
            customizeOpen: false,
          }
        : emptyBanner(),
    );
    setBannerStep(0);
    setBannerOpen(true);
  };

  const setBannerStatus = async (row: PrivacyBanner, status: 'draft' | 'published') => {
    setSaving(true);
    try {
      apply(await updatePrivacyBanner(row.id, { status }));
      toast(
        status === 'draft' ? 'Consent banner unpublished' : 'Consent banner published',
        'success',
      );
    } catch (error) {
      toast(errorText(error), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const cloneBanner = async () => {
    if (!cloneSource || !cloneTargets.length) return;
    setSaving(true);
    try {
      apply(await clonePrivacyBanner(cloneSource.id, cloneTargets));
      toast(
        cloneTargets.length === 1
          ? `${cloneSource.name} copied to ${cloneTargets[0]}`
          : `${cloneSource.name} copied to ${cloneTargets.length} domains`,
        'success',
      );
      setCloneSource(null);
    } catch (error) {
      toast(errorText(error), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const removeBanner = async (row: PrivacyBanner) => {
    const ok = await confirm({
      title: 'Delete consent banner?',
      message: `${row.name} will be removed. Visitors will no longer see it.`,
      confirmLabel: 'Delete',
      danger: true,
    });
    if (!ok) return;
    setSaving(true);
    try {
      apply(await deletePrivacyBanner(row.id));
      toast('Consent banner deleted', 'success');
    } catch (error) {
      toast(errorText(error), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const publishBanner = async () => {
    if (!banner.name.trim() || !banner.bannerType) return;
    setSaving(true);
    try {
      const body: CreatePrivacyBannerBody = {
        name: banner.name.trim(),
        domain: bannerDomain,
        urlPath: banner.urlPath.trim(),
        countries: banner.countries,
        gpc: banner.gpc,
        gpcText: banner.gpc ? editorHtml('privacy-gpc-text') || banner.gpcText : null,
        gpcLanguage: banner.gpcLanguage || null,
        deactivateCookies: banner.deactivateCookies,
        allowAllCookies: banner.allowAllCookies,
        bannerType: banner.bannerType,
        optByCategory: banner.optByCategory,
        analyticsCookies: banner.analyticsCookies,
        advertisingCookies: banner.advertisingCookies,
        language: banner.language || 'English',
      };
      apply(
        editingBannerId
          ? await updatePrivacyBanner(editingBannerId, body)
          : await createPrivacyBanner(body),
      );
      setBannerOpen(false);
      setEditingBannerId(null);
      toast(editingBannerId ? 'Consent banner saved' : 'Consent banner published', 'success');
    } catch (error) {
      toast(errorText(error), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const categoryEnabled =
    (banner.bannerType === 'optin' || banner.bannerType === 'optout') && banner.optByCategory;
  const filteredLanguages = CONSENT_LANGUAGES.filter((name) =>
    name.toLowerCase().includes(languageQuery.trim().toLowerCase()),
  );
  const filteredCountries = (list: string[]) =>
    list.filter((name) => name.toLowerCase().includes(countryQuery.trim().toLowerCase()));

  return (
    <div className="privacy-page">
      {confirmDialog}
      <header className="set-head">
        <div>
          <h1 className="set-head__title">Data Privacy &amp; Consent</h1>
          <p className="set-head__sub">
            Collect consent, honour opt-outs and keep a lawful basis for the contacts you store.
          </p>
        </div>
      </header>

      <SetTabs
        label="Data Privacy & Consent"
        tabs={TABS}
        active={tab}
        onSelect={setTab}
        boxed
        className="privacy-tabs"
      />

      <TabPanel id="privacy-setup" active={tab}>
        <div className="privacy-section-heading">
          <h2>
            GDPR &amp; regional settings{' '}
            <span className="privacy-region-tags">
              <span>EU</span>
              <span>U.K.</span>
              <span>Canada</span>
              <span>Brazil</span>
            </span>
          </h2>
          <p>
            Required if you market to or collect data from EU, U.K., Canadian, or Brazilian
            residents.
          </p>
        </div>
        <div className="privacy-settings-card">
          <div className="privacy-card-row">
            <div className="privacy-card-copy">
              <h3>Data privacy settings</h3>
              <p>
                Turn on settings that help you comply with data privacy laws. This will enable tools
                in your account for tracking and collecting legal basis and consent, and reduce risk
                of unlawful processing.
              </p>
              <div className="privacy-muted">
                <details className="privacy-inline-details">
                  <summary>
                    What will happen in my account?{' '}
                    <button
                      type="button"
                      className="link"
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        openInfo('privacy-guide');
                      }}
                    >
                      Learn more <ExternalIcon />
                    </button>
                  </summary>
                  <ul>
                    <li>
                      Legal basis field added to contact imports, bulk edits, and manual creation
                    </li>
                    <li>
                      Privacy footer auto-added to new forms (manual if using the new editor (BETA))
                    </li>
                    <li>Privacy footer auto-added to new meeting pages</li>
                    <li>Unsubscribe links added to one-to-one emails</li>
                    <li>Cookie consent banner turned on immediately</li>
                  </ul>
                </details>
              </div>
            </div>
            <PrivacySwitch
              name="privacy_on"
              label="Data privacy settings"
              checked={enabled}
              onChange={(next) => {
                if (next) {
                  setEnabled(true);
                  openInfo('privacy-toggle-confirm');
                  return;
                }
                setEnabled(false);
                void patch({ enabled: false });
              }}
            />
          </div>
        </div>
        <div className="privacy-settings-card privacy-action-card">
          <div className="privacy-card-copy">
            <h3>Review your legal reasons for storing customer data</h3>
            <p>
              Define the text for all the legal reasons why your business needs permission to store
              and process customer data.
            </p>
          </div>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => {
              setTab('privacy-consent-options');
              window.requestAnimationFrame(() => window.scrollTo(0, 0));
            }}
          >
            Review text <ExternalIcon />
          </button>
        </div>
        <div className="privacy-settings-card privacy-action-card">
          <div className="privacy-card-copy">
            <h3>Data privacy request page</h3>
            <p>
              Help contacts exercise their data privacy rights with a form. Process requests in Data
              Request Manager.{' '}
              <button type="button" className="link" onClick={() => openInfo('request-help')}>
                Learn more
              </button>
            </p>
          </div>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => openInfo('request-page')}
          >
            Configure
          </button>
        </div>
        <div className="privacy-section-heading privacy-section-heading--sub">
          <h2>Additional settings</h2>
          <p>Automate how you handle personal contact data.</p>
        </div>
        <div className="privacy-settings-card privacy-settings-card--stack">
          <div className="privacy-card-row">
            <div className="privacy-card-copy">
              <h3>Process data enrichment requests automatically</h3>
              <p>Auto-delete data enrichment when your contacts opt out.</p>
            </div>
          </div>
          <button
            type="button"
            className="privacy-accordion"
            aria-expanded={!!openAccordions['delete-enriched']}
            onClick={() =>
              setOpenAccordions((cur) => ({ ...cur, 'delete-enriched': !cur['delete-enriched'] }))
            }
          >
            <AccordionChevron /> Delete enriched data when request is received{' '}
            <span className="privacy-accordion-end" onClick={(e) => e.stopPropagation()}>
              <PrivacySwitch
                name="delete_enriched"
                checked={settings?.deleteEnriched ?? true}
                onChange={(next) => void patch({ deleteEnriched: next })}
              />
            </span>
          </button>
          <div className="privacy-accordion-content" hidden={!openAccordions['delete-enriched']}>
            <p>When enriched data deletion request is received</p>
            <p className="privacy-action-line">
              <ActionArrow /> Delete contact enriched data and mark request as completed
            </p>
          </div>
        </div>
        <div className="privacy-settings-card privacy-settings-card--stack privacy-inactive-card">
          <div className="privacy-card-copy">
            <h3>Delete inactive contacts automatically</h3>
            <p>
              On the 1st of each month, contacts that are inactive in your account will be
              automatically deleted.{' '}
              <button type="button" className="link" onClick={() => openInfo('inactive-contacts')}>
                View inactive contact criteria <ExternalIcon />
              </button>
            </p>
          </div>
          <div className="privacy-inactive-row">
            <button
              type="button"
              className="privacy-accordion"
              aria-expanded={!!openAccordions['inactive-contact-detail']}
              onClick={() =>
                setOpenAccordions((cur) => ({
                  ...cur,
                  'inactive-contact-detail': !cur['inactive-contact-detail'],
                }))
              }
            >
              <AccordionChevron /> Delete Contacts with no activity
            </button>
            <div className="privacy-inactive-actions">
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => openInfo('inactive-contacts')}
              >
                Edit
              </button>
              <PrivacySwitch
                name="delete_inactive"
                checked={settings?.deleteInactive ?? false}
                onChange={(next) => void patch({ deleteInactive: next })}
              />
            </div>
          </div>
          <div
            className="privacy-accordion-content"
            hidden={!openAccordions['inactive-contact-detail']}
          >
            <p>
              When there are no updates to the contact properties: time of last session, last
              marketing email open date, or last engagement date.
            </p>
            <p className="privacy-action-line">
              <ActionArrow /> Delete contact
            </p>
          </div>
          <p className="privacy-footnote">
            After {settings?.inactiveDays ?? 365} days, contacts will be permanently deleted. Check
            out a list of{' '}
            <Link href="/recycle-bin?object=contact">
              restorable contacts <ExternalIcon />
            </Link>
            .
          </p>
        </div>
        <p className="privacy-legal-footnote">
          This page may suggest features to help support your data privacy compliance efforts.
          Discuss their use with your legal advisors to understand applicable legal and compliance
          requirements.{' '}
          <a href="#">
            Learn more <ExternalIcon />
          </a>
        </p>
      </TabPanel>

      <TabPanel id="privacy-consent-options" active={tab}>
        <p className="privacy-intro">
          Customize the consent text that appears on your forms and your privacy policy. These
          settings apply to forms that use GDPR, so they can correctly describe the information that
          will be used.
        </p>
        <div className="privacy-language-row">
          <label htmlFor="privacy-language">Current language:</label>
          <div className="privacy-search-language">
            <button
              type="button"
              id="privacy-language"
              className="input"
              aria-expanded={languageMenu}
              onClick={() => setLanguageMenu((open) => !open)}
            >
              {settings?.consentLanguage ?? 'English'} <ChevronDown />
            </button>
            <div className="privacy-main-language-menu" hidden={!languageMenu}>
              <div className="privacy-language-search-wrap">
                <span aria-hidden="true">
                  <SearchGlyph />
                </span>
                <input
                  className="input"
                  type="search"
                  placeholder="Search"
                  value={languageQuery}
                  onChange={(e) => setLanguageQuery(e.target.value)}
                />
              </div>
              <div>
                {filteredLanguages.map((name) => (
                  <button
                    key={name}
                    type="button"
                    hidden={!name.toLowerCase().includes(languageQuery.trim().toLowerCase())}
                    onClick={() => {
                      setLanguageMenu(false);
                      setLanguageQuery('');
                      void patch({ consentLanguage: name });
                    }}
                  >
                    {name}
                  </button>
                ))}
              </div>
            </div>
          </div>
          <span>
            You are modifying this language. To edit others, select them from the dropdown.
          </span>
        </div>
        <div className="privacy-consent-list">
          {CONSENT_ITEMS.map((item) => (
            <article
              key={item.key}
              className={cn('privacy-consent-item', editedKeys.has(item.key) && 'is-edited')}
            >
              <div>
                <h3>{item.title}</h3>
                <p>{item.description}</p>
              </div>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => setEditItem(item)}
              >
                <EditPencil />
                <span>Edit</span>
              </button>
            </article>
          ))}
        </div>
      </TabPanel>

      <TabPanel id="privacy-cookies" active={tab}>
        {domainView ? (
          <section className="privacy-domain-view">
            <button type="button" className="link" onClick={() => setDomainView(null)}>
              ‹ Back to all domains
            </button>
            <h2 className="privacy-domain-view__title">{domainView}</h2>
            <div className="privacy-domains__head">
              <div>
                <h3>Consent Banners</h3>
                <p>
                  Consent banners let you control how you ask your website visitors for consent to
                  use tracking cookies. For each banner, you can control where it applies, what
                  language it&apos;s in, and how much control visitors have over which cookies to
                  accept.
                </p>
              </div>
              <div className="privacy-domains__tools">
                <input
                  type="search"
                  className="input"
                  placeholder="Search for banner"
                  aria-label="Search banners"
                  value={bannerSearch}
                  onChange={(e) => setBannerSearch(e.target.value)}
                />
                <button
                  type="button"
                  className="btn-crm btn-crm--primary btn-crm--sm"
                  onClick={() => openBanner()}
                >
                  Create consent banner
                </button>
              </div>
            </div>
            <table className="privacy-domain-table">
              <thead>
                <tr>
                  <th>Banner Name</th>
                  <th>URLs</th>
                  <th>Countries</th>
                  <th>Status</th>
                  <th>
                    <span className="crm-visually-hidden">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {(() => {
                  const q = bannerSearch.trim().toLowerCase();
                  const rows = (settings?.banners ?? []).filter(
                    (b) =>
                      (b.domain === domainView || b.domain === null) &&
                      (!q || b.name.toLowerCase().includes(q)),
                  );
                  if (!rows.length) {
                    return (
                      <tr>
                        <td colSpan={5} className="privacy-domain-empty">
                          {q
                            ? `No banners match “${bannerSearch.trim()}”`
                            : 'No consent banners yet'}
                        </td>
                      </tr>
                    );
                  }
                  return rows.map((row) => (
                    <tr key={row.id}>
                      <td>
                        <strong>{row.name}</strong>
                        <span className="privacy-banner-sub">
                          {BANNER_TYPE_LABEL[row.bannerType] ?? row.bannerType}
                          {row.domain === null ? ' · all domains' : ''}
                        </span>
                      </td>
                      <td>/{row.urlPath}</td>
                      <td>{row.countries.length ? row.countries.join(', ') : 'All Countries'}</td>
                      <td>{row.status === 'published' ? 'Published' : 'Draft'}</td>
                      <td className="privacy-domain-actions">
                        <button type="button" className="link" onClick={() => openBanner(row)}>
                          Edit
                        </button>
                        <button
                          type="button"
                          className="link"
                          disabled={externalDomains.length < 2}
                          title={
                            externalDomains.length < 2
                              ? 'Add another external domain to clone to'
                              : undefined
                          }
                          onClick={() => {
                            setCloneSource(row);
                            setCloneTargets([]);
                          }}
                        >
                          Clone to another domain
                        </button>
                        <button
                          type="button"
                          className="link"
                          disabled={saving}
                          onClick={() =>
                            void setBannerStatus(
                              row,
                              row.status === 'published' ? 'draft' : 'published',
                            )
                          }
                        >
                          {row.status === 'published' ? 'Unpublish' : 'Publish'}
                        </button>
                        <button
                          type="button"
                          className="link privacy-domain-remove"
                          disabled={saving}
                          onClick={() => void removeBanner(row)}
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  ));
                })()}
              </tbody>
            </table>
          </section>
        ) : (
          <>
            {/* Sheet 24 Nov / QA #510: HubSpot's two domain tables. An added external domain is
            listed here with its banners and can be removed. */}
            <section className="privacy-domains" aria-labelledby="privacy-connected-domains">
              <h2 id="privacy-connected-domains">Domains connected to the CRM</h2>
              <p>
                These domains are connected to your account and can be edited in tracking settings.
              </p>
              <table className="privacy-domain-table">
                <thead>
                  <tr>
                    <th>Domain Name</th>
                    <th>Domain Type</th>
                    <th>Consent Banners</th>
                  </tr>
                </thead>
                <tbody>
                  {settings?.trackingDomain ? (
                    <tr>
                      <td>{settings.trackingDomain}</td>
                      <td>Tracked domain</td>
                      <td>{settings.banners.length ? 'Active' : 'None'}</td>
                    </tr>
                  ) : (
                    <tr>
                      <td colSpan={3} className="privacy-domain-empty">
                        No data available
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </section>
            {/* Design settings-privacy.php: the External Domains table shows once a domain exists;
            before that the "Get started" block below offers Add external domain. */}
            {externalDomains.length ? (
              <section className="privacy-domains" aria-labelledby="privacy-external-domains">
                <div className="privacy-domains__head">
                  <div>
                    <h2 id="privacy-external-domains">External Domains</h2>
                    <p>
                      These domains are not connected to your account and can be added and deleted
                      here.
                    </p>
                  </div>
                  <div className="privacy-domains__tools">
                    <input
                      type="search"
                      className="input"
                      placeholder="Search for domain"
                      aria-label="Search external domains"
                      value={domainSearch}
                      onChange={(e) => setDomainSearch(e.target.value)}
                    />
                    <button
                      type="button"
                      className="btn-crm btn-crm--outline btn-crm--sm"
                      onClick={() => openInfo('external-domain')}
                    >
                      Add external domain
                    </button>
                  </div>
                </div>
                <table className="privacy-domain-table">
                  <thead>
                    <tr>
                      <th>Domain Name</th>
                      <th>Domain Type</th>
                      <th>Consent Banners</th>
                      <th>
                        <span className="crm-visually-hidden">Actions</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {externalDomains
                      .filter((d) => d.includes(domainSearch.trim().toLowerCase()))
                      .map((domain) => (
                        <tr key={domain}>
                          <td>{domain}</td>
                          <td>External Domain</td>
                          <td>{settings?.banners.length ? 'Active' : 'None'}</td>
                          <td className="privacy-domain-actions">
                            <button
                              type="button"
                              className="link"
                              onClick={() => {
                                setBannerSearch('');
                                setDomainView(domain);
                              }}
                            >
                              Manage banners
                            </button>
                            <button
                              type="button"
                              className="link privacy-domain-remove"
                              onClick={() => void removeExternalDomain(domain)}
                            >
                              Delete
                            </button>
                          </td>
                        </tr>
                      ))}
                    {externalDomains.some((d) =>
                      d.includes(domainSearch.trim().toLowerCase()),
                    ) ? null : (
                      <tr>
                        <td colSpan={4} className="privacy-domain-empty">
                          No domains match “{domainSearch.trim()}”
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </section>
            ) : null}
            {hasBanners ? (
              <div className="privacy-cookie-created">
                <div className="privacy-created-header">
                  <div>
                    <h2>Cookie consent banners</h2>
                    <p>Manage cookie consent banners for your tracked domains.</p>
                  </div>
                  <button
                    type="button"
                    className="btn-crm btn-crm--primary btn-crm--sm"
                    onClick={() => openBanner()}
                  >
                    ＋ Create consent banner
                  </button>
                </div>
                {settings?.banners.map((row) => (
                  <div className="privacy-settings-card" key={row.id}>
                    <strong>{row.name}</strong>
                    <p>
                      Consent banner
                      {row.domain ? ` · ${row.domain}` : ' · all domains'}
                      {row.urlPath ? ` · /${row.urlPath}` : ''}
                      {' · '}
                      <span>{row.status === 'published' ? 'Published' : 'Draft'}</span>
                    </p>
                    <div className="crm-d-flex crm-gap-2 crm-mt-2">
                      <button
                        type="button"
                        className="btn-crm btn-crm--outline btn-crm--sm"
                        onClick={() => openBanner(row)}
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        className="btn-crm btn-crm--outline btn-crm--sm"
                        disabled={saving}
                        onClick={() =>
                          void setBannerStatus(
                            row,
                            row.status === 'published' ? 'draft' : 'published',
                          )
                        }
                      >
                        {row.status === 'published' ? 'Unpublish' : 'Publish'}
                      </button>
                      <button
                        type="button"
                        className="btn-crm btn-crm--outline btn-crm--sm"
                        disabled={saving}
                        onClick={() => void removeBanner(row)}
                      >
                        Delete
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <>
                <div className="privacy-cookie-empty">
                  <div className="privacy-cookie-illustration" aria-hidden="true">
                    <svg viewBox="0 0 180 130">
                      <rect
                        x="22"
                        y="15"
                        width="112"
                        height="82"
                        rx="7"
                        fill="#eaf0ff"
                        stroke="#2456e6"
                        strokeWidth="2"
                      />
                      <rect
                        x="32"
                        y="26"
                        width="91"
                        height="59"
                        rx="3"
                        fill="#fff"
                        stroke="#b9c8f7"
                      />
                      <path
                        d="M42 39h46M42 48h65M42 57h35"
                        stroke="#9baedb"
                        strokeWidth="3"
                        strokeLinecap="round"
                      />
                      <rect x="48" y="65" width="25" height="12" rx="3" fill="#2456e6" />
                      <path
                        d="M82 66h26M82 73h18"
                        stroke="#d5def8"
                        strokeWidth="3"
                        strokeLinecap="round"
                      />
                      <path d="M13 103h130l-12 10H26z" fill="#f4c7a2" />
                      <circle cx="144" cy="33" r="17" fill="#f8d5b7" />
                      <path
                        d="M144 23v20M134 33h20"
                        stroke="#d66b2c"
                        strokeWidth="3"
                        strokeLinecap="round"
                      />
                    </svg>
                  </div>
                  <div className="privacy-cookie-empty__copy">
                    {connectedDomain ? (
                      <>
                        <h2>Keep your site compliant with custom consent banners!</h2>
                        <p>
                          You haven’t created any consent banners for this domain. Add a consent
                          banner or visit our Knowledge Base article to find out how.{' '}
                          <a href="#">
                            Learn more. <ExternalIcon />
                          </a>
                        </p>
                        <button
                          type="button"
                          className="btn-crm btn-crm--outline btn-crm--sm"
                          onClick={() => openBanner()}
                        >
                          Create consent banner
                        </button>
                      </>
                    ) : (
                      <>
                        <h2>
                          Get started with data privacy with easy-to-create cookie consent banners.
                        </h2>
                        <p>
                          Welcome to the cookie banner tool! You haven’t connected any domains to
                          this this account. Add a domain to create a cookie consent banner or visit
                          our Knowledge Base. <a href="#">Learn more.</a>
                        </p>
                        <button
                          type="button"
                          className="btn-crm btn-crm--outline btn-crm--sm"
                          onClick={() => openInfo('external-domain')}
                        >
                          Add external domain
                        </button>
                      </>
                    )}
                  </div>
                </div>
                {connectedDomain ? null : (
                  <>
                    <div className="privacy-default-banners">
                      <h2>Default consent banners</h2>
                      <p>
                        Default consent banners will show on all websites linked to your account,
                        including any external sites that use your tracking code. If you set up a
                        consent banner for a specific domain, it’ll override the default banner on
                        that site.
                      </p>
                      <button
                        type="button"
                        className="btn-crm btn-crm--outline btn-crm--sm"
                        onClick={() => openInfo('default-banners')}
                      >
                        View default banners
                      </button>
                    </div>
                    <div className="privacy-cookie-create-inline">
                      <button
                        type="button"
                        className="btn-crm btn-crm--primary btn-crm--sm"
                        onClick={() => openBanner()}
                      >
                        ＋ Create consent banner
                      </button>
                    </div>
                  </>
                )}
              </>
            )}
          </>
        )}
      </TabPanel>

      <TabPanel id="privacy-data-hosting" active={tab}>
        <p className="privacy-intro">View or change the data hosting location for your account.</p>
        <div className="privacy-hosting-content">
          <h2>Data Hosting</h2>
          <div className="privacy-hosting-label">
            Your data hosting location{' '}
            <button
              type="button"
              className="privacy-info-icon"
              aria-label="About data hosting"
              onClick={() => openInfo('hosting-info')}
            >
              <InfoGlyph />
            </button>
          </div>
          <div className="privacy-hosting-row">
            <input
              className="input"
              value={settings?.hostingLocation ?? 'United States (West)'}
              readOnly
              aria-label="Current data hosting location"
            />
            <button type="button" className="link" onClick={() => openInfo('hosting-change')}>
              Change
            </button>
          </div>
        </div>
      </TabPanel>

      <TabPanel id="privacy-request-manager" active={tab}>
        <div className="privacy-section-heading">
          <h2>Data request manager</h2>
          <p>Manage requests from contacts to access, export, or delete their personal data.</p>
        </div>
        <div className="privacy-request-info">
          <strong>Receive other types of data privacy requests</strong>
          <p>
            You’ll receive enriched data deletion requests by default. To allow other types of
            requests,{' '}
            <button type="button" className="link" onClick={() => openInfo('request-page')}>
              set up your data privacy request page <ExternalIcon />
            </button>{' '}
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              onClick={() => openInfo('request-page')}
            >
              Set up page <ExternalIcon />
            </button>
          </p>
        </div>
        <div className="privacy-request-manager-heading">
          <h2>Data privacy request manager</h2>
          <p>
            View, assign, and process requests coming from your Data Privacy Request page. Requests
            should usually be completed within 30 days, according to data privacy laws.{' '}
            <button type="button" className="link" onClick={() => openInfo('request-help')}>
              Learn more <ExternalIcon />
            </button>
          </p>
        </div>
        <div className="privacy-request-stats">
          <div>
            <strong>
              OVERDUE <InfoGlyph />
            </strong>
            <b>{settings?.requestStats.overdue ?? 0}</b>
          </div>
          <div>
            <strong>
              EXPIRING SOON <InfoGlyph />
            </strong>
            <b>{settings?.requestStats.expiringSoon ?? 0}</b>
          </div>
          <div>
            <strong>
              COMPLETED <InfoGlyph />
            </strong>
            <b>{settings?.requestStats.completed ?? 0}</b>
            <small>Last 30 days</small>
          </div>
          <div>
            <strong>TOTAL</strong>
            <b>{settings?.requestStats.total ?? 0}</b>
            <small>Last 30 days</small>
          </div>
        </div>
        <div className="privacy-request-empty-state">
          <div className="privacy-request-empty-copy">
            <h3>Manage your Data Privacy Requests</h3>
            <ul>
              <li>
                <strong>View, assign and process</strong> data privacy requests from your contacts
                in one place.
              </li>
              <li>
                <strong>Stay compliant</strong> by responding on time to your data privacy requests.{' '}
                <button type="button" className="link" onClick={() => openInfo('request-help')}>
                  Learn more about GDPR <ExternalIcon />
                </button>
              </li>
              <li>
                <strong>Control the types of requests</strong> that you want to offer to your
                contacts.{' '}
                <button type="button" className="link" onClick={() => openInfo('request-help')}>
                  Learn more <ExternalIcon />
                </button>
              </li>
            </ul>
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              onClick={() => openInfo('request-page')}
            >
              Setup page <ExternalIcon />
            </button>
            <p className="privacy-footnote">
              *You’ll receive enriched data deletion requests by default.
            </p>
          </div>
          <div className="privacy-request-illustration" aria-hidden="true">
            <svg viewBox="0 0 220 190" fill="none">
              <path d="M15 143 101 91l102 53-90 38z" fill="#f7dfb9" />
              <path d="M49 33 133 8l35 19-84 28z" fill="#dff7fb" stroke="#34495e" strokeWidth="2" />
              <path d="M49 33v91l35 19V55z" fill="#b7e8ef" stroke="#34495e" strokeWidth="2" />
              <path d="M84 55 168 27v92l-84 24z" fill="#e9f8fb" stroke="#34495e" strokeWidth="2" />
              <rect x="99" y="44" width="51" height="9" rx="2" fill="#fff" stroke="#7bbbc8" />
              <rect x="99" y="60" width="42" height="8" rx="2" fill="#fff" stroke="#7bbbc8" />
              <rect x="99" y="76" width="49" height="8" rx="2" fill="#fff" stroke="#7bbbc8" />
              <circle cx="103" cy="102" r="10" fill="#4fc5c9" stroke="#34495e" strokeWidth="2" />
              <path
                d="m98 102 4 4 7-8"
                stroke="#fff"
                strokeWidth="2.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
              <path
                d="m153 113 18 16-11 3-3 12-12-22z"
                fill="#fff"
                stroke="#34495e"
                strokeWidth="2"
              />
            </svg>
          </div>
        </div>
      </TabPanel>

      <SetDialog
        open={editItem !== null}
        onClose={() => setEditItem(null)}
        labelledBy="privacy-edit-title"
        className="privacy-edit-dialog"
      >
        <form
          onSubmit={(e) => {
            e.preventDefault();
            void (async () => {
              if (!editItem || !settings) return;
              const html = editorHtml('privacy-edit-text');
              const textsPatch: Partial<ConsentTexts> = { [editItem.key]: html };
              if (editItem.checkboxKey) {
                textsPatch[editItem.checkboxKey] = editorHtml('privacy-checkbox-text');
              }
              const ok = await patch(
                {
                  consentTexts: {
                    language: settings.consentLanguage,
                    texts: textsPatch,
                  },
                },
                'Consent text updated',
              );
              if (ok) {
                setEditedKeys((cur) => new Set(cur).add(editItem.key));
                setEditItem(null);
              }
            })();
          }}
        >
          <DialogHead
            id="privacy-edit-title"
            title={editItem?.title ?? 'Edit consent text'}
            onClose={() => setEditItem(null)}
          />
          <div className="set-modal__body">
            <p className="privacy-editor-description">{editItem?.description}</p>
            {editItem && texts ? (
              <PrivacyRichEditor
                key={`${editItem.key}-${settings?.consentLanguage ?? 'English'}`}
                id="privacy-edit-text"
                label="Consent text"
                html={texts[editItem.key]}
              />
            ) : null}
            {editItem?.extra ? (
              <div className="privacy-editor-extra">
                {editItem.extra === 'communicate' ? (
                  <div className="field">
                    <label className="field__label" htmlFor="privacy-subscription-type">
                      Subscription type
                    </label>
                    <p className="field__help">
                      Choose the type of content the contact would be receiving.
                    </p>
                    <select
                      className="input"
                      id="privacy-subscription-type"
                      defaultValue={subscriptionNames[0]}
                    >
                      {subscriptionNames.map((name) => (
                        <option key={name}>{name}</option>
                      ))}
                    </select>
                  </div>
                ) : null}
                <label className="field__label" htmlFor="privacy-checkbox-text">
                  {editItem.extra === 'explicit'
                    ? 'Explicit consent to process data checkbox text'
                    : 'Consent to communicate checkbox text'}
                </label>
                <p className="field__help">
                  {editItem.extra === 'explicit'
                    ? 'Use the text field below to explain that this checkbox grants permission to store and process a contact’s personal information.'
                    : 'Use the text field below to inform customers what type of communication they’re consenting to.'}
                </p>
                {editItem.checkboxKey && texts ? (
                  <PrivacyRichEditor
                    key={`${editItem.checkboxKey}-${settings?.consentLanguage ?? 'English'}`}
                    id="privacy-checkbox-text"
                    label="Consent checkbox text"
                    html={texts[editItem.checkboxKey]}
                  />
                ) : null}
              </div>
            ) : null}
          </div>
          <div className="set-modal__foot">
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setEditItem(null)}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="btn-crm btn-crm--primary"
              data-privacy-edit-save
              disabled={saving}
            >
              {saving ? 'Saving…' : 'Save'}
            </button>
          </div>
        </form>
      </SetDialog>

      <SetDialog
        open={cloneSource !== null}
        onClose={() => setCloneSource(null)}
        labelledBy="privacy-clone-title"
      >
        <form
          onSubmit={(e) => {
            e.preventDefault();
            void cloneBanner();
          }}
        >
          <DialogHead
            id="privacy-clone-title"
            title="Clone a banner to another domain"
            onClose={() => setCloneSource(null)}
          />
          <div className="set-modal__body">
            <p>
              Copy <strong>{cloneSource?.name}</strong> with all its settings to these domains.
            </p>
            <div className="privacy-clone-list">
              {externalDomains
                .filter((d) => d !== (cloneSource?.domain ?? domainView))
                .map((d) => (
                  <label key={d} className="privacy-clone-option">
                    <input
                      type="checkbox"
                      checked={cloneTargets.includes(d)}
                      onChange={(e) =>
                        setCloneTargets((cur) =>
                          e.target.checked ? [...cur, d] : cur.filter((x) => x !== d),
                        )
                      }
                    />
                    {d}
                  </label>
                ))}
            </div>
          </div>
          <div className="set-modal__foot">
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setCloneSource(null)}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="btn-crm btn-crm--primary"
              disabled={saving || !cloneTargets.length}
            >
              Clone banner
            </button>
          </div>
        </form>
      </SetDialog>

      <SetDialog
        open={bannerOpen}
        onClose={() => setBannerOpen(false)}
        labelledBy="privacy-drawer-title"
        drawer
        className="privacy-drawer"
      >
        <div className="privacy-drawer-shell">
          <header className="privacy-drawer-head">
            <h2 id="privacy-drawer-title">Create consent banner</h2>
            <button
              type="button"
              className="icon-btn icon-btn--ghost set-modal__close"
              aria-label="Close"
              onClick={() => setBannerOpen(false)}
            >
              ×
            </button>
          </header>
          <div className="privacy-drawer-progress" data-privacy-progress>
            <span className={cn(bannerStep === 0 && 'is-active', bannerStep > 0 && 'is-done')} />
            <i />
            <span className={cn(bannerStep === 1 && 'is-active')} />
            <div>
              <strong className={cn(bannerStep === 0 && 'is-active')}>Configuration</strong>
              <strong className={cn(bannerStep === 1 && 'is-active')}>Notification</strong>
            </div>
          </div>
          <div className="privacy-drawer-scroll">
            <section hidden={bannerStep !== 0}>
              <div className="field">
                <label className="field__label" htmlFor="banner-name">
                  Internal consent banner name *
                </label>
                <input
                  className="input"
                  id="banner-name"
                  placeholder="e.g. Main website banner"
                  value={banner.name}
                  onChange={(e) => setBanner((cur) => ({ ...cur, name: e.target.value }))}
                />
                <p className="field__help">
                  Give this consent banner an internal name. This name will only appear in your this
                  account.
                </p>
              </div>
              <div className="field">
                <label className="field__label" htmlFor="banner-url">
                  URL Path
                </label>
                <div className="privacy-url-input">
                  <span>/</span>
                  <input
                    className="input"
                    id="banner-url"
                    placeholder="yourwebsite.com"
                    value={banner.urlPath}
                    onChange={(e) => setBanner((cur) => ({ ...cur, urlPath: e.target.value }))}
                  />
                </div>
                <p className="field__help">Set a subdirectory for a more targeted banner.</p>
              </div>
              <div className="field privacy-country-field">
                <label className="field__label" htmlFor="banner-countries-trigger">
                  Countries
                </label>
                <p className="field__help">
                  Choose the countries to apply these settings to. If no countries are selected,
                  these settings will be displayed to all visitors.
                </p>
                <button
                  type="button"
                  id="banner-countries-trigger"
                  className="input privacy-country-trigger"
                  aria-expanded={countryMenu}
                  onClick={() => setCountryMenu((open) => !open)}
                >
                  {banner.countries.length
                    ? `${banner.countries.length} countries selected`
                    : 'Select countries'}{' '}
                  <ChevronDown />
                </button>
                <div className="privacy-country-menu" hidden={!countryMenu}>
                  <div className="privacy-language-search-wrap">
                    <span aria-hidden="true">
                      <SearchGlyph />
                    </span>
                    <input
                      className="input"
                      type="search"
                      placeholder="Search countries"
                      value={countryQuery}
                      onChange={(e) => setCountryQuery(e.target.value)}
                    />
                  </div>
                  <div className="privacy-country-options">
                    <div className="privacy-country-group-label">European Union</div>
                    {filteredCountries(EU_COUNTRIES).map((country) => (
                      <label className="check privacy-country-option" key={country}>
                        <input
                          type="checkbox"
                          checked={banner.countries.includes(country)}
                          onChange={(e) =>
                            setBanner((cur) => ({
                              ...cur,
                              countries: e.target.checked
                                ? [...cur.countries, country]
                                : cur.countries.filter((c) => c !== country),
                            }))
                          }
                        />
                        <span className="check__box" aria-hidden="true" />
                        <span className="privacy-country-code">{COUNTRY_CODES[country] || ''}</span>
                        <span>{country}</span>
                      </label>
                    ))}
                    <div className="privacy-country-group-label">Other countries</div>
                    {filteredCountries(OTHER_COUNTRIES).map((country) => (
                      <label className="check privacy-country-option" key={country}>
                        <input
                          type="checkbox"
                          checked={banner.countries.includes(country)}
                          onChange={(e) =>
                            setBanner((cur) => ({
                              ...cur,
                              countries: e.target.checked
                                ? [...cur.countries, country]
                                : cur.countries.filter((c) => c !== country),
                            }))
                          }
                        />
                        <span className="check__box" aria-hidden="true" />
                        <span className="privacy-country-code">{COUNTRY_CODES[country] || ''}</span>
                        <span>{country}</span>
                      </label>
                    ))}
                  </div>
                  <div className="privacy-country-foot">
                    <button
                      type="button"
                      className="link"
                      onClick={() => setBanner((cur) => ({ ...cur, countries: [] }))}
                    >
                      Clear
                    </button>
                    <button
                      type="button"
                      className="btn-crm btn-crm--primary btn-crm--sm"
                      onClick={() => setCountryMenu(false)}
                    >
                      Done
                    </button>
                  </div>
                </div>
              </div>
              <div className="field">
                <label className="field__label">
                  Global Privacy Control (GPC) <InfoGlyph />
                </label>
                <p className="field__help">
                  Support Global Privacy Control browser signals on pages with this consent banner.
                </p>
                <label className="check privacy-check-row">
                  <input
                    type="checkbox"
                    checked={banner.gpc}
                    onChange={(e) => setBanner((cur) => ({ ...cur, gpc: e.target.checked }))}
                  />
                  <span className="check__box" aria-hidden="true" />
                  <span>
                    Respond to Global Privacy Control signalling.{' '}
                    <button type="button" className="link" onClick={() => openInfo('gpc-help')}>
                      Learn more.
                    </button>
                  </span>
                </label>
                <div className="privacy-gpc-text" hidden={!banner.gpc}>
                  <div className="privacy-field-label-row">
                    <label className="field__label">Global Privacy Control banner text *</label>
                    <div className="privacy-language-picker privacy-language-picker--gpc">
                      <button
                        type="button"
                        className="input"
                        aria-expanded={gpcLangMenu}
                        onClick={() => setGpcLangMenu((open) => !open)}
                      >
                        {banner.gpcLanguage || 'Choose default text'} <ChevronDown />
                      </button>
                      <div
                        className="privacy-language-menu privacy-language-menu--search"
                        hidden={!gpcLangMenu}
                      >
                        <div className="privacy-language-search-wrap">
                          <span aria-hidden="true">
                            <SearchGlyph />
                          </span>
                          <input
                            className="input"
                            type="search"
                            placeholder="Search"
                            value={gpcLangQuery}
                            onChange={(e) => setGpcLangQuery(e.target.value)}
                          />
                        </div>
                        <div className="privacy-language-options">
                          {BANNER_LANGUAGES.filter((name) =>
                            name.toLowerCase().includes(gpcLangQuery.trim().toLowerCase()),
                          ).map((name) => (
                            <button
                              key={name}
                              type="button"
                              className={cn(banner.gpcLanguage === name && 'is-selected')}
                              onClick={() => {
                                setBanner((cur) => ({
                                  ...cur,
                                  gpcLanguage: name,
                                  gpcText: GPC_DEFAULTS[name] ?? cur.gpcText,
                                }));
                                setGpcLangMenu(false);
                              }}
                            >
                              {name}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                  <PrivacyRichEditor
                    key={banner.gpcLanguage || 'gpc'}
                    id="privacy-gpc-text"
                    label="Global Privacy Control banner text"
                    html={banner.gpcText ?? ''}
                  />
                  <p className="field__help privacy-success-text">
                    Choose from the default options or write your own. You may want to review these
                    terms with a lawyer.
                  </p>
                </div>
              </div>
              <details className="privacy-advanced">
                <summary>Advanced cookie banner settings</summary>
                <p>
                  Enabling one of these options will mean a banner won&apos;t display on these
                  pages. Your website visitors won&apos;t have the option to consent or decline
                  tracking through your banner.
                </p>
                <div className="privacy-advanced-row">
                  <div>
                    <strong>Deactivate cookies?</strong>
                    <p>
                      Enable this option if you want to never allow cookie tracking for the pages or
                      countries specified above.
                    </p>
                  </div>
                  <label className="switch">
                    <input
                      type="checkbox"
                      checked={banner.deactivateCookies}
                      onChange={(e) =>
                        setBanner((cur) => ({
                          ...cur,
                          deactivateCookies: e.target.checked,
                          allowAllCookies: e.target.checked ? false : cur.allowAllCookies,
                        }))
                      }
                    />
                    <span className="switch__track" />
                  </label>
                </div>
                <div className="privacy-advanced-row">
                  <div>
                    <strong>Allow all cookies?</strong>
                    <p>
                      Enable this option if you want to always allow cookie tracking for the pages
                      or domains specified above.
                    </p>
                  </div>
                  <label className="switch">
                    <input
                      type="checkbox"
                      checked={banner.allowAllCookies}
                      onChange={(e) =>
                        setBanner((cur) => ({
                          ...cur,
                          allowAllCookies: e.target.checked,
                          deactivateCookies: e.target.checked ? false : cur.deactivateCookies,
                        }))
                      }
                    />
                    <span className="switch__track" />
                  </label>
                </div>
              </details>
            </section>
            <section hidden={bannerStep !== 1}>
              <h3 className="privacy-drawer-subtitle">Select a banner type *</h3>
              <p className="field__help">
                Choose how you want to communicate to visitors about cookie tracking on your site.
              </p>
              {(
                [
                  {
                    value: 'notification' as const,
                    title: 'Notification',
                    help: 'Visitors are automatically opted in to accepting cookies and will be shown the banner just to notify them of that fact.',
                  },
                  {
                    value: 'optin' as const,
                    title: 'Opt-in',
                    badge: 'Suggested for: Europe',
                    help: 'Visitors will only accept cookies if they opt-in via the banner.',
                    category: 'Allow opt-in by category',
                  },
                  {
                    value: 'optout' as const,
                    title: 'Opt-out',
                    help: 'Visitors will automatically accept all cookies but can opt out via the banner.',
                    category: 'Allow opt-out by category',
                  },
                ] as const
              ).map((option) => (
                <div className="privacy-radio-card" key={option.value}>
                  <label className="privacy-radio-main">
                    <input
                      type="radio"
                      name="banner-type"
                      checked={banner.bannerType === option.value}
                      onChange={() =>
                        setBanner((cur) => ({
                          ...cur,
                          bannerType: option.value,
                          optByCategory:
                            option.value === cur.bannerType ? cur.optByCategory : false,
                          customizeOpen: false,
                        }))
                      }
                    />
                    <span>
                      <strong>
                        {option.title}{' '}
                        {'badge' in option && option.badge ? (
                          <em className="privacy-suggested-badge">{option.badge}</em>
                        ) : null}
                      </strong>
                      <small>{option.help}</small>
                    </span>
                  </label>
                  {'category' in option && option.category ? (
                    <label className="check privacy-nested-check">
                      <input
                        type="checkbox"
                        disabled={banner.bannerType !== option.value}
                        checked={banner.bannerType === option.value && banner.optByCategory}
                        onChange={(e) =>
                          setBanner((cur) => ({
                            ...cur,
                            optByCategory: e.target.checked,
                            customizeOpen: e.target.checked ? cur.customizeOpen : false,
                          }))
                        }
                      />
                      <span className="check__box" aria-hidden="true" />
                      <span>{option.category}</span>
                    </label>
                  ) : null}
                </div>
              ))}
              <div className="privacy-customize-row">
                <button
                  type="button"
                  className="link"
                  disabled={!categoryEnabled}
                  aria-expanded={banner.customizeOpen}
                  onClick={() =>
                    setBanner((cur) => ({ ...cur, customizeOpen: !cur.customizeOpen }))
                  }
                >
                  Customize cookies display
                </button>
                <select
                  className="input privacy-actions-select"
                  disabled={!categoryEnabled}
                  aria-label="Cookie display actions"
                  defaultValue=""
                  onChange={(e) => {
                    const value = e.target.value;
                    e.target.value = '';
                    if (value === 'select-all') {
                      setBanner((cur) => ({
                        ...cur,
                        analyticsCookies: true,
                        advertisingCookies: true,
                      }));
                    }
                    if (value === 'clear-all') {
                      setBanner((cur) => ({
                        ...cur,
                        analyticsCookies: false,
                        advertisingCookies: false,
                      }));
                    }
                  }}
                >
                  <option value="">Actions</option>
                  <option value="select-all">Select all categories</option>
                  <option value="clear-all">Clear optional categories</option>
                </select>
              </div>
              <div
                className="privacy-cookie-customize"
                hidden={!banner.customizeOpen || !categoryEnabled}
              >
                <CheckRow checked disabled>
                  Strictly necessary cookies
                </CheckRow>
                <CheckRow
                  checked={banner.analyticsCookies}
                  onChange={(next) => setBanner((cur) => ({ ...cur, analyticsCookies: next }))}
                >
                  Analytics cookies
                </CheckRow>
                <CheckRow
                  checked={banner.advertisingCookies}
                  onChange={(next) => setBanner((cur) => ({ ...cur, advertisingCookies: next }))}
                >
                  Advertising cookies
                </CheckRow>
              </div>
              <div className="privacy-notification-language">
                <p>
                  Choose from the default options or write your own. You may want to review these
                  terms with a lawyer.
                </p>
                <div className="privacy-language-picker">
                  <button
                    type="button"
                    className="input"
                    aria-expanded={bannerLangMenu}
                    onClick={() => setBannerLangMenu((open) => !open)}
                  >
                    {banner.language || 'Choose a language'} <ChevronDown />
                  </button>
                  <div
                    className="privacy-language-menu privacy-language-menu--search"
                    hidden={!bannerLangMenu}
                  >
                    <div className="privacy-language-search-wrap">
                      <span aria-hidden="true">
                        <SearchGlyph />
                      </span>
                      <input
                        className="input"
                        type="search"
                        placeholder="Search"
                        value={bannerLangQuery}
                        onChange={(e) => setBannerLangQuery(e.target.value)}
                      />
                    </div>
                    <div className="privacy-language-options">
                      {BANNER_LANGUAGES.filter((name) =>
                        name.toLowerCase().includes(bannerLangQuery.trim().toLowerCase()),
                      ).map((name) => (
                        <button
                          key={name}
                          type="button"
                          className={cn(banner.language === name && 'is-selected')}
                          onClick={() => {
                            setBanner((cur) => ({ ...cur, language: name }));
                            setBannerLangMenu(false);
                          }}
                        >
                          {name}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
              {bannerStep === 1 ? (
                <div className="privacy-settings-card crm-mt-3" aria-label="Banner preview">
                  <strong>Preview</strong>
                  <p>
                    {banner.name || 'Untitled banner'}
                    {banner.language ? ` · ${banner.language}` : ''}
                    {banner.bannerType ? ` · ${banner.bannerType}` : ''}
                  </p>
                  <p>
                    {banner.bannerType === 'optin'
                      ? 'We use cookies. Accept to allow analytics and advertising cookies, or reject to keep only the ones this site needs.'
                      : banner.bannerType === 'optout'
                        ? 'We use cookies. You can opt out of analytics and advertising cookies.'
                        : 'This site uses cookies to remember your visit and understand how the site is used.'}
                  </p>
                </div>
              ) : null}
            </section>
          </div>
          <footer className="privacy-drawer-foot">
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              hidden={bannerStep === 0}
              onClick={() => setBannerStep(0)}
            >
              Back
            </button>
            <span className="privacy-drawer-foot-spacer" />
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              hidden={bannerStep === 1}
              disabled={!banner.name.trim()}
              onClick={() => {
                if (!banner.name.trim()) return;
                setBanner((cur) => ({
                  ...cur,
                  gpcText: editorHtml('privacy-gpc-text') || cur.gpcText,
                }));
                setBannerStep(1);
              }}
            >
              Next
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              hidden={bannerStep !== 1}
              disabled={!banner.bannerType || saving}
              onClick={() => void publishBanner()}
            >
              {editingBannerId ? 'Save' : 'Publish'}
            </button>
          </footer>
        </div>
      </SetDialog>

      <SetDialog
        open={infoKey !== null}
        onClose={closeInfo}
        labelledBy="privacy-info-title"
        className={cn('privacy-info-dialog', asDrawer && 'privacy-info-as-drawer')}
      >
        <form
          onSubmit={(e) => {
            e.preventDefault();
            void saveInfo();
          }}
        >
          <DialogHead
            id="privacy-info-title"
            title={infoKey ? INFO_TITLES[infoKey] : 'Privacy settings'}
            onClose={closeInfo}
          />
          <div className="set-modal__body">
            {infoKey === 'legal-reasons' ? (
              <>
                <p>
                  Review the wording shown to contacts when your business records a legal basis for
                  storing and processing their data.
                </p>
                <div className="field">
                  <label className="field__label" htmlFor="legal-reason-text">
                    Legal reason text
                  </label>
                  <textarea
                    className="input"
                    id="legal-reason-text"
                    rows={5}
                    value={legalText}
                    onChange={(e) => setLegalText(e.target.value)}
                  />
                </div>
              </>
            ) : null}
            {infoKey === 'request-page' ? (
              <>
                <p>
                  Configure the page where contacts can submit requests to access, export, or delete
                  their personal data.
                </p>
                <div className="field">
                  <label className="field__label" htmlFor="request-page-title">
                    Page heading
                  </label>
                  <input
                    className="input"
                    id="request-page-title"
                    value={requestPage.heading}
                    onChange={(e) => setRequestPage((cur) => ({ ...cur, heading: e.target.value }))}
                  />
                </div>
                <div className="field">
                  <label className="field__label" htmlFor="request-page-intro">
                    Intro text
                  </label>
                  <textarea
                    className="input"
                    id="request-page-intro"
                    rows={3}
                    value={requestPage.intro}
                    onChange={(e) => setRequestPage((cur) => ({ ...cur, intro: e.target.value }))}
                  />
                </div>
                <div className="field">
                  <label className="field__label" htmlFor="request-page-email">
                    Notification email
                  </label>
                  <input
                    className="input"
                    id="request-page-email"
                    type="email"
                    placeholder="privacy@yourcompany.example"
                    value={requestPage.email ?? ''}
                    onChange={(e) => setRequestPage((cur) => ({ ...cur, email: e.target.value }))}
                  />
                </div>
                <div className="field">
                  <label className="field__label">Available request types</label>
                  <div className="privacy-info-checks">
                    <CheckRow
                      checked={requestPage.access}
                      onChange={(next) => setRequestPage((cur) => ({ ...cur, access: next }))}
                    >
                      Access my data
                    </CheckRow>
                    <CheckRow
                      checked={requestPage.delete}
                      onChange={(next) => setRequestPage((cur) => ({ ...cur, delete: next }))}
                    >
                      Delete my data
                    </CheckRow>
                    <CheckRow
                      checked={requestPage.export}
                      onChange={(next) => setRequestPage((cur) => ({ ...cur, export: next }))}
                    >
                      Export my data
                    </CheckRow>
                  </div>
                </div>
              </>
            ) : null}
            {infoKey === 'default-banners' ? (
              <>
                <p>
                  Default consent banners apply to tracked websites that do not have a custom banner
                  configured.
                </p>
                <div className="privacy-info-checks">
                  <CheckRow checked={showDefault} onChange={setShowDefault}>
                    Show default consent banner
                  </CheckRow>
                  <CheckRow checked={includePreferences} onChange={setIncludePreferences}>
                    Include cookie preferences
                  </CheckRow>
                </div>
                <p className="field__help">
                  Changes to default banners will apply to the websites connected to your account.
                </p>
              </>
            ) : null}
            {infoKey === 'hosting-change' ? (
              <>
                <p>
                  To change where your data is hosted you’ll need to schedule a data migration.
                  Here’s what you need to know:
                </p>
                <ul className="privacy-migration-notes">
                  <li>
                    Your account will be unavailable during the migration. Most finish within 24
                    hours; some can take up to 36. Your public content will remain online.
                  </li>
                  <li>
                    After the migration completes, your data and settings will remain unchanged, but
                    some steps may be needed to keep everything running smoothly.
                  </li>
                  <li>
                    If you have active Sandboxes, they’ll be selected too, but only eligible ones
                    will be migrated—you may need to take action.
                  </li>
                  <li>
                    For more details, check our{' '}
                    <a href="#">
                      FAQ <ExternalIcon />
                    </a>{' '}
                    or{' '}
                    <a href="#">
                      contact support <ExternalIcon />
                    </a>
                    .
                  </li>
                </ul>
                <div className="field">
                  <label className="field__label" htmlFor="hosting-location">
                    New data hosting location *
                  </label>
                  <select
                    className="input"
                    id="hosting-location"
                    value={hostingDraft}
                    onChange={(e) => setHostingDraft(e.target.value)}
                  >
                    <option value="">Choose a location</option>
                    {HOSTING_OPTIONS.map((name) => (
                      <option key={name}>{name}</option>
                    ))}
                  </select>
                </div>
              </>
            ) : null}
            {infoKey === 'external-domain' ? (
              <>
                <p>Add the domains to use with your consent banners.</p>
                {externalDomainDrafts.map((draft, index) => (
                  <div className="field privacy-domain-field" key={index}>
                    <label className="field__label" htmlFor={`external-domain-${index}`}>
                      External domain{externalDomainDrafts.length > 1 ? ` ${index + 1}` : ''}
                    </label>
                    <div className="privacy-domain-field__row">
                      <input
                        className="input"
                        id={`external-domain-${index}`}
                        placeholder="www.example.com"
                        value={draft}
                        onChange={(e) =>
                          setExternalDomainDrafts((cur) =>
                            cur.map((d, i) => (i === index ? e.target.value : d)),
                          )
                        }
                      />
                      {externalDomainDrafts.length > 1 ? (
                        <button
                          type="button"
                          className="link"
                          aria-label={`Remove domain ${index + 1}`}
                          onClick={() =>
                            setExternalDomainDrafts((cur) => cur.filter((_, i) => i !== index))
                          }
                        >
                          Remove
                        </button>
                      ) : null}
                    </div>
                  </div>
                ))}
                <button
                  type="button"
                  className="link"
                  disabled={externalDomainDrafts.length >= 10}
                  onClick={() => setExternalDomainDrafts((cur) => [...cur, ''])}
                >
                  + Add another domain
                </button>
              </>
            ) : null}
            {infoKey === 'privacy-toggle-confirm' ? (
              <>
                <p>
                  Some settings will be automatically defaulted in your account. After, you’ll see
                  the tools where a data privacy section is missing and you’ll be able to set up
                  additional settings to help you follow privacy rules.
                </p>
                <p>
                  You’ll get a confirmation email when you turn on this setting in your account.
                </p>
              </>
            ) : null}
            {infoKey === 'privacy-guide' ? (
              <p>
                Data privacy settings help your team record a lawful basis for processing personal
                data, manage consent, and respond to privacy requests.
              </p>
            ) : null}
            {infoKey === 'request-help' ? (
              <p>
                Contacts can use the privacy request page to ask for access to, export of, or
                deletion of their personal data. Submitted requests are managed in Data request
                manager.
              </p>
            ) : null}
            {infoKey === 'gpc-help' ? (
              <p>
                Global Privacy Control is a browser signal that can communicate a visitor’s privacy
                preferences to websites.
              </p>
            ) : null}
            {infoKey === 'inactive-contacts' ? (
              <>
                <p>When this happens</p>
                <div className="field">
                  <label className="field__label" htmlFor="inactive-days">
                    Days that have passed *
                  </label>
                  <input
                    className="input"
                    type="number"
                    id="inactive-days"
                    min={1}
                    value={inactiveDaysDraft}
                    onChange={(e) => setInactiveDaysDraft(Number(e.target.value))}
                  />
                </div>
                <p>
                  since the contact creation date, and there have been no updates or the value is
                  unknown for the following contact properties: time of last session, last marketing
                  email open date, and last engagement date.
                </p>
                <h3 className="privacy-drawer-subtitle">Then do this</h3>
                <div className="privacy-action-preview">Delete contact</div>
              </>
            ) : null}
            {infoKey === 'hosting-info' ? (
              <p>
                Your account data is currently hosted in{' '}
                {settings?.hostingLocation ?? 'United States (West)'}. Changing the hosting location
                requires scheduling a data migration.
              </p>
            ) : null}
          </div>
          <div className="set-modal__foot">
            <button type="button" className="btn-crm btn-crm--outline" onClick={closeInfo}>
              Close
            </button>
            <button
              type="submit"
              className="btn-crm btn-crm--primary"
              disabled={saving || (infoKey === 'hosting-change' && !hostingDraft)}
            >
              {saveLabel}
            </button>
          </div>
        </form>
      </SetDialog>
    </div>
  );
}
