'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { listMembers, listTeams, type Member, type Team } from '@/features/members/api.client';
import { getMeetingSettings, updateMeetingSettings } from '../../workspace-settings.client';
import {
  SetTabs,
  SettingsForm,
  SettingsFormsProvider,
  TabPanel,
  useHashTab,
  type SettingsSaveHandler,
} from '../settings-ui';
import {
  EXCLUSION_SUGGESTIONS,
  LANGUAGES,
  REMINDER_UNITS,
  VOICES,
  defaultMeetingsDraft,
  uid,
  type MeetingsDraft,
  type Reminder,
  type Rotation,
  type RotationLogic,
  type RotationUser,
} from './data';
import { GripIcon, MtgDrawer, TrashIcon } from './MtgDrawer';

const TABS = [
  { id: 'configurations', label: 'Meeting Configurations' },
  { id: 'rotations', label: 'Meeting Rotations' },
  { id: 'notetaker-bot', label: "CRM's Notetaker Bot" },
];

const USERS_PAGE_SIZE = 7;

type Drawer = 'outcomes' | 'types' | 'never-log' | 'exclusions' | 'rotation' | 'users' | null;

function Switch({
  id,
  checked,
  onChange,
  name,
}: {
  id: string;
  checked: boolean;
  name: string;
  onChange: (v: boolean) => void;
}) {
  return (
    <label className="switch" htmlFor={id}>
      <input
        id={id}
        name={name}
        type="checkbox"
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span className="switch__track" />
    </label>
  );
}

function OptionListEditor({
  values,
  onChange,
  ariaLabel,
  confirmDelete,
}: {
  values: string[];
  onChange: (next: string[]) => void;
  ariaLabel: string;
  confirmDelete?: boolean;
}) {
  const [pendingDelete, setPendingDelete] = useState<number | null>(null);

  return (
    <>
      <div className="mtg-option-list">
        {values.map((value, index) => (
          <div className="mtg-option-row" key={`${index}-${value.slice(0, 12)}`}>
            <span className="mtg-option-grip" aria-hidden>
              <GripIcon />
            </span>
            <input
              className="input"
              aria-label={ariaLabel}
              value={value}
              onChange={(e) => {
                const next = [...values];
                next[index] = e.target.value;
                onChange(next);
              }}
            />
            <button
              type="button"
              className="mtg-option-remove"
              aria-label={`Delete ${ariaLabel.toLowerCase()}`}
              title="Delete"
              onClick={() => {
                if (confirmDelete) setPendingDelete(index);
                else onChange(values.filter((_, i) => i !== index));
              }}
            >
              <TrashIcon />
            </button>
          </div>
        ))}
      </div>
      <button
        type="button"
        className="mtg-inline-add"
        onClick={() => {
          if (values.some((v) => !v.trim())) return;
          onChange([...values, '']);
        }}
      >
        <CrmIcon name="plus" className="iconSize-14" /> Add{' '}
        {ariaLabel.toLowerCase().includes('type') ? 'type' : 'outcome'}
      </button>
      {pendingDelete !== null ? (
        <div className="mtg-delete-confirm" style={{ position: 'relative', marginTop: 12 }}>
          <strong>Delete this meeting outcome?</strong>
          <p>
            Deleting a meeting outcome will remove it permanently and may affect its usage in
            workflows, lists and reports. This can&apos;t be undone.
          </p>
          <div>
            <button
              type="button"
              className="mtg-delete-confirm__delete"
              onClick={() => {
                onChange(values.filter((_, i) => i !== pendingDelete));
                setPendingDelete(null);
              }}
            >
              Delete
            </button>
            <button
              type="button"
              className="mtg-delete-confirm__cancel"
              onClick={() => setPendingDelete(null)}
            >
              Cancel
            </button>
          </div>
        </div>
      ) : null}
    </>
  );
}

function ExclusionTable({
  entries,
  onRemove,
  search,
  empty,
}: {
  entries: string[];
  onRemove: (value: string) => void;
  search: string;
  empty: React.ReactNode;
}) {
  const filtered = entries.filter((v) => v.toLowerCase().includes(search.trim().toLowerCase()));
  if (!filtered.length) return <>{empty}</>;
  return (
    <>
      {filtered.map((value) => (
        <div className="mtg-exclusion-row" key={value}>
          <span className="mtg-exclusion-row__value">{value}</span>
          <span className="mtg-exclusion-row__scope">All users</span>
          <button type="button" aria-label={`Remove ${value}`} onClick={() => onRemove(value)}>
            <TrashIcon />
          </button>
        </div>
      ))}
    </>
  );
}

/** Why a rotation can't be deleted: the scheduling pages booking through it (BUG-04). */
function usedByText(pages: Rotation['usedBy']): string | undefined {
  if (!pages?.length) return undefined;
  const names = pages.map((p) => `“${p.title}”`).join(', ');
  return pages.length === 1
    ? `Used by 1 scheduling page: ${names}. Choose other hosts on it to delete this rotation.`
    : `Used by ${pages.length} scheduling pages: ${names}. Choose other hosts on them to delete this rotation.`;
}

export function MeetingsSettingsView() {
  const businessName = useCurrentUser().business.name;
  const toast = useToast();
  const [active, selectTab] = useHashTab(TABS, 'configurations');
  const [baseline, setBaseline] = useState<MeetingsDraft>(() => defaultMeetingsDraft());
  const [draft, setDraft] = useState<MeetingsDraft>(() => defaultMeetingsDraft());
  // Saves wait until the account's saved configuration has loaded, so defaults never overwrite it.
  const [loaded, setLoaded] = useState(false);
  const [drawer, setDrawer] = useState<Drawer>(null);
  const [tipDismissed, setTipDismissed] = useState(false);

  // Drawer drafts
  const [optionDraft, setOptionDraft] = useState<string[]>([]);
  const [neverDraft, setNeverDraft] = useState<string[]>([]);
  const [neverEntry, setNeverEntry] = useState('');
  const [neverSearch, setNeverSearch] = useState('');
  const [exclDraft, setExclDraft] = useState<string[]>([]);
  const [exclEntry, setExclEntry] = useState('');
  const [exclSearch, setExclSearch] = useState('');
  const [exclSuggestionsOpen, setExclSuggestionsOpen] = useState(false);

  // Rotation form
  const [editingRotationId, setEditingRotationId] = useState<string | null>(null);
  const [rotationName, setRotationName] = useState('');
  const [rotationMembers, setRotationMembers] = useState<string[]>([]);
  const [rotationLogic, setRotationLogic] = useState<RotationLogic>('even');
  const [rotationWeights, setRotationWeights] = useState<Record<string, number>>({});
  const [memberMenuOpen, setMemberMenuOpen] = useState(false);
  const [memberSearch, setMemberSearch] = useState('');
  const [rotationErrors, setRotationErrors] = useState<{
    name?: boolean;
    members?: boolean;
    weight?: boolean;
  }>({});
  const [accountTeams, setAccountTeams] = useState<Team[]>([]);
  const [accountUsers, setAccountUsers] = useState<Member[]>([]);

  // Users drawer
  const [userSearch, setUserSearch] = useState('');
  const [userFilter, setUserFilter] = useState<'user' | 'team' | 'access'>('user');
  const [userPage, setUserPage] = useState(1);

  const patch = useCallback((partial: Partial<MeetingsDraft>) => {
    setDraft((prev) => ({ ...prev, ...partial }));
  }, []);

  // `input`, not `change`: React's onChange ignores a change event fired on the form itself, so
  // drawer saves (rotations, outcomes, types) never showed the save bar.
  const bumpDirty = () => {
    document
      .querySelector<HTMLFormElement>('#meetings-settings-form')
      ?.dispatchEvent(new Event('input', { bubbles: true }));
  };

  const openOutcomes = () => {
    setOptionDraft([...draft.outcomes]);
    setDrawer('outcomes');
  };
  const openTypes = () => {
    setOptionDraft([...draft.types]);
    setDrawer('types');
  };
  const openNeverLog = () => {
    setNeverDraft([...draft.neverLog]);
    setNeverEntry('');
    setNeverSearch('');
    setDrawer('never-log');
  };
  const openExclusions = () => {
    setExclDraft([...draft.exclusions]);
    setExclEntry('');
    setExclSearch('');
    setExclSuggestionsOpen(false);
    setDrawer('exclusions');
  };
  const openRotation = (existing?: Rotation) => {
    if (existing) {
      setEditingRotationId(existing.id);
      setRotationName(existing.name);
      setRotationMembers([...existing.members]);
      setRotationLogic(existing.logic);
      setRotationWeights({ ...existing.weights });
    } else {
      setEditingRotationId(null);
      setRotationName('');
      setRotationMembers([]);
      setRotationLogic('even');
      setRotationWeights({});
    }
    setMemberMenuOpen(false);
    setMemberSearch('');
    setRotationErrors({});
    setDrawer('rotation');
  };

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

  const save: SettingsSaveHandler = async () => {
    if (!loaded) {
      toast('Meeting settings are still loading', 'info');
      return false;
    }
    const clean = (list: string[]) => list.map((s) => s.trim()).filter(Boolean);
    try {
      const saved = await updateMeetingSettings({
        ...draft,
        outcomes: clean(draft.outcomes),
        types: clean(draft.types),
        neverLog: clean(draft.neverLog),
        exclusions: clean(draft.exclusions),
      });
      setBaseline(saved);
      setDraft(saved);
      toast('Meeting settings saved', 'success');
    } catch (error) {
      toast(errorText(error), 'danger');
      return false;
    }
  };

  const filteredUsers = useMemo(() => {
    const q = userSearch.trim().toLowerCase();
    return accountUsers
      .map((user) => {
        const team = user.defaultTeam?.name ?? user.extraTeams[0]?.name ?? '—';
        return [user.name, team, ''] as [string, string, string];
      })
      .filter(([name, team, issue]) => {
        const matches = !q || `${name} ${team}`.toLowerCase().includes(q);
        const accessOk = userFilter !== 'access' || issue.length > 0;
        const teamOk = userFilter !== 'team' || team !== '—';
        return matches && accessOk && teamOk;
      });
  }, [accountUsers, userSearch, userFilter]);
  const userPages = Math.max(1, Math.ceil(filteredUsers.length / USERS_PAGE_SIZE));
  const userSlice = filteredUsers.slice(
    (userPage - 1) * USERS_PAGE_SIZE,
    userPage * USERS_PAGE_SIZE,
  );

  const weightTotal = rotationMembers.reduce((sum, m) => sum + (rotationWeights[m] ?? 0), 0);

  const saveRotation = () => {
    const errors: typeof rotationErrors = {};
    if (!rotationName.trim()) errors.name = true;
    if (!rotationMembers.length) errors.members = true;
    if (rotationLogic === 'weighted' && weightTotal !== 100) errors.weight = true;
    setRotationErrors(errors);
    if (Object.keys(errors).length) return;

    const editing = draft.rotations.find((r) => r.id === editingRotationId);
    const next: Rotation = {
      id: editingRotationId ?? uid('rot'),
      name: rotationName.trim(),
      members: rotationMembers,
      logic: rotationLogic,
      weights: rotationLogic === 'weighted' ? { ...rotationWeights } : {},
      users: rotationMembers.map(userOf),
      dropped: editing?.dropped ?? [],
    };
    patch({
      rotations: editingRotationId
        ? draft.rotations.map((r) => (r.id === editingRotationId ? next : r))
        : [...draft.rotations, next],
    });
    setDrawer(null);
    window.setTimeout(bumpDirty, 0);
  };

  useEffect(() => {
    let alive = true;
    Promise.all([listTeams(), listMembers({ limit: 200 })]).then(
      ([teams, members]) => {
        if (!alive) return;
        setAccountTeams(teams.data);
        setAccountUsers(members.data.filter((member) => member.status === 'active'));
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, []);

  const memberQuery = memberSearch.trim().toLowerCase();
  const teamNameOf = (user: Member) =>
    user.defaultTeam?.name ?? user.extraTeams[0]?.name ?? 'No team';
  const filteredTeams = accountTeams.filter(
    (team) => !memberQuery || team.name.toLowerCase().includes(memberQuery),
  );
  const rotationUsers = accountUsers.filter((user) => {
    if (!memberQuery) return true;
    return (
      user.name.toLowerCase().includes(memberQuery) ||
      user.email.toLowerCase().includes(memberQuery) ||
      teamNameOf(user).toLowerCase().includes(memberQuery)
    );
  });
  // Rotation members are user ids; the deactivated ones the API still lists keep their name.
  const userOf = (id: string): RotationUser => {
    const account = accountUsers.find((user) => user.userId === id);
    if (account) return { id, name: account.name, active: true };
    const known = draft.rotations.flatMap((r) => r.users).find((user) => user.id === id);
    return known ?? { id, name: 'Unknown user', active: false };
  };
  const nameOf = (id: string) => userOf(id).name;
  // Selected members who aren't active users any more, so they can still be unticked.
  const inactiveMembers = rotationMembers
    .filter((id) => !accountUsers.some((user) => user.userId === id))
    .map(userOf);
  const toggleMember = (id: string, checked: boolean) => {
    setRotationMembers((prev) => (checked ? prev.filter((m) => m !== id) : [...prev, id]));
    setRotationErrors((prev) => ({ ...prev, members: false }));
    setRotationWeights((prev) => {
      if (checked) {
        const next = { ...prev };
        delete next[id];
        return next;
      }
      return { ...prev, [id]: prev[id] ?? 0 };
    });
  };
  const toggleTeam = (team: Team) => {
    const ids = accountUsers
      .filter((user) => team.memberIds.includes(user.userId))
      .map((user) => user.userId);
    if (!ids.length) return;
    const allIn = ids.every((id) => rotationMembers.includes(id));
    setRotationMembers((prev) =>
      allIn ? prev.filter((id) => !ids.includes(id)) : [...new Set([...prev, ...ids])],
    );
    setRotationErrors((prev) => ({ ...prev, members: false }));
  };

  return (
    <SettingsFormsProvider>
      <SettingsForm
        id="meetings-settings-form"
        onSave={save}
        onReset={() =>
          setDraft({ ...baseline, reminders: baseline.reminders.map((r) => ({ ...r })) })
        }
      >
        <main className="mtg-page" id="meetings-settings">
          <header className="set-head">
            <div>
              <h1 className="set-head__title">Meetings</h1>
            </div>
          </header>

          <SetTabs
            label="Meeting settings"
            tabs={TABS}
            active={active}
            onSelect={selectTab}
            boxed
          />

          <TabPanel id="configurations" active={active}>
            <p className="set-intro">
              These settings will apply to everyone using CRM Meetings in your account. To manage
              your own meeting settings, go to{' '}
              <Link className="link" href="/settings/profile#tab-calendar">
                User Meeting Settings
              </Link>
              .
            </p>

            <div className="mtg-config-block">
              <div className="mtg-setting-row">
                <Switch
                  id="mtg-track-outcomes"
                  name="trackOutcomes"
                  checked={draft.trackOutcomes}
                  onChange={(v) => patch({ trackOutcomes: v })}
                />
                <div className="mtg-setting-copy">
                  <div className="mtg-setting-heading">
                    <strong>Track meeting outcomes</strong>
                    <button type="button" className="link mtg-text-action" onClick={openOutcomes}>
                      Edit options
                    </button>
                  </div>
                  <p>
                    Organize how your team logs activities by providing custom meeting outcomes.
                    Report on this to track meeting outcomes.
                  </p>
                </div>
              </div>

              <div className="mtg-setting-row">
                <Switch
                  id="mtg-track-types"
                  name="trackTypes"
                  checked={draft.trackTypes}
                  onChange={(v) => patch({ trackTypes: v })}
                />
                <div className="mtg-setting-copy">
                  <div className="mtg-setting-heading">
                    <strong>Track call and meeting types</strong>
                    <button type="button" className="link mtg-text-action" onClick={openTypes}>
                      Edit options
                    </button>
                  </div>
                  <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="mtg-setting-row mtg-setting-row--reminders">
                <Switch
                  id="mtg-reminders"
                  name="reminders"
                  checked={draft.remindersOn}
                  onChange={(v) => patch({ remindersOn: v })}
                />
                <div className="mtg-setting-copy">
                  <strong>Turn on meeting reminders by default</strong>
                  <p>
                    Set up email reminders to send to attendees before a meeting starts. Reminder
                    times can be edited prior to booking.
                  </p>
                </div>
              </div>

              {draft.remindersOn ? (
                <div className="mtg-reminders" id="mtg-reminder-settings">
                  <label className="mtg-field-label">Scheduled reminder email</label>
                  <div className="mtg-reminder-list">
                    {draft.reminders.map((rem) => (
                      <div className="mtg-reminder-item" key={rem.id}>
                        <input
                          className="mtg-number-input"
                          type="number"
                          min={1}
                          max={30}
                          value={rem.amount}
                          aria-label="Reminder amount"
                          onChange={(e) => {
                            const amount = Math.min(30, Math.max(1, Number(e.target.value) || 1));
                            patch({
                              reminders: draft.reminders.map((r) =>
                                r.id === rem.id ? { ...r, amount } : r,
                              ),
                            });
                          }}
                        />
                        <select
                          name="reminder_unit[]"
                          aria-label="Reminder timing"
                          value={rem.unit}
                          onChange={(e) => {
                            patch({
                              reminders: draft.reminders.map((r) =>
                                r.id === rem.id
                                  ? { ...r, unit: e.target.value as Reminder['unit'] }
                                  : r,
                              ),
                            });
                          }}
                        >
                          {REMINDER_UNITS.map((u) => (
                            <option key={u} value={u}>
                              {u}
                            </option>
                          ))}
                        </select>
                        <button
                          type="button"
                          className="mtg-icon-button"
                          aria-label="Remove reminder"
                          title="Remove reminder"
                          onClick={() =>
                            patch({ reminders: draft.reminders.filter((r) => r.id !== rem.id) })
                          }
                        >
                          <TrashIcon />
                        </button>
                      </div>
                    ))}
                  </div>
                  <button
                    type="button"
                    className="mtg-inline-add"
                    onClick={() =>
                      patch({
                        reminders: [
                          ...draft.reminders,
                          { id: uid('rem'), amount: 1, unit: 'hour before' },
                        ],
                      })
                    }
                  >
                    <CrmIcon name="plus" className="iconSize-14" /> Add reminder
                  </button>
                </div>
              ) : null}
            </div>

            <div className="mtg-section-divider" />

            <section className="mtg-never-log">
              <div className="mtg-section-title-row">
                <h2>Never Log</h2>
                <span className="mtg-new-pill">New</span>
              </div>
              <p>
                Specify domains and email addresses for all users to never log meetings and emails
                automatically to your CRM. Manage your personal never log list in{' '}
                <Link className="link" href="/settings/profile#tab-email">
                  email preferences
                </Link>
                .{' '}
                <a className="link" href="#mtg-never-log-help" onClick={(e) => e.preventDefault()}>
                  Learn more
                </a>
              </p>
              <button
                type="button"
                className="btn-crm btn-crm--outline mtg-manage-never"
                onClick={openNeverLog}
              >
                Manage never log for all users <CrmIcon name="external" className="iconSize-14" />
              </button>
            </section>
          </TabPanel>

          <TabPanel id="rotations" active={active}>
            <p className="set-intro">
              These settings will apply to everyone using CRM Meetings in your account. To manage
              your own meeting settings, go to{' '}
              <Link className="link" href="/settings/profile#tab-calendar">
                User Meeting Settings
              </Link>
              .
            </p>
            <div className="mtg-rotations-heading">
              <h2>Meeting Rotations</h2>
              {draft.rotations.length ? (
                <button
                  type="button"
                  className="btn-crm btn-crm--primary"
                  onClick={() => openRotation()}
                >
                  Create a rotation
                </button>
              ) : null}
            </div>

            {draft.rotations.length ? (
              <div className="mtg-rotation-list">
                <div className="card set-table-card">
                  <div className="mtg-table-wrap">
                    <table className="set-table mtg-rotation-table">
                      <thead>
                        <tr>
                          <th>Rotation name</th>
                          <th>Rotation members</th>
                          <th>Distribution logic</th>
                          <th className="mtg-table-actions">Actions</th>
                        </tr>
                      </thead>
                      <tbody>
                        {draft.rotations.map((rot) => (
                          <tr key={rot.id}>
                            <td>
                              <strong>{rot.name}</strong>
                            </td>
                            <td>
                              <div className="mtg-member-pills">
                                {rot.members.map((m) => (
                                  <span className="mtg-member-pill" key={m}>
                                    {nameOf(m)}
                                    {userOf(m).active ? '' : ' (deactivated)'}
                                  </span>
                                ))}
                              </div>
                              {rot.dropped.length ? (
                                <p className="mtg-help mtg-help--sentence">
                                  Not found, removed when you save:{' '}
                                  {rot.dropped
                                    .map((d) =>
                                      d.reason === 'ambiguous'
                                        ? `${d.entry} (more than one user has this name)`
                                        : d.entry,
                                    )
                                    .join(', ')}
                                </p>
                              ) : null}
                            </td>
                            <td>{rot.logic === 'weighted' ? 'Weighted' : 'Even distribution'}</td>
                            <td>
                              <div className="mtg-row-actions">
                                <button type="button" onClick={() => openRotation(rot)}>
                                  Edit
                                </button>
                                {/* QA round 1 (BUG-04): a rotation pages book through stays. */}
                                <button
                                  type="button"
                                  className={rot.usedBy?.length ? 'is-disabled' : undefined}
                                  aria-disabled={rot.usedBy?.length ? true : undefined}
                                  title={usedByText(rot.usedBy)}
                                  onClick={() => {
                                    const inUse = usedByText(rot.usedBy);
                                    if (inUse) {
                                      toast(inUse, 'danger');
                                      return;
                                    }
                                    patch({
                                      rotations: draft.rotations.filter((r) => r.id !== rot.id),
                                    });
                                    // QA round 2 BUG-13: a delete is a change the save bar must offer.
                                    window.setTimeout(bumpDirty, 0);
                                  }}
                                >
                                  Delete
                                </button>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            ) : (
              <div className="mtg-empty-state" id="mtg-rotation-empty">
                <div className="mtg-empty-state__copy">
                  <h3>Create your first meeting rotation</h3>
                  <p>
                    Schedule meetings for the rep that is “next up” in a rotation using an even
                    distribution round robin right from the CRM.
                  </p>
                  <button
                    type="button"
                    className="btn-crm btn-crm--primary"
                    onClick={() => openRotation()}
                  >
                    Create a rotation
                  </button>
                </div>
                <div className="mtg-empty-state__art" aria-hidden>
                  <svg viewBox="0 0 240 180" role="img">
                    <path
                      d="M24 128 81 32q7-12 20-4l111 72q12 8 4 19l-59 48q-8 7-18 1L24 145q-13-6 0-17Z"
                      fill="#fff0cf"
                    />
                    <path
                      d="m58 104 38-68q5-9 15-3l92 58q7 5 3 13l-37 56q-5 8-14 3l-94-47q-9-5-3-12Z"
                      fill="#fff"
                      stroke="#334b62"
                      strokeWidth="4"
                      strokeLinejoin="round"
                    />
                    <path
                      d="M58 104 94 39l112 67-37 55Z"
                      fill="#e9f1f7"
                      stroke="#334b62"
                      strokeWidth="3"
                    />
                    <path
                      d="m94 39 112 67-5-26-99-59q-8-5-13 4Z"
                      fill="#f58d58"
                      stroke="#334b62"
                      strokeWidth="3"
                    />
                    <path
                      d="M99 24v19m15-20v19m15-9v19m15-9v19m15-9v19m15-9v19"
                      stroke="#e84f3c"
                      strokeWidth="5"
                      strokeLinecap="round"
                    />
                    <path
                      d="m79 108 31-46m-15 57 31-46m-14 58 30-45"
                      stroke="#334b62"
                      strokeWidth="4"
                      strokeLinecap="round"
                    />
                    <rect
                      x="95"
                      y="128"
                      width="48"
                      height="25"
                      rx="4"
                      fill="#fff"
                      stroke="#334b62"
                      strokeWidth="3"
                      transform="rotate(-12 95 128)"
                    />
                    <path
                      d="m108 136 24-5m-21 13 24-5"
                      stroke="#3156d9"
                      strokeWidth="3"
                      strokeLinecap="round"
                    />
                  </svg>
                </div>
              </div>
            )}
          </TabPanel>

          <TabPanel id="notetaker-bot" active={active}>
            {!tipDismissed ? (
              <div className="mtg-pro-tip">
                <strong>Pro tip</strong>
                <span>
                  Start setting up all your notetaking options under{' '}
                  <Link className="link" href="/settings/notetaker">
                    Notetaker
                  </Link>
                  .
                </span>
                <button
                  type="button"
                  className="mtg-pro-tip__close"
                  aria-label="Dismiss tip"
                  onClick={() => setTipDismissed(true)}
                >
                  <CrmIcon name="x" className="iconSize-14" />
                </button>
              </div>
            ) : null}

            <div className="mtg-bot-master">
              <Switch
                id="mtg-bot-enabled"
                name="botEnabled"
                checked={draft.botEnabled}
                onChange={(v) => patch({ botEnabled: v })}
              />
              <strong>CRM&apos;s notetaker bot</strong>
              <span className="mtg-muted-icon" title="Notetaker bot">
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  aria-hidden
                >
                  <rect x="3" y="11" width="18" height="10" rx="2" />
                  <circle cx="12" cy="5" r="2" />
                  <path d="M12 7v4M8 16h.01M16 16h.01" />
                </svg>
              </span>
            </div>
            <p className="mtg-description">
              Turn on this setting to allow CRM&apos;s notetaker bot to attend your Zoom, Google
              Meet, and Microsoft Teams calls. CRM will record, transcribe, and run analysis on your
              call data (including audio, text, and video). Call recording data will be used by CRM
              to provide meeting insights, summaries and other suggested actions.
            </p>
            <p className="mtg-description">
              Any connected app settings (e.g. Zoom) in your CRM account will not apply to your use
              of this feature and you may need to enable permissions for this feature to work.{' '}
              <a className="link" href="#mtg-connected-apps" onClick={(e) => e.preventDefault()}>
                Learn more
              </a>
            </p>
            <p className="mtg-description">
              By enabling this setting, you understand and agree that this feature is supported by
              {businessName}, which will process call data.
            </p>

            {draft.botEnabled ? (
              <div className="mtg-notetaker-settings">
                <section className="mtg-settings-section">
                  <h2>Auto-join settings</h2>
                  <p>
                    Choose whether the notetaker bot joins upcoming meetings automatically for users
                    who have access.
                  </p>
                  <label className="mtg-check-line check">
                    <input
                      type="checkbox"
                      name="bot_auto_join"
                      checked={draft.botAutoJoin}
                      onChange={(e) => patch({ botAutoJoin: e.target.checked })}
                    />
                    <span className="check__box" aria-hidden />
                    <span>
                      <strong>Notetaker bot auto-join</strong>
                      <small>
                        Invite the notetaker bot to join all upcoming meetings automatically. Your
                        users can override this for themselves under their own{' '}
                        <Link className="link" href="/settings/profile#tab-calendar">
                          User Meeting Settings
                        </Link>
                        .
                      </small>
                    </span>
                  </label>
                  <div className="mtg-exclusion-inline">
                    <strong>Domain and email exclusions</strong>
                    <p>
                      Add specific email addresses or domains that the notetaker bot should never
                      auto-join. The notetaker bot will be turned off by default for meetings with
                      these emails or domains.
                    </p>
                    <button
                      type="button"
                      className="btn-crm btn-crm--outline btn-crm--sm"
                      onClick={openExclusions}
                    >
                      <CrmIcon name="plus" className="iconSize-14" /> Domain or email
                    </button>
                    {draft.exclusions.length ? (
                      <p className="mtg-help" style={{ marginTop: 8 }}>
                        {draft.exclusions.length} exclusion
                        {draft.exclusions.length === 1 ? '' : 's'} saved
                      </p>
                    ) : null}
                  </div>
                </section>

                <section className="mtg-settings-section">
                  <h2>Notetaker bot access</h2>
                  <p>
                    Choose which users should receive access to the notetaker bot. Users with a paid
                    sales or service seat and a connected calendar are eligible to have the
                    notetaker bot join any upcoming meeting that includes at least one external
                    contact.
                  </p>
                  <strong className="mtg-small-heading">Choose notetaker bot access method</strong>
                  <label className="mtg-radio-line">
                    <input
                      type="radio"
                      name="bot_access"
                      value="automatic"
                      checked={draft.botAccess === 'automatic'}
                      onChange={() => patch({ botAccess: 'automatic' })}
                    />
                    <span>
                      Automatically grant eligible users notetaker bot access
                      <small>
                        <b>
                          {accountUsers.length}{' '}
                          {accountUsers.length === 1 ? 'user has' : 'users have'} access
                        </b>{' '}
                        <button
                          type="button"
                          className="link"
                          onClick={() => {
                            setUserSearch('');
                            setUserFilter('user');
                            setUserPage(1);
                            setDrawer('users');
                          }}
                        >
                          View users
                        </button>
                      </small>
                    </span>
                  </label>
                  <label className="mtg-radio-line">
                    <input
                      type="radio"
                      name="bot_access"
                      value="manual"
                      checked={draft.botAccess === 'manual'}
                      onChange={() => patch({ botAccess: 'manual' })}
                    />
                    <span>
                      Manually grant users with sales or service seats notetaker bot access
                    </span>
                  </label>
                </section>

                <section className="mtg-settings-section">
                  <h2>Preferences</h2>
                  <p>
                    Customize how the notetaker bot appears and behaves in meetings across your
                    account.
                  </p>

                  <div className="mtg-preference-group">
                    <strong>Notetaker bot name</strong>
                    <p>
                      Choose how your notetaker bot appears in meetings. Use the default brand name
                      or set a custom name that aligns with your brand.
                    </p>
                    <label className="mtg-radio-line">
                      <input
                        type="radio"
                        name="bot_name_mode"
                        value="brand"
                        checked={draft.botNameMode === 'brand'}
                        onChange={() => patch({ botNameMode: 'brand' })}
                      />
                      <span>
                        Use brand name
                        <small>Notetaker bot will join as “Your Company Notetaker”.</small>
                      </span>
                    </label>
                    <label className="mtg-radio-line">
                      <input
                        type="radio"
                        name="bot_name_mode"
                        value="custom"
                        checked={draft.botNameMode === 'custom'}
                        onChange={() => patch({ botNameMode: 'custom' })}
                      />
                      <span>Custom notetaker bot name</span>
                    </label>
                    {draft.botNameMode === 'custom' ? (
                      <div className="mtg-custom-name">
                        <label className="mtg-field-label" htmlFor="mtg-bot-name">
                          Custom bot name
                        </label>
                        <input
                          className="input"
                          id="mtg-bot-name"
                          name="bot_name"
                          placeholder="Enter a bot name"
                          maxLength={60}
                          value={draft.botName}
                          onChange={(e) => patch({ botName: e.target.value })}
                        />
                      </div>
                    ) : null}
                  </div>

                  <div className="mtg-preference-group">
                    <strong>Announcement</strong>
                    <p>
                      Select the notetaker bot&apos;s announcement method when joining a meeting.
                    </p>
                    <label className="mtg-radio-line">
                      <input
                        type="radio"
                        name="announcement"
                        value="verbal"
                        checked={draft.announcement === 'verbal'}
                        onChange={() => patch({ announcement: 'verbal' })}
                      />
                      <span>
                        Verbal and chat announcement
                        <small>
                          The notetaker bot will introduce itself out loud and send a message in the
                          meeting chat.
                        </small>
                      </span>
                    </label>
                    {draft.announcement === 'verbal' ? (
                      <div className="mtg-voice-controls">
                        <div className="field">
                          <label className="mtg-field-label" htmlFor="mtg-language">
                            Language
                          </label>
                          <select
                            className="input"
                            id="mtg-language"
                            name="language"
                            value={draft.language}
                            onChange={(e) => patch({ language: e.target.value })}
                          >
                            {LANGUAGES.map((l) => (
                              <option key={l}>{l}</option>
                            ))}
                          </select>
                        </div>
                        <div className="field">
                          <label className="mtg-field-label" htmlFor="mtg-voice">
                            Voice
                          </label>
                          <select
                            className="input"
                            id="mtg-voice"
                            name="voice"
                            value={draft.voice}
                            onChange={(e) => patch({ voice: e.target.value })}
                          >
                            {VOICES.map((v) => (
                              <option key={v}>{v}</option>
                            ))}
                          </select>
                        </div>
                        <button
                          type="button"
                          className="mtg-play-voice"
                          aria-label="Play voice sample"
                          onClick={() => toast('Voice sample coming soon', 'info')}
                        >
                          <svg
                            width="14"
                            height="14"
                            viewBox="0 0 24 24"
                            fill="currentColor"
                            aria-hidden
                          >
                            <path d="M8 5v14l11-7z" />
                          </svg>
                        </button>
                      </div>
                    ) : null}
                    <label className="mtg-radio-line">
                      <input
                        type="radio"
                        name="announcement"
                        value="chat"
                        checked={draft.announcement === 'chat'}
                        onChange={() => patch({ announcement: 'chat' })}
                      />
                      <span>
                        Chat message announcement only
                        <small>
                          The notetaker bot will introduce itself with a message in the meeting chat
                          only (no spoken announcement).
                        </small>
                      </span>
                    </label>
                  </div>

                  <div className="mtg-preference-group">
                    <strong>Notetaker bot join time</strong>
                    <p>
                      Choose how early the notetaker bot joins meetings (up to 5 minutes before
                      start time).
                    </p>
                    <label className="mtg-field-label" htmlFor="mtg-join-time">
                      Join before meeting start
                    </label>
                    <select
                      className="input mtg-join-select"
                      id="mtg-join-time"
                      name="join_time"
                      value={draft.joinTime}
                      onChange={(e) => patch({ joinTime: e.target.value })}
                    >
                      <option value="0">0 minutes (at start time)</option>
                      <option value="1">1 minute before</option>
                      <option value="2">2 minutes before</option>
                      <option value="3">3 minutes before</option>
                      <option value="4">4 minutes before</option>
                      <option value="5">5 minutes before</option>
                    </select>
                  </div>

                  <div className="mtg-preference-group mtg-consent-group">
                    <strong>Explicit consent</strong>
                    <p>
                      Choose to turn on notetaker bot only when meeting participants have already
                      given their explicit consent to recording and transcription. This setting is
                      intended for jurisdictions that require explicit participant consent. Consent
                      will be requested by email before the meeting. If any participant does not
                      consent or does not respond to the email, the meeting will not be recorded.
                      Add to Live Meeting isn&apos;t available when this setting is enabled.{' '}
                      <a
                        className="link"
                        href="#mtg-consent-help"
                        onClick={(e) => e.preventDefault()}
                      >
                        Learn more
                      </a>
                    </p>
                    <label className="mtg-check-line check">
                      <input
                        type="checkbox"
                        name="explicit_consent"
                        checked={draft.explicitConsent}
                        onChange={(e) => patch({ explicitConsent: e.target.checked })}
                      />
                      <span className="check__box" aria-hidden />
                      <span>
                        <strong>Require explicit consent</strong>
                      </span>
                    </label>
                  </div>
                </section>
              </div>
            ) : null}
          </TabPanel>
        </main>
      </SettingsForm>

      {/* Outcomes drawer */}
      <MtgDrawer
        open={drawer === 'outcomes'}
        onClose={() => setDrawer(null)}
        title="Edit meeting outcomes"
        titleId="mtg-outcomes-title"
        foot={
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!optionDraft.some((v) => v.trim()) || optionDraft.some((v) => !v.trim())}
              onClick={() => {
                const cleaned = optionDraft.map((v) => v.trim()).filter(Boolean);
                if (!cleaned.length) return;
                patch({ outcomes: cleaned });
                setDrawer(null);
                window.setTimeout(bumpDirty, 0);
              }}
            >
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDrawer(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <OptionListEditor
          values={optionDraft}
          onChange={setOptionDraft}
          ariaLabel="Meeting outcome"
          confirmDelete
        />
      </MtgDrawer>

      {/* Types drawer */}
      <MtgDrawer
        open={drawer === 'types'}
        onClose={() => setDrawer(null)}
        title="Edit call and meeting types"
        titleId="mtg-types-title"
        foot={
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!optionDraft.some((v) => v.trim()) || optionDraft.some((v) => !v.trim())}
              onClick={() => {
                const cleaned = optionDraft.map((v) => v.trim()).filter(Boolean);
                if (!cleaned.length) return;
                patch({ types: cleaned });
                setDrawer(null);
                window.setTimeout(bumpDirty, 0);
              }}
            >
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDrawer(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <OptionListEditor values={optionDraft} onChange={setOptionDraft} ariaLabel="Meeting type" />
      </MtgDrawer>

      {/* Never log drawer */}
      <MtgDrawer
        open={drawer === 'never-log'}
        onClose={() => setDrawer(null)}
        title="Never log for all users"
        titleId="mtg-never-log-title"
        foot={
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => {
                patch({ neverLog: neverDraft });
                setDrawer(null);
                window.setTimeout(bumpDirty, 0);
              }}
            >
              Save selections
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDrawer(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <p className="mtg-help">
          Emails and meetings with these domains or addresses are never logged automatically to your
          CRM.
        </p>
        <label className="mtg-field-label" htmlFor="mtg-never-log-entry">
          Add a domain or email address
        </label>
        <div className="mtg-exclusion-entry">
          <input
            className="input"
            id="mtg-never-log-entry"
            placeholder="e.g. competitor.com or ceo@client.com"
            value={neverEntry}
            onChange={(e) => setNeverEntry(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                const value = neverEntry.trim().toLowerCase();
                if (!value) return;
                if (!neverDraft.some((item) => item.toLowerCase() === value)) {
                  setNeverDraft([...neverDraft, value]);
                }
                setNeverEntry('');
              }
            }}
            onInput={(e) => e.stopPropagation()}
          />
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => {
              const value = neverEntry.trim().toLowerCase();
              if (!value) return;
              if (!neverDraft.some((item) => item.toLowerCase() === value)) {
                setNeverDraft([...neverDraft, value]);
              }
              setNeverEntry('');
            }}
          >
            Add
          </button>
        </div>
        <div className="mtg-exclusion-search">
          <input
            className="input"
            type="search"
            placeholder="Search emails or domains"
            aria-label="Search Never Log list"
            value={neverSearch}
            onChange={(e) => setNeverSearch(e.target.value)}
            onInput={(e) => e.stopPropagation()}
          />
          <CrmIcon name="search" className="iconSize-14" />
        </div>
        <div className="mtg-exclusion-table">
          <div className="mtg-exclusion-table__head">
            <span>Domains and Email Addresses</span>
            <span>Blocked for</span>
            <span />
          </div>
          <ExclusionTable
            entries={neverDraft}
            search={neverSearch}
            onRemove={(value) => setNeverDraft(neverDraft.filter((item) => item !== value))}
            empty={<p className="mtg-empty-mini">No domains or email addresses found.</p>}
          />
        </div>
      </MtgDrawer>

      {/* Exclusions drawer */}
      <MtgDrawer
        open={drawer === 'exclusions'}
        onClose={() => setDrawer(null)}
        title="Domain & email auto-join exclusions"
        titleId="mtg-exclusions-title"
        foot={
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => {
                patch({ exclusions: exclDraft });
                setDrawer(null);
                window.setTimeout(bumpDirty, 0);
              }}
            >
              Save selections
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDrawer(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <label className="mtg-field-label" htmlFor="mtg-exclusion-entry">
          Email or domain to exclude
        </label>
        <div className="mtg-exclusion-entry">
          <div className="mtg-exclusion-combo">
            <input
              className="input"
              id="mtg-exclusion-entry"
              placeholder="Enter an email or domain"
              autoComplete="off"
              value={exclEntry}
              onChange={(e) => setExclEntry(e.target.value)}
              onFocus={() => setExclSuggestionsOpen(true)}
              onInput={(e) => e.stopPropagation()}
            />
            <button
              type="button"
              className="mtg-combo-chevron"
              aria-label="Show suggestions"
              onClick={() => setExclSuggestionsOpen((o) => !o)}
            >
              <CrmIcon name="chevron-down" className="iconSize-14" />
            </button>
            {exclSuggestionsOpen ? (
              <div className="mtg-exclusion-suggestions" id="mtg-exclusion-suggestions">
                {EXCLUSION_SUGGESTIONS.filter(
                  (s) =>
                    !exclEntry.trim() || s.toLowerCase().includes(exclEntry.trim().toLowerCase()),
                ).map((s) => (
                  <button
                    key={s}
                    type="button"
                    className="mtg-exclusion-suggestion"
                    onClick={() => {
                      setExclEntry(s);
                      setExclSuggestionsOpen(false);
                    }}
                  >
                    {s}
                  </button>
                ))}
              </div>
            ) : null}
          </div>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => {
              const value = exclEntry.trim().toLowerCase();
              if (!value) return;
              if (!exclDraft.some((item) => item.toLowerCase() === value)) {
                setExclDraft([...exclDraft, value]);
              }
              setExclEntry('');
              setExclSuggestionsOpen(false);
            }}
          >
            Add
          </button>
        </div>
        <div className="mtg-exclusion-search">
          <input
            className="input"
            type="search"
            placeholder="Search"
            aria-label="Search excluded domains and emails"
            value={exclSearch}
            onChange={(e) => setExclSearch(e.target.value)}
            onInput={(e) => e.stopPropagation()}
          />
          <CrmIcon name="search" className="iconSize-14" />
        </div>
        <div className="mtg-exclusion-table">
          <div className="mtg-exclusion-table__head">
            <span>Email Or Domain</span>
            <span>Excluded For</span>
            <span />
          </div>
          {exclDraft.filter((v) => v.toLowerCase().includes(exclSearch.trim().toLowerCase()))
            .length === 0 ? (
            <div className="mtg-empty-mini">
              <p>Any excluded email or domain will appear here.</p>
            </div>
          ) : (
            <ExclusionTable
              entries={exclDraft}
              search={exclSearch}
              onRemove={(value) => setExclDraft(exclDraft.filter((item) => item !== value))}
              empty={null}
            />
          )}
        </div>
      </MtgDrawer>

      {/* Rotation drawer */}
      <MtgDrawer
        open={drawer === 'rotation'}
        onClose={() => setDrawer(null)}
        title={editingRotationId ? 'Edit rotation' : 'Create a rotation'}
        titleId="mtg-rotation-title"
        foot={
          <>
            <button type="button" className="btn-crm btn-crm--primary" onClick={saveRotation}>
              {editingRotationId ? 'Save changes' : 'Save'}
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDrawer(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <div className="field">
          <label className="mtg-field-label" htmlFor="mtg-rotation-name">
            Rotation name <span className="mtg-required">*</span>
          </label>
          <input
            className="input"
            id="mtg-rotation-name"
            placeholder="Enter a rotation name"
            value={rotationName}
            onChange={(e) => {
              setRotationName(e.target.value);
              if (e.target.value.trim()) setRotationErrors((prev) => ({ ...prev, name: false }));
            }}
            onInput={(e) => e.stopPropagation()}
          />
          {rotationErrors.name ? (
            <p className="mtg-field-error is-visible">Enter a rotation name.</p>
          ) : null}
        </div>
        <div className="field crm-mt-3">
          <label className="mtg-field-label" htmlFor="mtg-rotation-members">
            Rotation members{' '}
            <span className="mtg-info" title="Select users who should receive meetings">
              ⓘ
            </span>
          </label>
          <div className="mtg-multi-select">
            <button
              type="button"
              className="mtg-multi-select__trigger"
              aria-expanded={memberMenuOpen}
              onClick={() => setMemberMenuOpen((o) => !o)}
            >
              <span>
                {rotationMembers.length ? `${rotationMembers.length} selected` : 'Select members'}
              </span>
              <CrmIcon name="chevron-down" className="iconSize-14" />
            </button>
            {memberMenuOpen ? (
              <div className="mtg-multi-select__options">
                <label className="mtg-member-search">
                  <input
                    type="search"
                    placeholder="Search"
                    aria-label="Search teams and members"
                    value={memberSearch}
                    onChange={(e) => setMemberSearch(e.target.value)}
                    onInput={(e) => e.stopPropagation()}
                  />
                  <CrmIcon name="search" className="iconSize-14" />
                </label>
                <div className="mtg-team-group">
                  <strong>Teams</strong>
                  {filteredTeams.length === 0 ? (
                    <p className="mtg-help">No teams match.</p>
                  ) : (
                    filteredTeams.map((team) => {
                      const ids = accountUsers
                        .filter((user) => team.memberIds.includes(user.userId))
                        .map((user) => user.userId);
                      const checked =
                        ids.length > 0 && ids.every((id) => rotationMembers.includes(id));
                      return (
                        <label className="mtg-team-option check" key={team.id}>
                          <input
                            type="checkbox"
                            checked={checked}
                            disabled={ids.length === 0}
                            onChange={() => toggleTeam(team)}
                          />
                          <span className="check__box" aria-hidden />
                          <span>
                            {team.name}
                            <small>
                              {team.memberCount} member{team.memberCount === 1 ? '' : 's'}
                            </small>
                          </span>
                        </label>
                      );
                    })
                  )}
                </div>
                <div className="mtg-team-group">
                  <strong>Users</strong>
                  {rotationUsers.length === 0 ? (
                    <p className="mtg-help">No users match.</p>
                  ) : (
                    rotationUsers.map((user) => {
                      const checked = rotationMembers.includes(user.userId);
                      return (
                        <label className="mtg-team-option check" key={user.userId}>
                          <input
                            type="checkbox"
                            checked={checked}
                            onChange={() => toggleMember(user.userId, checked)}
                          />
                          <span className="check__box" aria-hidden />
                          <span>
                            {user.name}
                            <small>{teamNameOf(user)}</small>
                          </span>
                        </label>
                      );
                    })
                  )}
                  {inactiveMembers.map((user) => (
                    <label className="mtg-team-option check" key={user.id}>
                      <input type="checkbox" checked onChange={() => toggleMember(user.id, true)} />
                      <span className="check__box" aria-hidden />
                      <span>
                        {user.name}
                        <small>Deactivated, never booked</small>
                      </span>
                    </label>
                  ))}
                </div>
              </div>
            ) : null}
          </div>
          {rotationErrors.members ? (
            <p className="mtg-field-error is-visible">Select at least one member.</p>
          ) : null}
        </div>
        <div className="mtg-drawer-divider" />
        <div className="field">
          <strong className="mtg-field-label">Distribution logic</strong>
          <p className="mtg-help">
            Select how meetings should be assigned to members.{' '}
            <a className="link" href="#mtg-rotation-learn" onClick={(e) => e.preventDefault()}>
              Learn more
            </a>
          </p>
          <label className="mtg-radio-line">
            <input
              type="radio"
              name="rotation_logic"
              value="even"
              checked={rotationLogic === 'even'}
              onChange={() => setRotationLogic('even')}
            />
            <span>Distribute meetings evenly between members</span>
          </label>
          <label className="mtg-radio-line">
            <input
              type="radio"
              name="rotation_logic"
              value="weighted"
              checked={rotationLogic === 'weighted'}
              onChange={() => setRotationLogic('weighted')}
            />
            <span>Distribute meetings based on a weighted percentage assigned to each member</span>
          </label>
        </div>
        {rotationLogic === 'weighted' ? (
          <div className="mtg-weighted-fields">
            <div className="mtg-weighted-head">
              <strong>Member</strong>
              <strong>Weight</strong>
            </div>
            {rotationMembers.map((m) => (
              <div className="mtg-weighted-row" key={m}>
                <span>{nameOf(m)}</span>
                <input
                  type="number"
                  min={0}
                  max={100}
                  aria-label={`${nameOf(m)} weight percentage`}
                  value={rotationWeights[m] ?? 0}
                  onChange={(e) =>
                    setRotationWeights((prev) => ({
                      ...prev,
                      [m]: Math.min(100, Math.max(0, Number(e.target.value) || 0)),
                    }))
                  }
                  onInput={(e) => e.stopPropagation()}
                />
              </div>
            ))}
            <p className="mtg-weight-total">
              Total: <strong>{weightTotal}%</strong>{' '}
              <span
                className={cn(weightTotal === 100 ? 'is-valid' : 'is-invalid')}
                data-mtg-weight-status
              >
                {weightTotal === 100 ? 'Looks good' : 'Please make the total 100%.'}
              </span>
            </p>
          </div>
        ) : null}
      </MtgDrawer>

      {/* Users drawer */}
      <MtgDrawer
        open={drawer === 'users'}
        onClose={() => setDrawer(null)}
        title="View users"
        titleId="mtg-users-title"
        users
        foot={
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => setDrawer(null)}
          >
            Close
          </button>
        }
      >
        <div className="mtg-users-toolbar">
          <label className="mtg-search-field">
            <input
              className="input"
              type="search"
              placeholder="Search users"
              value={userSearch}
              onChange={(e) => {
                setUserSearch(e.target.value);
                setUserPage(1);
              }}
              onInput={(e) => e.stopPropagation()}
            />
            <CrmIcon name="search" className="iconSize-14" />
          </label>
          <label className="mtg-filter-select">
            Filter by
            <select
              value={userFilter}
              onChange={(e) => {
                setUserFilter(e.target.value as typeof userFilter);
                setUserPage(1);
              }}
            >
              <option value="user">User</option>
              <option value="team">Team</option>
              <option value="access">Access issues</option>
            </select>
          </label>
        </div>
        <div className="mtg-users-table">
          <div className="mtg-users-table__head">
            <span>CRM user ↑</span>
            <span>Team ↑</span>
          </div>
          {userSlice.length === 0 ? (
            <p className="mtg-help">No users found.</p>
          ) : (
            userSlice.map(([name, team, issue]) => (
              <div className="mtg-user-row" key={name}>
                <span className="mtg-user-row__content">
                  <span className="mtg-user-row__name">{name}</span>
                  <small className="mtg-user-row__issue">{issue}</small>
                </span>
                <span className="mtg-user-row__team">{team}</span>
              </div>
            ))
          )}
        </div>
        <div className="mtg-pagination">
          <button
            type="button"
            aria-label="Previous page"
            disabled={userPage <= 1}
            onClick={() => setUserPage((p) => Math.max(1, p - 1))}
          >
            ‹
          </button>
          <span>{userPage}</span>
          <button
            type="button"
            aria-label="Next page"
            disabled={userPage >= userPages}
            onClick={() => setUserPage((p) => Math.min(userPages, p + 1))}
          >
            ›
          </button>
        </div>
      </MtgDrawer>
    </SettingsFormsProvider>
  );
}
