'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { listMembers, type Member } from '@/features/members/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { SettingsForm, SettingsFormsProvider, type SettingsSaveHandler } from '../settings-ui';
import {
  getNotetakerSettings,
  updateNotetakerSettings,
  type NotetakerSettings,
  type NotetakerShareScope,
} from './api.client';
import {
  CheckPath,
  ExtIcon,
  InfoIcon,
  MeetIcon,
  MeetingsIcon,
  MobileIcon,
  PhoneIcon,
  SwitchKnob,
  TeamsIcon,
  ZoomIcon,
} from './icons';

const USERS_PAGE_SIZE = 8;
const EXCLUDE_PAGE_SIZE = 8;

type ConfirmKind = 'recording' | 'transcription' | 'meetings' | null;

type Draft = Omit<NotetakerSettings, 'updatedAt'>;

function toDraft(s: NotetakerSettings): Draft {
  const { updatedAt: _, ...rest } = s;
  void _;
  return rest;
}

function HsSwitch({
  checked,
  disabled,
  labeled,
  name,
  onChange,
}: {
  checked: boolean;
  disabled?: boolean;
  labeled?: boolean;
  name: string;
  onChange?: (next: boolean) => void;
}) {
  return (
    <label
      className={cn(
        'hs-switch',
        labeled && 'hs-switch--labeled',
        disabled && 'hs-switch--disabled',
      )}
    >
      <input
        type="checkbox"
        name={name}
        checked={checked}
        disabled={disabled}
        onChange={(e) => onChange?.(e.target.checked)}
      />
      <span className="hs-switch__track">
        <span className="hs-switch__label hs-switch__label--on">ON</span>
        <span className="hs-switch__label hs-switch__label--off">OFF</span>
        <SwitchKnob />
      </span>
    </label>
  );
}

function RoundCheck({
  checked,
  label,
  name,
  onToggle,
  warnLast,
}: {
  checked: boolean;
  label: string;
  name: string;
  onToggle: (next: boolean) => void;
  warnLast: boolean;
}) {
  const [showTip, setShowTip] = useState(false);
  return (
    <div className="nt-popover-anchor">
      <label
        className="nt-round-check"
        onClick={(e) => {
          if (checked && warnLast) {
            e.preventDefault();
            setShowTip(true);
            window.setTimeout(() => setShowTip(false), 2200);
          }
        }}
      >
        <input
          type="checkbox"
          name={name}
          checked={checked}
          onChange={(e) => {
            if (!e.target.checked && warnLast) {
              setShowTip(true);
              window.setTimeout(() => setShowTip(false), 2200);
              return;
            }
            onToggle(e.target.checked);
          }}
        />
        <span className="nt-round-check__box">
          <svg viewBox="0 0 16 16" fill="currentColor">
            <CheckPath />
          </svg>
        </span>
        <span className="nt-round-check__label">{label}</span>
      </label>
      {showTip ? (
        <div className="nt-popover" role="tooltip">
          At least one asset type must be selected.
        </div>
      ) : null}
    </div>
  );
}

export function NotetakerSettingsView() {
  const toast = useToast();
  const [saved, setSaved] = useState<NotetakerSettings | null>(null);
  const [draft, setDraft] = useState<Draft | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [members, setMembers] = useState<Member[]>([]);
  const [confirm, setConfirm] = useState<ConfirmKind>(null);
  const [usersDrawer, setUsersDrawer] = useState(false);
  const [excludeDrawer, setExcludeDrawer] = useState(false);
  const [usersPage, setUsersPage] = useState(1);
  const [excludePage, setExcludePage] = useState(1);
  const [excludeSearch, setExcludeSearch] = useState('');
  const [excludeDraft, setExcludeDraft] = useState<string[]>([]);
  const [assetWarn, setAssetWarn] = useState(false);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        const settings = await getNotetakerSettings();
        if (cancelled) return;
        setSaved(settings);
        setDraft(toDraft(settings));
      } catch (err) {
        if (!cancelled) setLoadError(errorText(err));
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      const all: Member[] = [];
      let cursor: string | undefined;
      try {
        do {
          const page = await listMembers({ limit: 200, cursor });
          all.push(...page.data);
          cursor = page.nextCursor ?? undefined;
        } while (cursor);
        if (!cancelled) setMembers(all.filter((m) => m.status === 'active'));
      } catch {
        /* drawers fall back to empty */
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const patchDraft = useCallback((partial: Partial<Draft>) => {
    setDraft((prev) => (prev ? { ...prev, ...partial } : prev));
  }, []);

  const eligible = members;
  const excludedSet = useMemo(
    () => new Set(draft?.excludedUserIds ?? []),
    [draft?.excludedUserIds],
  );
  const accessCount =
    draft?.shareScope === 'except'
      ? eligible.filter((m) => !excludedSet.has(m.userId)).length
      : eligible.length;

  const usersPages = Math.max(1, Math.ceil(eligible.length / USERS_PAGE_SIZE));
  const usersSlice = eligible.slice((usersPage - 1) * USERS_PAGE_SIZE, usersPage * USERS_PAGE_SIZE);

  const filteredExclude = useMemo(() => {
    const q = excludeSearch.trim().toLowerCase();
    if (!q) return eligible;
    return eligible.filter(
      (m) => m.name.toLowerCase().includes(q) || m.email.toLowerCase().includes(q),
    );
  }, [eligible, excludeSearch]);
  const excludePages = Math.max(1, Math.ceil(filteredExclude.length / EXCLUDE_PAGE_SIZE));
  const excludeSlice = filteredExclude.slice(
    (excludePage - 1) * EXCLUDE_PAGE_SIZE,
    excludePage * EXCLUDE_PAGE_SIZE,
  );

  const assetOnCount = draft
    ? [draft.shareVideo, draft.shareAudio, draft.shareTranscript, draft.shareAiSummary].filter(
        Boolean,
      ).length
    : 0;

  const requestToggle = (kind: ConfirmKind, next: boolean) => {
    if (!draft) return;
    if (kind === 'recording') {
      if (!next && draft.conversationRecording) {
        setConfirm('recording');
        return;
      }
      patchDraft({ conversationRecording: next });
      return;
    }
    if (kind === 'transcription') {
      if (!next && draft.transcriptionAnalysis) {
        setConfirm('transcription');
        return;
      }
      patchDraft({ transcriptionAnalysis: next });
      return;
    }
    if (kind === 'meetings') {
      if (next && !draft.channelMeetings) {
        setConfirm('meetings');
        return;
      }
      patchDraft({ channelMeetings: next });
    }
  };

  const bumpDirty = () => {
    document
      .querySelector<HTMLFormElement>('form[data-settings-form]')
      ?.dispatchEvent(new Event('change', { bubbles: true }));
  };

  const applyConfirm = () => {
    if (!draft || !confirm) return;
    if (confirm === 'recording') {
      patchDraft({
        conversationRecording: false,
        channelMeetings: false,
        channelMobile: false,
      });
    } else if (confirm === 'transcription') {
      patchDraft({
        transcriptionAnalysis: false,
        channelMeetings: false,
        channelMobile: false,
      });
    } else if (confirm === 'meetings') {
      patchDraft({ channelMeetings: true });
    }
    setConfirm(null);
    window.setTimeout(bumpDirty, 0);
  };

  const save: SettingsSaveHandler = async () => {
    if (!draft) return false;
    if (
      draft.externalSharing &&
      !draft.shareVideo &&
      !draft.shareAudio &&
      !draft.shareTranscript &&
      !draft.shareAiSummary
    ) {
      setAssetWarn(true);
      toast('At least one asset type must be selected', 'danger');
      return false;
    }
    try {
      const next = await updateNotetakerSettings(draft);
      setSaved(next);
      setDraft(toDraft(next));
      setAssetWarn(false);
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  const openExclude = () => {
    setExcludeDraft([...(draft?.excludedUserIds ?? [])]);
    setExcludeSearch('');
    setExcludePage(1);
    setExcludeDrawer(true);
  };

  if (loadError) {
    return (
      <div className="nt-wrap">
        <header className="nt-header">
          <h1 className="nt-title">Notetaker</h1>
          <p className="nt-desc">{loadError}</p>
        </header>
      </div>
    );
  }

  if (!draft) {
    return (
      <div className="nt-wrap">
        <header className="nt-header">
          <h1 className="nt-title">Notetaker</h1>
          <p className="nt-desc">Loading settings…</p>
        </header>
      </div>
    );
  }

  const mobileOn = draft.conversationRecording && draft.transcriptionAnalysis;

  const confirmCopy =
    confirm === 'recording'
      ? {
          title: 'Turn off conversation recording?',
          body1:
            'This will stop recording new meetings, calls, and in-person conversations going forward. If Notetaker is enabled in your portal, it will also be turned off.',
          body2:
            'Existing recordings and transcripts will not be deleted and will remain accessible.',
          action: 'Turn off recording',
        }
      : confirm === 'transcription'
        ? {
            title: 'Turn off transcription and analysis?',
            body1:
              'This will stop creating new transcripts and AI analysis for meetings, calls, and in-person conversations. Capture options that depend on transcription will be turned off.',
            body2:
              'Existing transcripts and summaries will not be deleted and will remain accessible.',
            action: 'Turn off transcription',
          }
        : {
            title: 'Turn on Meetings capture?',
            body1:
              "CRM's notetaker bot will join eligible video meetings as a participant to record and transcribe them.",
            body2:
              'You can change this anytime. Supported platforms: Zoom, Google Meet, Microsoft Teams.',
            action: 'Turn on Meetings',
          };

  return (
    <SettingsFormsProvider>
      <SettingsForm
        onSave={save}
        onReset={() => {
          if (saved) setDraft(toDraft(saved));
          setAssetWarn(false);
        }}
      >
        <div className="nt-wrap">
          <header className="nt-header">
            <h1 className="nt-title">Notetaker</h1>
            <p className="nt-desc">
              Configure transcript and recording to turn conversation context into suggested CRM
              updates, next steps, and follow up recommendations.
            </p>
            <p className="nt-legal">
              Laws governing call recording, notetakers, and transcription vary by jurisdiction. You
              are responsible for ensuring compliance with applicable laws, including providing any
              notices, obtaining any consents or permissions, and establishing appropriate legal
              basis for processing personal data.
            </p>
          </header>

          {/* QA #384: no HubSpot seat / credit allowance notice here. */}

          {/* Capture options */}
          <div className="nt-card">
            <h2 className="nt-card__title">Capture options</h2>
            <p className="nt-card__desc">
              Configure how conversations are recorded and transcribed using CRM&apos;s built-in
              notetaker to automatically get suggested CRM updates, next steps, and follow-up tasks.{' '}
              <a href="#" className="nt-link" onClick={(e) => e.preventDefault()}>
                What capture option should I use? <ExtIcon />
              </a>
            </p>

            <h3 className="nt-subhead">General settings</h3>
            <p className="nt-subhead__desc">
              These settings are required for CRM notetaker options Meetings, Phone calls, and
              Mobile conversations to function. Both settings below are enabled by default.
            </p>

            <div className="nt-toggle-row">
              <div className="nt-toggle-row__left">
                <div className="nt-toggle-row__title">Conversation recording</div>
                <div className="nt-toggle-row__desc">
                  Enables all conversation recording for your entire account.
                </div>
              </div>
              <div className="nt-toggle-row__right">
                <HsSwitch
                  labeled
                  name="conversationRecording"
                  checked={draft.conversationRecording}
                  onChange={(v) => requestToggle('recording', v)}
                />
              </div>
            </div>

            <div className="nt-toggle-row">
              <div className="nt-toggle-row__left">
                <div className="nt-toggle-row__title">Transcription and analysis</div>
                <div className="nt-toggle-row__desc">
                  Turn on this setting to transcribe, and run analysis on your calls and meetings.
                </div>
              </div>
              <div className="nt-toggle-row__right">
                <HsSwitch
                  labeled
                  name="transcriptionAnalysis"
                  checked={draft.transcriptionAnalysis}
                  onChange={(v) => requestToggle('transcription', v)}
                />
              </div>
            </div>

            <hr className="nt-divider" />

            {/* Meetings */}
            <div className="nt-channel">
              <div className="nt-channel__header">
                <div className="nt-channel__title-wrap">
                  <span className="nt-channel__icon">
                    <MeetingsIcon />
                  </span>
                  <div className="nt-channel__title">
                    <a href="/settings/meetings" className="nt-link--dark">
                      Meetings <ExtIcon size={12} />
                    </a>
                  </div>
                </div>
                <HsSwitch
                  name="channelMeetings"
                  checked={draft.channelMeetings}
                  disabled={!draft.conversationRecording || !draft.transcriptionAnalysis}
                  onChange={(v) => requestToggle('meetings', v)}
                />
              </div>
              <div className="nt-channel__sub">
                CRM&apos;s notetaker bot{' '}
                <a href="#" className="nt-link" onClick={(e) => e.preventDefault()}>
                  Learn more <ExtIcon size={12} />
                </a>
              </div>
              <div className="nt-channel__desc">
                CRM&apos;s notetaker bot records and transcribes video meetings by joining as a
                participant.
              </div>
              <div className="nt-channel__grid">
                <div>
                  <div className="nt-channel__col-label">
                    Enabled for{' '}
                    <button
                      type="button"
                      className="nt-info-btn"
                      title="Enabled for users"
                      aria-label="Enabled for users"
                    >
                      <InfoIcon />
                    </button>
                  </div>
                  <div className="nt-channel__col-val">
                    {draft.channelMeetings ? 'All eligible users' : 'No users'}
                  </div>
                </div>
                <div>
                  <div className="nt-channel__col-label">Supported platforms</div>
                  <div className="nt-channel__col-val">Zoom, Google Meet, Microsoft Teams</div>
                </div>
              </div>
              <div className="nt-channel__footer-link">
                <a href="/settings/meetings#notetaker-bot" className="nt-link">
                  CRM&apos;s notetaker bot settings <ExtIcon size={12} />
                </a>
              </div>
            </div>

            <hr className="nt-divider" />

            {/* Phone — disabled (Call Setup required); UI only */}
            <div className="nt-channel">
              <div className="nt-channel__header">
                <div className="nt-channel__title-wrap">
                  <span className="nt-channel__icon">
                    <PhoneIcon />
                  </span>
                  <div className="nt-channel__title">
                    <span>Phone calls</span>
                  </div>
                </div>
                <div
                  className="nt-disabled-switch crm-popover-wrap"
                  tabIndex={0}
                  role="group"
                  aria-label="Phone calls switch unavailable"
                >
                  <HsSwitch name="channelPhone" checked={false} disabled />
                  <div
                    className="nt-disabled-switch__popover crm-popover crm-popover--left"
                    role="note"
                  >
                    To use this feature, you need to{' '}
                    <a href="/settings/call-setup">
                      set up CRM phone numbers in Call Setup <ExtIcon />
                    </a>
                  </div>
                </div>
              </div>
              <div className="nt-channel__sub">
                CRM&apos;s Calling recording &amp; transcription{' '}
                <a href="#" className="nt-link" onClick={(e) => e.preventDefault()}>
                  Learn more <ExtIcon size={12} />
                </a>
              </div>
              <div className="nt-channel__desc">
                Record and transcribe phone calls made or received in CRM Calling.{' '}
                <a href="#" className="nt-link" onClick={(e) => e.preventDefault()}>
                  Learn more <ExtIcon />
                </a>
              </div>
              <div className="nt-channel__grid">
                <div>
                  <div className="nt-channel__col-label">Available for</div>
                  <div className="nt-channel__col-val">No users</div>
                </div>
                <div>
                  <div className="nt-channel__col-label">Supported platforms</div>
                  <div className="nt-channel__col-val">CRM Calling only</div>
                </div>
              </div>
            </div>

            <hr className="nt-divider" />

            {/* Mobile — disabled / auto */}
            <div className="nt-channel">
              <div className="nt-channel__header">
                <div className="nt-channel__title-wrap">
                  <span className="nt-channel__icon">
                    <MobileIcon />
                  </span>
                  <div className="nt-channel__title">
                    <span className="nt-link--dark">
                      Mobile <ExtIcon size={12} />
                    </span>
                  </div>
                </div>
                <div
                  className="nt-disabled-switch"
                  tabIndex={0}
                  role="group"
                  aria-label="Mobile switch unavailable"
                >
                  <HsSwitch name="channelMobile" checked={mobileOn} disabled />
                  <div className="nt-disabled-switch__popover" role="note">
                    This capture option is automatically turned on when{' '}
                    <strong>Conversation recording</strong> and{' '}
                    <strong>Transcription and analysis</strong> are turned on.
                  </div>
                </div>
              </div>
              <div className="nt-channel__sub">
                CRM&apos;s mobile app voice recording &amp; transcription{' '}
                <a href="#" className="nt-link" onClick={(e) => e.preventDefault()}>
                  Learn more <ExtIcon size={12} />
                </a>
              </div>
              <div className="nt-channel__desc">
                Record in-person meetings and post-meeting voice recordings using the CRM mobile
                app. Choose whether to save recordings and transcripts for each recording session.{' '}
                <a href="#" className="nt-link" onClick={(e) => e.preventDefault()}>
                  Learn more <ExtIcon size={12} />
                </a>
              </div>
              <div className="nt-channel__grid">
                <div>
                  <div className="nt-channel__col-label">Enabled for</div>
                  <div className="nt-channel__col-val">All users</div>
                </div>
                <div>
                  <div className="nt-channel__col-label">Supported platforms</div>
                  <div className="nt-channel__col-val">iOS and Android</div>
                </div>
              </div>
            </div>
          </div>

          {/* Integrations — UI only, no API */}
          <div className="nt-card">
            <h2 className="nt-card__title">Integrations</h2>
            <p className="nt-card__desc">
              Sync video meetings from Zoom, Google Meet, or Teams — no bot join. CRM pulls in your
              recordings and transcriptions to automatically provide suggested CRM updates, next
              steps, and follow-up tasks.
            </p>
            <h3 className="nt-int-subhead">Other available integrations</h3>
            <div className="nt-int-grid">
              {(
                [
                  { name: 'Zoom', installs: '93K installs', icon: <ZoomIcon />, split: true },
                  {
                    name: 'Google Meet',
                    installs: '76K installs',
                    icon: <MeetIcon />,
                    split: true,
                  },
                  {
                    name: 'Microsoft Teams',
                    installs: '65K installs',
                    icon: <TeamsIcon />,
                    split: false,
                  },
                ] as const
              ).map((app) => (
                <div className="nt-int-card" key={app.name}>
                  <div className="nt-int-card__info">
                    <div className="nt-int-card__icon">{app.icon}</div>
                    <div>
                      <div className="nt-int-card__name">{app.name}</div>
                      <div className="nt-int-card__meta">By CRM</div>
                      <div className="nt-int-card__installs">{app.installs}</div>
                    </div>
                  </div>
                  <div className="nt-int-card__btn-wrap">
                    <button
                      type="button"
                      className={cn('nt-btn-install', app.split && 'nt-btn-install--split')}
                      onClick={() => toast(`${app.name} install coming soon`, 'info')}
                    >
                      <span>Install</span>
                      {app.split ? (
                        <>
                          <span className="nt-btn-install__divider" />
                          <svg
                            width="10"
                            height="10"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2.5"
                            aria-hidden
                          >
                            <path d="m6 9 6 6 6-6" />
                          </svg>
                        </>
                      ) : null}
                    </button>
                  </div>
                </div>
              ))}
            </div>
            <div className="nt-marketplace-link">
              <a
                href="#"
                className="nt-link"
                onClick={(e) => {
                  e.preventDefault();
                  toast('Marketplace coming soon', 'info');
                }}
              >
                View more integrations in the app marketplace →
              </a>
            </div>
          </div>

          {/* Sharing recordings */}
          <div className="nt-card">
            <h2 className="nt-card__title">Sharing recordings</h2>
            <p className="nt-card__desc">
              Determines if a recording is able to be shared with external recipients outside of
              CRM. Applies to all recordings &amp; transcripts.
            </p>

            <div className="nt-toggle-row">
              <div className="nt-toggle-row__left">
                <div className="nt-toggle-row__title">External sharing</div>
                <div className="nt-toggle-row__desc">
                  Enables recordings, transcripts, and AI-generated summaries to be shared
                  externally via public link. Links can be given an expiration date and revoked at
                  any time.
                </div>
              </div>
              <div className="nt-toggle-row__right">
                <HsSwitch
                  labeled
                  name="externalSharing"
                  checked={draft.externalSharing}
                  onChange={(v) => patchDraft({ externalSharing: v })}
                />
              </div>
            </div>

            {draft.externalSharing ? (
              <div className="nt-external-options">
                <hr className="nt-divider" />
                <div className="nt-ext-section">
                  <div className="nt-ext-section__title">Assets available for external sharing</div>
                  <div className="nt-ext-section__desc">
                    Select which asset types can be included in shared links. At least one must be
                    selected.
                  </div>
                  <div className="nt-ext-checks">
                    {(
                      [
                        ['shareVideo', 'Video recording', draft.shareVideo],
                        ['shareAudio', 'Audio recording', draft.shareAudio],
                        ['shareTranscript', 'Transcript', draft.shareTranscript],
                        ['shareAiSummary', 'AI summary', draft.shareAiSummary],
                      ] as const
                    ).map(([key, label, checked]) => (
                      <RoundCheck
                        key={key}
                        name={key}
                        label={label}
                        checked={checked}
                        warnLast={checked && assetOnCount <= 1}
                        onToggle={(next) => {
                          patchDraft({ [key]: next });
                          setAssetWarn(false);
                        }}
                      />
                    ))}
                  </div>
                  {assetWarn ? (
                    <p className="nt-ext-section__desc" style={{ color: '#b91c1c', marginTop: 8 }}>
                      At least one asset type must be selected.
                    </p>
                  ) : null}
                </div>

                <hr className="nt-divider" />

                <div className="nt-ext-section">
                  <div className="nt-ext-section__title">Who can share externally</div>
                  <div className="nt-ext-section__desc">
                    Choose which users can create external share links. Users with access to
                    Notetaker are eligible.
                  </div>
                  <div className="nt-ext-radios">
                    <div className="nt-ext-radio-option">
                      <label className="nt-round-radio">
                        <input
                          type="radio"
                          name="shareScope"
                          value="all"
                          checked={draft.shareScope === 'all'}
                          onChange={() => patchDraft({ shareScope: 'all' as NotetakerShareScope })}
                        />
                        <span className="nt-round-radio__circle" />
                        <span className="nt-round-radio__label">
                          All eligible users can share externally
                        </span>
                      </label>
                      <div className="nt-ext-radio__sub">
                        {eligible.length} users have access ·{' '}
                        <button
                          type="button"
                          className="nt-link--teal"
                          onClick={() => {
                            setUsersPage(1);
                            setUsersDrawer(true);
                          }}
                        >
                          View users
                        </button>
                      </div>
                    </div>

                    <div className="nt-ext-radio-option" style={{ marginTop: 14 }}>
                      <label className="nt-round-radio">
                        <input
                          type="radio"
                          name="shareScope"
                          value="except"
                          checked={draft.shareScope === 'except'}
                          onChange={() => patchDraft({ shareScope: 'except' })}
                        />
                        <span className="nt-round-radio__circle" />
                        <span className="nt-round-radio__label">
                          All eligible users except specific users
                        </span>
                      </label>
                      <div className="nt-ext-radio__sub">
                        {draft.excludedUserIds.length} users excluded ·{' '}
                        <button type="button" className="nt-link--teal" onClick={openExclude}>
                          Manage
                        </button>
                        <br />
                        {accessCount} of {eligible.length} users have access
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ) : null}
          </div>
        </div>
      </SettingsForm>

      {/* Users with access drawer */}
      {usersDrawer ? (
        <div className="nt-drawer-backdrop" onClick={() => setUsersDrawer(false)}>
          <aside
            className="nt-drawer"
            role="dialog"
            aria-modal="true"
            aria-labelledby="ntUsersDrawerTitle"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="nt-drawer__head">
              <h2 className="nt-drawer__title" id="ntUsersDrawerTitle">
                Users with external sharing access
              </h2>
              <button
                type="button"
                className="nt-drawer__close"
                aria-label="Close drawer"
                onClick={() => setUsersDrawer(false)}
              >
                ×
              </button>
            </div>
            <div className="nt-drawer__body">
              {usersSlice.length === 0 ? (
                <p className="nt-drawer__intro">No eligible users found.</p>
              ) : (
                usersSlice.map((m) => (
                  <div className="nt-user-row" key={m.userId}>
                    <div className="nt-user-row__name">{m.name}</div>
                    <div className="nt-user-row__email">{m.email}</div>
                  </div>
                ))
              )}
            </div>
            {usersPages > 1 ? (
              <div className="nt-drawer__pagination">
                <button
                  type="button"
                  className="nt-page-nav nt-page-nav--prev"
                  disabled={usersPage <= 1}
                  onClick={() => setUsersPage((p) => Math.max(1, p - 1))}
                >
                  ‹ Prev
                </button>
                {Array.from({ length: usersPages }, (_, i) => i + 1).map((n) => (
                  <button
                    key={n}
                    type="button"
                    className={cn('nt-page-num', n === usersPage && 'is-active')}
                    onClick={() => setUsersPage(n)}
                  >
                    {n}
                  </button>
                ))}
                <button
                  type="button"
                  className="nt-page-nav nt-page-nav--next"
                  disabled={usersPage >= usersPages}
                  onClick={() => setUsersPage((p) => Math.min(usersPages, p + 1))}
                >
                  Next ›
                </button>
              </div>
            ) : null}
          </aside>
        </div>
      ) : null}

      {/* Exclude users drawer */}
      {excludeDrawer ? (
        <div className="nt-drawer-backdrop" onClick={() => setExcludeDrawer(false)}>
          <aside
            className="nt-drawer"
            role="dialog"
            aria-modal="true"
            aria-labelledby="ntExcludeDrawerTitle"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="nt-drawer__head">
              <h2 className="nt-drawer__title" id="ntExcludeDrawerTitle">
                Exclude users from external sharing
              </h2>
              <button
                type="button"
                className="nt-drawer__close"
                aria-label="Close drawer"
                onClick={() => setExcludeDrawer(false)}
              >
                ×
              </button>
            </div>
            <div className="nt-drawer__body">
              <p className="nt-drawer__intro">
                Selected users keep access to recordings but can&apos;t create external share links.
              </p>
              <div className="nt-drawer__search-wrap">
                <input
                  type="text"
                  className="nt-drawer__search"
                  placeholder="Search users"
                  autoComplete="off"
                  spellCheck={false}
                  value={excludeSearch}
                  onChange={(e) => {
                    setExcludeSearch(e.target.value);
                    setExcludePage(1);
                  }}
                  onInput={(e) => e.stopPropagation()}
                />
                <svg
                  className="nt-drawer__search-icon"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                  aria-hidden
                >
                  <path
                    fillRule="evenodd"
                    d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
                    clipRule="evenodd"
                  />
                </svg>
              </div>
              <div className="nt-exclude-list">
                {excludeSlice.map((m) => {
                  const checked = excludeDraft.includes(m.userId);
                  return (
                    <label className="nt-exclude-item" key={m.userId}>
                      <input
                        type="checkbox"
                        className="nt-exclude-cb"
                        checked={checked}
                        onChange={() => {
                          setExcludeDraft((prev) =>
                            checked ? prev.filter((id) => id !== m.userId) : [...prev, m.userId],
                          );
                        }}
                      />
                      <span className="nt-exclude-box">
                        <svg viewBox="0 0 16 16" fill="currentColor">
                          <CheckPath />
                        </svg>
                      </span>
                      <span className="nt-exclude-item__info">
                        <span className="nt-exclude-item__name">{m.name}</span>
                        <span className="nt-exclude-item__email">{m.email}</span>
                      </span>
                    </label>
                  );
                })}
                {excludeSlice.length === 0 ? (
                  <div className="nt-exclude-empty">No users match your search.</div>
                ) : null}
              </div>
            </div>
            {excludePages > 1 ? (
              <div className="nt-drawer__pagination nt-drawer__pagination--exclude">
                <button
                  type="button"
                  className="nt-page-nav nt-page-nav--prev"
                  disabled={excludePage <= 1}
                  onClick={() => setExcludePage((p) => Math.max(1, p - 1))}
                >
                  ‹ Prev
                </button>
                {Array.from({ length: excludePages }, (_, i) => i + 1).map((n) => (
                  <button
                    key={n}
                    type="button"
                    className={cn('nt-page-num', n === excludePage && 'is-active')}
                    onClick={() => setExcludePage(n)}
                  >
                    {n}
                  </button>
                ))}
                <button
                  type="button"
                  className="nt-page-nav nt-page-nav--next"
                  disabled={excludePage >= excludePages}
                  onClick={() => setExcludePage((p) => Math.min(excludePages, p + 1))}
                >
                  Next ›
                </button>
              </div>
            ) : null}
            <div className="nt-drawer__foot">
              <span className="nt-drawer__foot-count">{excludeDraft.length} selected</span>
              <div className="nt-drawer__foot-actions">
                <button
                  type="button"
                  className="nt-drawer__btn nt-drawer__btn--cancel"
                  onClick={() => setExcludeDrawer(false)}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="nt-drawer__btn nt-drawer__btn--save"
                  onClick={() => {
                    patchDraft({ excludedUserIds: excludeDraft, shareScope: 'except' });
                    setExcludeDrawer(false);
                    window.setTimeout(bumpDirty, 0);
                  }}
                >
                  Save changes
                </button>
              </div>
            </div>
          </aside>
        </div>
      ) : null}

      {/* Confirm modal */}
      {confirm ? (
        <div className="nt-modal-backdrop" onClick={() => setConfirm(null)}>
          <div
            className="nt-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="ntModalTitle"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="nt-modal__title" id="ntModalTitle">
              {confirmCopy.title}
            </h2>
            <hr className="nt-modal__divider" />
            <div className="nt-modal__body">
              <p className="nt-modal__text">{confirmCopy.body1}</p>
              <p className="nt-modal__text">{confirmCopy.body2}</p>
            </div>
            <div className="nt-modal__actions">
              <button
                type="button"
                className="nt-modal__btn nt-modal__btn--primary"
                onClick={applyConfirm}
              >
                {confirmCopy.action}
              </button>
              <button
                type="button"
                className="nt-modal__btn nt-modal__btn--cancel"
                onClick={() => setConfirm(null)}
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </SettingsFormsProvider>
  );
}
