import {
  STATEMENT_LOCALES,
  isStatementLocale,
  type StatementData,
  type StatementLocale,
  type StatementLocalizedFields,
  type TemporaryColumns,
} from "@accessibit/types";
import type { StatementContentPayload, StatementPayload } from "../client";

// The statement form as data: its shape, what it must answer before the
// statement can be generated, and its three adapters: to the wire
// (`formToPayload`), to the renderer (`formToStatementData`) and back from a
// saved row (`statementToForm`). No React in here: the page and its sections
// read it, and so do their tests.

/**
 * The three free-text fields, as the form holds them: always a string, never
 * `undefined`, because they are bound to controlled textareas. An empty one is
 * meaningful — the renderer falls back to the primary language (English) for
 * it, and prints nothing at all when that one is blank too.
 */
export type LocalizedDraft = Required<StatementLocalizedFields>;
export type LocalizedByLocale = Record<StatementLocale, LocalizedDraft>;

/**
 * Form shape mirrors the apps/app statement form, plus the
 * conformance/measures/limitations fields the dashboard ships on top.
 * Internal naming keeps the dashboard's existing tokens (orgName,
 * contactEmail, statementDate) to avoid rippling through dict keys;
 * `formToPayload` renames them to the columns the statement is stored in, and
 * `formToStatementData` renames them again to what the renderer reads.
 */
export interface StatementForm {
  // identity
  orgName: string;
  firstName: string;
  lastName: string;
  contactEmail: string;
  entityType: "public" | "private";
  // site
  websiteUrl: string;
  siteCMS: string;
  sitePublicationDate: string;
  // conformance (dashboard-only)
  conformanceLevel: string;
  statementDate: string;
  /**
   * Required of public administrations and optional for private entities — see
   * `PUBLIC_ENTITY_REQUIRED_FIELDS`. Blank means "not declared", not zero,
   * everywhere it is read: the renderer omits the section when BOTH are blank,
   * and for a private entity it also omits whichever single row is blank
   * rather than declaring it "not provided". Never default these to "0" —
   * that publishes "0 employees with disabilities, 0 adapted workstations" on
   * the customer's own site, which is what the old template did unasked.
   */
  employeesWithDisabilities: string;
  workstationsForDisabilities: string;
  includePdfDisclaimer: boolean;
  /** The AgID model's Yes/No answers; `false` is "No", which is the default. */
  lawNonCompliance: boolean;
  disproportionateBurden: boolean;
  outOfScopeContent: boolean;
  usabilityTestsPerformed: boolean;
  /** Measures, limitations and closing notes, one set per language. */
  localized: LocalizedByLocale;
}

export type StatementStatus =
  | "draft"
  | "queued"
  | "processing"
  | "ready"
  | "failed";

/**
 * What a generation has left behind, as far as the page reads it: when, and
 * in which languages there is a published page. The files' own addresses and
 * the downloads are not here: the page hands out the entry point alone
 * (ACC-523) and offers no copy to download.
 */
export interface StatementArtifacts {
  /** When the pages were last written; null on a statement never generated. */
  generatedAt: string | null;
  /**
   * One published artifact per language. A map rather than a single URL since
   * ACC-260: `StatementFile` is one row per locale, so there is no longer a
   * "the" public URL to read.
   */
  publicHtmlUrls: Partial<Record<StatementLocale, string>>;
}

/**
 * The document a visitor gets when they speak none of the three, and the one
 * the renderer falls back to for a free-text field left blank in another
 * language.
 *
 * A constant rather than a form field: the statement is published in all three
 * languages whatever the customer does, so the only thing left to decide is
 * which one a visitor gets when their own is not among them. English, because
 * that visitor is by definition not an Italian or Spanish speaker — a German
 * or Japanese reader is likelier to get something out of the English version
 * than out of the Italian one, however Italian the underlying law is.
 */
export const PRIMARY_LOCALE: StatementLocale = "en";

const mapLocales = (
  build: (locale: StatementLocale) => LocalizedDraft,
): LocalizedByLocale =>
  Object.fromEntries(
    STATEMENT_LOCALES.map((locale) => [locale, build(locale)]),
  ) as LocalizedByLocale;

/**
 * A new statement starts with every free-text field blank, in every language.
 *
 * The measures and the limitations used to open on a sample paragraph out of
 * the renderer's catalogs (ACC-515). A sample left alone is published as the
 * customer's own words, and one of them said the site runs the AccessiBit
 * widget — true of some customers, printed for all of them. Both fields are
 * optional: left blank, the renderer drops the heading rather than printing it
 * over nothing.
 */
export const blankLocalized = (): LocalizedByLocale =>
  mapLocales(() => ({
    measuresTaken: "",
    knownLimitations: "",
    additionalNotes: "",
    lawNonComplianceReason: "",
    disproportionateBurdenReason: "",
    outOfScopeContentReason: "",
  }));

export const LOCALIZED_FIELDS = [
  "measuresTaken",
  "knownLimitations",
  "additionalNotes",
] as const satisfies readonly (keyof LocalizedDraft)[];

export type LocalizedTextField = (typeof LOCALIZED_FIELDS)[number];

/**
 * Which documents will publish an optional section without it (ACC-527).
 *
 * The renderer resolves each of these texts as the document's own language,
 * then English, then nothing — and drops the heading when it gets nothing. So
 * a section written in Italian only is in the Italian document and absent
 * from the English and Spanish ones. That is a gap exactly when the field has
 * text somewhere and English is blank; with English written every language
 * has something to fall back to.
 *
 * Blank is `trim()` empty, as in `resolveLocalizedField`: whitespace alone is
 * neither a written section nor something that keeps one in.
 *
 * `null` when there is nothing to say: blank everywhere (the section is simply
 * not in the statement, which is the user's call) or written in English.
 */
export function languagesOmittingSection(
  form: StatementForm,
  field: LocalizedTextField,
): { writtenIn: StatementLocale[]; missingIn: StatementLocale[] } | null {
  const blank = (locale: StatementLocale) =>
    !form.localized[locale][field].trim();
  if (!blank(PRIMARY_LOCALE)) return null;
  const writtenIn = STATEMENT_LOCALES.filter((locale) => !blank(locale));
  if (writtenIn.length === 0) return null;
  return { writtenIn, missingIn: STATEMENT_LOCALES.filter(blank) };
}

/**
 * The three "Contenuti non accessibili" answers whose "Yes" has to say what it
 * covers, each with the per-language field holding that text, the id of the
 * textarea that edits it, and its placeholder — out of scope asks for the
 * content only, the other two for the content and why.
 */
export const ANSWER_REASONS = [
  {
    answer: "lawNonCompliance",
    reason: "lawNonComplianceReason",
    id: "law-non-compliance-reason",
    placeholder: "answerReasonPlaceholder",
  },
  {
    answer: "disproportionateBurden",
    reason: "disproportionateBurdenReason",
    id: "disproportionate-burden-reason",
    placeholder: "answerReasonPlaceholder",
  },
  {
    answer: "outOfScopeContent",
    reason: "outOfScopeContentReason",
    id: "out-of-scope-content-reason",
    placeholder: "outOfScopeContentReasonPlaceholder",
  },
] as const satisfies readonly {
  answer: keyof StatementForm;
  reason: keyof LocalizedDraft;
  id: string;
  placeholder: string;
}[];

export type ReasonField = (typeof ANSWER_REASONS)[number]["reason"];

/**
 * The languages whose document would print a "Yes" with nothing under it.
 *
 * A blank language falls back to the primary one at render time, so the text
 * is complete exactly when the primary (English) version is written. Any other
 * language alone is NOT enough: Italian only leaves the English and Spanish
 * documents with a bare "Yes". Empty when complete; otherwise English plus
 * every other blank language.
 */
export function languagesMissingReason(
  form: StatementForm,
  reason: ReasonField,
): StatementLocale[] {
  const blank = (locale: StatementLocale) =>
    !form.localized[locale][reason].trim();
  if (!blank(PRIMARY_LOCALE)) return [];
  return STATEMENT_LOCALES.filter(blank);
}

/**
 * Upper bound on the two declared headcounts — the widest value the `INTEGER`
 * columns hold. Without it the inputs accept any run of digits, and
 * `99999999999` reaches Postgres as an out-of-range integer: the save 400s on
 * something the form said was fine. Upstream clamps to the same number; this
 * one states the bound to the user (and to assistive tech) before they hit it.
 */
export const MAX_COUNT = 2147483647;

/**
 * Fields the user MUST fill before the statement can be generated, whoever is
 * answering. The dashboard adds entityType + the measures/limitations on top,
 * and neither blocks: the first always holds a value, and the other two are
 * optional — left blank, their section is simply not in the document.
 */
export const REQUIRED_FIELDS = [
  "orgName",
  "contactEmail",
  "siteCMS",
  "sitePublicationDate",
  "statementDate",
] as const satisfies readonly (keyof StatementForm)[];

/**
 * Required of a public administration only — what the AgID model asks of an
 * administration and of nobody else. Everything in this list is SHOWN to
 * everyone: a private entity may declare its headcounts (ACC-379) and may name
 * a person responsible for accessibility, it just never has to. Most private
 * customers have nobody to name, and an unanswerable requirement would have
 * stopped every one of them from generating at all (ACC-341).
 *
 * A blank answer is therefore a valid end state, not an unfinished form. The
 * renderer DROPS the row from the published document rather than declaring it
 * "not provided" — these are duties an operator outside the AgID regime does
 * not have, so announcing the gap would invent a shortfall. See `officerRow`
 * and the organisation section in @accessibit/doc-generators/statement, which
 * both still spell the gap out for a public entity, which does owe the answer.
 */
export const PUBLIC_ENTITY_REQUIRED_FIELDS = [
  "employeesWithDisabilities",
  "workstationsForDisabilities",
  "firstName",
  "lastName",
] as const satisfies readonly (keyof StatementForm)[];

export type ColumnRequiredField =
  | (typeof REQUIRED_FIELDS)[number]
  | (typeof PUBLIC_ENTITY_REQUIRED_FIELDS)[number];

export type RequiredField = ColumnRequiredField | ReasonField;

/** What the form must answer, given who is answering it. */
export function requiredFieldsFor(
  form: StatementForm,
): readonly ColumnRequiredField[] {
  return form.entityType === "public"
    ? [...REQUIRED_FIELDS, ...PUBLIC_ENTITY_REQUIRED_FIELDS]
    : REQUIRED_FIELDS;
}

export function missingRequiredFields(form: StatementForm): RequiredField[] {
  const missing: RequiredField[] = requiredFieldsFor(form).filter(
    (key) => !String(form[key] ?? "").trim(),
  );
  // A "Yes" is only complete with what it covers; a "No" asks for nothing.
  for (const { answer, reason } of ANSWER_REASONS) {
    if (form[answer] && languagesMissingReason(form, reason).length > 0) {
      missing.push(reason);
    }
  }
  return missing;
}

/**
 * Dates that record something that has already happened, so a value after
 * today is always wrong: the site went live on `sitePublicationDate`, and the
 * statement was drawn up on `statementDate`. Neither is a planned date.
 *
 * Only these two — every other date the page shows is read off an audit and
 * never typed here.
 */
export const PAST_ONLY_DATE_FIELDS = [
  "sitePublicationDate",
  "statementDate",
] as const satisfies readonly (keyof StatementForm)[];

export type PastOnlyDateField = (typeof PAST_ONLY_DATE_FIELDS)[number];

/**
 * The past-only dates the form currently puts in the future.
 *
 * Compared as strings: both sides are `YYYY-MM-DD`, which sorts
 * lexicographically in calendar order, so this never goes through `Date` and
 * never picks up the UTC-midnight shift `isoDay` exists to avoid. A blank or
 * half-typed value is not "in the future" — that is the required check's
 * business, not this one's.
 */
export function futureDateFields(
  form: StatementForm,
  today: string,
): PastOnlyDateField[] {
  return PAST_ONLY_DATE_FIELDS.filter((key) => {
    const value = form[key].trim();
    return /^\d{4}-\d{2}-\d{2}$/.test(value) && value > today;
  });
}

/**
 * DOM id of each required input, so a rejected submit can move focus to the
 * first gap. Kept next to `REQUIRED_FIELDS` — the `Record` makes TypeScript
 * fail the build if a required field is added without an id to focus.
 */
export const REQUIRED_FIELD_IDS: Record<RequiredField, string> = {
  orgName: "org-name",
  firstName: "first-name",
  lastName: "last-name",
  contactEmail: "contact-email",
  siteCMS: "site-cms",
  sitePublicationDate: "site-publication-date",
  statementDate: "statement-date",
  employeesWithDisabilities: "employees-with-disabilities",
  workstationsForDisabilities: "workstations-for-disabilities",
  lawNonComplianceReason: "law-non-compliance-reason",
  disproportionateBurdenReason: "disproportionate-burden-reason",
  outOfScopeContentReason: "out-of-scope-content-reason",
};

/**
 * Where each column the temporary statement requires (ACC-504) is typed on
 * this form, so a refused publication can land on the first gap. Every one of
 * them is a field the regular statement requires too, under the form's own
 * name for it.
 */
export const TEMPORARY_FIELD_IDS: Partial<
  Record<keyof TemporaryColumns, string>
> = {
  companyName: REQUIRED_FIELD_IDS.orgName,
  feedbackEmail: REQUIRED_FIELD_IDS.contactEmail,
  siteCMS: REQUIRED_FIELD_IDS.siteCMS,
  sitePublicationDate: REQUIRED_FIELD_IDS.sitePublicationDate,
  firstName: REQUIRED_FIELD_IDS.firstName,
  lastName: REQUIRED_FIELD_IDS.lastName,
  employeesWithDisabilities: REQUIRED_FIELD_IDS.employeesWithDisabilities,
  workstationsForDisabilities: REQUIRED_FIELD_IDS.workstationsForDisabilities,
};

const KNOWN_STATUSES = new Set<StatementStatus>([
  "draft",
  "queued",
  "processing",
  "ready",
  "failed",
]);

/**
 * Narrows an arbitrary upstream value to `StatementStatus`. Anything
 * outside the known set falls back to `fallback` rather than crashing
 * the status badge — defensive in case the backend ever ships a new
 * state ahead of the client.
 */
export function normalizeStatus(
  value: unknown,
  fallback: StatementStatus,
): StatementStatus {
  return typeof value === "string" &&
    KNOWN_STATUSES.has(value as StatementStatus)
    ? (value as StatementStatus)
    : fallback;
}

/**
 * The wire shape audit-api persists as columns. `siteUrl`,
 * `siteUpdateReleaseDate` and `statementReleaseDate` are deliberately absent:
 * the first is overwritten from `Website.url` at render time, and the other two
 * had no reader left once the Google Docs placeholders went.
 *
 * EVERY column, on every save, whether or not the user touched it: upstream
 * writes the columns from the body alone, so a field left out is not "leave it
 * as it was" — it is "write the default over it". Omitting `entityType` demotes
 * a public administration's statement to private, which relabels the declared
 * headcounts and drops whichever of the two is blank. `contents` merges the other
 * way, per language, but the form holds all three languages in full, so
 * sending all three is both correct and lossless — what must never be sent is
 * an EMPTY object for a language, which upstream reads as "erase it".
 */
export function formToPayload(form: StatementForm) {
  return {
    companyName: form.orgName,
    firstName: form.firstName,
    lastName: form.lastName,
    feedbackEmail: form.contactEmail,
    entityType: form.entityType,
    siteCMS: form.siteCMS,
    sitePublicationDate: form.sitePublicationDate,
    statementDate: form.statementDate,
    conformanceLevel: form.conformanceLevel,
    // Sent as typed, blank included: blank is "not declared", and upstream
    // stores that as NULL rather than as a zero the customer never claimed.
    employeesWithDisabilities: form.employeesWithDisabilities,
    workstationsForDisabilities: form.workstationsForDisabilities,
    includePdfDisclaimer: form.includePdfDisclaimer,
    lawNonCompliance: form.lawNonCompliance,
    disproportionateBurden: form.disproportionateBurden,
    outOfScopeContent: form.outOfScopeContent,
    usabilityTestsPerformed: form.usabilityTestsPerformed,
    contents: form.localized,
  };
}

/**
 * The form as the RENDERER wants it — a different shape from the wire, and
 * deliberately so. `StatementData` belongs to `@accessibit/doc-generators` and
 * describes a document; the payload above describes a database row. The two
 * disagree on both of the fields below, which is exactly why the preview needs
 * its own adapter rather than a cast:
 *  - `siteUrl` is the site's own column, never a stored copy. Generation reads
 *    `Website.url`, so previewing anything else shows a string the published
 *    document will not carry.
 *  - the issue date is `statementCompletionDate` here and `statementDate` on
 *    the wire.
 */
export function formToStatementData(
  form: StatementForm,
  siteUrl: string,
): StatementData {
  return {
    companyName: form.orgName,
    firstName: form.firstName,
    lastName: form.lastName,
    feedbackEmail: form.contactEmail,
    entityType: form.entityType,
    siteUrl,
    siteCMS: form.siteCMS,
    sitePublicationDate: form.sitePublicationDate,
    statementCompletionDate: form.statementDate,
    conformanceLevel: form.conformanceLevel,
    employeesWithDisabilities: form.employeesWithDisabilities,
    workstationsForDisabilities: form.workstationsForDisabilities,
    includePdfDisclaimer: form.includePdfDisclaimer,
    lawNonCompliance: form.lawNonCompliance,
    disproportionateBurden: form.disproportionateBurden,
    outOfScopeContent: form.outOfScopeContent,
    usabilityTestsPerformed: form.usabilityTestsPerformed,
    localized: form.localized,
  };
}

const asString = (value: unknown): string =>
  typeof value === "string" ? value : "";

/**
 * The calendar day out of what the API sends for a `@db.Date` column: an ISO
 * timestamp at midnight UTC, which the date inputs want as `YYYY-MM-DD`.
 * Sliced rather than parsed — anything that goes through `Date` reintroduces
 * the timezone shift the column exists to avoid.
 */
const isoDay = (value: unknown): string =>
  typeof value === "string" ? value.slice(0, 10) : "";

/**
 * A declared count back to the string the number input holds.
 *
 * `0` is a DECLARED value — an administration may genuinely have no adapted
 * workstations — so the test is against null/undefined and never truthiness:
 * `n ? String(n) : ""` would read that zero back as "not declared" and
 * republish the statement without the figure the customer typed.
 */
const countToString = (value: number | string | null | undefined): string =>
  String(value ?? "");

/**
 * The per-language free text out of a saved statement's `contents` rows, one
 * entry per published language.
 *
 * A language with no row was never written, so it opens on `fallback` — which
 * is blank, exactly as on a brand-new statement. The case that reaches it is a
 * statement written before ACC-260: the backfill filed its single set of free
 * text under ONE locale and wrote no row for the other two.
 *
 * Until ACC-515 the fallback was a sample paragraph, so those two languages
 * opened pre-filled and the first save published our words under the
 * customer's name. Blank has a cost there and it is the intended one:
 * `formToPayload` sends the blanks back, and `resolveLocalizedField` only
 * falls back to the primary language — so a statement whose one row is not
 * the primary language prints no measures or limitations section in the other
 * two documents until someone writes one.
 */
function readContents(
  contents: StatementContentPayload[] | undefined,
  fallback: LocalizedByLocale,
): LocalizedByLocale {
  if (!Array.isArray(contents) || contents.length === 0) return fallback;
  const byLocale = new Map(contents.map((row) => [row?.locale, row]));
  return mapLocales((locale) => {
    const row = byLocale.get(locale);
    // No row for this language: never written, so it opens blank.
    if (!row) return fallback[locale];
    return {
      measuresTaken: asString(row.measuresTaken),
      knownLimitations: asString(row.knownLimitations),
      additionalNotes: asString(row.additionalNotes),
      lawNonComplianceReason: asString(row.lawNonComplianceReason),
      disproportionateBurdenReason: asString(row.disproportionateBurdenReason),
      outOfScopeContentReason: asString(row.outOfScopeContentReason),
    };
  });
}

/**
 * The language a single-language statement's free text is filed under, or null
 * when it carries text in more than one language (or none at all).
 *
 * Every statement written before ACC-260 had one set of free text, and the
 * backfill filed it under the row's own language — one `StatementContent` row
 * and no others. The working-language select otherwise opens on the dashboard's
 * own language, which for those statements would show three empty boxes with
 * the real text one control away.
 */
export function localeWithLegacyText(
  statement: StatementPayload,
): StatementLocale | null {
  const contents = Array.isArray(statement?.contents) ? statement.contents : [];
  if (contents.length !== 1) return null;
  const only = contents[0];
  const hasText = LOCALIZED_FIELDS.some(
    (field) => asString(only?.[field]).trim().length > 0,
  );
  if (!hasText) return null;
  if (isStatementLocale(only?.locale)) return only.locale;
  return isStatementLocale(statement?.locale)
    ? statement.locale
    : PRIMARY_LOCALE;
}

export function statementToForm(
  statement: StatementPayload | null | undefined,
  fallback: StatementForm,
): StatementForm {
  if (!statement) return fallback;
  const entityType =
    statement.entityType === "public" || statement.entityType === "private"
      ? statement.entityType
      : fallback.entityType;
  return {
    orgName: asString(statement.companyName) || fallback.orgName,
    // Verbatim, blank included — NOT `|| fallback`, unlike every other field
    // here. Since ACC-341 a private entity may deliberately name no officer,
    // and the fallback is the SIGNED-IN USER's own name: re-seeding it on
    // reload would show a name the published document does not carry, settle
    // as `savedForm` so nothing reads dirty, and publish the account holder as
    // the site's accessibility officer on the next save. Seeding from the user
    // is a first-visit convenience, which the `!statement` return above still
    // covers.
    firstName: asString(statement.firstName),
    lastName: asString(statement.lastName),
    contactEmail: asString(statement.feedbackEmail) || fallback.contactEmail,
    entityType,
    // Deliberately NOT read back off the statement: the field is read-only and
    // belongs to the site, not to the document. Generation reads `Website.url`
    // at render time, so a stored copy that had since drifted would only ever
    // show the user a string the published document does not carry — which is
    // why there is no column for it at all any more.
    websiteUrl: fallback.websiteUrl,
    siteCMS: asString(statement.siteCMS) || fallback.siteCMS,
    sitePublicationDate:
      isoDay(statement.sitePublicationDate) || fallback.sitePublicationDate,
    statementDate: isoDay(statement.statementDate) || fallback.statementDate,
    conformanceLevel:
      asString(statement.conformanceLevel) || fallback.conformanceLevel,
    // NULL is "not declared", which is not the same as a declared zero — hence
    // `countToString` rather than a truthiness test.
    employeesWithDisabilities: countToString(
      statement.employeesWithDisabilities,
    ),
    workstationsForDisabilities: countToString(
      statement.workstationsForDisabilities,
    ),
    // Defaults to "off": the column is NOT NULL upstream, but a payload that
    // omits it must not inherit a truthy fallback either.
    includePdfDisclaimer: statement.includePdfDisclaimer === true,
    // Same rule: only an explicit `true` is a "Yes", so a statement saved
    // before these were asked reopens on the "No" it has always published.
    lawNonCompliance: statement.lawNonCompliance === true,
    disproportionateBurden: statement.disproportionateBurden === true,
    outOfScopeContent: statement.outOfScopeContent === true,
    usabilityTestsPerformed: statement.usabilityTestsPerformed === true,
    localized: readContents(statement.contents, fallback.localized),
  };
}

export const EMPTY_ARTIFACTS: StatementArtifacts = {
  generatedAt: null,
  publicHtmlUrls: {},
};

export function computeArtifacts(
  statement: StatementPayload | null | undefined,
): StatementArtifacts {
  const files = Array.isArray(statement?.files) ? statement.files : [];
  if (!statement || files.length === 0) return EMPTY_ARTIFACTS;

  const publicHtmlUrls: Partial<Record<StatementLocale, string>> = {};
  for (const file of files) {
    if (isStatementLocale(file.locale) && file.publicHtmlUrl) {
      publicHtmlUrls[file.locale] = file.publicHtmlUrl;
    }
  }

  // The statement's OWN language is the row that dates the generation; fall
  // back to a generated row for a statement whose language was switched after
  // the last one. `publicHtmlUrl`, not the storage key: public API v1 does not
  // return keys (ACC-615).
  const primary = isStatementLocale(statement.locale) ? statement.locale : null;
  const primaryFile =
    (primary ? files.find((file) => file.locale === primary) : null) ??
    files.find((file) => file.publicHtmlUrl) ??
    files[0];

  return {
    generatedAt: primaryFile?.generatedAt ?? null,
    publicHtmlUrls,
  };
}

export function splitName(full: string | null): {
  first: string;
  last: string;
} {
  if (!full) return { first: "", last: "" };
  const trimmed = full.trim();
  if (!trimmed) return { first: "", last: "" };
  const idx = trimmed.indexOf(" ");
  if (idx < 0) return { first: trimmed, last: "" };
  return {
    first: trimmed.slice(0, idx),
    last: trimmed.slice(idx + 1).trim(),
  };
}
