/**
 * G5 (beyond the design, the user's call on 18 Nov 2026): the Create contact drawer's "Suggested
 * from email domain" line, under Associate record. The design's old drawer has the line as fixed
 * text (create-popup.php:482-484); the form that runs on Contacts (create-form.js) has none.
 *
 * It says what Create will do with no company picked (QA D-08, `associateCompanyByDomain`), from
 * `GET /contacts/company-by-domain`, which runs the create's own rules: link this company, make
 * one with the domain, or nothing. Asked as the duplicate check is (contactEmailDuplicates.ts):
 * after a pause in typing, answers kept by the email asked about, a failed lookup shows nothing.
 * An existing company's name picks it into Associate record (the user's call), so a label can be
 * chosen for it; a new one has no id yet, so its name stays text.
 */

/** The API's answer: what a create would do for the email. */
export type DomainSuggestion =
  | { kind: 'link'; company: { id: string; name: string; domain: string | null } }
  | { kind: 'create'; domain: string };

/**
 * The email to ask about: the duplicate check's (`emailLookupKey`: a whole email, on the form),
 * and none while a company is picked (the create sends it and ignores the domain).
 */
export function domainLookupKey(emailKey: string | null, companyPicked: boolean): string | null {
  return companyPicked ? null : emailKey;
}

/** Answers by the email asked about; each reset starts a new round, as `EmailAnswers`. */
export type DomainAnswers = { round: number; byEmail: Record<string, DomainSuggestion | null> };

export const NO_DOMAIN_ANSWERS: DomainAnswers = { round: 0, byEmail: {} };

export type DomainAnswerAction =
  | { type: 'answer'; email: string; round: number; suggestion: DomainSuggestion | null }
  /** The lookup failed: that email shows nothing, not an earlier answer for it. */
  | { type: 'failed'; email: string }
  /** The form was reset (opened, closed, "Create and add another"). */
  | { type: 'reset' };

export function domainAnswers(state: DomainAnswers, action: DomainAnswerAction): DomainAnswers {
  switch (action.type) {
    case 'answer':
      if (action.round !== state.round) return state;
      return { ...state, byEmail: { ...state.byEmail, [action.email]: action.suggestion } };
    case 'failed': {
      if (!(action.email in state.byEmail)) return state;
      const byEmail = { ...state.byEmail };
      delete byEmail[action.email];
      return { ...state, byEmail };
    }
    case 'reset':
      return { round: state.round + 1, byEmail: {} };
  }
}

/** What the line says: the company to pick, or the name the new company would get. */
export type DomainHint =
  { kind: 'link'; company: { id: string; name: string } } | { kind: 'create'; name: string };

/**
 * The line for the email now in the box, or null. A new company is named as the API names it:
 * the Company name the create sends (`companyNameSent`, null when that field isn't sent), else the
 * domain (api `companyByDomain`).
 */
export function domainHint(
  key: string | null,
  answers: DomainAnswers,
  companyNameSent: string | null,
): DomainHint | null {
  const found = key ? answers.byEmail[key] : undefined;
  if (!found) return null;
  if (found.kind === 'link') {
    return { kind: 'link', company: { id: found.company.id, name: found.company.name } };
  }
  return { kind: 'create', name: companyNameSent?.trim() || found.domain };
}

/** The design's line (create-popup.php:482-484), or nothing. */
export function DomainSuggestionHint({
  hint,
  onPick,
}: {
  hint: DomainHint | null;
  onPick: (company: { id: string; name: string }) => void;
}) {
  if (!hint) return null;
  if (hint.kind === 'link') {
    const { company } = hint;
    return (
      <div className="suggestion crm-fs-8 crm-mt-2">
        {'Suggested from email domain: '}
        <button
          type="button"
          className="cc-suggest__pick"
          aria-label={`Associate ${company.name}`}
          onClick={() => onPick(company)}
        >
          <strong className="crm-fs-8">{company.name}</strong>
        </button>
      </div>
    );
  }
  return (
    <div className="suggestion crm-fs-8 crm-mt-2">
      {'Suggested from email domain: '}
      <strong className="crm-fs-8">{hint.name}</strong>
      {' (new company)'}
    </div>
  );
}
