﻿'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { canEditPropertySettings } from '@/features/permission-sets/property-settings';
import { errorText } from '@/lib/api/errors';
import {
  DEFAULT_CALL_SETTINGS,
  getCallSettings,
  updateCallSettings,
  type CallSettings,
} from '../../workspace-settings.client';
import { SetTabs, useHashTab } from '../settings-ui';
import { CallOutcomesDrawer } from './CallOutcomesDrawer';
import { HsSwitch } from './HsSwitch';

const TABS = [
  { id: 'phone', label: 'Phone Numbers' },
  { id: 'config', label: 'Call Configurations' },
];

type PhoneRow = {
  phone: string;
  country: string;
  assigned: string;
};

/** CRM number provisioning is not live yet (HUB-416). Keep empty until real numbers are loaded. */
const INITIAL_PHONES: PhoneRow[] = [];

function Ext() {
  return <CrmIcon name="external" className="iconSize-14" />;
}

function EditIcon() {
  return (
    <svg
      className="icon iconSize-14 crm-d-inline-block"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M12 20h9" />
      <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />
    </svg>
  );
}

export function CallSetupView() {
  const toast = useToast();
  const me = useCurrentUser();
  const [tab, selectTab] = useHashTab(TABS, 'phone');
  const soon = (msg: string) => toast(msg, 'info');

  // Phone numbers tab
  const [phones, setPhones] = useState(INITIAL_PHONES);
  const [search, setSearch] = useState('');
  const [actionsOpen, setActionsOpen] = useState<string | null>(null);
  const [countryOpen, setCountryOpen] = useState(false);
  const [assignedOpen, setAssignedOpen] = useState(false);
  const [countries, setCountries] = useState<string[]>([]);
  const [assignedFilters, setAssignedFilters] = useState<string[]>([]);

  // Call configurations: one document saved to the account. Each change is saved right away.
  const [settings, setSettings] = useState<CallSettings>(DEFAULT_CALL_SETTINGS);
  const [loaded, setLoaded] = useState(false);
  const latest = useRef(settings);
  const {
    placeCalls,
    trackTypes,
    outcomeRequired,
    recording,
    recordInbound,
    recordOutbound,
    transcription,
    autoAssoc,
    callTypes,
  } = settings;

  const [turnOffOpen, setTurnOffOpen] = useState(false);
  const [turnOffText, setTurnOffText] = useState('');
  // The option drawers edit drafts; Save stores them, Cancel drops them.
  const [typesDrawer, setTypesDrawer] = useState(false);
  const [typesDraft, setTypesDraft] = useState<string[]>([]);
  // CGL2: call outcomes are the call outcome picklist (what Log a call offers), not this document.
  const [outcomesDrawer, setOutcomesDrawer] = useState(false);
  const closeOutcomes = useCallback(() => setOutcomesDrawer(false), []);

  const applySaved = (saved: CallSettings) => {
    latest.current = saved;
    setSettings(saved);
  };

  useEffect(() => {
    let cancelled = false;
    getCallSettings()
      .then((saved) => {
        if (cancelled) return;
        latest.current = saved;
        setSettings(saved);
        setLoaded(true);
      })
      .catch((error: unknown) => {
        if (!cancelled) toast(errorText(error), 'danger');
      });
    return () => {
      cancelled = true;
    };
  }, [toast]);

  /** Saves one or more changes to the whole document. Failure reverts to the saved copy. */
  const persist = async (change: Partial<CallSettings>, success?: string) => {
    if (!loaded) {
      toast('Call settings are still loading', 'info');
      return;
    }
    const next = { ...latest.current, ...change };
    applySaved(next);
    try {
      await updateCallSettings(next);
      if (success) toast(success, 'success');
    } catch (error) {
      toast(errorText(error), 'danger');
      try {
        applySaved(await getCallSettings());
      } catch {
        // Keep the local copy; the error toast above already explains the failure.
      }
    }
  };

  const filteredPhones = useMemo(() => {
    const q = search.trim().toLowerCase();
    return phones.filter((p) => {
      if (q && !p.phone.toLowerCase().includes(q)) return false;
      if (countries.length && !countries.includes(p.country)) return false;
      if (assignedFilters.length && !assignedFilters.includes(p.assigned)) return false;
      return true;
    });
  }, [phones, search, countries, assignedFilters]);

  const requestPlaceCalls = (next: boolean) => {
    if (!next && placeCalls) {
      setTurnOffText('');
      setTurnOffOpen(true);
      return;
    }
    void persist({ placeCalls: next });
  };

  const monthLabel = new Date().toLocaleString('en-US', { month: 'long' });

  return (
    <div className="call-setup-page call-setup-main">
        <header className="set-head call-setup-head">
          <h1 className="set-head__title crm-mb-2">Call Setup</h1>
        </header>

        <SetTabs
          label="Call setup sections"
          tabs={TABS}
          active={tab}
          onSelect={selectTab}
          boxed
          className="call-setup-tabs"
        />

        <p className="call-setup-intro">
          These settings will apply to everyone in your account. To manage your own phone numbers, go
          to{' '}
          <Link href="/settings/profile#tab-calling" className="link">
            User Call Settings <Ext />
          </Link>
          . To manage your call integrations, go to{' '}
          <Link href="/settings/connected-apps" className="link">
            Connected Apps <Ext />
          </Link>
          . To manage your own calendar and notetaker, go to{' '}
          <Link href="/settings/profile#tab-calendar" className="link">
            Calendar <Ext />
          </Link>
          .
        </p>

        {tab === 'phone' ? (
          <section className="call-setup-panel" role="tabpanel">
            <section className="call-setup-section">
              <div className="call-setup-section-heading">
                <h2>CRM numbers</h2>
                <p>
                  These are phone numbers that were acquired through CRM and are either assigned to
                  users in your account or are connected to channels. Set up and use{' '}
                  <a href="#" className="link" onClick={(e) => { e.preventDefault(); soon('CRM numbers help coming soon'); }}>
                    CRM numbers <Ext />
                  </a>{' '}
                  to make and receive calls with automatic call logging.
                </p>
              </div>
              <div className="call-setup-actions">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm call-setup-audio-btn"
                  disabled
                  title="Audio messages are coming soon"
                >
                  Edit audio messages
                </button>
                <span className="call-setup-usage">
                  {phones.length} of 5 CRM Numbers Used{' '}
                  <button
                    type="button"
                    className="call-setup-info calling-info--popover"
                    aria-label="About CRM number limits"
                  >
                    <CrmIcon name="info" className="iconSize-14" />
                    <span className="calling-info__popover" role="tooltip">
                      <span className="crm-d-block crm-mb-2">
                        Your team has used {phones.length} of 5 CRM numbers.
                      </span>
                      <span className="crm-d-block">
                        Learn more about getting more phone numbers.
                      </span>
                    </span>
                  </button>
                </span>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm call-setup-pill-btn"
                  disabled
                  title="Porting a number is coming soon"
                >
                  Port a number
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--primary btn-crm--sm call-number-pill-btn call-setup-get-btn"
                  disabled
                  title="Getting a CRM number is coming soon"
                >
                  Get a CRM number
                </button>
              </div>

              {!phones.length ? (
                <div className="call-setup-empty call-setup-empty--CRM">
                  <div className="call-setup-empty-copy">
                    <h3>
                      Use CRM Calling to streamline your communication and keep all your
                      conversations in one place
                    </h3>
                    <p>
                      Use a CRM number, port an existing number or connect a third-party integration
                      to start making and receiving calls with automatic call logging.
                    </p>
                  </div>
                  <div className="call-setup-illustration" aria-hidden>
                    <CrmIcon name="phone" className="iconSize-48" />
                  </div>
                </div>
              ) : null}
            </section>

            {phones.length ? (
              <div className="ivr-table-wrap">
                <div className="cpt-toolbar">
                  <div className="cpt-toolbar__left">
                    <div className="cpt-search-wrap">
                      <input
                        type="text"
                        className="cpt-search-input"
                        placeholder="Search phone numbers"
                        aria-label="Search phone numbers"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                      />
                      <span className="cpt-search-icon" aria-hidden>
                        <CrmIcon name="search" className="iconSize-16" />
                      </span>
                    </div>

                    <div className="cpt-filter-wrap">
                      <button
                        type="button"
                        className="cpt-filter-btn"
                        aria-expanded={countryOpen}
                        onClick={() => {
                          setCountryOpen((o) => !o);
                          setAssignedOpen(false);
                        }}
                      >
                        <span className="cpt-filter-label">
                          {countries.length ? `Country (${countries.length})` : 'Country'}
                        </span>
                        <svg className="cpt-caret" viewBox="0 0 10 6" width="10" height="6" fill="currentColor" aria-hidden>
                          <path d="M0 0l5 5 5-5z" />
                        </svg>
                      </button>
                      {countryOpen ? (
                        <div className="cpt-filter-menu">
                          <label className="cpt-option">
                            <input
                              type="checkbox"
                              className="cpt-checkbox"
                              checked={countries.includes('United States')}
                              onChange={() =>
                                setCountries((prev) =>
                                  prev.includes('United States') ? [] : ['United States'],
                                )
                              }
                            />
                            <span className="cpt-option-label">United States</span>
                          </label>
                        </div>
                      ) : null}
                    </div>

                    <div className="cpt-filter-wrap">
                      <button
                        type="button"
                        className="cpt-filter-btn"
                        aria-expanded={assignedOpen}
                        onClick={() => {
                          setAssignedOpen((o) => !o);
                          setCountryOpen(false);
                        }}
                      >
                        <span className="cpt-filter-label">
                          Assigned to ({assignedFilters.length})
                        </span>
                        <svg className="cpt-caret" viewBox="0 0 10 6" width="10" height="6" fill="currentColor" aria-hidden>
                          <path d="M0 0l5 5 5-5z" />
                        </svg>
                      </button>
                      {assignedOpen ? (
                        <div className="cpt-filter-menu">
                          {['Help desk', 'Inbox', 'Interactive Voice Response (IVR)', 'Unassigned', 'User'].map(
                            (a) => (
                              <label className="cpt-option" key={a}>
                                <input
                                  type="checkbox"
                                  className="cpt-checkbox"
                                  checked={assignedFilters.includes(a)}
                                  onChange={() =>
                                    setAssignedFilters((prev) =>
                                      prev.includes(a)
                                        ? prev.filter((x) => x !== a)
                                        : [...prev, a],
                                    )
                                  }
                                />
                                <span className="cpt-option-label">{a}</span>
                              </label>
                            ),
                          )}
                        </div>
                      ) : null}
                    </div>
                  </div>
                </div>

                <div className="calling-phone-table-wrap">
                  <table className="calling-phone-number-table">
                    <thead>
                      <tr>
                        <th className="cpt-th cpt-th--phone">
                          <div className="cpt-th-content">
                            <span className="cpt-th-title">Phone Number</span>
                            <span className="cpt-sort-icon">↑↓</span>
                          </div>
                        </th>
                        <th className="cpt-th cpt-th--connected">
                          <div className="cpt-th-content">
                            <span className="cpt-th-title">Connected To</span>
                          </div>
                        </th>
                        <th className="cpt-th cpt-th--callerid">
                          <div className="cpt-th-content">
                            <span className="cpt-th-title">Caller ID</span>
                          </div>
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredPhones.map((row) => (
                        <tr key={row.phone}>
                          <td>
                            <div className="cpt-phone-cell">
                              <span className="cpt-phone-val">{row.phone}</span>
                              <div className="cpt-actions-wrap">
                                <button
                                  type="button"
                                  className="cpt-actions-btn"
                                  aria-expanded={actionsOpen === row.phone}
                                  onClick={() =>
                                    setActionsOpen((cur) => (cur === row.phone ? null : row.phone))
                                  }
                                >
                                  Actions
                                  <svg className="cpt-actions-caret" viewBox="0 0 10 6" width="9" height="5" fill="currentColor" aria-hidden>
                                    <path d="M0 0l5 5 5-5z" />
                                  </svg>
                                </button>
                                {actionsOpen === row.phone ? (
                                  <div className="cpt-actions-menu">
                                    <button
                                      type="button"
                                      className="cpt-action-item"
                                      onClick={() => {
                                        setActionsOpen(null);
                                        soon('Connect to channel coming soon');
                                      }}
                                    >
                                      Connected to Channel
                                    </button>
                                    <hr className="cpt-actions-divider" />
                                    <button
                                      type="button"
                                      className="cpt-action-item cpt-action-item--danger"
                                      onClick={() => {
                                        setPhones((prev) => prev.filter((p) => p.phone !== row.phone));
                                        setActionsOpen(null);
                                        toast('Number removed (local only)', 'success');
                                      }}
                                    >
                                      Delete
                                    </button>
                                  </div>
                                ) : null}
                              </div>
                            </div>
                          </td>
                          <td>{row.assigned}</td>
                          <td>
                            <button
                              type="button"
                              className="cpt-verify-btn"
                              onClick={() => soon('Verify to turn on Caller ID coming soon')}
                            >
                              Verify to turn on
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            ) : null}

            <section className="call-setup-section">
              <div className="call-setup-section-heading">
                <h2>Registered numbers</h2>
                <p className="crm-mb-2">
                  These are phone numbers you have added that were not acquired through CRM. These
                  lines can only be used to place outbound calls from the CRM and face increased risk
                  of blocked calls and spam labeling from local carriers.
                </p>
              </div>
              <div className="call-setup-empty call-setup-empty--registered">
                <div className="call-setup-illustration" aria-hidden>
                  <CrmIcon name="search" className="iconSize-32" />
                </div>
                <p>There are no registered phone numbers in your account.</p>
              </div>
            </section>

            <section className="call-setup-section call-setup-section--usage">
              <div className="call-setup-section-heading">
                <h2>Usage, limits, and subscriptions</h2>
                <p>
                  This is the accumulative overview for all users of calling in your account. You can
                  also view historical minute usage on the call analytics dashboard.
                </p>
              </div>
              <div className="call-setup-meter-card">
                <div className="call-setup-meter-top">
                  <strong>
                    {monthLabel} minute usage&nbsp; 0 / 12,000
                  </strong>
                  <Link href="/settings/billing" className="link">
                    Manage minute subscription <Ext />
                  </Link>
                </div>
                <div className="call-setup-progress">
                  <span style={{ width: '0%' }} />
                </div>
                <p>
                  Usage resets at the start of each month. The available minutes are based on your
                  CRM plan and any minute subscriptions in your account.
                </p>
              </div>
              <div className="call-setup-meter-card call-setup-meter-card--compact">
                <div className="call-setup-meter-top">
                  <strong>Phone numbers in use&nbsp; {phones.length} / 5</strong>
                  <Link href="/settings/billing" className="link">
                    Manage phone number subscription <Ext />
                  </Link>
                </div>
                <p>
                  The limit includes phone numbers provided in your CRM plan and any phone number
                  subscriptions in your account.
                </p>
              </div>
            </section>

            <section className="call-setup-section call-setup-integration">
              <h2>Connect an integration</h2>
              <a
                href="/settings/connected-apps"
                className="call-setup-integration-link"
              >
                <span aria-hidden>
                  <CrmIcon name="sparkles" className="iconSize-24" />
                </span>
                <span>
                  <strong>
                    Explore third-party integrations <Ext />
                  </strong>
                  <small>Integrate a calling provider for making calls in CRM</small>
                </span>
              </a>
            </section>
          </section>
        ) : (
          <section className="call-setup-panel" role="tabpanel">
            <section className="call-setup-config-section">
              <h2>Calling</h2>
              <div className="call-setup-setting-row">
                <HsSwitch checked={placeCalls} onChange={requestPlaceCalls} name="placeCalls" />
                <div>
                  <h3>Place calls using CRM calling</h3>
                  <p>
                    CRM calling is powered by Twilio, which is used to record and store any calls that
                    are recorded. Recordings can only be accessed by users in your portal unless the
                    URL is shared externally by one of your users. Allow CRM calling as a provider for
                    calls. When turned off, other calling integrations can still be used.
                  </p>
                </div>
              </div>
              <div className="call-setup-setting-row">
                <HsSwitch checked={trackTypes} onChange={(v) => void persist({ trackTypes: v })} name="trackTypes" />
                <div>
                  <h3>
                    Track call and meeting types{' '}
                    <button
                      type="button"
                      className="call-setup-inline-link"
                      onClick={() => {
                        setTypesDraft(callTypes);
                        setTypesDrawer(true);
                      }}
                    >
                      <EditIcon /> Edit options
                    </button>
                  </h3>
                  <p>
                    Organize how your team logs activities by providing custom meeting and call
                    types. Use these custom activity types to report on which calls and meetings are
                    most successful in your sales process.
                  </p>
                </div>
              </div>
              <div className="call-setup-setting-row call-setup-setting-row--plain">
                <div>
                  <h3>
                    Track call outcomes{' '}
                    <button
                      type="button"
                      className="call-setup-inline-link"
                      onClick={() => setOutcomesDrawer(true)}
                    >
                      <EditIcon /> Edit options
                    </button>
                  </h3>
                  <p>
                    Organize how your team logs activities by providing custom call outcomes. Report
                    on this to track call patterns.
                  </p>
                </div>
              </div>
              <div className="call-setup-setting-row">
                <HsSwitch
                  checked={outcomeRequired}
                  onChange={(v) => void persist({ outcomeRequired: v })}
                  name="outcomeRequired"
                />
                <div>
                  <h3>Make call outcome required</h3>
                  <p>
                    Requires users to select the outcome of a call when it is completed or logged on
                    a record.
                  </p>
                </div>
              </div>
            </section>

            <section className="call-setup-config-section">
              <h2>Recording and transcription</h2>
              <p className="call-setup-config-copy">
                Laws and regulations around call recording, meeting notetakers, and transcription are
                complex. You are responsible for determining and ensuring compliance with the laws
                that apply to you and your use of these features.
              </p>
              <div className="call-setup-setting-row">
                <HsSwitch checked={recording} onChange={(v) => void persist({ recording: v })} name="recording" />
                <div>
                  <h3>Call recording</h3>
                  <p>
                    This setting enables call recording for your entire account. Before enabling call
                    recording, make sure your team understands when consent to record is required by
                    law.
                  </p>
                  {recording ? (
                    <div className="call-setup-nested-setting">
                      <label>
                        <input
                          type="checkbox"
                          checked={recordInbound}
                          onChange={(e) => void persist({ recordInbound: e.target.checked })}
                        />{' '}
                        <span>
                          <strong>Record inbound calls</strong>
                          <small>
                            Record all incoming calls for this account, except for numbers on the
                            exemption list.
                          </small>
                          <button
                            type="button"
                            className="btn-crm btn-crm--secondary btn-crm--sm"
                            onClick={() => soon('Edit inbound exemptions coming soon')}
                          >
                            Edit inbound exemptions
                          </button>
                        </span>
                      </label>
                      <label>
                        <input
                          type="checkbox"
                          checked={recordOutbound}
                          onChange={(e) => void persist({ recordOutbound: e.target.checked })}
                        />{' '}
                        <span>
                          <strong>Record outbound calls</strong>
                          <small>
                            Record all outbound calls for this account, except for numbers on the
                            exemption list.
                          </small>
                          <button
                            type="button"
                            className="btn-crm btn-crm--secondary btn-crm--sm"
                            onClick={() => soon('Edit outbound exemptions coming soon')}
                          >
                            Edit outbound exemptions
                          </button>
                        </span>
                      </label>
                    </div>
                  ) : null}
                </div>
              </div>
              <div className="call-setup-setting-row">
                <HsSwitch
                  checked={transcription}
                  onChange={(v) => void persist({ transcription: v })}
                  name="transcription"
                />
                <div>
                  <h3>Transcription and analysis</h3>
                  <p>
                    Turn on this setting to record, transcribe, and run analysis on your calls
                    (including video calls and calls from third party integrations like Zoom).
                  </p>
                  {transcription ? (
                    <div className="call-setup-usage-div">
                      <div className="call-setup-usage-line">
                        <span>Usage this month</span>
                        <strong>Hours (0 out of 1,500 used)</strong>
                      </div>
                      <div className="call-setup-progress">
                        <span style={{ width: '0%' }} />
                      </div>
                      <h3>Tracked Terms</h3>
                      <p>
                        Report on the tracked term mentions across all transcribed calls in your
                        account.
                      </p>
                      <button
                        type="button"
                        className="crm-mt-2 btn-crm btn-crm--secondary btn-crm--sm"
                        onClick={() => soon('Edit tracked terms coming soon')}
                      >
                        Edit tracked terms
                      </button>
                    </div>
                  ) : null}
                </div>
              </div>
            </section>

            <section className="call-setup-config-section">
              <h2>Automatic associations</h2>
              <div className="call-setup-setting-row">
                <HsSwitch checked={autoAssoc} onChange={(v) => void persist({ autoAssoc: v })} name="autoAssoc" />
                <div>
                  <h3>Automatically link calls to associated objects using CRM AI</h3>
                  <p>
                    Learn more about{' '}
                    <a
                      href="#"
                      className="link"
                      onClick={(e) => {
                        e.preventDefault();
                        soon('Automatic associations help coming soon');
                      }}
                    >
                      automatic associations <Ext />
                    </a>
                    .
                  </p>
                </div>
              </div>
            </section>
          </section>
        )}

      {/* Turn off calling modal */}
      {turnOffOpen ? (
        <div className="call-modal-backdrop" onClick={() => setTurnOffOpen(false)}>
          <div
            className="call-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="turnOffCallingTitle"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="call-modal__title" id="turnOffCallingTitle">
              Turn off CRM calling for all users?
            </h2>
            <p>
              Users will no longer be able to place or receive calls with CRM calling. Existing call
              recordings and logs will not be deleted.
            </p>
            <p>
              Type <strong>turn off</strong> to confirm.
            </p>
            <input
              type="text"
              className="call-modal__input"
              placeholder="turn off"
              autoComplete="off"
              spellCheck={false}
              value={turnOffText}
              onChange={(e) => setTurnOffText(e.target.value)}
            />
            <div className="call-modal__actions">
              <button
                type="button"
                className="call-modal__btn-turnoff"
                disabled={turnOffText.trim().toLowerCase() !== 'turn off'}
                onClick={() => {
                  setTurnOffOpen(false);
                  void persist({ placeCalls: false }, 'CRM calling turned off');
                }}
              >
                Turn off
              </button>
              <button
                type="button"
                className="call-modal__btn-cancel"
                onClick={() => setTurnOffOpen(false)}
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      ) : null}

      {/* Call types drawer */}
      {typesDrawer ? (
        <>
          <div className="call-types-drawer-backdrop" onClick={() => setTypesDrawer(false)} />
          <aside className="call-types-drawer" role="dialog" aria-modal="true" aria-labelledby="callTypesDrawerTitle">
            <header className="call-types-drawer__head">
              <h2 id="callTypesDrawerTitle">Edit call and meeting types</h2>
              <button
                type="button"
                className="call-types-drawer__close"
                aria-label="Close"
                onClick={() => setTypesDrawer(false)}
              >
                ×
              </button>
            </header>
            <div className="call-types-list">
              {typesDraft.map((t, i) => (
                <div className="call-types-row" key={`${t}-${i}`}>
                  <input
                    className="input"
                    value={t}
                    onChange={(e) => {
                      const next = [...typesDraft];
                      next[i] = e.target.value;
                      setTypesDraft(next);
                    }}
                  />
                  <button
                    type="button"
                    aria-label="Remove type"
                    onClick={() => setTypesDraft(typesDraft.filter((_, idx) => idx !== i))}
                  >
                    ×
                  </button>
                </div>
              ))}
              <button
                type="button"
                className="call-types-add-btn"
                onClick={() => setTypesDraft([...typesDraft, ''])}
              >
                + Add type
              </button>
            </div>
            <footer className="call-types-drawer__foot">
              <button
                type="button"
                className="call-drawer-pill-btn call-drawer-pill-btn--save"
                onClick={() => {
                  setTypesDrawer(false);
                  void persist(
                    { callTypes: typesDraft.map((t) => t.trim()).filter(Boolean) },
                    'Call types updated',
                  );
                }}
              >
                Save
              </button>
              <button
                type="button"
                className="call-drawer-pill-btn"
                onClick={() => setTypesDrawer(false)}
              >
                Cancel
              </button>
            </footer>
          </aside>
        </>
      ) : null}

      {/* Outcomes drawer (CGL2) */}
      {outcomesDrawer ? (
        <CallOutcomesDrawer canEdit={canEditPropertySettings(me)} onClose={closeOutcomes} />
      ) : null}
    </div>
  );
}
