/* @canonical/react-ds-global-form — density & baseline alignment (FORM APPLICATION)
 *
 * The GENERIC density primitives — the context/density modifier families
 * (.app/.site/.docs × .comfortable/.dense) and their --density-* outputs
 * (--density-line-height(-effective), --density-target-baseline-px,
 * --density-padding-inline, --density-space-sm/-md/-lg) — now live in
 * @canonical/styles (`modifiers.density.css`), so EVERY package can read them
 * (ds-global's Accordion as well as this form package). See that file for the
 * 2×3 matrix and the value table.
 *
 * THIS file is the FORM APPLICATION layer: it applies those primitives to the
 * form's own controls (`.ds.input`, `.ds.field-label/description/error`, the
 * textarea) — sizing their boxes to the density cell and seating their text on the
 * 4px grid. The --form-* token mapping lives in index.css.
 *
 * NB the BUTTON is a ds-global component, so its density seat lives in ds-global
 * (Button/styles.css), reading the same shared --density-* primitives — an app
 * that ships ds-global without the form package still gets a seated button.
 *
 * Text baseline sits on the density target — round(nearest, height × 2/3) — so
 * every control shares one baseline index. Controls use the INTRINSIC seat from
 * @canonical/styles (--control-seat-line/-basis): no fixed heights; border +
 * seat pads + line-height add up to the density cell. Zero-JS (cap-unit
 * approximation); holds to the cap tolerance.
 *
 * Layer: ds.components.global (@canonical/styles README, "Cascade layers").
 */

@layer ds.components.global {
  /* ── TRANSITIONAL: the fixed-height box (direct date/time chromes only) ──────
   * The ORIGINAL density box: a FIXED grid-multiple height with border-box so the
   * border is absorbed into the height. The composite text family, the select and
   * the textarea have all moved OFF this rule onto the intrinsic seat (their
   * equal-specificity rules further down override it); it still governs the
   * remaining direct chromes — date, time, datetime — whose multi-part UA
   * internals need their own measured pass before they join.
   *
   * Controls no longer carry `.p` — the density system supplies the body font tier
   * (font-size / weight / family) here. */
  /* NB `.ds.input.textarea` is EXCLUDED: the textarea seats intrinsically (its own
   * rule below) and must keep its multi-row min-height. */
  :is(.comfortable, .dense, .app, .site, .docs) .ds.input:not(.textarea) {
    box-sizing: border-box;
    /* Same effective line-height the target-baseline uses (single source of the
       fallback chain), so a bare context class keeps a valid box height too. */
    --density-box-height: var(--density-line-height-effective);
    block-size: var(--density-box-height);
    min-block-size: var(--density-box-height);
    align-items: flex-start;
    justify-content: flex-start;
    /* Kill the UA BOTTOM padding only. Do NOT zero padding-block-start here: this
       selector is more specific (0,4,0) than the placement rule below (0,2,0), so a
       `padding-block: 0` shorthand would out-specify and WIPE the placement's
       `padding-block-start: var(--space-before)` — leaving the label pinned to the
       box top (off the baseline). The placement rule owns the start. */
    padding-block-end: 0;

    /* Body font tier — what `.p` used to supply. */
    font-size: var(--typography-text-primary-font-size);
    font-family: var(--typography-text-primary-font-family);
  }

  /* The input WRAPPER is the box (like the button element): don't stretch its
   * child, top-reference it so the input's own space-before governs. Needs to beat
   * the TextInput's `.ds.input.text { align-items: stretch }` (0,3,0). */
  :is(.comfortable, .dense, .app, .site, .docs) .ds.input.text,
  :is(.comfortable, .dense, .app, .site, .docs) .ds.input {
    align-items: flex-start;
  }

  /* The <input> is the text carrier — treat it exactly like the button label:
   * same body font tier, and normalised so only the space-before (below) positions
   * its text. (It's content-box with an intrinsic height, so reset that.) */
  :is(.comfortable, .dense, .app, .site, .docs) .ds.input > input {
    box-sizing: border-box;
    min-block-size: 0;
    block-size: auto;
    margin-block: 0;
    font-size: var(--typography-text-primary-font-size);
    font-family: var(--typography-text-primary-font-family);
  }

  /* ── Baseline placement: `.baseline` nudge + `--space-before` ───────────────
   * Two parts, the combination that put controls ON the grid:
   *
   *  1. NUDGE (the DS.01 `.baseline` mechanism): --bl-start-nudge snaps the text's
   *     first baseline onto the NEAREST grid line, computed from the element's own
   *     font (1cap + line-height) — font-relative, so it's exact at any size and
   *     needs no per-element fudge. This is what lands text exactly on a line.
   *
   *  2. --space-before: whole baselines added to move that snapped baseline DOWN to
   *     the density TARGET line (round-up of the remaining distance), less the box's
   *     own top border.
   *
   *     padding-block-start = bl-start-nudge + space-before − border-top
   *     space-before = round(up, target − bl-start-nudge − border-top, baseline)
   *
   * Applies to the button, the input, and the field label/description/error — i.e.
   * CONTROL-like text only. Bare prose (p / .p / h1–h6) is DELIBERATELY NOT here:
   * running text belongs to the typography engine, which already seats it on the
   * grid (snapped --computed-line-height + --start/--end-nudge) and lets `.editorial`
   * add its inter-block margins. Density crushing prose to line-height:1 fought that
   * engine (and only ever put the FIRST line on-grid — wrapped lines drifted). By
   * partitioning prose OUT, density and the engine write to disjoint element sets,
   * so `.editorial` composes with density with no specificity war. `:is()` (not
   * `:where()`) still gives the control seat the specificity to beat a control's own
   * centring (e.g. the Button's `align-items: center`). */
  /* Body font tier for the field label/description/error plus the toggle control
     row (its own line metrics must match the label's so the control row centres
     exactly), which lost `.p`. Scoped to just these (NOT the headings, which
     keep their own tier). */
  :is(.comfortable, .dense, .app, .site, .docs)
  :is(
    .ds.field-label,
    .ds.field-description,
    .ds.field-error,
    .ds.field-toggle,
    .ds.option
  ) {
    font-size: var(--typography-text-primary-font-size);
    font-family: var(--typography-text-primary-font-family);
  }

  :is(.comfortable, .dense, .app, .site, .docs)
    :is(
      .ds.field-label,
      .ds.field-description,
      .ds.field-error,
      .ds.field-toggle,
      .ds.option
    ) {
    line-height: 1;
    /* Baseline within a line-height:1 box (font-relative cap approximation). */
    --natural-baseline: calc((1em + 1cap) / 2);
    /* Pad the top so the baseline lands at the density target, less the box's own
       top border. */
    --space-before: max(
      0px,
      calc(
        var(--density-target-baseline-px, 0px) -
        var(--natural-baseline) -
        var(--border-top-width, 0px)
      )
    );
    padding-block-start: var(--space-before);
    padding-block-end: 0;
  }

  /* ── Intrinsic control seat: the composite text-input family ─────────────────
   * The single-line <input> no longer uses the line-height:1 crush + space-before
   * padding above (that rule is now labels-only). Instead it consumes the SHARED
   * control seat from @canonical/styles (modifiers.density.css): the input's own
   * line box (cell − 2 baselines) is the control interior, `--control-seat-before`
   * seats its baseline on the density target, and the CHROME closes the box with
   * `--control-seat-after` — so the chrome's height is INTRINSIC (no fixed
   * block-size) yet lands exactly on the density cell, both edges on the grid.
   *
   * Placed AFTER the fixed-height box rule above so this (equal-specificity)
   * rule wins for the text family. Direct chromes (select/date/time) and the
   * textarea keep the previous model until their own cutover pass. */
  :is(.comfortable, .dense, .app, .site, .docs)
  .ds.input:is(.text, .number, .password, .phone) {
    /* The COMPOSITE chrome family — every wrapper with an inner <input> leaf
       (text, number, password, phone). One selector, one seat: the wrapper is
       the box, the leaf carries the line. */

    /* NO drift term here — deliberately. The old ~2px "native input renders low"
       compensation was an artifact of the line-height:1 crush structure: give the
       <input> a real line box (--control-seat-line below) and it renders its text
       exactly like a <span> (measured; see the drift note at the end of this
       file). Subtracting the stale 2px lifted the text 2px too high. */

    /* The UA enforces a line-height FLOOR of `normal` (1.2em for Ubuntu) on a
       single-line <input> — a specified line-height below it is silently clamped
       (measured: dense's 16px line rendered 16.8px tall, pushing the chrome to
       24.8). So the seat computes with the FLOORED line the UA will actually
       use; the box then closes to the cell exactly in every density cell. */
    --seat-line-floored: max(var(--control-seat-line), 1.2em);

    /* The chrome's border folds in HERE (a var() inside a custom property
       substitutes at its declaring element, so the shared layer cannot read it).
       Derived from the target directly — not --control-seat-basis — because the
       basis assumes the unfloored line. Both the leaf's top pad and the chrome's
       closing pad read this SAME `--seat-before`, keeping the complement
       consistent. Rounded to ¼px so the pad is exactly representable in 1/64px
       layout units (the fractional 1cap term otherwise leaves ~1/60px residues
       on the box height). */
    --seat-before: round(
      nearest,
      max(
        0px,
        calc(
          var(--density-target-baseline-px, 0px) -
          (var(--seat-line-floored) + 1cap) /
          2 -
          var(--form-input-border-width, 0px)
        )
      ),
      0.25px
    );
    --seat-after: max(
      0px,
      calc(
        var(--density-line-height-effective) -
        var(--seat-line-floored) -
        var(--seat-before) -
        2 *
        var(--form-input-border-width, 0px)
      )
    );

    block-size: auto;
    min-block-size: 0;
    padding-block-end: var(--seat-after);
    /* Stretch (not the box rule's flex-start): a prefix/suffix — the password's
       reveal-toggle, the number's unit affix — spans the leaf's column and its
       own `align-items: center` centres its icon on the TEXT, which is the
       optical pairing (centring on the box would float it into the asymmetric
       closing pad). The old fixed-height model needed flex-start to top-pin the
       crushed leaf; the intrinsic leaf seats itself, so stretch is safe again. */
    align-items: stretch;
  }
  :is(.comfortable, .dense, .app, .site, .docs)
    .ds.input:is(.text, .number, .password, .phone)
    > input {
    line-height: var(--seat-line-floored);
    padding-block-start: var(--seat-before);
    padding-block-end: 0;
  }

  /* ── Textarea: many rows of the SAME intrinsic seat ──────────────────────────
   * The textarea is a single element (it carries the chrome itself), so it seats
   * like the button: the interior line box is `--control-seat-line` — which is a
   * WHOLE baseline multiple in every cell (cell − 2 bU) — so EVERY row advances
   * one grid interval, not just the first. The complement pad closes the box so
   * border + seat-before + N·line + seat-after + border ends on a grid line for
   * ANY row count N: the N-independent part equals (cell − line) ≡ 0 (mod 1 bU).
   * One seat, no multi-line special case.
   *
   * Two deliberate differences from the single-line input:
   *   · NO line-height floor — the UA's `normal` clamp is specific to single-line
   *     <input>; a textarea honours its specified line-height, and a floored
   *     16.8px line would knock every dense row off the grid.
   *   · NO drift term — like the single-line input, the old ~2px knob was an
   *     artifact of the crush-era structure (see the drift note below).
   *
   * The previous revision seated the first row via --td-space-before ON TOP of
   * the chrome's 8px block padding, targeting the OLD round(up) table; under the
   * round(nearest) targets that formula clamps to zero in every cell (the full
   * cell line-height puts the natural baseline below the target), which left the
   * textarea unseated entirely. The interior line box makes the target reachable
   * again. */
  :is(.comfortable, .dense, .app, .site, .docs) .ds.input.textarea {
    line-height: var(--control-seat-line);
    font-size: var(--typography-text-primary-font-size);
    font-family: var(--typography-text-primary-font-family);

    --seat-before: round(
      nearest,
      max(
        0px,
        calc(var(--control-seat-basis) - var(--form-input-border-width, 0px))
      ),
      0.25px
    );
    --seat-after: max(
      0px,
      calc(
        var(--density-line-height-effective) -
        var(--control-seat-line) -
        var(--seat-before) -
        2 *
        var(--form-input-border-width, 0px)
      )
    );

    block-size: auto;
    padding-block: var(--seat-before) var(--seat-after);
    /* Five whole rows + the closing geometry (border-box), so the default box
       ends on-grid with the last row fully visible: 4·line + cell. */
    min-block-size: calc(
      4 *
      var(--control-seat-line) +
      var(--density-line-height-effective)
    );
  }

  /* ── Select: a single-element direct chrome on the intrinsic seat ────────────
   * The <select> IS the chrome (border and text on one element), so it seats
   * like the button: interior line box + seat pads, height emerging as exactly
   * the density cell. Replaces the old fixed-height + 8px-block-padding path,
   * which never seated the option text at all and CLIPPED it in apps/dense
   * (24px fixed box − 8px pad left too little room for the line).
   * The line is floored like the single-line input's: a <select> shows one line,
   * so if the UA imposes a `normal` floor the formula already matches it, and if
   * it does not the specified floor is simply what renders — correct either way
   * (unlike the textarea, where flooring would break the multi-row rhythm).
   * Remaining direct chromes (date/time/datetime) stay on the previous model
   * until their own pass — their multi-part UA internals need their own
   * measurement. */
  :is(.comfortable, .dense, .app, .site, .docs) .ds.input.select {
    --seat-line-floored: max(var(--control-seat-line), 1.2em);
    line-height: var(--seat-line-floored);

    --seat-before: round(
      nearest,
      max(
        0px,
        calc(
          var(--density-target-baseline-px, 0px) -
          (var(--seat-line-floored) + 1cap) /
          2 -
          var(--form-input-border-width, 0px)
        )
      ),
      0.25px
    );
    --seat-after: max(
      0px,
      calc(
        var(--density-line-height-effective) -
        var(--seat-line-floored) -
        var(--seat-before) -
        2 *
        var(--form-input-border-width, 0px)
      )
    );

    block-size: auto;
    min-block-size: 0;
    padding-block: var(--seat-before) var(--seat-after);
  }

  /* ── Bottom rhythm: density-seated flow text only (NOT prose) ─────────────────
   * A BORDERED control (button, input wrapper) has a fixed `block-size` that is
   * already a whole baseline multiple, so its bottom rhythm is the box height —
   * no bottom padding needed (and it would be inert against the fixed height).
   *
   * The field label/description/error are density-seated with line-height:1, so
   * their box ends at the text descender; with `padding-block-end: 0` a following
   * grid/flow sibling (e.g. the textarea below a field label) resumes off-grid.
   * Fill the box out to a whole density line-height so its bottom lands on a grid
   * line. The `- 1em` term is correct precisely because these are line-height:1.
   *
   * Bare prose (p / .p / h1–h6) is NOT here: it is no longer density-seated (see the
   * partition above), so its box is its OWN snapped line-height and the engine's
   * --end-nudge already lands its bottom on the grid. Adding a density fill on top
   * would double-pad. Prose bottom rhythm belongs to the engine / `.editorial`. */
  :is(.comfortable, .dense, .app, .site, .docs)
  :is(.ds.field-label, .ds.field-description, .ds.field-error) {
    padding-block-end: max(
      0px,
      calc(
        var(
          --density-line-height,
          var(--density-lh-comfy, calc(var(--baseline-height) * 8))
        ) -
        var(--space-before) -
        1em
      )
    );
  }

  /* ── The native-control text drift — RESOLVED for single-line inputs ──────────
   * The old ~2px "native <input> renders its text lower than a <span> at
   * byte-identical CSS" compensation (--control-text-drift-AVOID-USAGE) turned
   * out to be an artifact of the line-height:1 crush structure, NOT an inherent
   * UA quirk: with a real line box (line-height: --control-seat-line, the
   * intrinsic seat above) the <input> positions its text exactly like a <span>
   * (measured: input baseline == label baseline to 0.01px with no drift term).
   * That answers TODO(#15)'s "find the structural cause and delete it": the
   * intrinsic seat carries NO drift anywhere — the textarea's local copy went
   * with its old parallel seat when it joined the intrinsic model. The knob no
   * longer exists in this file. */
}
