/* ============================================================
 * css/math.css — Shared MathML rendering layer for KAIS
 *
 * Native MathML only. No KaTeX, no MathJax, no LaTeX delimiters.
 * The KAIS content pipeline emits `<math xmlns="http://www.w3.org/1998/Math/MathML">…</math>`
 * directly (block math is wrapped in `<div class="math-block">`).
 * Browsers (Firefox, Safari, recent Chromium) render MathML
 * natively — no JS is required and none is loaded.
 *
 * Typography (KAIS house style): everything in `<math>` renders
 * UPRIGHT by default — variables, numerals, operators, units,
 * function names. This deliberately overrides the browser UA
 * stylesheet, which would otherwise auto-italicize single-char
 * `<mi>` tokens per the ISO 80000-2 convention. KAIS readers
 * found global italic math harder to scan, so the default is
 * flipped. Content authors who need an italic variable opt in
 * explicitly with `<mi mathvariant="italic">x</mi>` or
 * `<mi class="italic">x</mi>`. This layer:
 *   - resets any aggressive global reset (Tailwind preflight etc.)
 *     that would strip native MathML layout primitives;
 *   - forces upright on every MathML token element;
 *   - provides an explicit italic escape hatch;
 *   - styles the `.math-block` wrapper used by the generator;
 *   - provides print + reduced-motion fallbacks.
 *
 * Surface stylesheets (slides.css, note.css, flashcards.css,
 * workout.css) layer on top of this file to add per-surface
 * sizing, color, and scoped overrides (e.g. the dark code-frame
 * protection on `.slide .sourceCode:has(> math)`).
 *
 * Project tokens consumed: --surface, --accent (declared per
 * surface — slides.css L6-7, note.css L65-68, playground.css L10-11).
 * Sensible defaults are provided in `var(--token, fallback)` so
 * the layer is usable on pages that don't declare those tokens.
 * ============================================================ */


/* 1. Defensive reset.
 * Protect native MathML from any global `* { margin: 0; padding: 0; }`
 * reset (Tailwind preflight, flashcards.css L53-59). Without `all: revert`
 * fractions, super/subscripts and matrices collapse visually because
 * the UA-stylesheet padding/margins disappear.
 */
math, math * {
  all: revert;
  font-family: math, "STIX Two Math", "Latin Modern Math",
               "Cambria Math", "Asana Math", "Noto Sans Math",
               "Times New Roman", serif;
  line-height: normal;
  text-rendering: optimizeLegibility;
}


/* 2. Container reset — break italic inheritance & match parent size.
 * MathML inside `<em>`, `<blockquote>`, or any italic parent would
 * otherwise inherit `font-style: italic` and italicize numerals.
 * `font-size: inherit` ensures math glyphs scale with the
 * surrounding heading / paragraph / list-item — a `λ` inside an
 * `<h1>` should look as big as the H1 text, not stuck at body size.
 * `color: inherit` matches the surrounding text color (heading
 * accent, link color, etc).
 */
math {
  font-style: normal;
  font-size: inherit;
  font-variant-numeric: lining-nums tabular-nums;
  color: inherit;
}


/* 3. Inline math — flows inside the sentence.
 * `inline-block` (not `inline`) preserves the MathML layout box
 * across all engines without forcing a new line. `display: inline`
 * collapses some browsers' MathML layout, and `display: block`
 * would break the sentence flow. `inline-block` is the safe middle.
 * The `:not([display="block"])` guard keeps this rule from competing
 * with rule 4 — bare `<math>` and `<math display="inline">` match
 * here; only `<math display="block">` falls through to rule 4.
 */
math,
math[display="inline"],
math:not([display="block"]) {
  display: inline-block;
  vertical-align: baseline;
  margin: 0 0.15em;
}


/* 4. Block math — centered, horizontally scrollable for wide
 * content (matrices, long derivations). Triggered ONLY by the
 * explicit `display="block"` attribute on `<math>`. Wrapper-based
 * triggers (e.g. `.math-block math`) are deliberately omitted so
 * that an inline `<math>` accidentally placed inside a wrapper
 * still flows with the surrounding text.
 */
math[display="block"] {
  display: block;
  margin: 1em auto;
  text-align: center;
  width: fit-content;
  max-width: 100%;
  overflow-x: auto;
}


/* 5. Block-math wrapper.
 * The KAIS markdown→HTML generator wraps block equations in
 * `<div class="math-block">` so we have a styleable surface.
 * The plate is a subtle surface tint so glyphs always read
 * against the page background regardless of theme.
 */
.math-block {
  margin: 1.25em auto;
  padding: 0.6em 0.9em;
  background: var(--surface, rgba(15, 23, 42, 0.04));
  border-radius: 0.5rem;
  overflow-x: auto;
  max-width: 100%;
}


/* 6. Upright-by-default for every MathML token element.
 * Overrides the browser UA stylesheet, which auto-italicizes
 * single-char `<mi>`. KAIS house style is upright math; italic
 * is opt-in via the escape hatches in rule 7.
 */
math mi,
math mn,
math mo,
math mtext,
math mspace,
math ms {
  font-style: normal !important;
}


/* 7. Explicit italic escape hatch.
 * Content authors who genuinely want an italic variable (legacy
 * physics notation, a published-textbook reproduction, etc.) opt
 * in per-token with `mathvariant="italic"` or `class="italic"`.
 * `!important` here matches rule 6 so the escape hatch wins.
 */
math mi[mathvariant="italic"],
math mi.italic {
  font-style: italic !important;
}


/* 8. Padding around operators for readability. */
math mo {
  padding: 0 0.1em;
}


/* 9. Fractions and roots — small horizontal padding so the divisor
 * bar and radical have breathing room. */
math mfrac,
math msqrt,
math mroot {
  padding: 0 0.1em;
}


/* 10. Matrices and tables — collapse borders, pad cells. */
math mtable {
  border-collapse: collapse;
}
math mtr,
math mtd {
  padding: 0.15em 0.5em;
}


/* 11. <mtext> adjacency spacing — both directions.
 *
 * Two adjacency patterns need horizontal breathing room so that
 * prose hints embedded inside `<math>` (like solve-step labels
 * "Subtract ", "Simplify: ", "where ", "between ") don't run flush
 * against the math glyph next to them.
 *
 * 11a. Trailing direction — math token then <mtext>.
 *      Original units-spacing rule ("5 kg", "9.81 m/s²") extended
 *      to fractions, roots, super/subscripts so trailing hints
 *      like "<mi>x</mi><mtext> from both sides</mtext>" or
 *      "<msqrt>...</msqrt><mtext> approximately</mtext>" breathe.
 *
 * 11b. Leading direction — <mtext> then math token.
 *      Pins the user-reported "Subtractx" / "Simplify:2x" bug.
 *      Whenever a hint `<mtext>` is followed by `<mi>`, `<mn>`,
 *      `<mfrac>`, `<msqrt>`, `<mroot>`, `<msup>`, `<msub>`, the
 *      adjacent-sibling margin gives the math glyph room.
 *
 * The adjacent-sibling combinator (`A + B`) attaches the margin
 * to the SECOND element, so we always use `margin-left` on the
 * right-hand side regardless of direction. `:is(...)` groups the
 * math token list once so adding a new token type stays one edit.
 *
 * Regression-pinned by:
 *   - kais/tests/test_math_inline_mtext_adjacency_spacing.py
 *   - kais/tests/test_note_math_inline_spacing.py
 */
math :is(mi, mn, mfrac, msqrt, mroot, msup, msub) + mtext,
math mtext + :is(mi, mn, mfrac, msqrt, mroot, msup, msub) {
  margin-left: 0.2em;
}

/* Backwards-compatible verbatim selectors — kept so the original
 * units-spacing test pins ("5 kg", "9.81 m/s²") continue to match
 * the literal selector text. The :is() group above is the canonical
 * source; these are aliases. */
math mn + mtext,
math mi + mtext {
  margin-left: 0.2em;
}


/* 12. Keyboard scroll affordance for wide block math.
 * The generator may emit `tabindex="0"` on `.math-block` so the
 * overflow region is keyboard-scrollable. Give that focus state
 * a visible ring.
 */
.math-block:focus-visible {
  outline: 2px solid var(--accent, #ff9a00);
  outline-offset: 2px;
}


/* 13. LaTeX-delimiter fallback canary.
 * If raw `\(...\)` or `$...$` ever slips through the pipeline,
 * wrap it in `.math-fallback` so QA spots it in red. KAIS is
 * MathML-only — these are bugs, not features.
 */
.math-fallback {
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  color: #b91c1c;
  background: #fef2f2;
  padding: 0 0.25em;
  border-radius: 0.25em;
  border: 1px dashed #fca5a5;
}


/* 14. Print — strip surface tints, force black ink, avoid splitting
 * equations across page breaks. */
@media print {
  math {
    color: black !important;
  }
  .math-block {
    break-inside: avoid;
    page-break-inside: avoid;
    background: transparent;
    box-shadow: none;
    border: 1px solid #ccc;
  }
}


/* 15. Reduced motion — no animations or transitions on math. */
@media (prefers-reduced-motion: reduce) {
  math,
  .math-block {
    transition: none !important;
    animation: none !important;
  }
}
