'use client';

/**
 * The editor's popover panels from the 17 Nov design (message-templates.js): the token form
 * (insert in body / subject, edit a chip), the Insert menu (tokens, snippets, documents, meetings,
 * video), the link / image address panel and the preview's contact picker.
 */
import { useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { listSnippets, type Snippet } from '@/features/snippets/api.client';
import { MtIcon, MtPop, MtSelect } from '@/features/snippets/ui/mt';
import { errorText } from '@/lib/api/errors';
import {
  TOKEN_GROUPS,
  customTokensOf,
  fieldLabel,
  type TokenField,
  type TokenGroupKey,
} from '@/features/sequences/ui/DynamicStepDrawers';
import { listDocuments, updateDocument } from '@/features/documents/api.client';
import type { TrackedDocument } from '@/features/documents/types';
import { listBookingPages } from '@/features/meetings/api.client';
import type { BookingPage } from '@/features/meetings/types';
import { bookingUrl } from '@/features/meetings/scheduler';
import { cn } from '@/lib/utils/cn';
import { findPreviewContacts } from '../api.client';
import { SENDER_MEETING_PLACEHOLDER, documentPlaceholder, type MergeToken } from '../model';

export const COMING_SOON = 'Coming soon';

export function Field({
  label,
  tip,
  children,
}: {
  label: string;
  tip?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="field">
      <span className="field__label">
        {label}
        {tip ? (
          <span
            className="mt-tip"
            data-mt-tip={tip}
            tabIndex={0}
            style={{ marginLeft: 6, display: 'inline-flex', verticalAlign: 'middle' }}
          >
            <MtIcon name="info" size={14} />
          </span>
        ) : null}
      </span>
      {children}
    </div>
  );
}

export function BtnSm({
  label,
  primary,
  disabled,
  onClick,
}: {
  label: string;
  primary?: boolean;
  disabled?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      className={cn('btn-crm btn-crm--sm', primary ? 'btn-crm--primary' : 'btn-crm--outline')}
      disabled={disabled}
      onClick={onClick}
    >
      {label}
    </button>
  );
}

function PanelHead({
  title,
  onBack,
  right,
}: {
  title: string;
  onBack: () => void;
  right?: React.ReactNode;
}) {
  return (
    <div className="mt-panel__head">
      <button type="button" className="mt-panel__back" aria-label="Back" onClick={onBack}>
        <MtIcon name="chevron-left" />
      </button>
      <span className="mt-panel__sep" />
      <span className="mt-panel__title">{title}</span>
      {right ? <span className="mt-panel__right">{right}</span> : null}
    </div>
  );
}

// --- Tokens --------------------------------------------------------------------------------------

/** Custom fields per token group, loaded once (shared with the sequences step editor). */
export function useCustomTokens(): Record<TokenGroupKey, TokenField[]> {
  const [custom, setCustom] = useState<Record<TokenGroupKey, TokenField[]>>({
    contact: [],
    company: [],
    deal: [],
    owner: [],
    sender: [],
  });
  useEffect(() => {
    let alive = true;
    void Promise.all(TOKEN_GROUPS.map((g) => customTokensOf(g.key))).then((lists) => {
      if (!alive) return;
      setCustom(
        Object.fromEntries(TOKEN_GROUPS.map((g, i) => [g.key, lists[i] ?? []])) as Record<
          TokenGroupKey,
          TokenField[]
        >,
      );
    });
    return () => {
      alive = false;
    };
  }, []);
  return custom;
}

export function tokenOptions(group: TokenGroupKey, custom: Record<TokenGroupKey, TokenField[]>) {
  const standard = TOKEN_GROUPS.find((g) => g.key === group)?.fields ?? [];
  return [
    ...standard.map((f) => ({ value: f, label: fieldLabel(f) })),
    ...(custom[group] ?? [])
      .filter((c) => !(standard as readonly string[]).includes(c.name))
      .map((c) => ({ value: c.name, label: c.label })),
  ];
}

/** "Contact: First name": the design's chip label for one of our merge fields. */
export function labelOfToken(t: MergeToken, custom: Record<TokenGroupKey, TokenField[]>): string {
  const group = TOKEN_GROUPS.find((g) => g.key === t.type);
  const field =
    custom[t.type as TokenGroupKey]?.find((c) => c.name === t.key)?.label ?? fieldLabel(t.key);
  return `${group?.label ?? t.type}: ${field}`;
}

/** The design's `tokenForm`: Type, Token (searchable), optional Fallback, submit / Cancel. */
export function TokenForm({
  initial,
  allowFallback,
  submitLabel,
  custom,
  onSubmit,
  onCancel,
}: {
  initial?: MergeToken;
  allowFallback?: boolean;
  submitLabel: string;
  custom: Record<TokenGroupKey, TokenField[]>;
  onSubmit: (t: MergeToken) => void;
  onCancel: () => void;
}) {
  const startGroup = TOKEN_GROUPS.some((g) => g.key === initial?.type)
    ? (initial!.type as TokenGroupKey)
    : 'contact';
  const [group, setGroup] = useState<TokenGroupKey>(startGroup);
  const [token, setToken] = useState<string | null>(initial?.key ?? null);
  const [fallback, setFallback] = useState(initial?.fallback ?? '');
  const g = TOKEN_GROUPS.find((x) => x.key === group)!;
  return (
    <div className="mt-panel__body">
      <Field label="Type">
        <MtSelect
          value={group}
          options={TOKEN_GROUPS.map((x) => ({ value: x.key, label: x.label }))}
          onChange={(v) => {
            setGroup(v as TokenGroupKey);
            setToken(null);
          }}
        />
      </Field>
      <Field label="Token">
        <MtSelect
          value={token}
          options={tokenOptions(group, custom)}
          searchable
          placeholder={`Search ${g.label.toLowerCase()} tokens`}
          onChange={setToken}
        />
      </Field>
      {allowFallback ? (
        <Field label="Fallback value" tip="Used when the contact has no value for this token">
          <input
            className="input"
            type="text"
            placeholder="Enter fallback value (optional)"
            maxLength={200}
            autoComplete="off"
            value={fallback}
            onChange={(e) => setFallback(e.target.value)}
          />
        </Field>
      ) : null}
      <div className="mt-panel__actions">
        <BtnSm
          label={submitLabel}
          primary
          disabled={!token}
          onClick={() =>
            token &&
            onSubmit({ type: group, key: token, fallback: allowFallback ? fallback.trim() : '' })
          }
        />
        <BtnSm label="Cancel" onClick={onCancel} />
      </div>
    </div>
  );
}

// --- Insert menu ---------------------------------------------------------------------------------

type InsertView = 'main' | 'tokens' | 'snippets' | 'documents' | 'meetings';

const plainOf = (html: string) =>
  html
    .replace(/<[^>]*>/g, ' ')
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/\s+/g, ' ')
    .trim();

/**
 * The design's Insert popover. Subject: personalization tokens only. Body: tokens, snippets
 * (GET /snippets), documents (a placeholder each contact's tracked link replaces on sending),
 * meeting links (my booking pages) and Video (the design's Vidyard flyout).
 */
export function InsertMenu({
  mode,
  custom,
  meId,
  onToken,
  onSnippet,
  onMeetingLink,
  onDocument,
  onVideo,
  onClose,
}: {
  mode: 'body' | 'subject';
  custom: Record<TokenGroupKey, TokenField[]>;
  meId: string;
  onToken: (t: MergeToken) => void;
  onSnippet: (s: Snippet) => void;
  onMeetingLink: (href: string, text: string) => void;
  /** Documents: the placeholder link, its text, and whether to box it as a preview. */
  onDocument: (href: string, text: string, preview: boolean) => void;
  /** Video › Record with Vidyard; left out where the menu has no Video. */
  onVideo?: () => void;
  onClose: () => void;
}) {
  const [view, setView] = useState<InsertView>('main');
  const [videoBtn, setVideoBtn] = useState<HTMLElement | null>(null);
  if (view === 'tokens') {
    return (
      <div className="mt-insert" style={{ width: '100%' }}>
        <PanelHead title="Insert personalization token" onBack={() => setView('main')} />
        <TokenForm
          submitLabel="Insert"
          custom={custom}
          onSubmit={(t) => {
            onClose();
            onToken(t);
          }}
          onCancel={onClose}
        />
      </div>
    );
  }
  if (view === 'snippets') {
    return (
      <div className="mt-insert" style={{ width: '100%' }}>
        <SnippetsPanel
          onBack={() => setView('main')}
          onPick={(s) => {
            onClose();
            onSnippet(s);
          }}
        />
      </div>
    );
  }
  if (view === 'documents') {
    return (
      <div className="mt-insert" style={{ width: '100%' }}>
        <DocumentsPanel
          onBack={() => setView('main')}
          onCancel={onClose}
          onInsert={(href, text, preview) => {
            onClose();
            onDocument(href, text, preview);
          }}
        />
      </div>
    );
  }
  if (view === 'meetings') {
    return (
      <div className="mt-insert" style={{ width: '100%' }}>
        <MeetingsPanel
          meId={meId}
          onBack={() => setView('main')}
          onCancel={onClose}
          onInsert={(href, text) => {
            onClose();
            onMeetingLink(href, text);
          }}
        />
      </div>
    );
  }
  const item = (
    icon: string | null,
    label: string,
    onClick: (() => void) | null,
    o: { sub?: string; chevron?: boolean } = {},
  ) => (
    <button
      type="button"
      className="mt-menu__item"
      role="menuitem"
      disabled={!onClick}
      title={!onClick ? COMING_SOON : undefined}
      onClick={onClick ?? undefined}
    >
      {icon ? <MtIcon name={icon} /> : null}
      <span className="mt-menu__txt">
        <span>{label}</span>
        {o.sub ? <span className="mt-menu__sub">{o.sub}</span> : null}
      </span>
      {o.chevron ? <MtIcon name="chevron-right" size={14} className="mt-menu__chev" /> : null}
    </button>
  );
  return (
    <div className="mt-insert" style={{ width: '100%' }}>
      <div className="mt-menu" role="menu">
        {mode === 'subject' ? (
          item(null, 'Insert a personalization token', () => setView('tokens'), {
            sub: 'Add a personalization token to the subject line',
          })
        ) : (
          <>
            {item('pencil', 'Personalization tokens', () => setView('tokens'), { chevron: true })}
            {item('snippet', 'Snippets', () => setView('snippets'), { chevron: true })}
            {item('documents', 'Documents', () => setView('documents'), { chevron: true })}
            {item('meetings', 'Meetings', () => setView('meetings'), { chevron: true })}
            <button
              type="button"
              className="mt-menu__item"
              role="menuitem"
              aria-haspopup="menu"
              aria-expanded={!!videoBtn}
              onClick={(e) => {
                const anchor = e.currentTarget;
                setVideoBtn((cur) => (cur ? null : anchor));
              }}
            >
              <MtIcon name="video" />
              <span className="mt-menu__txt">
                <span>Video</span>
              </span>
              <MtIcon name="chevron-right" size={14} className="mt-menu__chev" />
            </button>
            {videoBtn ? (
              <MtPop
                anchor={videoBtn}
                onClose={() => setVideoBtn(null)}
                placement="right"
                role="menu"
              >
                <div className="mt-menu" role="menu">
                  <button
                    type="button"
                    className="mt-menu__item"
                    role="menuitem"
                    onClick={() => {
                      onClose();
                      onVideo?.();
                    }}
                  >
                    Record with Vidyard
                  </button>
                  <button
                    type="button"
                    className="mt-menu__item"
                    role="menuitem"
                    disabled
                    title="Not available on your plan"
                  >
                    <span>Select from library</span>
                    <MtIcon name="lock" size={14} className="mt-menu__chev" />
                  </button>
                </div>
              </MtPop>
            ) : null}
          </>
        )}
      </div>
    </div>
  );
}

export function SnippetsPanel({
  onBack,
  onPick,
}: {
  onBack: () => void;
  onPick: (s: Snippet) => void;
}) {
  const [snippets, setSnippets] = useState<Snippet[] | null>(null);
  const [failed, setFailed] = useState(false);
  const [q, setQ] = useState('');
  useEffect(() => {
    let alive = true;
    listSnippets().then(
      (res) => alive && setSnippets(res.data),
      () => alive && setFailed(true),
    );
    return () => {
      alive = false;
    };
  }, []);
  const term = q.trim().toLowerCase();
  const shown = (snippets ?? []).filter(
    (s) => !term || `${s.name} ${plainOf(s.bodyHtml)}`.toLowerCase().includes(term),
  );
  return (
    <div>
      <PanelHead
        title="Snippets"
        onBack={onBack}
        right={
          <>
            <BtnSm label="Create new" onClick={() => window.open('/snippets', '_blank')} />
            <BtnSm label="Manage" onClick={() => window.open('/snippets', '_blank')} />
          </>
        }
      />
      <div className="mt-panel__search">
        <input
          className="input"
          type="search"
          placeholder="Search snippets..."
          aria-label="Search snippets"
          autoComplete="off"
          autoFocus
          style={{ border: '2px solid var(--brand)' }}
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <MtIcon name="search" className="mt-search__icon" />
      </div>
      <div className="mt-panel__list">
        {snippets === null && !failed ? (
          <div className="mt-empty-opt">Loading snippets…</div>
        ) : null}
        {failed ? <div className="mt-empty-opt">Could not load snippets.</div> : null}
        {snippets !== null && !shown.length ? (
          <div className="mt-empty-opt">No snippets found</div>
        ) : null}
        {shown.map((s) => (
          <button key={s.id} type="button" className="mt-snippet" onClick={() => onPick(s)}>
            <span className="mt-snippet__name">{s.name}</span>
            <span className="mt-snippet__text">{plainOf(s.bodyHtml)}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function PanelCheck({
  label,
  tip,
  checked,
  onChange,
}: {
  label: string;
  tip?: string;
  checked: boolean;
  onChange: (on: boolean) => void;
}) {
  return (
    <label className="check">
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
      <span className="check__box" />
      {label}
      {tip ? (
        <span className="mt-tip" data-mt-tip={tip} tabIndex={0} style={{ display: 'inline-flex' }}>
          <MtIcon name="info" size={14} />
        </span>
      ) : null}
    </label>
  );
}

/** The design's `panelDocs`: pick a document, its link text and sharing options. */
function DocumentsPanel({
  onBack,
  onCancel,
  onInsert,
}: {
  onBack: () => void;
  onCancel: () => void;
  onInsert: (href: string, text: string, preview: boolean) => void;
}) {
  const toast = useToast();
  const [documents, setDocuments] = useState<TrackedDocument[] | null>(null);
  const [failed, setFailed] = useState(false);
  const [docId, setDocId] = useState<string | null>(null);
  const [text, setText] = useState('');
  const [typed, setTyped] = useState(false);
  const [requireEmail, setRequireEmail] = useState(true);
  const [allowDownload, setAllowDownload] = useState(true);
  const [preview, setPreview] = useState(false);
  const [saving, setSaving] = useState(false);
  useEffect(() => {
    let alive = true;
    listDocuments().then(
      (res) => alive && setDocuments(res.data),
      () => alive && setFailed(true),
    );
    return () => {
      alive = false;
    };
  }, []);
  const picked = documents?.find((d) => d.id === docId) ?? null;

  const insert = async () => {
    if (!picked) return;
    // "Allow download" is the document's own setting: changed here only when the box differs.
    if (allowDownload !== picked.allowDownload) {
      setSaving(true);
      try {
        await updateDocument(picked.id, { allowDownload });
      } catch (err) {
        toast(errorText(err), 'danger');
        setSaving(false);
        return;
      }
    }
    onInsert(documentPlaceholder(picked.id, requireEmail), text.trim() || picked.name, preview);
  };

  return (
    <div>
      <PanelHead
        title="Insert document"
        onBack={onBack}
        right={<BtnSm label="Manage" onClick={() => window.open('/documents', '_blank')} />}
      />
      <div className="mt-panel__body">
        <Field label="Document">
          <MtSelect
            value={docId}
            options={(documents ?? []).map((d) => ({ value: d.id, label: d.name }))}
            searchable
            placeholder="Search documents..."
            onChange={(id) => {
              const found = documents?.find((d) => d.id === id);
              setDocId(id);
              if (!found) return;
              setAllowDownload(found.allowDownload);
              if (!typed) setText(found.name);
            }}
          />
        </Field>
        {failed ? <div className="mt-empty-opt">Could not load documents.</div> : null}
        {documents !== null && !documents.length ? (
          <div className="mt-empty-opt">
            No documents yet.{' '}
            <a className="link" href="/documents" target="_blank" rel="noopener">
              Upload one
            </a>
          </div>
        ) : null}
        <Field label="Link display text">
          <input
            className="input"
            type="text"
            maxLength={200}
            autoComplete="off"
            aria-label="Link display text"
            value={text}
            onChange={(e) => {
              setText(e.target.value);
              setTyped(true);
            }}
          />
        </Field>
        <div className="mt-checks">
          <PanelCheck
            label="Require email to view document"
            checked={requireEmail}
            onChange={setRequireEmail}
          />
          <PanelCheck
            label="Allow download"
            tip="Viewers can download a copy of the document. This is the document's own setting: it applies to all its links"
            checked={allowDownload}
            onChange={setAllowDownload}
          />
          <PanelCheck label="Include link preview" checked={preview} onChange={setPreview} />
        </div>
        <div className="mt-panel__actions">
          <BtnSm
            label="Insert"
            primary
            disabled={!picked || saving}
            onClick={() => void insert()}
          />
          <BtnSm label="Cancel" onClick={onCancel} />
        </div>
      </div>
    </div>
  );
}

function MeetingsPanel({
  meId,
  onBack,
  onCancel,
  onInsert,
}: {
  meId: string;
  onBack: () => void;
  onCancel: () => void;
  onInsert: (href: string, text: string) => void;
}) {
  const [pages, setPages] = useState<BookingPage[] | null>(null);
  const [linkId, setLinkId] = useState<string | null>(null);
  const [text, setText] = useState('');
  const [mode, setMode] = useState<'mine' | 'sender'>('mine');
  useEffect(() => {
    let alive = true;
    listBookingPages().then(
      (res) => {
        if (!alive) return;
        const mine = res.data.filter((p) => p.active && (!p.ownerId || p.ownerId === meId));
        setPages(mine);
        setLinkId(mine[0]?.id ?? null);
      },
      () => alive && setPages([]),
    );
    return () => {
      alive = false;
    };
  }, [meId]);
  const origin = typeof window === 'undefined' ? '' : window.location.origin;
  const picked = pages?.find((p) => p.id === linkId) ?? null;
  return (
    <div>
      <PanelHead
        title="Insert meeting link"
        onBack={onBack}
        right={<BtnSm label="Manage" onClick={() => window.open('/meeting-scheduler', '_blank')} />}
      />
      <div className="mt-panel__body">
        <Field label="Text to display">
          <input
            className="input"
            type="text"
            maxLength={200}
            placeholder="e.g. Schedule a call with me"
            autoComplete="off"
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </Field>
        <div className="mt-radio-block">
          <span className="field__label">Link to:</span>
          <div className="mt-radio-row">
            <label className="mt-radio">
              <input
                type="radio"
                name="mttMeetMode"
                checked={mode === 'mine'}
                onChange={() => setMode('mine')}
              />
              <span className="mt-radio__dot" />
              <span>Your meeting link</span>
            </label>
            {picked ? (
              <a
                className="link"
                href={bookingUrl(origin, picked.slug)}
                target="_blank"
                rel="noopener noreferrer"
              >
                Preview booking page
                <MtIcon name="external" size={14} />
              </a>
            ) : null}
          </div>
          {pages === null ? (
            <div className="mt-empty-opt">Loading meeting links…</div>
          ) : pages.length ? (
            <MtSelect
              value={linkId}
              options={pages.map((p, i) => ({
                value: p.id,
                label: p.title + (i === 0 ? ' (Default)' : ''),
                sub: bookingUrl(origin, p.slug),
              }))}
              onChange={setLinkId}
            />
          ) : (
            <div className="mt-empty-opt">
              You have no meeting links yet.{' '}
              <a className="link" href="/meeting-scheduler" target="_blank" rel="noopener">
                Manage links
              </a>
            </div>
          )}
          <div className="mt-radio-row">
            <label className="mt-radio">
              <input
                type="radio"
                name="mttMeetMode"
                checked={mode === 'sender'}
                onChange={() => setMode('sender')}
              />
              <span className="mt-radio__dot" />
              <span>Sender&apos;s meetings link</span>
            </label>
            <span
              className="mt-tip"
              data-mt-tip="Whoever sends the email links to their own default meetings page"
              tabIndex={0}
              style={{ display: 'inline-flex' }}
            >
              <MtIcon name="info" size={14} />
            </span>
          </div>
        </div>
        <div className="mt-panel__actions">
          <BtnSm
            label="Insert"
            primary
            disabled={mode === 'mine' && !picked}
            onClick={() => {
              const label = text.trim() || 'Schedule a call with me';
              if (mode === 'sender') onInsert(SENDER_MEETING_PLACEHOLDER, label);
              else if (picked) onInsert(bookingUrl(origin, picked.slug), label);
            }}
          />
          <BtnSm label="Cancel" onClick={onCancel} />
        </div>
      </div>
    </div>
  );
}

// --- Link / image address ------------------------------------------------------------------------

/** The design's `safeUrl`: http(s), and mailto: / tel: for links. */
export function safeUrl(raw: string, allowMail: boolean): string {
  // No spaces or control characters (a "java\nscript:" trick).
  let u = [...raw]
    .filter((ch) => {
      const code = ch.charCodeAt(0);
      return code > 0x1f && code !== 0x7f && !/\s/.test(ch);
    })
    .join('');
  // Another kind of address is refused, not turned into a broken web one.
  if (/^(javascript|data|vbscript|file|blob):/i.test(u)) return '';
  if (u && !/^(https?:\/\/|mailto:|tel:)/i.test(u)) u = `https://${u}`;
  if (/^https?:\/\/[^/]/i.test(u)) return u;
  if (allowMail && /^(mailto:|tel:)./i.test(u)) return u;
  return '';
}

/** The design's `urlPopover`: an address (and alt text for images), apply / Cancel. */
export function UrlPanel({
  title,
  button,
  extra,
  allowMail,
  onApply,
  onCancel,
  onInvalid,
}: {
  title: string;
  button: string;
  extra?: { label: string; placeholder: string };
  allowMail: boolean;
  onApply: (url: string, extra: string) => void;
  onCancel: () => void;
  onInvalid: () => void;
}) {
  const [url, setUrl] = useState('');
  const [alt, setAlt] = useState('');
  const submit = () => {
    const clean = safeUrl(url.trim(), allowMail);
    if (!clean) {
      onInvalid();
      return;
    }
    onApply(clean, alt.trim());
  };
  return (
    <div className="mt-panel__body" style={{ paddingTop: 16, width: 320 }}>
      <Field label={title}>
        <input
          className="input"
          type="url"
          placeholder="https://"
          autoComplete="off"
          aria-label={title}
          autoFocus
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.preventDefault();
              submit();
            }
          }}
        />
      </Field>
      {extra ? (
        <Field label={extra.label}>
          <input
            className="input"
            type="text"
            placeholder={extra.placeholder}
            aria-label={extra.placeholder}
            autoComplete="off"
            value={alt}
            onChange={(e) => setAlt(e.target.value)}
          />
        </Field>
      ) : null}
      <div className="mt-panel__actions">
        <BtnSm label={button} primary onClick={submit} />
        <BtnSm label="Cancel" onClick={onCancel} />
      </div>
    </div>
  );
}

// --- Preview contact picker ----------------------------------------------------------------------

export interface PreviewContact {
  id: string;
  email: string | null;
  name: string;
  company: string | null;
}

/** The design's searchable "Select a contact" select, searching the CRM's contacts. */
export function ContactPicker({
  value,
  onChange,
}: {
  value: PreviewContact | null;
  onChange: (c: PreviewContact) => void;
}) {
  const [btn, setBtn] = useState<HTMLButtonElement | null>(null);
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const [found, setFound] = useState<PreviewContact[] | null>(null);
  const seq = useRef(0);
  useEffect(() => {
    if (!open) return;
    const mine = ++seq.current;
    const t = window.setTimeout(
      () => {
        findPreviewContacts(q).then(
          (list) => mine === seq.current && setFound(list),
          () => mine === seq.current && setFound([]),
        );
      },
      q ? 250 : 0,
    );
    return () => window.clearTimeout(t);
  }, [q, open]);
  return (
    <>
      <button
        ref={setBtn}
        type="button"
        className="mt-select"
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
      >
        <span className={cn('mt-select__label', !value && 'is-placeholder')}>
          {value
            ? value.name && value.email && value.name !== value.email
              ? `${value.name} · ${value.email}`
              : value.name || value.email || 'Contact'
            : 'Select a contact'}
        </span>
        <MtIcon name="chevron-down" />
      </button>
      {open ? (
        <MtPop anchor={btn} onClose={() => setOpen(false)} arrow={false}>
          <div
            className="mt-listbox"
            style={{ width: Math.max(btn?.getBoundingClientRect().width ?? 0, 260) }}
          >
            <div className="mt-listbox__search">
              <input
                className="input"
                type="search"
                placeholder="Select a contact"
                aria-label="Search contacts"
                autoComplete="off"
                autoFocus
                value={q}
                onChange={(e) => setQ(e.target.value)}
              />
              <MtIcon name="search" className="mt-search__icon" />
            </div>
            <div className="mt-listbox__list" role="listbox" aria-label="Contacts">
              {found === null ? <div className="mt-empty-opt">Loading contacts…</div> : null}
              {found !== null && !found.length ? (
                <div className="mt-empty-opt">No contacts found</div>
              ) : null}
              {(found ?? []).map((c) => {
                const title = c.name || c.email || 'Contact';
                const sub = [c.name && c.email ? c.email : null, c.company]
                  .filter(Boolean)
                  .join(' - ');
                return (
                  <div
                    key={c.id}
                    className="mt-opt"
                    role="option"
                    aria-selected={value?.id === c.id ? 'true' : 'false'}
                    tabIndex={-1}
                    onClick={() => {
                      setOpen(false);
                      onChange(c);
                    }}
                  >
                    <span className="mt-opt__txt">
                      <span className="mt-opt__title">{title}</span>
                      {sub ? <span className="mt-opt__sub">{sub}</span> : null}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        </MtPop>
      ) : null}
    </>
  );
}
