'use client';

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type PointerEvent as ReactPointerEvent,
  type ReactNode,
} from 'react';
import { AnchoredPopover } from '@/components/crm/AnchoredPopover';
import { ComposeRichText } from '@/components/crm/ComposeRichText';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { getCompany } from '@/features/companies/api.client';
import { getContact } from '@/features/contacts/api.client';
import { CustomFieldInput, formatCustomValue } from '@/features/contacts/ui/actions/custom-fields';
import {
  followUpDueDate,
  FollowUpTaskControls,
} from '@/features/contacts/ui/actions/FollowUpTaskControls';
import { actionErrorText } from '@/features/contacts/ui/actions/shared';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { getDeal } from '@/features/deals/api.client';
import { getObjectRecord } from '@/features/objects/api.client';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import type { SnippetTarget } from '@/features/snippets/api.client';
import { cn } from '@/lib/utils/cn';
import type { PlaybookBlock, PlaybookQuestion } from '../types';
import { formatUserDate } from '@/features/activities/readable';
import {
  getPlaybookRun,
  savePlaybookDraft,
  submitPlaybook,
  type DraftTask,
  type LogType,
  type PlaybookRun,
  type RunAnswer,
  type RunAnswers,
} from './api';
import {
  DEFAULT_TASK,
  dueIndexOf,
  dueKeyOf,
  fieldKindOf,
  isAnswered,
  logChoices,
  loggedText,
  missingKeys,
  missingText,
  runView,
  selfOnly,
  showsNotes,
  submitAnswers,
  targetIdOf,
  targetsOf,
  type RunItem,
  type RunnerRecord,
} from './runnerModel';

/**
 * PB7: the playbook window on record pages (27 Nov design, record-playbook.js `RP` and
 * record-playbook.css): header (minimize, "<Playbook> <Record>", maximize, close; drag, double
 * click), "Playbook contents" rail, the published playbook's blocks and questions, and the footer
 * (Log engagement ▾, follow-up task, "Draft saved"), with a resize grip. Answers are a draft on
 * the server; Log engagement logs them, writes property answers and adds the task.
 */

/** RP:613-618: 1240×860, at most the screen less 48 px, at least 640×420; centred. */
const SIZE = { w: 1240, h: 860, minW: 640, minH: 420 };
/** The size a person dragged the window to (RP:834), as the design keeps it. */
const GEO_KEY = 'crm.playbook.geo';
/** Below this width the window fills the screen (the design's popup-window rule). */
const MOBILE_WIDTH = 768;
/** RP:341: the draft is saved this long after the last change. */
const SAVE_DELAY_MS = 450;

const BUBBLE = (
  <>
    <path d="M5 3h11a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-5l-4 3.5V15H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z" />
    <path d="M20 8h.5A1.5 1.5 0 0 1 22 9.5v8a1.5 1.5 0 0 1-1.5 1.5H19v3l-3.5-3H11" />
    <path d="M8.6 7.3a2 2 0 1 1 2.6 1.9c-.5.2-.7.6-.7 1.1v.4M10.5 12.6h.01" />
  </>
);
function Svg({
  children,
  className,
  sw = 2,
}: {
  children: ReactNode;
  className?: string;
  sw?: number;
}) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={sw}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      {children}
    </svg>
  );
}
const Caret = () => (
  <svg className="pbw-caret" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
    <path d="M6 9h12l-6 7z" />
  </svg>
);
const WarnIcon = () => (
  <Svg className="pbw-ic pbw-ic--warn" sw={1.8}>
    <path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z" />
    <path d="M12 9v4M12 17h.01" />
  </Svg>
);
const CheckIcon = () => (
  <Svg>
    <path d="m5 12 5 5L20 7" />
  </Svg>
);

type Geo = { left: number; top: number; w: number; h: number };

function initialGeo(): Geo {
  const vw = window.innerWidth;
  const vh = window.innerHeight;
  let saved: { w?: number; h?: number } | null = null;
  try {
    saved = JSON.parse(localStorage.getItem(GEO_KEY) ?? 'null');
  } catch {
    saved = null;
  }
  let w = Math.min(saved?.w || SIZE.w, vw - 48);
  let h = Math.min(saved?.h || SIZE.h, vh - 48);
  w = Math.max(Math.min(SIZE.minW, vw - 16), w);
  h = Math.max(Math.min(SIZE.minH, vh - 16), h);
  return { left: Math.round((vw - w) / 2), top: Math.max(8, Math.round((vh - h) / 2)), w, h };
}

/** A linked record's custom property values, for "Current value" (loaded when picked). */
function loadValues(objectType: string, id: string): Promise<Record<string, unknown>> {
  if (objectType === 'contact') return getContact(id).then((r) => r.customProperties ?? {});
  if (objectType === 'company') return getCompany(id).then((r) => r.customProperties ?? {});
  if (objectType === 'deal') return getDeal(id).then((r) => r.customProperties ?? {});
  return getObjectRecord(objectType, id).then((r) => r.customProperties ?? {});
}

type SaveState = 'idle' | 'saving' | 'saved' | 'error';

export function PlaybookRunner({
  playbookId,
  playbookName,
  record,
  snippetTarget,
  onClose,
  onLogged,
}: {
  playbookId: string;
  playbookName: string;
  record: RunnerRecord;
  snippetTarget?: SnippetTarget;
  onClose: () => void;
  /** After logging: the page reloads its timeline, properties and tasks. */
  onLogged: () => void;
}) {
  const toast = useToast();
  const me = useCurrentUser();
  const prefs = useUserPrefs();
  const winRef = useRef<HTMLElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const [geo, setGeo] = useState<Geo | null>(null);
  const [minimized, setMinimized] = useState(false);
  const [maximized, setMaximized] = useState(false);
  const [run, setRun] = useState<PlaybookRun | null>(null);
  const [loadError, setLoadError] = useState(false);
  const [loadKey, setLoadKey] = useState(0);
  const [answers, setAnswers] = useState<RunAnswers>({});
  const [task, setTask] = useState<DraftTask>(DEFAULT_TASK);
  const [customDue, setCustomDue] = useState('');
  const [save, setSave] = useState<SaveState>('idle');
  const [defs, setDefs] = useState<Record<string, CustomPropertyDefinition[]>>({});
  const [values, setValues] = useState<Record<string, Record<string, unknown> | 'error'>>({});
  const [current, setCurrent] = useState<string | null>(null);
  const [logOpen, setLogOpen] = useState(false);
  const [logging, setLogging] = useState(false);
  const logRef = useRef<HTMLButtonElement>(null);
  const dirty = useRef(false);
  const ref = useMemo(
    () => ({ objectType: record.objectType, recordId: record.id }),
    [record.objectType, record.id],
  );

  // --- Load ---------------------------------------------------------------------------------
  useEffect(() => {
    let live = true;
    setLoadError(false);
    getPlaybookRun(playbookId, ref).then(
      (r) => {
        if (!live) return;
        setRun(r);
        setAnswers(r.draft?.answers ?? {});
        setTask(r.draft?.task ?? DEFAULT_TASK);
        setSave(r.draft ? 'saved' : 'idle');
      },
      () => live && setLoadError(true),
    );
    return () => {
      live = false;
    };
  }, [playbookId, ref, loadKey]);

  const view = useMemo(() => (run ? runView(run.content) : null), [run]);

  // Property definitions of each object the questions update.
  const propTypes = useMemo(
    () => [
      ...new Set(
        (view?.questions ?? []).flatMap(({ q }) =>
          q.kind === 'property' && q.objectType ? [q.objectType] : [],
        ),
      ),
    ],
    [view],
  );
  /** Definitions and linked records already asked for (one request each). */
  const requested = useRef(new Set<string>());
  useEffect(() => {
    for (const type of propTypes) {
      if (defs[type] || requested.current.has(`defs:${type}`)) continue;
      requested.current.add(`defs:${type}`);
      listCustomProperties({ objectType: type }).then(
        (list) => setDefs((d) => ({ ...d, [type]: list })),
        () => setDefs((d) => ({ ...d, [type]: [] })),
      );
    }
  }, [propTypes, defs]);
  const defOf = useCallback(
    (q: PlaybookQuestion) =>
      q.objectType ? defs[q.objectType]?.find((d) => d.name === q.property) : undefined,
    [defs],
  );

  // "Current value" of linked records that are picked (this record's come with the page).
  const valuesOf = useCallback(
    (objectType: string, id: string): Record<string, unknown> | 'error' | undefined =>
      objectType === record.objectType && id === record.id
        ? record.values
        : values[`${objectType}:${id}`],
    [record, values],
  );
  useEffect(() => {
    if (!view) return;
    for (const { key, q } of view.questions) {
      if (q.kind !== 'property' || !q.objectType) continue;
      const id = targetIdOf(q.objectType, record, answers[key]);
      const k = `${q.objectType}:${id}`;
      if (!id || valuesOf(q.objectType, id) !== undefined || requested.current.has(k)) continue;
      requested.current.add(k);
      loadValues(q.objectType, id).then(
        (vals) => setValues((v) => ({ ...v, [k]: vals })),
        () => setValues((v) => ({ ...v, [k]: 'error' })),
      );
    }
  }, [view, record, answers, valuesOf]);

  // --- Draft --------------------------------------------------------------------------------
  useEffect(() => {
    if (!run || !dirty.current) return;
    setSave('saving');
    const t = window.setTimeout(() => {
      savePlaybookDraft(playbookId, { ...ref, answers, task }).then(
        () => setSave('saved'),
        () => setSave('error'),
      );
    }, SAVE_DELAY_MS);
    return () => window.clearTimeout(t);
  }, [answers, task, run, playbookId, ref]);

  const setAnswer = (key: string, patch: Partial<RunAnswer>) => {
    dirty.current = true;
    setAnswers((a) => ({ ...a, [key]: { ...a[key], ...patch } }));
  };
  const changeTask = (patch: Partial<DraftTask>) => {
    dirty.current = true;
    setTask((t) => ({ ...t, ...patch }));
  };

  // --- Window -------------------------------------------------------------------------------
  useLayoutEffect(() => {
    if (window.innerWidth >= MOBILE_WIDTH) setGeo(initialGeo());
  }, []);

  useEffect(() => {
    const prev = document.activeElement as HTMLElement | null;
    winRef.current?.querySelector<HTMLElement>('[data-pbw-close]')?.focus({ preventScroll: true });
    return () => {
      if (prev && document.contains(prev)) prev.focus();
    };
  }, []);

  // RP:776-780: Esc closes a popover first (they handle it), then a maximized window restores,
  // then the window closes.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape' || e.defaultPrevented) return;
      const focus = document.activeElement;
      if (focus !== document.body && !winRef.current?.contains(focus)) return;
      if (maximized) setMaximized(false);
      else onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [maximized, onClose]);

  const drag = useRef<{ dx: number; dy: number } | null>(null);
  const onHeadDown = (e: ReactPointerEvent<HTMLElement>) => {
    if (e.button !== 0 || maximized || !geo || (e.target as Element).closest('button')) return;
    drag.current = { dx: e.clientX - geo.left, dy: e.clientY - geo.top };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onHeadMove = (e: ReactPointerEvent<HTMLElement>) => {
    const d = drag.current;
    if (!d) return;
    setGeo((g) =>
      g
        ? {
            ...g,
            left: Math.max(120 - g.w, Math.min(e.clientX - d.dx, window.innerWidth - 120)),
            top: Math.max(8, Math.min(e.clientY - d.dy, window.innerHeight - 56)),
          }
        : g,
    );
  };
  const onHeadUp = () => {
    drag.current = null;
  };

  const resize = useRef<{ x: number; y: number; w: number; h: number } | null>(null);
  const onGripDown = (e: ReactPointerEvent<HTMLElement>) => {
    if (e.button !== 0 || maximized || !geo) return;
    e.preventDefault();
    resize.current = { x: e.clientX, y: e.clientY, w: geo.w, h: geo.h };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onGripMove = (e: ReactPointerEvent<HTMLElement>) => {
    const r = resize.current;
    if (!r) return;
    setGeo((g) =>
      g
        ? {
            ...g,
            w: Math.max(SIZE.minW, Math.min(window.innerWidth - g.left - 8, r.w + e.clientX - r.x)),
            h: Math.max(SIZE.minH, Math.min(window.innerHeight - g.top - 8, r.h + e.clientY - r.y)),
          }
        : g,
    );
  };
  const onGripUp = () => {
    if (!resize.current) return;
    resize.current = null;
    if (geo) {
      try {
        localStorage.setItem(GEO_KEY, JSON.stringify({ w: geo.w, h: geo.h }));
      } catch {
        // Private mode: the size isn't kept.
      }
    }
  };

  // Highlight the question in view (RP:801-806).
  const onScroll = () => {
    const sc = scrollRef.current;
    if (!sc) return;
    const top = sc.getBoundingClientRect().top + 80;
    let cur: string | null = null;
    sc.querySelectorAll<HTMLElement>('[data-pbw-q]').forEach((el) => {
      if (el.getBoundingClientRect().top <= top) cur = el.dataset.pbwQ ?? null;
    });
    setCurrent(cur);
  };

  const goTo = (domId: string) => {
    const el = winRef.current?.querySelector<HTMLElement>(`#${CSS.escape(domId)}`);
    if (!el) return;
    el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    const f = el.querySelector<HTMLElement>('[data-pbw-focus], [contenteditable], input, button');
    if (f) window.setTimeout(() => f.focus({ preventScroll: true }), 350);
  };

  // --- Log engagement -----------------------------------------------------------------------
  const missing = view ? missingKeys(view.questions, answers) : [];
  const choices = run ? logChoices(run.settings.engagements) : [];

  const log = async (engagement: LogType) => {
    setLogOpen(false);
    if (!run || !view) return;
    if (missing.length) {
      goTo(`pbw-${missing[0]}`);
      toast(missingText(missing.length), 'danger');
      return;
    }
    const prepared = submitAnswers(view.questions, answers, defOf, prefs.timeZone);
    if ('error' in prepared) {
      goTo(`pbw-${prepared.key}`);
      toast(prepared.error, 'danger');
      return;
    }
    setLogging(true);
    try {
      const result = await submitPlaybook(run.id, {
        ...ref,
        engagement,
        answers: prepared.answers,
        ...(task.create && {
          task: {
            title: `Follow up with ${record.name}`,
            taskType: task.taskType,
            dueDate: followUpDueDate(dueKeyOf(task.due), prefs.timeZone, customDue),
          },
        }),
      });
      dirty.current = false;
      toast(
        loggedText(
          engagement,
          result.updated.length,
          result.skipped.length,
          Boolean(result.taskId),
        ),
        'success',
      );
      onLogged();
      onClose();
    } catch (err) {
      toast(actionErrorText(err), 'danger');
    } finally {
      setLogging(false);
    }
  };

  // --- Render -------------------------------------------------------------------------------
  const style =
    geo && !maximized ? { left: geo.left, top: geo.top, width: geo.w, height: geo.h } : undefined;

  const renderItem = (item: RunItem) =>
    item.kind === 'question' ? (
      <Question
        key={item.key}
        qKey={item.key}
        q={item.q}
        answer={answers[item.key]}
        record={record}
        def={defOf(item.q)}
        valuesOf={valuesOf}
        snippetTarget={snippetTarget}
        onChange={(patch) => setAnswer(item.key, patch)}
        currency={me.business.currency}
      />
    ) : (
      <BlockView key={item.key} block={item.block} />
    );

  return (
    <section
      ref={winRef}
      className={cn('pbw is-open', minimized && 'is-min', maximized && 'pw-max')}
      role="dialog"
      aria-labelledby="pbwTitle"
      style={style}
    >
      <header
        className="pbw__head"
        onPointerDown={onHeadDown}
        onPointerMove={onHeadMove}
        onPointerUp={onHeadUp}
        onPointerCancel={onHeadUp}
        onDoubleClick={(e) => {
          if (!(e.target as Element).closest('button')) setMaximized((m) => !m);
        }}
      >
        <button
          type="button"
          className="pbw__hbtn pbw__collapse"
          aria-label={minimized ? 'Expand' : 'Minimize'}
          title={minimized ? 'Expand' : 'Minimize'}
          onClick={() => {
            setMaximized(false);
            setMinimized((m) => !m);
          }}
        >
          <CrmIcon name="chevron-down" className="iconSize-18" />
        </button>
        <h2 className="pbw__title" id="pbwTitle">
          <strong>{run?.name ?? playbookName}</strong>
          <span>{record.name}</span>
        </h2>
        <button
          type="button"
          className="pbw__hbtn"
          aria-label={maximized ? 'Restore' : 'Maximize'}
          title={maximized ? 'Restore' : 'Maximize'}
          onClick={() => {
            setMinimized(false);
            setMaximized((m) => !m);
          }}
        >
          <CrmIcon name={maximized ? 'minimize' : 'maximize'} className="iconSize-18" />
        </button>
        <button
          type="button"
          className="pbw__hbtn"
          data-pbw-close
          aria-label="Close"
          title="Close"
          onClick={onClose}
        >
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>

      <div className="pbw__body">
        {loadError ? (
          <div className="pbw__state" role="alert">
            <p>Couldn&rsquo;t load this playbook.</p>
            <button
              type="button"
              className="btn-crm btn-crm--sm"
              onClick={() => setLoadKey((k) => k + 1)}
            >
              Retry
            </button>
          </div>
        ) : !view ? (
          <div className="pbw__state" aria-busy="true">
            <p>Loading…</p>
          </div>
        ) : (
          <>
            <nav className="pbw__nav" aria-label="Playbook contents">
              <h3>Playbook contents</h3>
              <ol className="pbw__navlist">
                {view.intro
                  .filter((i) => i.kind === 'question')
                  .map((i) => (
                    <NavQuestion
                      key={i.key}
                      item={i}
                      answered={isAnswered(answers[i.key])}
                      current={current === i.key}
                      onGo={goTo}
                    />
                  ))}
                {view.sections.map((s) => (
                  <SectionNav
                    key={s.id}
                    title={s.title}
                    id={s.id}
                    items={s.items}
                    answers={answers}
                    current={current}
                    onGo={goTo}
                  />
                ))}
              </ol>
            </nav>
            <div className="pbw__content" ref={scrollRef} onScroll={onScroll}>
              {view.intro.map(renderItem)}
              {view.sections.map((s) => (
                <div key={s.id}>
                  <h2 className="pbw-sec" id={s.id}>
                    {s.title}
                  </h2>
                  {s.items.map(renderItem)}
                </div>
              ))}
            </div>
          </>
        )}
      </div>

      <footer className="pbw__foot">
        <button
          ref={logRef}
          type="button"
          className={cn('pbw-log', run && !missing.length && 'is-ready')}
          aria-haspopup="menu"
          aria-expanded={logOpen}
          disabled={!run || logging || !record.canLog || !choices.length}
          title={
            !record.canLog
              ? "You don't have permission to log activity"
              : missing.length
                ? `${missing.length} required question${missing.length > 1 ? 's' : ''} left`
                : 'Log your answers to the record'
          }
          onClick={() => setLogOpen((o) => !o)}
        >
          {logging ? 'Logging…' : 'Log engagement'} <Caret />
        </button>
        <AnchoredPopover
          open={logOpen}
          anchorRef={logRef}
          onClose={() => setLogOpen(false)}
          preferred="up"
          menu
          returnFocus
          label="Log engagement"
          className="pbw-float pbw-float__menu"
        >
          <div role="menu">
            {choices.map((c) => (
              <button key={c.key} type="button" role="menuitem" onClick={() => void log(c.key)}>
                {c.label}
              </button>
            ))}
          </div>
        </AnchoredPopover>
        <div className="pbw-follow">
          <FollowUpTaskControls
            composer
            enabled={task.create}
            onEnabledChange={(v) => changeTask({ create: v })}
            taskType={task.taskType}
            onTaskTypeChange={(v) => changeTask({ taskType: v, create: true })}
            dueKey={dueKeyOf(task.due)}
            onDueKeyChange={(k) => changeTask({ due: dueIndexOf(k), create: true })}
            customDate={customDue}
            onCustomDateChange={setCustomDue}
            timeZone={prefs.timeZone}
          />
        </div>
        <span className="pbw-saved" aria-live="polite">
          {save === 'saving' ? (
            'Saving…'
          ) : save === 'saved' ? (
            <>
              <CheckIcon />
              Draft saved
            </>
          ) : save === 'error' ? (
            'Draft not saved'
          ) : null}
        </span>
      </footer>
      {!maximized && geo ? (
        <span
          className="pbw__grip"
          aria-hidden
          onPointerDown={onGripDown}
          onPointerMove={onGripMove}
          onPointerUp={onGripUp}
          onPointerCancel={onGripUp}
        />
      ) : null}
    </section>
  );
}

function NavQuestion({
  item,
  answered,
  current,
  onGo,
}: {
  item: Extract<RunItem, { kind: 'question' }>;
  answered: boolean;
  current: boolean;
  onGo: (id: string) => void;
}) {
  const required = item.q.required && !answered;
  return (
    <li>
      <a
        href={`#pbw-${item.key}`}
        className={cn(current && 'is-current')}
        title={item.q.text}
        onClick={(e) => {
          e.preventDefault();
          onGo(`pbw-${item.key}`);
        }}
      >
        <span
          className="pbw-nav__s"
          aria-label={answered ? 'Answered' : required ? 'Required, not answered' : 'Optional'}
        >
          {required ? (
            <WarnIcon />
          ) : (
            <Svg className="pbw-ic pbw-ic--q" sw={1.5}>
              {BUBBLE}
            </Svg>
          )}
        </span>
        <span className="pbw-nav__t">{item.q.text}</span>
      </a>
    </li>
  );
}

function SectionNav({
  title,
  id,
  items,
  answers,
  current,
  onGo,
}: {
  title: string;
  id: string;
  items: RunItem[];
  answers: RunAnswers;
  current: string | null;
  onGo: (id: string) => void;
}) {
  return (
    <>
      <li className="pbw-nav__sec">
        <a
          href={`#${id}`}
          onClick={(e) => {
            e.preventDefault();
            onGo(id);
          }}
        >
          {title}
        </a>
      </li>
      {items.map((i) =>
        i.kind === 'question' ? (
          <NavQuestion
            key={i.key}
            item={i}
            answered={isAnswered(answers[i.key])}
            current={current === i.key}
            onGo={onGo}
          />
        ) : null,
      )}
    </>
  );
}

/** Text, images, videos, embeds, actions and documents, shown as the editor's preview. */
function BlockView({ block }: { block: PlaybookBlock }) {
  switch (block.type) {
    case 'p':
    case 'h1':
    case 'h2':
    case 'h3':
      return <div className="pbw-intro" dangerouslySetInnerHTML={{ __html: block.html }} />;
    case 'h4':
      return <h4 className="pbw-h4" dangerouslySetInnerHTML={{ __html: block.html }} />;
    case 'image':
      // eslint-disable-next-line @next/next/no-img-element
      return <img className="pbw-media" src={block.src} alt={block.alt} />;
    case 'video':
    case 'embed':
      return (
        <iframe
          className="pbw-media pbw-media--frame"
          src={block.url}
          title={block.type === 'video' ? 'Video' : 'Embedded content'}
          sandbox="allow-scripts allow-same-origin allow-presentation"
          allowFullScreen
        />
      );
    case 'action':
      return <p className="pbw-chip">{block.label}</p>;
    case 'doc':
      return <p className="pbw-chip">{block.name}</p>;
    default:
      return null;
  }
}

function Question({
  qKey,
  q,
  answer,
  record,
  def,
  valuesOf,
  snippetTarget,
  onChange,
  currency,
}: {
  qKey: string;
  q: PlaybookQuestion;
  answer: RunAnswer | undefined;
  record: RunnerRecord;
  def: CustomPropertyDefinition | undefined;
  valuesOf: (type: string, id: string) => Record<string, unknown> | 'error' | undefined;
  snippetTarget?: SnippetTarget;
  onChange: (patch: Partial<RunAnswer>) => void;
  currency?: string;
}) {
  const prefs = useUserPrefs();
  const answered = isAnswered(answer);
  const labelId = `pbw-l-${qKey}`;
  const kind = fieldKindOf(q);
  const value = answer?.value;

  let field: ReactNode;
  if (kind === 'rich') {
    field = (
      <ComposeRichText
        openKey={qKey}
        value={typeof value === 'string' ? value : ''}
        onChange={(html) => onChange({ value: html })}
        label={q.text}
        placeholder="Type your answer"
        minHeight={44}
        snippetTarget={snippetTarget}
        noFiles
      />
    );
  } else if (kind === 'select') {
    field = (
      <CustomSelect
        id={`pbw-in-${qKey}`}
        placeholder=""
        value={typeof value === 'string' ? value : ''}
        options={q.options.map((o) => ({ value: o, label: o }))}
        searchable={q.options.length > 6}
        onChange={(v) => onChange({ value: v })}
        className="pbw-dd"
        portal
      />
    );
  } else if (kind === 'checks') {
    const picked = Array.isArray(value) ? value : [];
    field = (
      <div className="pbw-opts" role="group" aria-labelledby={labelId}>
        {q.options.map((o) => (
          <label key={o} className="pbw-opt">
            <input
              type="checkbox"
              checked={picked.includes(o)}
              onChange={(e) =>
                onChange({
                  value: e.target.checked ? [...picked, o] : picked.filter((x) => x !== o),
                })
              }
            />
            <span>{o}</span>
          </label>
        ))}
      </div>
    );
  } else if (def) {
    field = (
      <CustomFieldInput
        def={def}
        id={`pbw-in-${qKey}`}
        value={value ?? (def.type === 'multiselect' ? [] : '')}
        onChange={(v) => onChange({ value: v })}
        designSelect
      />
    );
  } else {
    field = <p className="pbw-q__cur">This property is no longer available.</p>;
  }

  let property: ReactNode = null;
  if (kind === 'property' && q.objectType) {
    const objectType = q.objectType;
    const targets = targetsOf(objectType, record);
    const targetId = targetIdOf(objectType, record, answer);
    const propLabel = def?.label ?? q.property ?? q.text;
    const vals = targetId ? valuesOf(objectType, targetId) : undefined;
    const raw = vals && vals !== 'error' && def ? vals[def.name] : undefined;
    const cur =
      vals === 'error'
        ? 'couldn’t load'
        : def
          ? formatCustomValue(def, toStoredForDisplay(raw), currency, (iso) =>
              formatUserDate(iso, { region: prefs.regionFormat, timeZone: prefs.timeZone }),
            )
          : '--';
    const solo = selfOnly(objectType, record) || !targets.length;
    property = (
      <>
        <p className="pbw-q__sub">
          {solo
            ? `Update ${objectType} property (${propLabel})`
            : `Select ${objectType} to update property (${propLabel})`}
        </p>
        {!answered ? <p className="pbw-q__cur">Current value: {cur}</p> : null}
        {solo ? (
          <div className="pbw-q__field pbw-q__field--wide">{field}</div>
        ) : (
          <div className="pbw-q__row">
            <TargetPicker
              targets={targets}
              value={targetId}
              onPick={(id) => onChange({ targetId: id })}
            />
            <div className="pbw-q__field">{field}</div>
          </div>
        )}
      </>
    );
  }

  return (
    <div
      className={cn('pbw-q', q.required && !answered && 'is-invalid')}
      id={`pbw-${qKey}`}
      data-pbw-q={qKey}
    >
      <span className="pbw-q__icon">
        <Svg sw={1.6}>{BUBBLE}</Svg>
      </span>
      <div className="pbw-q__main">
        <h4 className="pbw-q__label" id={labelId}>
          <span>{q.text}</span>
          {q.required ? (
            <span className="pbw-req" aria-label="required">
              *
            </span>
          ) : null}
        </h4>
        {property ?? <div className="pbw-q__field pbw-q__field--wide">{field}</div>}
        {q.required && !answered ? (
          <p className="pbw-err">Response is required for this question</p>
        ) : null}
        {showsNotes(q) ? (
          <div className="pbw-q__notes">
            <ComposeRichText
              openKey={`${qKey}-notes`}
              value={answer?.notes ?? ''}
              onChange={(html) => onChange({ notes: html })}
              label={`Notes: ${q.text}`}
              placeholder="Notes"
              minHeight={44}
              snippetTarget={snippetTarget}
              noFiles
            />
          </div>
        ) : null}
      </div>
    </div>
  );
}

/** A stored value as `formatCustomValue` takes it. */
const toStoredForDisplay = (raw: unknown) => raw as Parameters<typeof formatCustomValue>[1];

/** "<Company> Primary ▾" (RP:235-239, 710-719): the record a property answer goes to. */
function TargetPicker({
  targets,
  value,
  onPick,
}: {
  targets: Array<{ id: string; name: string; primary: boolean }>;
  value: string | null;
  onPick: (id: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const btn = useRef<HTMLButtonElement>(null);
  const cur = targets.find((t) => t.id === value) ?? targets[0];
  if (!cur) return null;
  return (
    <>
      <button
        ref={btn}
        type="button"
        className="pbw-target"
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={`Record to update: ${cur.name}`}
        onClick={() => setOpen((o) => !o)}
      >
        <span className="pbw-target__n">{cur.name}</span>
        {cur.primary ? <span className="pbw-pill">Primary</span> : null}
        <Caret />
      </button>
      <AnchoredPopover
        open={open}
        anchorRef={btn}
        onClose={() => setOpen(false)}
        returnFocus
        label="Record to update"
        className="pbw-float pbw-float--list pbw-float--target"
      >
        <ul className="pbw-float__list" role="listbox">
          {targets.map((t) => (
            <li
              key={t.id}
              role="option"
              tabIndex={-1}
              aria-selected={t.id === cur.id}
              onClick={() => {
                setOpen(false);
                onPick(t.id);
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  setOpen(false);
                  onPick(t.id);
                }
              }}
            >
              <span>{t.name}</span>
              {t.primary ? <span className="pbw-pill">Primary</span> : null}
            </li>
          ))}
        </ul>
      </AnchoredPopover>
    </>
  );
}
