'use client';

import Link from 'next/link';
import {
  useCallback,
  useEffect,
  useMemo,
  useReducer,
  useRef,
  useState,
  type ReactNode,
} from 'react';
import { Alert } from '@/components/crm/Alert';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { listCompanies } from '@/features/companies/api.client';
import {
  createContact,
  findCompanyByEmailDomain,
  findContactDuplicates,
} from '@/features/contacts/api.client';
import type { Contact, CreateContactBody } from '@/features/contacts/types';
import {
  getCreateForm,
  standardLabels,
  type CreateFormField,
} from '@/features/create-forms/api.client';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import {
  applyPropertyLogic,
  propertyLogicValues,
  usePropertyLogic,
} from '@/features/custom-properties/logic';
import { linkRecords, listLinkLabels } from '@/features/objects/api.client';
import { ownerOnCreate } from '@/features/owners/labels';
import type { FieldAccess } from '@/features/permission-sets/field-access';
import { getPrivacySettings } from '@/features/settings/api.client';
import { isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  emailError,
  isValidEmail,
  phoneError,
  sanitizePhoneInput,
} from '@/lib/validation/contact-company';
import {
  CustomFieldsForm,
  customValuesForCreate,
  type CustomUiValue,
} from './actions/custom-fields';
import {
  contactFieldLabel,
  customFieldProblem,
  focusFirstInvalid,
  placeFieldErrors,
} from './actions/fieldErrors';
import {
  DUPLICATE_EMAIL_LOOKUP_MS,
  emailAnswers,
  createBlocked,
  emailFieldMessage,
  emailLookupKey,
  NO_EMAIL_ANSWERS,
  shownDuplicates,
} from './contactEmailDuplicates';
import {
  domainAnswers,
  domainHint,
  domainLookupKey,
  DomainSuggestionHint,
  NO_DOMAIN_ANSWERS,
} from './contactDomainSuggestion';
import { DuplicateContactNotice } from './DuplicateContactNotice';

/** Same values the API accepts (`LEGAL_BASIS_VALUES`). */
const LEGAL_BASIS: CustomSelectOption[] = [
  { value: 'legitimate_interest_lead', label: 'Legitimate interest – prospect/lead' },
  { value: 'legitimate_interest_customer', label: 'Legitimate interest – existing customer' },
  { value: 'legitimate_interest_other', label: 'Legitimate interest – other' },
  { value: 'contract', label: 'Performance of a contract' },
  { value: 'consent', label: 'Freely given consent from contact' },
  { value: 'not_applicable', label: 'Not applicable' },
];

const DEFAULT_FIELDS: CreateFormField[] = [
  { field: 'email', required: true },
  { field: 'firstName', required: true },
  { field: 'lastName', required: true },
  { field: 'companyName', required: true },
  { field: 'jobTitle', required: false },
  { field: 'phone', required: false },
  { field: 'ownerId', required: false },
  { field: 'lifecycleStage', required: false },
  { field: 'leadStatus', required: false },
];

/** HubSpot's create form opens with only these editable; the rest unlock once one is filled. */
const IDENTITY_FIELDS = new Set(['email', 'firstName', 'lastName']);
/** The design's email check (create-form.js:275). */
export const EMAIL_INVALID = 'Enter a valid email address, like name@company.com.';

type Form = {
  email: string;
  firstName: string;
  lastName: string;
  /** HubSpot's "Company name" text property. */
  companyName: string;
  jobTitle: string;
  phone: string;
  ownerId: string;
  lifecycleStage: string;
  leadStatus: string;
  legalBasis: string;
  /** The company linked in the Associations section, and its name for the picker. */
  companyId: string;
  linkedCompanyName: string;
  labelId: string;
};

type TextKey = 'email' | 'firstName' | 'lastName' | 'companyName' | 'jobTitle' | 'phone';

/**
 * D-18: each text input's type and the most characters the browser lets it take. As email, the
 * names, Company name and Job title take any length: an over-long one reaches the API, and its
 * limit shows under the field as "<Label> can be at most N characters." (CQ1), not cut off.
 */
export const CREATE_TEXT_INPUTS: Record<TextKey, { type?: string; maxLength?: number }> = {
  email: { type: 'email' },
  firstName: {},
  lastName: {},
  companyName: {},
  jobTitle: {},
  phone: { type: 'tel', maxLength: 16 },
};

/** The message after a create: `Contact "Ada Lovelace" created` (create-form.js). */
export function contactCreatedMessage(
  contact: Pick<Contact, 'firstName' | 'lastName' | 'email'>,
  singular = 'Contact',
): string {
  const name = [contact.firstName, contact.lastName].filter(Boolean).join(' ');
  return `${singular} "${name || contact.email || singular}" created`;
}

/**
 * A picklist value of a new contact: the one picked, else the design's default ("Lead", "New").
 * Picklists are per business, so a business without that option gets none.
 */
export function picklistOnCreate(
  picked: string,
  options: CustomSelectOption[],
  fallback: string,
): string | null {
  return picked || (options.some((o) => o.value === fallback) ? fallback : null);
}

/** A value the form opens with: the board column "+ Contact" was clicked on. */
export type CreatePrefill = { field: string; value: string };

const customName = (field: string) =>
  field.startsWith('custom.') ? field.slice('custom.'.length) : null;

/**
 * Whether a new contact can take this value of a board's grouping field. The form can't set the
 * others (team, additional owners, email status, source), and "Me" would land in a named column.
 */
export function canPrefill(
  { field, value }: CreatePrefill,
  {
    ownerOptions,
    lifecycleOptions,
    leadStatusOptions,
    customDefs,
    access,
  }: {
    ownerOptions: CustomSelectOption[];
    lifecycleOptions: CustomSelectOption[];
    leadStatusOptions: CustomSelectOption[];
    customDefs: CustomPropertyDefinition[];
    access: Pick<FieldAccess, 'locked'>;
  },
): boolean {
  if (access.locked(field)) return false;
  const name = customName(field);
  if (name) {
    const def = customDefs.find((d) => d.name === name);
    return Boolean(
      def &&
      def.type === 'select' &&
      !def.readOnly &&
      !def.calculated &&
      def.options?.some((o) => o.value === value && !o.archived),
    );
  }
  const options =
    field === 'ownerId'
      ? ownerOptions
      : field === 'lifecycleStage'
        ? lifecycleOptions
        : field === 'leadStatus'
          ? leadStatusOptions
          : [];
  return options.some((o) => o.value === value);
}

// The design's form starts with every dropdown on "Select" (owner, lifecycle stage, lead status).
// A company picked already ("Other contacts at <company>") also fills in Company name.
const emptyForm = (_ownerId: string, companyId = '', linkedCompanyName = ''): Form => ({
  email: '',
  firstName: '',
  lastName: '',
  companyName: linkedCompanyName,
  jobTitle: '',
  phone: '',
  ownerId: '',
  lifecycleStage: '',
  leadStatus: '',
  companyId,
  linkedCompanyName,
  labelId: '',
  legalBasis: '',
});

/**
 * CQ1 #23: the form starts fresh when `open` changes either way. The design removes its panel on
 * close (create-form.js:350-354); this one stays mounted for its slide-in (CT-003), so it is
 * emptied instead, during render, so neither the closed drawer nor a reopen's first frame shows
 * the last value or error.
 */
export function openChange(wasOpen: boolean, open: boolean): 'opened' | 'closed' | null {
  if (wasOpen === open) return null;
  return open ? 'opened' : 'closed';
}

/**
 * The company part of the create: the one picked in Associate record (or the drawer was opened
 * with); else QA D-08, the company of the email's domain, which the API links or makes.
 */
export function companyOnCreate(
  companyId: string,
): Pick<CreateContactBody, 'companyIds' | 'primaryCompanyId' | 'associateCompanyByDomain'> {
  return companyId
    ? { companyIds: [companyId], primaryCompanyId: companyId }
    : { associateCompanyByDomain: true };
}

/**
 * The Company name a create sends: left out (undefined) when the field isn't on the form, else
 * trimmed, or null when blank. G5's hint names a new company by it, as the API does
 * (`blank(companyName) ?? domain`), so both read this one function.
 */
export function companyNameOnCreate(value: string, onForm: boolean): string | null | undefined {
  return onForm ? value.trim() || null : undefined;
}

/** A fresh form: empty, but for the company or board value the drawer was opened with. */
export function freshCreate(
  prefill: CreatePrefill | null | undefined,
  prefillCompany: { id: string; name: string } | null | undefined,
): { form: Form; custom: Record<string, CustomUiValue> } {
  const name = prefill ? customName(prefill.field) : null;
  return {
    form: {
      ...emptyForm('', prefillCompany?.id, prefillCompany?.name),
      ...(prefill && !name ? { [prefill.field]: prefill.value } : {}),
    },
    custom: prefill && name ? { [name]: prefill.value } : {},
  };
}

/**
 * CQ1 #3: whether the person sees and can edit a field on this form, so a rejected value's
 * message can go under it: the standard fields shown (the permission set's locked ones are left
 * out already) and the custom fields shown after property logic.
 */
export function createOnForm(
  standardShown: string[],
  customShown: Pick<CustomPropertyDefinition, 'name'>[],
): (key: string) => boolean {
  return (key) => {
    const name = customName(key);
    return name ? customShown.some((d) => d.name === name) : standardShown.includes(key);
  };
}

/**
 * CQ1 #3: where a failed create says why: each field the API names under that field, the rest
 * in the top alert in words; an error naming no field keeps master's alert (its message).
 */
export function createFailure(
  err: unknown,
  onForm: (key: string) => boolean,
  customDefs: CustomPropertyDefinition[],
): { fields: Record<string, string>; form: string | null } {
  const placed = placeFieldErrors(err, {
    onForm,
    labelOf: (key) => contactFieldLabel(key, customDefs),
  });
  if (placed) return placed;
  return { fields: {}, form: isApiError(err) ? err.message : 'Could not create the contact.' };
}

/**
 * HUB-619 / HUB-593: the "Create contact" drawer, as HubSpot's: the fields of the business's
 * create form (Settings > Objects > Contacts > Setup) in its order, required ones marked and
 * checked with the error under the field (the design's words, CQ1); never read-only,
 * calculated or system fields. Required custom fields always show (the API needs them). The
 * company search asks the API, so every company can be found (sheet #149), and the link can
 * take an association label. "Create and add another" keeps the drawer open.
 */
export function CreateContactDrawer({
  open,
  singular,
  defaultOwnerId,
  ownerOptions,
  lifecycleOptions,
  leadStatusOptions,
  customDefs,
  access,
  timeZone,
  prefillCompany,
  prefill,
  onClose,
  onCreated,
}: {
  open: boolean;
  /** The object's label: "Create Contact", `Contact "Ada" created`. */
  singular: string;
  defaultOwnerId: string;
  ownerOptions: CustomSelectOption[];
  lifecycleOptions: CustomSelectOption[];
  leadStatusOptions: CustomSelectOption[];
  customDefs: CustomPropertyDefinition[];
  access: FieldAccess;
  timeZone: string;
  /** "+ Add" from "Other contacts at <company>": the company is picked already. */
  prefillCompany?: { id: string; name: string } | null;
  /** "+ Contact" on a board column: that column's value is picked already. */
  prefill?: CreatePrefill | null;
  onClose: () => void;
  onCreated: (contact: Contact) => void;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const isAdmin = Boolean(me.permissionSet.rules.app.manage_settings);
  const [loadedFields, setLoadedFields] = useState<CreateFormField[]>(DEFAULT_FIELDS);
  const formFields = useMemo(
    () =>
      // A form without the field would leave the value out, so the card lands in another column.
      prefill && !loadedFields.some((f) => f.field === prefill.field)
        ? [...loadedFields, { field: prefill.field, required: false }]
        : loadedFields,
    [loadedFields, prefill],
  );
  const [form, setForm] = useState<Form>(() => emptyForm(defaultOwnerId));
  const [custom, setCustom] = useState<Record<string, CustomUiValue>>({});
  const [privacyOn, setPrivacyOn] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formError, setFormError] = useState<string | null>(null);
  const [saving, setSaving] = useState<false | 'one' | 'another'>(false);
  const [labels, setLabels] = useState<CustomSelectOption[]>([]);
  /** D-07: the duplicate lookups' answers, by the email each asked about. */
  const [emailUsed, answerEmail] = useReducer(emailAnswers, NO_EMAIL_ANSWERS);
  /** G5: what Create would do with the email's domain, by the email each lookup asked about. */
  const [domainFound, answerDomain] = useReducer(domainAnswers, NO_DOMAIN_ANSWERS);
  const propertyLogic = usePropertyLogic('contact');
  const formRef = useRef<HTMLFormElement>(null);

  const reset = useCallback(() => {
    const fresh = freshCreate(prefill, prefillCompany);
    setForm(fresh.form);
    setCustom(fresh.custom);
    setErrors({});
    setFormError(null);
    // A contact just made with "Create and add another" must not keep its "not used" answer.
    answerEmail({ type: 'reset' });
    answerDomain({ type: 'reset' });
  }, [prefillCompany, prefill]);

  // CQ1 #23: fresh on open and on close, during render (see openChange); and, as master's open
  // effect did, when the opener's company or board value changes while open.
  const prefillKey = [prefill?.field, prefill?.value, prefillCompany?.id, prefillCompany?.name]
    .map((v) => v ?? '')
    .join('\u0000');
  // Starts as closed, so a drawer mounted open starts fresh too (master's effect did).
  const [seen, setSeen] = useState({ open: false, prefillKey: '' });
  if (openChange(seen.open, open) || (open && seen.prefillKey !== prefillKey)) {
    setSeen({ open, prefillKey });
    reset();
  }

  useEffect(() => {
    if (!open) return;
    getPrivacySettings().then(
      (s) => setPrivacyOn(s.enabled),
      () => setPrivacyOn(false),
    );
    getCreateForm('contact').then(
      (res) => setLoadedFields(res.fields),
      () => setLoadedFields(DEFAULT_FIELDS),
    );
    listLinkLabels('contact', 'company').then(
      (rows) =>
        setLabels(
          rows.map((l) => ({
            value: l.id,
            // As the contact reads it: the a-side name, else the inverse name (HUB-233).
            label: l.aType === 'contact' ? l.name : (l.inverseName ?? l.name),
          })),
        ),
      () => setLabels([]),
    );
  }, [open, reset]);

  // The design focuses the first field (Email) when the panel opens.
  useEffect(() => {
    if (!open) return;
    const t = window.setTimeout(
      () => formRef.current?.querySelector<HTMLElement>('input, textarea')?.focus(),
      120,
    );
    return () => window.clearTimeout(t);
  }, [open]);

  // CT-003: closing makes the drawer inert, which drops focus on <body>; give it back to the
  // control that opened the drawer ("Add contacts"), as LpSide does.
  useEffect(() => {
    if (!open) return;
    const opener = document.activeElement as HTMLElement | null;
    return () => {
      if (opener && opener !== document.body && opener.isConnected) {
        opener.focus({ preventScroll: true });
      }
    };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    document.documentElement.classList.add('company-drawer-open');
    document.body.classList.add('company-drawer-open');
    return () => {
      document.documentElement.classList.remove('company-drawer-open');
      document.body.classList.remove('company-drawer-open');
    };
  }, [open]);

  /** The form's standard fields the permission set lets this person set, in order. */
  const standard = formFields.filter(
    (f) => !f.field.startsWith('custom.') && !access.locked(f.field),
  );
  const required = new Set(formFields.filter((f) => f.required).map((f) => f.field));
  const identity = standard.filter((f) => IDENTITY_FIELDS.has(f.field));
  const others = standard.filter((f) => !IDENTITY_FIELDS.has(f.field));
  // As HubSpot: everything below the name and email stays dimmed and inert until a valid email,
  // a first name or a last name is typed. Without any identity field on the form, nothing locks.
  const locked =
    identity.length > 0 &&
    !isValidEmail(form.email) &&
    !form.firstName.trim() &&
    !form.lastName.trim();

  // D-07: once a whole email is typed and typing pauses, say whether a contact already uses it.
  // Only for an Email the person can set (`standard` leaves locked fields out).
  const emailKey = open
    ? emailLookupKey(
        form.email,
        standard.some((f) => f.field === 'email'),
      )
    : null;
  const emailRound = emailUsed.round;
  useEffect(() => {
    if (!emailKey) return;
    const t = window.setTimeout(() => {
      // Kept by email and round, so an answer arriving late never shows for another email, nor
      // after a reset. A failed lookup shows nothing and blocks nothing; Create still gets the
      // API's 409.
      findContactDuplicates(emailKey).then(
        (found) =>
          answerEmail({
            type: 'answer',
            email: emailKey,
            matches: found.matches,
            hidden: found.hidden,
            round: emailRound,
          }),
        () => answerEmail({ type: 'failed', email: emailKey }),
      );
    }, DUPLICATE_EMAIL_LOOKUP_MS);
    return () => window.clearTimeout(t);
  }, [emailKey, emailRound]);
  // G5: with no company picked, after the same pause, ask what Create would do with the email's
  // domain (D-08). Kept by email and round as above; a failed lookup shows no line.
  const domainKey = domainLookupKey(emailKey, Boolean(form.companyId));
  const domainRound = domainFound.round;
  useEffect(() => {
    if (!domainKey) return;
    const t = window.setTimeout(() => {
      findCompanyByEmailDomain(domainKey).then(
        (suggestion) =>
          answerDomain({ type: 'answer', email: domainKey, round: domainRound, suggestion }),
        () => answerDomain({ type: 'failed', email: domainKey }),
      );
    }, DUPLICATE_EMAIL_LOOKUP_MS);
    return () => window.clearTimeout(t);
  }, [domainKey, domainRound]);
  /** Only the fields on the form, and never the ones the permission set locks (HUB-317). */
  const onForm = (field: string) =>
    standard.some((f) => f.field === field) && !access.locked(field);
  const suggestion = domainHint(
    domainKey,
    domainFound,
    companyNameOnCreate(form.companyName, onForm('companyName')) ?? null,
  );
  /** D07b: the contacts using the typed email (the card), and whether Create is off for it. */
  const duplicate = shownDuplicates(emailKey, emailUsed);
  const blocked = createBlocked(emailKey, emailUsed);
  /** The message under a field: Email's also says when the typed email is already used. */
  const messageOf = (field: string): string | undefined =>
    field === 'email' ? emailFieldMessage(errors.email, emailKey, emailUsed) : errors[field];
  /** The form's custom fields, then required custom fields it leaves out (the API needs them). */
  const formCustom = useMemo(() => {
    const byName = new Map(customDefs.map((d) => [d.name, d]));
    const listed = formFields
      .filter((f) => f.field.startsWith('custom.'))
      .flatMap((f) => {
        const def = byName.get(f.field.slice('custom.'.length));
        return def && !def.readOnly && !def.calculated
          ? [{ ...def, required: def.required || f.required }]
          : [];
      });
    const extra = customDefs.filter(
      (d) => d.required && !d.readOnly && !d.calculated && !listed.some((l) => l.name === d.name),
    );
    return applyPropertyLogic(
      [...listed, ...extra],
      propertyLogic,
      propertyLogicValues(
        'contact',
        { lifecycleStage: form.lifecycleStage, leadStatus: form.leadStatus },
        custom,
      ),
    );
  }, [customDefs, formFields, propertyLogic, custom, form.lifecycleStage, form.leadStatus]);

  const label = (field: string) => standardLabels('contact')[field] ?? field;
  const clearError = (field: string) =>
    setErrors((e) => {
      const rest = { ...e };
      delete rest[field];
      return rest;
    });
  const setField = (key: keyof Form, value: string) => {
    setForm((f) => ({ ...f, [key]: value }));
    clearError(key);
  };

  const validate = (): Record<string, string> => {
    const out: Record<string, string> = {};
    const need = (field: string, empty: boolean) => {
      // A field the permission set locks is not on the form, so it can't block Create.
      if (required.has(field) && empty && !access.locked(field)) {
        out[field] = `${label(field)} is required.`;
      }
    };
    need('email', !form.email.trim());
    need('firstName', !form.firstName.trim());
    need('lastName', !form.lastName.trim());
    need('companyName', !form.companyName.trim());
    need('jobTitle', !form.jobTitle.trim());
    need('phone', !form.phone.trim());
    need('ownerId', !form.ownerId);
    need('lifecycleStage', !form.lifecycleStage);
    need('leadStatus', !form.leadStatus);
    if (!out.email && form.email.trim() && !access.locked('email')) {
      const bad = emailError(form.email, { required: false });
      if (bad) out.email = EMAIL_INVALID;
    }
    if (!out.phone && form.phone.trim() && !access.locked('phone')) {
      const bad = phoneError(form.phone);
      if (bad) out.phone = bad;
    }
    // The API needs a name or an email.
    if (!form.firstName.trim() && !form.lastName.trim() && !form.email.trim()) {
      out.firstName ??= 'Enter a first name, last name or email.';
    }
    // CQ1: custom fields are checked with the rest, each under its own field, as the design
    // checks every field it shows (create-form.js:271-280).
    for (const def of formCustom) {
      if (def.calculated) continue;
      const bad = customFieldProblem(def, custom[def.name] ?? '', timeZone);
      if (bad) out[`custom.${def.name}`] = bad;
    }
    return out;
  };

  /** As the design (create-form.js:279): the first invalid field, in form order, gets focus. */
  const focusInvalid = (found: Record<string, string>) => {
    const ids = new Set(
      Object.keys(found).map((key) => {
        const name = customName(key);
        return name ? `contactCreateCustom-${name}` : `contactCreate-${key}`;
      }),
    );
    window.setTimeout(() => focusFirstInvalid(formRef.current, ids));
  };

  const submit = async (another: boolean) => {
    // D07b: Enter in a field submits the form even while the buttons are off for a used email.
    if (blocked) {
      formRef.current?.querySelector<HTMLElement>('#contactCreate-email')?.focus();
      return;
    }
    const found = validate();
    setErrors(found);
    setFormError(null);
    if (Object.keys(found).length) {
      focusInvalid(found);
      return;
    }
    const customValues = customValuesForCreate(formCustom, custom, timeZone);
    if ('error' in customValues) {
      setFormError(customValues.error);
      return;
    }
    const on = onForm;
    const text = (v: string) => v.trim() || null;
    const companyName = companyNameOnCreate(form.companyName, on('companyName'));
    const body: CreateContactBody = {
      ...(on('email') && form.email.trim() ? { email: form.email.trim() } : {}),
      ...(on('firstName') ? { firstName: text(form.firstName) } : {}),
      ...(on('lastName') ? { lastName: text(form.lastName) } : {}),
      ...(companyName !== undefined ? { companyName } : {}),
      ...(on('jobTitle') ? { jobTitle: text(form.jobTitle) } : {}),
      ...(on('phone') ? { phone: text(form.phone) } : {}),
      ...ownerOnCreate(form.ownerId, on('ownerId')),
      ...(access.locked('lifecycleStage')
        ? {}
        : { lifecycleStage: picklistOnCreate(form.lifecycleStage, lifecycleOptions, 'lead') }),
      ...(access.locked('leadStatus')
        ? {}
        : { leadStatus: picklistOnCreate(form.leadStatus, leadStatusOptions, 'new') }),
      ...(Object.keys(customValues.value).length ? { customProperties: customValues.value } : {}),
      ...(privacyOn && form.legalBasis
        ? { legalBasis: form.legalBasis as CreateContactBody['legalBasis'] }
        : {}),
      ...companyOnCreate(form.companyId),
    };
    setSaving(another ? 'another' : 'one');
    try {
      const created = await createContact(body);
      if (form.companyId && form.labelId) {
        // The association label of the company link (HUB-619), picked on the contact.
        await linkRecords({
          from: { type: 'contact', id: created.id },
          to: { type: 'company', id: form.companyId },
          labelIds: [form.labelId],
        }).catch(() => toast('Created, but the association label could not be set', 'info'));
      }
      onCreated(created);
      toast(contactCreatedMessage(created, singular), 'success');
      if (another) {
        reset();
        // The next contact starts at the first field: the button just used is disabled now.
        formRef.current?.querySelector<HTMLElement>('input, textarea')?.focus();
      } else {
        onClose();
      }
    } catch (err) {
      // CQ1 #3: each field the API names under that field (a 409 is not always the email).
      const failed = createFailure(
        err,
        createOnForm(
          standard.map((f) => f.field),
          formCustom,
        ),
        customDefs,
      );
      setErrors(failed.fields);
      setFormError(failed.form);
      focusInvalid(failed.fields);
    } finally {
      setSaving(false);
    }
  };

  const fieldBox = (field: string, input: ReactNode) => (
    <div key={field} className={cn('field', messageOf(field) && 'is-invalid')}>
      <label htmlFor={`contactCreate-${field}`}>
        {label(field)}
        {required.has(field) ? <span className="crm-text-danger"> *</span> : null}
      </label>
      {input}
      {messageOf(field) ? (
        <span className="field__error" id={`contactCreate-${field}-error`} role="alert">
          {messageOf(field)}
        </span>
      ) : null}
    </div>
  );

  const textInput = (
    field: TextKey,
    props: { type?: string; placeholder?: string; maxLength?: number } = {},
  ) =>
    fieldBox(
      field,
      <input
        className="input"
        id={`contactCreate-${field}`}
        type={props.type ?? 'text'}
        placeholder={props.placeholder}
        maxLength={props.maxLength}
        aria-invalid={Boolean(messageOf(field))}
        aria-describedby={messageOf(field) ? `contactCreate-${field}-error` : undefined}
        value={form[field]}
        onChange={(e) => {
          const value = field === 'phone' ? sanitizePhoneInput(e.target.value) : e.target.value;
          // As HubSpot: the email format message stays while the email is still invalid.
          const stillInvalid =
            field === 'email' && errors.email === EMAIL_INVALID && value.trim() !== '';
          if (stillInvalid && !isValidEmail(value)) setForm((f) => ({ ...f, email: value }));
          else setField(field, value);
        }}
        // An incomplete email shows its error on blur: with no name the form stays locked and
        // Create disabled, so the error would otherwise never appear.
        onBlur={
          field === 'email'
            ? () => {
                if (form.email.trim() && !isValidEmail(form.email)) {
                  setErrors((cur) => ({ ...cur, email: EMAIL_INVALID }));
                }
              }
            : undefined
        }
      />,
    );

  const renderField = (field: string): ReactNode => {
    switch (field) {
      case 'email':
      case 'firstName':
      case 'lastName':
      case 'companyName':
      case 'jobTitle':
      case 'phone':
        return textInput(field, CREATE_TEXT_INPUTS[field]);
      case 'ownerId':
        return fieldBox(
          field,
          <CustomSelect
            id="contactCreate-ownerId"
            className="company-drawer-select"
            placeholder="Select"
            value={form.ownerId}
            options={ownerOptions}
            onChange={(v) => setField('ownerId', v)}
          />,
        );
      case 'lifecycleStage':
        return fieldBox(
          field,
          <CustomSelect
            id="contactCreate-lifecycleStage"
            className="company-drawer-select"
            placeholder="Select"
            value={form.lifecycleStage}
            options={lifecycleOptions}
            onChange={(v) => setField('lifecycleStage', v)}
            searchable={false}
          />,
        );
      case 'leadStatus':
        return fieldBox(
          field,
          <CustomSelect
            id="contactCreate-leadStatus"
            className="company-drawer-select"
            placeholder="Select"
            value={form.leadStatus}
            options={leadStatusOptions}
            onChange={(v) => setField('leadStatus', v)}
            searchable={false}
          />,
        );
      default:
        return null;
    }
  };

  return (
    <>
      {open ? (
        <div
          className="popup-overlay is-visible company-create-overlay"
          onClick={onClose}
          aria-hidden
        />
      ) : null}
      <aside
        className={cn(
          'popup-drawer company-create-drawer contact-create-drawer',
          open && 'is-open',
        )}
        // CT-003: the closed drawer stays in the page (for its slide-in), so it is a dialog only
        // while open, and inert keeps it (and the Close button that had focus) out of the
        // accessibility tree, focus and automation once closed.
        role={open ? 'dialog' : undefined}
        aria-modal={open || undefined}
        aria-hidden={!open}
        inert={!open}
        aria-labelledby="createContactDrawerTitle"
      >
        <header className="drawer-header">
          <div className="drawer-header-content">
            <h2 className="drawer-title" id="createContactDrawerTitle">
              Create {singular}
            </h2>
          </div>
          <button type="button" className="drawer-close" aria-label="Close" onClick={onClose}>
            <svg
              className="icon iconSize-18"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              aria-hidden
            >
              <path d="M6 6l12 12M18 6 6 18" strokeLinecap="round" />
            </svg>
          </button>
        </header>

        <form
          ref={formRef}
          id="createContactDrawerForm"
          className="popup-body-form"
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void submit(false);
          }}
        >
          {isAdmin ? (
            <p className="cf-editlink cc-editlink">
              <Link href="/create-form-editor?object=contact" target="_blank" rel="noopener">
                Edit this form
                <svg
                  className="icon iconSize-14"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  aria-hidden
                >
                  <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3" />
                </svg>
                <span className="crm-visually-hidden"> (opens in a new tab)</span>
              </Link>
            </p>
          ) : null}
          {formError ? <Alert tone="danger">{formError}</Alert> : null}
          <div className="crm-d-grid crm-gap-3">
            {identity.map((f) => renderField(f.field))}
            {/* D07b: HubSpot's "Hold the phone!" card, below the name and email, in a live
                region that is always there (as Companies' note) so it is announced. */}
            <div role="status" aria-live="polite">
              {duplicate && emailKey ? (
                <DuplicateContactNotice
                  email={emailKey}
                  singular={singular}
                  matches={duplicate.matches}
                  hidden={duplicate.hidden}
                />
              ) : null}
            </div>
            {/* The lead drawer's lockbox: dimmed with its hint on top; the inner box is inert. */}
            <div className={cn('cf-lockbox cc-lockbox', locked && 'is-locked')}>
              {locked ? (
                <p className="cf-lockbox__msg">
                  Start by entering the contact&apos;s name, email, or both.
                </p>
              ) : null}
              <div inert={locked}>
                <div className="crm-d-grid crm-gap-3">
                  {others.map((f) => renderField(f.field))}
                  {privacyOn ? (
                    <div className="field">
                      <label className="field__label" htmlFor="contactCreate-legalBasis">
                        Legal basis
                      </label>
                      <CustomSelect
                        id="contactCreate-legalBasis"
                        className="company-drawer-select"
                        placeholder="Select"
                        value={form.legalBasis}
                        options={LEGAL_BASIS}
                        onChange={(v) => setForm((f) => ({ ...f, legalBasis: v }))}
                        searchable={false}
                      />
                    </div>
                  ) : null}
                  <CustomFieldsForm
                    defs={formCustom}
                    values={custom}
                    onChange={(name, value) => {
                      setCustom((cur) => ({ ...cur, [name]: value }));
                      clearError(`custom.${name}`);
                    }}
                    idPrefix="contactCreateCustom"
                    timeZone={timeZone}
                    errors={errors}
                  />
                </div>
                {/* As HubSpot: always at the end of the form, not one of its fields. */}
                <section className="cf-assoc cc-assoc" aria-labelledby="contactCreateAssoc">
                  <h3 id="contactCreateAssoc">Associations</h3>
                  <div className="cf-assoc__item">
                    <p className="cf-assoc__obj">Companies</p>
                    <div className="field">
                      <label htmlFor="contactCreate-company">Associate record</label>
                      <CompanySearch
                        id="contactCreate-company"
                        value={
                          form.companyId
                            ? { id: form.companyId, name: form.linkedCompanyName }
                            : null
                        }
                        onChange={(c) =>
                          setForm((f) => ({
                            ...f,
                            companyId: c?.id ?? '',
                            linkedCompanyName: c?.name ?? '',
                          }))
                        }
                      />
                      {/* G5: always there, so a new line is announced (as the duplicate card). */}
                      <div className="cc-suggest" role="status" aria-live="polite">
                        <DomainSuggestionHint
                          hint={suggestion}
                          onPick={(c) => {
                            setForm((f) => ({ ...f, companyId: c.id, linkedCompanyName: c.name }));
                            // The line goes once a company is picked: keep focus on the picker.
                            window.setTimeout(() =>
                              formRef.current
                                ?.querySelector<HTMLElement>('#contactCreate-company-change')
                                ?.focus(),
                            );
                          }}
                        />
                      </div>
                    </div>
                    <div className="field">
                      <label htmlFor="contactCreate-label">
                        Association label<span className="crm-text-danger"> *</span>
                      </label>
                      <CustomSelect
                        id="contactCreate-label"
                        className="company-drawer-select"
                        placeholder="Primary"
                        value={form.labelId}
                        options={[{ value: '', label: 'Primary' }, ...labels]}
                        onChange={(v) => setForm((f) => ({ ...f, labelId: v }))}
                        searchable={false}
                      />
                    </div>
                  </div>
                </section>
              </div>
            </div>
          </div>
        </form>

        <footer className="drawer-footer">
          {/* The design: Create · Create and add another · Cancel, from the left. */}
          <div className="drawer-footer-actions cc-foot">
            <button
              type="submit"
              form="createContactDrawerForm"
              className={cn('btn-crm btn-crm--primary', saving === 'one' && 'is-loading')}
              disabled={Boolean(saving) || locked || blocked}
            >
              <span className="btn-crm__spinner" aria-hidden />
              <span className="btn-crm__text">Create</span>
            </button>
            <button
              type="button"
              className={cn('btn-crm btn-crm--outline', saving === 'another' && 'is-loading')}
              disabled={Boolean(saving) || locked || blocked}
              onClick={() => void submit(true)}
            >
              <span className="btn-crm__spinner" aria-hidden />
              <span className="btn-crm__text">Create and add another</span>
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              Cancel
            </button>
          </div>
        </footer>
      </aside>
    </>
  );
}

/** Company picker that searches every company through the API (sheet #149). */
function CompanySearch({
  id,
  value,
  onChange,
}: {
  id: string;
  value: { id: string; name: string } | null;
  onChange: (company: { id: string; name: string } | null) => void;
}) {
  const [text, setText] = useState('');
  const [results, setResults] = useState<
    Array<{ id: string; name: string; domain?: string | null }>
  >([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const boxRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    setLoading(true);
    const t = window.setTimeout(() => {
      listCompanies({ search: text.trim() || undefined, limit: 20, sort: 'name', direction: 'asc' })
        .then((page) => {
          if (alive)
            setResults(page.data.map((c) => ({ id: c.id, name: c.name, domain: c.domain })));
        })
        .catch(() => {
          if (alive) setResults([]);
        })
        .finally(() => {
          if (alive) setLoading(false);
        });
    }, 250);
    return () => {
      alive = false;
      window.clearTimeout(t);
    };
  }, [text, open]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (!boxRef.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [open]);

  if (value) {
    return (
      <div className="crm-d-flex crm-align-items-center crm-gap-2">
        <span className="input crm-d-flex crm-align-items-center" style={{ flex: 1 }}>
          {value.name}
        </span>
        <button
          type="button"
          id={`${id}-change`}
          className="btn-crm btn-crm--ghost btn-crm--sm"
          onClick={() => onChange(null)}
        >
          Change
        </button>
      </div>
    );
  }
  return (
    <div ref={boxRef} className="custom-select" style={{ position: 'relative' }}>
      <input
        id={id}
        className="input"
        type="search"
        placeholder="Search companies"
        autoComplete="off"
        role="combobox"
        aria-expanded={open}
        aria-controls={`${id}-list`}
        value={text}
        onFocus={() => setOpen(true)}
        onChange={(e) => {
          setText(e.target.value);
          setOpen(true);
        }}
      />
      {open ? (
        <div
          id={`${id}-list`}
          className="custom-select__dropdown"
          role="listbox"
          style={{ display: 'block' }}
        >
          <ul className="custom-select__options">
            {loading ? <li className="custom-select__option">Searching…</li> : null}
            {!loading && results.length === 0 ? (
              <li className="custom-select__option">No companies found</li>
            ) : null}
            {results.map((c) => (
              <li
                key={c.id}
                className="custom-select__option"
                role="option"
                aria-selected={false}
                onMouseDown={(e) => {
                  e.preventDefault();
                  onChange({ id: c.id, name: c.name });
                  setText('');
                  setOpen(false);
                }}
              >
                <span className="custom-select__option-text">
                  {c.name}
                  {c.domain ? <span className="crm-text-muted"> · {c.domain}</span> : null}
                </span>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </div>
  );
}
