/* =========================================
   字幕アトリエ — main stylesheet
   Organized with @layer to control cascade order.

   This file holds the tokens, base, layout and utilities layers and the
   components shared across the app (buttons, inputs, switches, popovers).
   Components that belong to one feature live beside it, each adding to
   @layer components: toolbar.css, tab-languages.css, tab-filter.css,
   tab-obs.css, dialogs.css, color-picker.css. This file must load first —
   its @layer statement is what fixes the layer order for all of them.

   Design system (dark, Apple-inspired aesthetic):
   - the page itself is the subtitle background (--sub-bg, user-configured,
     a blue-tinted near-black by default — the same cool cast as the card's
     greys, so the card reads as part of it rather than cut out of a void; the
     subtitle window keeps its own fixed key green);
     the control card floats on it with its own dark palette, which climbs
     --color-bg (deepest: code blocks, wells) → surface-1 (card, dialogs) →
     surface-2 (inputs, inset tracks) → surface-3 (hover / raised chips);
     separation prefers hairlines + elevation over solid borders.
   - text hierarchy is white at three opacity levels (≈88/55/30%).
   - spacing uses a numeric 4/8/12/16/24 scale (--space-1..5).
   - type collapses onto a 4-step scale (--text-xs..lg).
   - focus is a soft accent ring (--focus-ring) everywhere.
   ========================================= */

@layer reset, tokens, base, layout, components, utilities;

/* ============ reset ============ */
@layer reset {
  *, *::before, *::after { box-sizing: border-box; }
  html, body, h1, h2, h3, h4, p, ul, ol, figure { margin: 0; padding: 0; }
  ul, ol { list-style: none; }
  button { font: inherit; cursor: pointer; background: none; border: 0; color: inherit; }
  input, select, textarea { font: inherit; color: inherit; }
  img, svg { display: block; max-width: 100%; }
  :focus-visible { outline: none; box-shadow: var(--focus-ring); }
}

/* ============ tokens ============ */
@layer tokens {
  :root {
    color-scheme: dark;

    /* --- typography --- */
    /* One superfamily for the whole UI. The regional face still switches with
       the interface language (see :root:lang(ja)) so each language keeps its
       correct glyph forms, but because Noto Sans TC and JP are cut from the
       same source they share metrics — switching language no longer resizes
       labels and nudges the layout. Latin always comes from Noto Sans, which
       harmonises with both.
       Rounded faces are deliberately NOT used here: their rounded terminals
       blur dense kanji at the 11.5–14px this panel runs at. */
    --font-ui:       "Noto Sans", "Noto Sans TC", system-ui, -apple-system, "Segoe UI", "Microsoft JhengHei", sans-serif;
    /* --font-subtitle lives in css/subtitle-display.css. */

    --text-xs: 0.72rem;
    --text-sm: 0.8rem;
    --text-md: 0.875rem;
    --text-lg: 1rem;

    /* --- UI palette (dark, Apple system colors) --- */
    --color-bg:            #151517;
    --color-surface-1:     #1d1d20;   /* header, control panel, dialogs */
    --color-surface-2:     #27272b;   /* inputs, inset tracks */
    --color-surface-3:     #323238;   /* hover states, raised segments */
    /* Menus and panels that open over the card. A step lighter than it, as
       macOS draws anything raised in dark mode: same as the card, a menu over
       it was told apart by a hairline alone. */
    --color-surface-popover: #2c2c2e;
    --color-border:        rgba(255, 255, 255, 0.08);   /* hairline */
    --color-border-strong: rgba(255, 255, 255, 0.16);
    --color-text:          rgba(255, 255, 255, 0.88);
    --color-text-dim:      rgba(255, 255, 255, 0.55);
    --color-text-faint:    rgba(255, 255, 255, 0.48);   /* ≈4.8:1 on surface-1, 4.5:1 on surface-2 */
    --color-accent:        #0a84ff;
    --color-accent-hover:  #2f94ff;
    --color-accent-fill:       #0071e3;   /* white text on accent: 4.7:1 (#0a84ff is only 3.65:1) */
    --color-accent-fill-hover: #0068d1;   /* hover darkens, so white text gets more contrast, not less */
    --color-accent-soft:   color-mix(in oklab, var(--color-accent) 20%, transparent);
    --color-danger:        #ff453a;
    --color-danger-fill:       #d70015;   /* white text on red: 5.4:1 (#ff453a is only 3.4:1) */
    --color-danger-fill-hover: #c4281c;   /* hover darkens, like --color-accent-fill-hover */
    --color-danger-text:       color-mix(in oklab, var(--color-danger) 85%, white);
    --color-success:       #32d74b;
    --color-warning:       #ffd60a;

    /* --- material fills (translucent, read over any surface) --- */
    --fill-1: rgba(255, 255, 255, 0.09);   /* resting controls */
    --fill-2: rgba(255, 255, 255, 0.14);   /* hovered controls */
    --fill-3: rgba(255, 255, 255, 0.22);   /* raised / selected chips */
    --fill-inset: rgba(0, 0, 0, 0.22);     /* inset tracks, darker than their chrome */
    --fill-track: rgba(255, 255, 255, 0.18); /* slider rails: lighter than the card, as macOS draws them */
    --fill-toggle: var(--fill-3);          /* switch track while off */

    /* --- motion (custom curves — built-in CSS easings are too weak) --- */
    --ease-out:    cubic-bezier(0.23, 1, 0.32, 1);    /* UI enter / press release */
    --ease-in-out: cubic-bezier(0.77, 0, 0.175, 1);   /* on-screen movement */
    --ease-drawer: cubic-bezier(0.32, 0.72, 0, 1);    /* iOS-like drawer slide */

    /* --- elevation / focus (soft, two-layer Apple shadows) --- */
    --shadow-1:       0 1px 2.5px rgba(0, 0, 0, 0.3);
    --shadow-2:       0 4px 16px rgba(0, 0, 0, 0.28), 0 1px 3px rgba(0, 0, 0, 0.3);
    --shadow-overlay: 0 24px 64px rgba(0, 0, 0, 0.5), 0 4px 16px rgba(0, 0, 0, 0.35);
    --shadow-popover: 0 12px 32px rgba(0, 0, 0, 0.45);
    --color-scrim:    rgba(0, 0, 0, 0.5);   /* dialog backdrop */
    --focus-ring:     0 0 0 3px color-mix(in oklab, var(--color-accent) 40%, transparent);

    /* --- layout sizing --- */
    /* The control card (toolbar + tab body); the manual panel matches it.
       Sized to the Languages tab, the one people sit on, rather than to the
       tallest tab: the OBS tab's instructions scroll instead (.tab-panel is
       overflow-y: auto). It was 324px while the engine column kept a footer
       row for the signature; moving that into the engine row freed 46px.
       Given back 24px once the toolbar moved to the card's bottom edge: the
       tab body ended flush against it there, and the panel is only this tall
       while setting up — captures run collapsed or from the subtitle window.
       Raised to 320px when the source group gained its pictures row
       (js/ui-deco.js): at 309px the colour row ended flush on the edge, and
       the new row pushed it 4px under; the rest is room so it no longer
       touches. */
    --control-panel-h: 320px;
    /* Widest the card grows to before it centres itself in the window. Sized
       to its content rather than the window: the Languages tab's matrix under
       a cloud style (its widest, seven columns: ~920px in English and
       Japanese, whose labels are the longest) plus the card's padding, which
       also holds the toolbar (~900px). Wider only left an empty band at the
       right of the matrix under a toolbar that spans the card. */
    --panel-measure:   976px;
    --radius-sm:       6px;
    --radius-md:       10px;
    --radius-lg:       16px;
    --radius-full:     999px;
    --space-1:         4px;
    --space-2:         8px;
    --space-3:         12px;
    --space-4:         16px;
    --space-5:         24px;

    /* How far the control card is inset from the window. The card being the
       centred object — rather than a full-width strip with centred content —
       is what keeps its edges and its content's edges from disagreeing. */
    --card-inset:      var(--space-4);

    /* Label column shared by every labelled row in every tab. One value means
       controls line up on a single seam, and switching tabs doesn't shift it. */
    --label-col:       130px;

    /* --- subtitle settings (driven from JS) --- */
    --sub-bg:                #0E1016;
    --sub-align:             center;
    --sub-overflow:          normal;        /* normal | shrink (max 2 lines) */

    --sub-source-color:      #FFFFFF;
    --sub-source-stroke:     #000000;
    --sub-source-stroke-w:   4px;
    --sub-source-size:       22px;

    --sub-target1-color:     #FFFFFF;
    --sub-target1-stroke:    #000000;
    --sub-target1-stroke-w:  4px;
    --sub-target1-size:      22px;

    --sub-target2-color:     #FFFFFF;
    --sub-target2-stroke:    #000000;
    --sub-target2-stroke-w:  4px;
    --sub-target2-size:      22px;
  }

  /* Light theme (js/theme.js sets data-theme). Warm rather than a white sheet:
     cream panels on a custard page, deep brown for text instead of black and
     caramel in place of the blue accent. The page itself (--sub-bg) is a user
     setting, not a token, so its light default lives in js/theme.js.
     Only the palette changes here; every component reads these names, which
     is the whole of what makes a second theme cheap. The few literal colours
     that do not survive a light surface are overridden beside their rules
     (search for data-theme="light").
     Contrast, measured: text 12.1:1 on surface-1; dim 5.7:1; faint 5.1:1 on
     surface-1 and 4.6:1 on surface-2; white on accent-fill 5.9:1. */
  :root[data-theme="light"] {
    color-scheme: light;

    --color-bg:            #F0E4C8;
    --color-surface-1:     #FBF3DF;
    --color-surface-2:     #F4E8CC;
    --color-surface-3:     #ECDDB9;
    /* The card's own cream: on a light surface the shadow raises a menu. */
    --color-surface-popover: var(--color-surface-1);
    --color-border:        rgba(94, 62, 30, 0.14);
    --color-border-strong: rgba(94, 62, 30, 0.26);
    --color-text:          #3E2B1F;
    --color-text-dim:      #6E5743;
    --color-text-faint:    #7A6350;
    --color-accent:        #8A5A2B;
    --color-accent-hover:  #9C6A36;
    --color-accent-fill:       #8A5A2B;
    --color-accent-fill-hover: #774B22;
    --color-danger:        #C9372C;
    --color-danger-fill:       #B42318;
    --color-danger-fill-hover: #9E1F15;
    --color-danger-text:       #A8291F;
    --color-success:       #3A8F3F;
    --color-warning:       #C98A00;

    /* Fills flip from white-on-dark to brown-on-cream. The raised chip is the
       exception: it becomes an opaque cream that sits above the inset track,
       the way a selected segment does in a light macOS control. */
    --fill-1: rgba(94, 62, 30, 0.07);
    --fill-2: rgba(94, 62, 30, 0.11);
    --fill-3: #FFFCF3;
    --fill-inset: rgba(94, 62, 30, 0.09);
    --fill-track: rgba(94, 62, 30, 0.22);
    /* Not --fill-3: a cream track on a cream card is no switch at all. */
    --fill-toggle: rgba(94, 62, 30, 0.2);

    /* Brown-tinted and lighter: black shadows at dark-theme strength read as
       smudges on cream. */
    --shadow-1:       0 1px 2px rgba(80, 50, 20, 0.16);
    --shadow-2:       0 4px 14px rgba(80, 50, 20, 0.14), 0 1px 3px rgba(80, 50, 20, 0.12);
    --shadow-overlay: 0 24px 56px rgba(80, 50, 20, 0.22), 0 4px 14px rgba(80, 50, 20, 0.14);
    --shadow-popover: 0 12px 28px rgba(80, 50, 20, 0.2);
    --color-scrim:    rgba(60, 40, 20, 0.32);
  }

  /* The second window (index.html?ch=2, js/channel.js): purple in place of
     the accent, in both themes, so the two windows are told apart at a glance
     — the start button above all. Nothing else changes; the subtitles are
     the user's colours either way.
     Contrast, measured: white on accent-fill 6.0:1 (dark), 6.9:1 (light). */
  :root[data-ch="2"] {
    --color-accent:            #bf5af2;
    --color-accent-hover:      #c86ff5;
    --color-accent-fill:       #8944ab;
    --color-accent-fill-hover: #7a3a99;
  }
  :root[data-ch="2"][data-theme="light"] {
    --color-accent:            #7b3fa0;
    --color-accent-hover:      #8c4db3;
    --color-accent-fill:       #7b3fa0;
    --color-accent-fill-hover: #6a3389;
  }

  /* 日文 UI 時把 CJK 那一段換成日文字形。同一個碼位在台日兩地的寫法不同
     （直、骨、喝…），這無法靠 fallback 順序處理，必須明確覆寫。
     TC 與 JP 同源，所以換的只是字形，字寬不變。
     字幕（--font-subtitle）刻意不跟著切換：一行裡可能同時有原文和兩種
     譯文，沒有單一語言可以跟。 */
  :root:lang(ja) {
    --font-ui: "Noto Sans", "Noto Sans JP", system-ui, "Yu Gothic UI", "Hiragino Sans", sans-serif;
  }
}

/* ============ base ============ */
@layer base {
  html, body { height: 100%; }

  body {
    font-family: var(--font-ui);
    /* The whole window is the user-configured subtitle background, near-black
       by default, and the control card floats on it with its own dark palette.
       In window-capture mode (obs.mode.capture) this window IS the output, so
       the user sets a key colour here for OBS to remove; anything drawn on
       --sub-bg is then judged by whether a keyer can remove it — see
       css/subtitle-core.css. The subtitle window does not follow this: its
       background is fixed key green (subtitle-window.html).
       (--color-bg stays the dark base for wells inside the card — code blocks,
       readonly fields.) */
    background: var(--sub-bg);
    color: var(--color-text);
    min-width: 1000px;
    overflow: hidden;
    /* A single row: .app-main owns the whole window. The keyed subtitle area
       sits flush with the top edge for OBS window capture, and the control card
       floats over the background below it. */
    display: grid;
    grid-template-rows: minmax(0, 1fr);
  }

  /* slim scrollbars for the few internal scroll areas (Chrome-only app) */
  .filter-list::-webkit-scrollbar,
  .obs-conn::-webkit-scrollbar,
  .tab-panel::-webkit-scrollbar,
  .dialog-body::-webkit-scrollbar { width: 8px; height: 8px; }

  .filter-list::-webkit-scrollbar-thumb,
  .obs-conn::-webkit-scrollbar-thumb,
  .tab-panel::-webkit-scrollbar-thumb,
  .dialog-body::-webkit-scrollbar-thumb {
    background: var(--color-surface-3);
    border-radius: var(--radius-sm);

    &:hover { background: var(--color-border-strong); }
  }

  .filter-list::-webkit-scrollbar-track,
  .obs-conn::-webkit-scrollbar-track,
  .tab-panel::-webkit-scrollbar-track,
  .dialog-body::-webkit-scrollbar-track { background: transparent; }
}

/* ============ layout ============ */
@layer layout {

  /* The card's single toolbar row. Two groups: what is used while streaming
     on the left (mic, start/stop, subtitle window), what is used while setting
     up on the right (the tab picker, then global actions). The tab picker used
     to sit centred on a 1fr/auto/1fr track, which capped each side at half of
     what it left — too little once the left group grew a third button. Now
     each group takes what it needs and the slack falls between them. */
  .control-toolbar {
    display: grid;
    /* minmax(0, 1fr) in the middle: the collapsed-state readout lives there,
       and its language names can run long. With a zero minimum it ellipsizes
       instead of pushing the groups — and .toolbar-actions, being mostly icon
       buttons, has nowhere to give. */
    grid-template-columns: auto minmax(0, 1fr) auto;
    align-items: center;
    gap: var(--space-3);
    padding: var(--space-2) var(--space-3);

    .toolbar-start   { grid-column: 1; }
    .toolbar-status  { grid-column: 2; justify-self: center; max-width: 100%; }
    .toolbar-actions { grid-column: 3; }

    /* Hidden until .panel-collapsed shows it (and hides the tabs). The
       transparent border and 6px padding reproduce the tab track's box (1px
       border + 3px + the button's own 3px), so the swap cannot change the
       toolbar's height and jolt the output. */
    .toolbar-status {
      display: none;
      margin: 0;
      padding: 6px var(--space-2);
      border: 1px solid transparent;
      font-size: var(--text-md);
      color: var(--color-text-dim);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }


    .toolbar-actions {
      justify-self: end;
      display: flex;
      align-items: center;
      gap: var(--space-2);

      /* Extra room between the setup capsules and the global actions. Space
         rather than a divider: the capsules already read as their own group,
         and the room goes with them when .panel-collapsed hides them. */
      > .settings-nav { margin-right: var(--space-2); }
    }
  }

  .app-main {
    /* Two stacked rows: the subtitle area on top and the control card below.
       Collapsing (.panel-collapsed) drops the card's tab body so the green area
       grows — this is the normal state while streaming a window capture — while
       the card's toolbar stays put. The manual-translate tool is an overlay
       over the subtitles (see .manual-translate-panel) so opening it never
       resizes the green box. */
    display: grid;
    grid-template-rows: minmax(0, 1fr) auto;
    position: relative;
    min-height: 0;
    /* The closed manual-translate drawer is parked below the bottom edge;
       clip it here so it can't peek out. */
    overflow: clip;
  }

  .output-pane {
    display: grid;
    grid-template-rows: minmax(0, 1fr);
    /* No background of its own — body paints --sub-bg across the whole window
       so the output pane and the area around the card are one continuous surface. */
    min-width: 0;
    min-height: 0;
    /* The lines below refuse to shrink, so on a short window the stack runs
       past the bottom of this pane. The control card covers the middle of that
       area but not the strips beside it (it stops at --panel-measure) or the
       inset below it, and half a character floating next to the panel is worse
       than a line that simply ends at the panel's edge. */
    overflow: hidden;

    /* .subtitle-display and its lines live in css/subtitle-display.css,
       shared with the subtitle window (subtitle-window.html). */
  }

  /* Manual text-translation slide-up overlay. Anchored to the bottom of
     .app-main (not the output pane) so it rises from the very bottom of the window
     and covers the control panel. Hidden by default (translated fully below its
     own height); .manual-open slides it into view. */
  .manual-translate-panel {
    position: absolute;
    /* left/right 0 + an explicit width + auto inline margins centres it on the
       control card's geometry, so the drawer arrives as the same object in the
       same place rather than as a full-width sheet over a centred card. */
    left: 0;
    right: 0;
    bottom: var(--card-inset);
    width: min(100% - var(--card-inset) * 2, var(--panel-measure));
    margin-inline: auto;
    height: var(--control-panel-h);
    z-index: 20;
    display: grid;
    grid-template-rows: auto minmax(0, 1fr) auto auto;
    gap: var(--space-2);
    background: var(--color-surface-1);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    /* No drop shadow, for the reason spelled out on .control-card — and this
       one bit even while the drawer was closed. Parked below the window, its
       --shadow-overlay (64px of blur) still reached up over the bottom edge:
       the last 16 rows of the capture measured 20480 pixels running from
       rgb(0,242,0) to rgb(0,204,0), a full-width dark green band that an OBS
       Color Key cannot remove. Open, the same shadow would land on the keyed
       area above the drawer instead. */
    padding: var(--space-3) var(--space-4);
    min-height: 0;
    /* Parked below its own height plus the inset, so it clears the window. */
    transform: translateY(calc(100% + var(--card-inset)));
    /* iOS-like drawer curve; this base rule times the exit (200ms) — the
       slower 300ms enter lives on .manual-open (transitions read their
       duration from the destination state), so closing feels snappier. */
    transition: transform 0.2s var(--ease-drawer);
  }

  .manual-panel-head {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .manual-panel-title {
      font-size: var(--text-md);
      font-weight: 600;
    }
  }

  .control-card {
    /* One floating surface holding the toolbar and the active tab. Because the
       card itself is the centred object, there are no full-width strips whose
       edges can disagree with the content inside — the earlier tab-bar-on-top /
       control-strip-at-the-bottom arrangement sandwiched the content between
       two bands, which read as an I-beam on wide displays.
       .panel-collapsed hides only the tab body, so the toolbar (and start/stop
       with it) stays reachable while the output fills the window.
       The toolbar is the card's bottom row and the tab body grows upward
       above it, so start/stop sits at the same height whether the panel is
       open, collapsed or being resized; with the toolbar on top, each of those
       moved it. Placed by grid row rather than DOM order, so the tabs still
       come before the panel they control in tab order. */
    position: relative;   /* anchors the height grip (.panel-resize) */
    display: grid;
    grid-template-rows: auto minmax(0, 1fr) auto;

    > .settings-head   { grid-row: 1; }
    > .settings-body   { grid-row: 2; }
    > .control-toolbar { grid-row: 3; }
    width: min(100% - var(--card-inset) * 2, var(--panel-measure));
    height: var(--control-panel-h);
    margin: 0 auto var(--card-inset);
    background: var(--color-surface-1);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    /* No drop shadow, deliberately. The window is always the keyed surface in
       obs.mode.capture, and --shadow-2 spills a 16px gradient of translucent
       black onto --sub-bg: measured on a 1280x720 render, the 26 rows above the
       card hold 15802 pixels that are green but not the key colour — a band
       running from rgb(0,253,0) down to rgb(0,201,0) at the window's bottom
       edge. OBS Color Key measures RGB distance, so rgb(0,201,0) sits 54 away
       from the key and survives as a dark green halo around the whole card.
       (The same page with the shadow removed measures 0.) The card still reads
       as a separate surface: it has an opaque fill and a 1px border.
       This used to be scoped to .panel-collapsed, which left the shadow on the
       key colour in the expanded state — the state the app opens in. */
    min-height: 0;
    /* Keeps the tab body's corners inside the card's radius. */
    overflow: hidden;

    /* Press feedback for the background gesture (js/ui-layout.js). The press
       lands outside this card, so the card is the only thing that can say what
       the press is about; it gives under the pointer the way a button does, at
       a fraction of the depth because the surface is a hundred times the size.
       Armed on pointerdown, and deliberately NOT armed while the gesture is
       locked — a press that produces nothing is how the lock explains itself
       without a label. */
    transition: transform 120ms var(--ease-out);

    &.is-arming { transform: scale(0.995); }

    /* The settings tabs along the card's top edge: plain labels over an
       underline rather than the inset capsule the toolbar's audio input wears,
       so the two no longer read as the same kind of control — one switches the
       body below it, the other opens a panel. The top padding clears the
       height grip, which sits on the card's edge above the labels. No
       animation on switching — tabs are flipped dozens of times a day. */
    .settings-head {
      padding: var(--space-3) var(--space-4) 0;
      border-bottom: 1px solid color-mix(in oklab, var(--color-border) 60%, transparent);
    }

    .settings-tabs {
      display: flex;
      align-items: flex-end;
      gap: var(--space-1);

      .tab-btn {
        position: relative;
        padding: 4px 12px 8px;
        font-size: var(--text-md);
        color: var(--color-text-dim);
        border-radius: var(--radius-md) var(--radius-md) 0 0;
        transition: color 0.15s, background 0.15s;

        &:hover {
          color: var(--color-text);
          background: var(--fill-1);
        }

        /* Sits on the head's hairline, so the active tab reads as opening
           onto the body below. */
        &::after {
          content: "";
          position: absolute;
          left: 8px;
          right: 8px;
          bottom: -1px;
          height: 2px;
          border-radius: 2px;
          background: transparent;
          transition: background 0.15s;
        }

        &.is-active {
          color: var(--color-text);
          font-weight: 600;
          &::after { background: var(--color-accent); }
        }
      }
    }

    /* The audio input (microphone, tab audio) in the toolbar, as one inset
       capsule — the same track as the .seg-switch controls in the tab bodies,
       so every segmented control in the card is one material. */
    .settings-nav {
      display: flex;
      align-items: center;
      gap: var(--space-2);

      .settings-nav-group {
        display: flex;
        align-items: center;
        gap: 2px;
        padding: 3px;
        background: var(--fill-inset);
        border: 1px solid var(--color-border);
        border-radius: var(--radius-full);
      }

      /* The source button is a material chip that rises on hover. */
      .mic-btn {
        padding: 3px 12px;
        font-size: var(--text-md);
        color: var(--color-text-dim);
        border-radius: var(--radius-full);
        transition: color 0.15s, background 0.15s, transform 0.15s var(--ease-out);

        &:hover {
          color: var(--color-text);
          background: var(--fill-1);
        }

        &:active { transform: scale(0.97); }

        &.is-active {
          color: var(--color-text);
          background: var(--fill-2);
        }
      }
    }

    .settings-body {
      min-height: 0;
      overflow: hidden;
      /* The tabs' hairline above does the separating. A step on every side;
         the one below keeps the tab's last full-width row (the presets row,
         the filter tab's add buttons) from running into the toolbar. */
      padding: var(--space-3) var(--space-4) var(--space-4);

      /* Tabs are designed to fit without scrolling (the Filter tab scrolls
         inside its rule lists instead); overflow-y is a graceful fallback
         for edge cases like very long engine status text. */
      .tab-panel {
        height: 100%;
        min-height: 0;
        overflow-y: auto;
        /* Reserve the scrollbar's width even while nothing overflows, so a
           tab growing taller (e.g. the custom-URL row appearing) doesn't
           shift the whole layout when the scrollbar pops in; the padding
           keeps content from sitting flush against the scrollbar. */
        scrollbar-gutter: stable;
        padding-right: var(--space-2);
      }
    }
  }
}

/* ============ components ============ */
@layer components {

  /* --- generic buttons: borderless material capsules; feedback is
         instant on press (scale), Apple-style --- */
  .btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: var(--space-1);
    padding: 5px var(--space-4);
    border: 0;
    border-radius: var(--radius-full);
    background: var(--fill-1);
    color: var(--color-text);
    font-size: var(--text-sm);
    transition: background 0.15s, color 0.15s, transform 0.15s var(--ease-out);

    &:hover:not(:disabled) {
      background: var(--fill-2);
    }

    &:active:not(:disabled) { transform: scale(0.97); }

    &:disabled { opacity: 0.45; cursor: not-allowed; }

    &.primary {
      background: var(--color-accent-fill);
      color: white;

      &:hover:not(:disabled) {
        background: var(--color-accent-fill-hover);
      }
    }

    &.danger {
      background: var(--color-danger-fill);
      color: white;

      &:hover:not(:disabled) {
        background: var(--color-danger-fill-hover);
      }
    }
  }

  /* --- panel height grip (top edge of the control card; js/ui-layout.js) ---
     A short bar centred on the edge, the usual sign for "this pulls". The hit
     area is the toolbar's top padding, so it covers no control. */
  .panel-resize {
    position: absolute;
    top: 0;
    left: 50%;
    translate: -50% 0;
    z-index: 1;
    width: 112px;
    height: var(--space-2);
    display: grid;
    place-items: center;
    cursor: ns-resize;
    touch-action: none;

    &::before {
      content: "";
      width: 72px;
      height: 4px;
      border-radius: var(--radius-full);
      background: var(--color-border-strong);
      transition: background 0.15s;
    }

    &:hover::before,
    &:focus-visible::before { background: var(--color-text-dim); }
    &:focus-visible { outline: none; }
  }

  /* While dragging, the pointer can wander over text and other cursors; keep
     the resize cursor and stop the drag from selecting anything. */
  .is-resizing-panel,
  .is-resizing-panel * {
    cursor: ns-resize !important;
    user-select: none;
  }
  .is-resizing-panel .panel-resize::before { background: var(--color-accent); }

  /* --- icon-only button (32×32) --- */
  .icon-btn {
    width: 32px;
    height: 32px;
    display: inline-grid;
    place-items: center;
    border-radius: var(--radius-md);
    color: var(--color-text-dim);
    transition: background 0.15s, color 0.15s, transform 0.15s var(--ease-out);

    &:hover { background: var(--fill-1); color: var(--color-text); }

    &:active { transform: scale(0.94); }

    /* pressed/active state (e.g. layout toggle while its panel is collapsed):
       a quiet accent tint rather than a full accent fill */
    &.is-active {
      background: var(--color-accent-soft);
      color: var(--color-accent-hover);

      &:hover {
        background: color-mix(in oklab, var(--color-accent) 28%, transparent);
        color: var(--color-accent-hover);
      }
    }

    svg { width: 18px; height: 18px; }
  }

  /* --- segmented switch (button-based for i18n switcher,
         radio-based for settings via <label><input><span></label>).
         An inset track; the active segment is a raised chip. --- */
  .seg-switch {
    /* Positioning context so the visually-hidden (position:absolute) radios
       below stay contained here instead of escaping to the viewport — an
       escaped radio gets focus-scrolled into view, scrolling the whole page
       and pushing the header off-screen. */
    position: relative;
    display: inline-flex;
    gap: 2px;
    padding: 2px;
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    background: var(--fill-inset);

    /* button-based variant (i18n switcher) */
    button {
      padding: 3px 10px;
      border-radius: calc(var(--radius-md) - 3px);
      color: var(--color-text-dim);
      font-size: var(--text-sm);
      letter-spacing: 0.5px;
      transition: background 0.15s, color 0.15s, transform 0.15s var(--ease-out);

      &:hover { color: var(--color-text); }

      &:active { transform: scale(0.97); }

      &.is-active {
        background: var(--fill-3);
        color: var(--color-text);
        box-shadow: var(--shadow-1);
      }
    }

    /* radio-based variant (settings) */
    label {
      display: inline-flex;
      cursor: pointer;
    }

    input[type="radio"] {
      position: absolute;
      opacity: 0;
      pointer-events: none;
    }

    label > span {
      padding: 3px 10px;
      border-radius: calc(var(--radius-md) - 3px);
      color: var(--color-text-dim);
      font-size: var(--text-sm);
      transition: background 0.15s, color 0.15s, transform 0.15s var(--ease-out);
      user-select: none;
    }

    label:hover > span { color: var(--color-text); }

    label:not(.is-disabled):active > span { transform: scale(0.97); }

    input[type="radio"]:checked + span {
      background: var(--fill-3);
      color: var(--color-text);
      box-shadow: var(--shadow-1);
    }

    input[type="radio"]:focus-visible + span {
      box-shadow: var(--focus-ring);
    }

    /* Engine option whose backend is unavailable (e.g. Chrome AI not ready). */
    label.is-disabled { cursor: not-allowed; }
    label.is-disabled > span { opacity: 0.4; }
    label.is-disabled:hover > span { color: var(--color-text-dim); }
  }

  /* icon-only variant (e.g., alignment switch) — fixed square cells */
  .seg-switch-icons {
    label > span {
      display: inline-grid;
      place-items: center;
      padding: 5px 8px;
    }
    svg { display: block; }
  }

  /* --- form rows (used inside tabs) --- */
  .form-row {
    display: grid;
    grid-template-columns: var(--label-col) 1fr;
    align-items: center;
    gap: var(--space-2);
    padding: var(--space-1) 0;

    .form-row-label {
      color: var(--color-text-dim);
      font-size: var(--text-md);
    }
  }

  /* Download button with the pack's name beside it. Wraps so a long name drops
     to its own line instead of widening the source column. */
  /* A row of a section's controls, optionally led by its heading. Inlining the
     heading costs no height — the control beside it is taller anyway — which
     matters in the shortest tab in the app. (Same idea as .style-wrap-head in
     the Style tab.) Wraps rather than overflowing when the column gets narrow. */
  .col-head {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: var(--space-3);

    .section-title { flex-shrink: 0; }
  }

  /* two-line layout (label above control) */
  .form-row-stack {
    grid-template-columns: 1fr;
    gap: var(--space-1);

    /* segmented controls hug their content (Apple-style) instead of being
       stretched to the column width by the grid */
    > .seg-switch { justify-self: start; }
  }

  /* Toggle rows read as one full-width unit, System Settings-style: the
     label fills the row and the switch sits on the trailing edge. Also
     prevents long labels from wrapping into orphans against the fixed
     130px label column. */
  .form-row:has(> .toggle) {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: var(--space-3);

    .form-row-label { flex: 1; }
  }

  /* two-column row: two label+control cells side by side, split by a thin
     vertical divider. Each cell stacks its label above its control. */
  .form-row-pair {
    display: grid;
    grid-template-columns: 1fr 1fr;
    align-items: stretch;
    padding: var(--space-1) 0;

    > * {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: var(--space-1);
      min-width: 0;
    }

    > *:first-child  { padding-right: var(--space-3); }
    > * + * {
      padding-left: var(--space-3);
      border-left: 1px solid color-mix(in oklab, var(--color-border) 55%, transparent);
    }
  }

  /* --- section header inside tabs --- */
  .section-title {
    font-size: var(--text-xs);
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    color: var(--color-text-dim);
  }

  /* --- generic horizontal column layout (Style / OBS tabs) --- */
  .panel-cols {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: var(--space-4);

    /* two-column variant (e.g. Filter tab: replace rules | blacklist) */
    &.cols-2 { grid-template-columns: 1fr 1fr; }

    /* a second row of columns in the same tab gets a separating rule above */
    & + & {
      margin-top: var(--space-3);
      padding-top: var(--space-3);
      border-top: 1px solid color-mix(in oklab, var(--color-border) 60%, transparent);
    }
  }

  .panel-col {
    display: flex;
    flex-direction: column;
    gap: var(--space-2);
    min-width: 0;

    /* thin divider between columns */
    & + & {
      padding-left: var(--space-4);
      border-left: 1px solid color-mix(in oklab, var(--color-border) 55%, transparent);
    }

    /* a second section heading in a column (e.g. 翻訳 2) gets breathing room */
    .section-title:not(:first-child) {
      margin-top: var(--space-2);
    }
  }

  /* Bubble shown beside its trigger via the native Popover API + CSS anchor
     positioning (Chrome/Edge). Sits to the right of the button (growing
     upward if tall) so it appears where the user just clicked; flips to the
     left if there isn't room. Shared look; each trigger names its own anchor.
     A popover — not a tooltip — because these hold instructions the user reads
     while doing something else, and a tooltip would vanish the moment the
     pointer moved away. */
  .help-popover {
    position-area: span-top right;
    position-try-fallbacks: flip-inline;
    inset: auto;
    margin: 0 var(--space-2);

    width: max-content;
    max-width: min(320px, 80vw);
    background: var(--color-surface-2);
    border: 1px solid var(--color-border-strong);
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-2);
    padding: var(--space-3);
    color: var(--color-text);
    font-size: var(--text-sm);
    line-height: 1.5;

    .format-help-examples { margin-top: 0; }
  }

  /* --- form inputs (dark theme) --- */

  .select,
  .text-input {
    background: var(--color-surface-2);
    color: var(--color-text);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 5px 10px;
    font-size: var(--text-md);
    width: 100%;
    min-width: 0;
    transition: border-color 0.15s;

    &:hover { border-color: var(--color-border-strong); }
    &:focus { border-color: var(--color-accent); outline: none; box-shadow: var(--focus-ring); }
  }

  .select {
    appearance: none;
    /* macOS pop-up button: paired up/down chevrons on the trailing edge */
    background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='white' stroke-opacity='0.6' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'><path d='M4.5 6.2 8 2.8l3.5 3.4M4.5 9.8 8 13.2l3.5-3.4'/></svg>");
    background-repeat: no-repeat;
    background-position: right 8px center;
    background-size: 14px;
    padding-right: 28px;

    /* The chevrons are a data URI, which cannot read a custom property, so
       the light theme swaps in a brown copy. */
    :root[data-theme="light"] & {
      background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%233E2B1F' stroke-opacity='0.6' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'><path d='M4.5 6.2 8 2.8l3.5 3.4M4.5 9.8 8 13.2l3.5-3.4'/></svg>");
    }
  }

  /* native <option>s — give the popup a dark background where possible */
  .select option {
    background: var(--color-surface-1);
    color: var(--color-text);
  }

  /* compact, fixed-width select for the language rows — the full-width default
     is far wider than the short language names need. Must come after .select so
     it wins on the (equal-specificity) width. */
  .select-compact {
    width: 150px;
    flex-shrink: 0;
  }

  /* Device names run long ("CABLE Output (VB-Audio Virtual Cable)"); wider than
     the language selects, and cut with an ellipsis past that. */
  .select-device {
    width: 240px;
    flex-shrink: 0;
    text-overflow: ellipsis;
  }

  .secret-input-wrap {
    position: relative;
    display: grid;
    min-width: 0;

    .secret-input {
      padding-right: 42px;
    }

    &[data-secret-visible="false"] .secret-input {
      -webkit-text-security: disc;
    }

    .secret-toggle {
      position: absolute;
      top: 50%;
      right: 3px;
      width: 28px;
      height: 28px;
      transform: translateY(-50%);
    }
  }

  /* Icon swap, shared by every masked control — single fields through
     .secret-input-wrap and the blacklist column through .blacklist-mask. Keyed
     off the state attribute rather than either wrapper class so a new masked
     control only has to carry data-secret-visible. The crossed-out eye offers
     "show"; the open eye offers "hide". */
  [data-secret-visible] {
    .icon-eye { display: none; }

    &[data-secret-visible="true"] {
      .icon-eye { display: block; }
      .icon-eye-off { display: none; }
    }
  }

  /* --- toggle switch (checkbox styled as iOS-style track + thumb) --- */
  .toggle {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    position: relative;

    input[type="checkbox"] {
      position: absolute;
      opacity: 0;
      pointer-events: none;
    }

    /* iOS proportions: the thumb is white in both states; only the
       track color flips. */
    .toggle-track {
      position: relative;
      display: inline-block;
      width: 38px;
      height: 22px;
      background: var(--fill-toggle);
      border-radius: var(--radius-full);
      transition: background 0.18s;
    }

    .toggle-thumb {
      position: absolute;
      top: 2px;
      left: 2px;
      width: 18px;
      height: 18px;
      background: white;
      border-radius: 50%;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4), 0 0 0 0.5px rgba(0, 0, 0, 0.08);
      transition: transform 0.18s var(--ease-out);
    }

    input[type="checkbox"]:checked + .toggle-track {
      background: var(--color-accent);
    }

    input[type="checkbox"]:checked + .toggle-track .toggle-thumb {
      transform: translateX(16px);
    }

    input[type="checkbox"]:focus-visible + .toggle-track {
      box-shadow: var(--focus-ring);
    }
  }

  /* Short variant for the language matrix's header row, where a full-height
     toggle would make the header row taller than its text labels. */
  .toggle.toggle-compact {
    .toggle-track { width: 28px; height: 16px; }
    .toggle-thumb { width: 12px; height: 12px; }
    input[type="checkbox"]:checked + .toggle-track .toggle-thumb {
      transform: translateX(12px);
    }
  }

  /* --- range slider + readout --- */
  .slider-group {
    display: grid;
    grid-template-columns: 1fr 28px;
    align-items: center;
    gap: var(--space-2);

    .slider-value {
      color: var(--color-text-dim);
      font-size: var(--text-sm);
      text-align: center;
      font-variant-numeric: tabular-nums;
    }
  }

  /* macOS-style slider: a light rail with a white round knob and a soft
     shadow. The rail is lifted above the card rather than sunk into it: a
     4px strip of --fill-inset sits within a shade of the card itself and
     disappears, and unlike .seg-switch it has no border to outline it. */
  input[type="range"] {
    appearance: none;
    -webkit-appearance: none;
    width: 100%;
    height: 4px;
    background: var(--fill-track);
    border-radius: 2px;
    outline: none;
    cursor: pointer;

    &::-webkit-slider-thumb {
      appearance: none;
      -webkit-appearance: none;
      width: 15px;
      height: 15px;
      background: white;
      border-radius: 50%;
      box-shadow: 0 0.5px 2.5px rgba(0, 0, 0, 0.5), 0 0 0 0.5px rgba(0, 0, 0, 0.1);
      cursor: pointer;
      transition: transform 0.1s var(--ease-out);

      &:hover { transform: scale(1.1); }
    }

    &::-moz-range-thumb {
      width: 15px;
      height: 15px;
      background: white;
      border: 0;
      border-radius: 50%;
      box-shadow: 0 0.5px 2.5px rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }

  /* --- animations --- */

  /* REC badge breathing (header start button while recognising) */
  @keyframes rec-pulse {
    50% { opacity: 0.35; }
  }

  /* OBS "connecting" status dot */
  @keyframes dot-pulse {
    50% { opacity: 0.4; }
  }
}

/* ============ utilities ============ */
/* ============ unsupported device ============ */
/* What a phone or tablet gets instead of the app (showUnsupported() in
   js/main.js). The body's desktop minimum width and its grid are lifted, so
   the notice fits the screen and scrolls if it has to. */
@layer components {
  body.is-unsupported {
    min-width: 0;
    overflow: auto;
    display: block;
    background: var(--color-bg);
    padding: var(--space-5) var(--space-4);
  }

  .unsupported-card {
    max-width: 480px;
    margin: 0 auto;
    padding: var(--space-5);
    background: var(--color-surface-1);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    line-height: 1.7;

    h1 { font-size: 1.25rem; margin: 0 0 var(--space-4); }
    p  { margin: 0 0 var(--space-3); }
  }

  .unsupported-url {
    padding: var(--space-2) var(--space-3);
    background: var(--color-surface-2);
    border-radius: var(--radius-sm);
    overflow-wrap: anywhere;
    user-select: all;
  }
}

@layer utilities {
  /* Nothing in index.html is ready to be looked at. Its static text is the
     Japanese the file is authored in, and the three tab panels are empty
     until their modules mount — both are corrected by init() in js/main.js,
     a fetch or two later. Painting that intermediate state cost nothing while
     ja was also the default interface language; now that the language is
     detected (see _detectUiLang() in js/store.js), an English or Chinese
     visitor would watch the app flash Japanese on every launch.

     visibility rather than display or opacity: the layout underneath settles
     while it is hidden, so the reveal has nothing left to reflow.

     The animation is a dead man's switch, not an effect. init() removes
     .is-booting itself, which cancels this long before it fires; it only ever
     runs if the module never executed at all (a parse error, a blocked
     import), and a broken app the user can see beats a blank window. */
  .is-booting body {
    visibility: hidden;
    animation: boot-reveal 0s linear 3s forwards;
  }
  @keyframes boot-reveal { to { visibility: visible; } }

  /* Capture mode: hide a panel so the subtitle area is unobstructed.
     Driven by body classes toggled from the header buttons (js/ui-layout.js).
     Both the control panel and the manual overlay are fully manual — nothing is
     auto-hidden while recognising. The header always stays so the toggles (and
     start/stop) remain reachable. */

  /* Collapsing and restoring is a click on the background — anywhere outside
     the control card (js/ui-layout.js). An invisible hit area needs an
     affordance, and the cursor is the only one available here, so it follows
     the lock: pointer while the gesture is live, back to normal once
     .panel-locked makes the background inert. `auto` rather than `default` on
     the foreground surfaces, so text fields keep their I-beam. */
  .app-main { cursor: pointer; }
  .panel-locked .app-main { cursor: auto; }
  .control-card,
  .manual-translate-panel { cursor: auto; }

  /* Collapsing drops only the tab body, so the output grows while the card
     shrinks to its toolbar — start/stop stays where it was instead of
     disappearing with the settings. */
  .panel-collapsed .settings-body { display: none; }
  .panel-collapsed .control-card  { height: auto; }
  .panel-collapsed .panel-resize  { display: none; }

  /* The tabs would drive a body that is no longer displayed, so they go with
     it; the audio input hands its toolbar cell to the read-only language
     readout (switching the input mid-stream should not be one stray click
     away). */
  .panel-collapsed .settings-head  { display: none; }
  .panel-collapsed .settings-nav   { display: none; }
  .panel-collapsed .toolbar-status { display: block; }

  /* Manual text-translation overlay: slide it up into view over the output.
     Enter is deliberately slower (300ms) than the 200ms exit on the base rule. */
  .manual-open .manual-translate-panel {
    transform: translateY(0);
    transition-duration: 0.3s;
  }

  /* The HTML [hidden] attribute defaults to `display: none` via the UA
     stylesheet, but any author rule with `display: <other>` (e.g. grid/flex
     on .form-row or .tab-panel) wins by source order. Re-asserting it in a
     later layer (utilities > components) restores the expected behavior. */
  [hidden] { display: none; }

  .visually-hidden {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
  }

  /* Reduced motion: keep the state changes (color/opacity feedback) but drop
     movement — the manual panel appears in place instead of sliding, presses
     don't scale, pulses stop. */
  @media (prefers-reduced-motion: reduce) {
    .manual-translate-panel { transition: none; }

    /* dialogs keep the opacity fade (comprehension) but not the scale.
       This utilities-layer rule also outranks the components-layer
       @starting-style scale during the enter frame. */
    .app-dialog { transform: none; }

    .btn:active:not(:disabled),
    .icon-btn:active,
    .tab-btn:active,
    .seg-switch button:active,
    .seg-switch label:active > span { transform: none; }

    /* The press still has to answer "did that register?", so the card keeps the
       feedback and trades the movement for a lift in its edge. */
    .control-card { transition: border-color 120ms var(--ease-out); }
    .control-card.is-arming {
      transform: none;
      border-color: var(--color-border-strong);
    }

    /* Same treatment as the dialogs: keep the fade, drop the scale — and this
       utilities-layer rule also outranks the components-layer @starting-style
       during the enter frame. */
    .color-popover,
    .mic-panel,
    .lang-menu,
    .engine-status-tip { transform: none; }
    .engine-status-chip:active,
    .sub-preset-row [data-preset]:active { transform: none; }
    .sub-preset-menu,
    .deco-menu { transform: none; }
    .color-preset,
    .color-preset:hover,
    .color-preset:active { transition: none; transform: none; }

    .speech-btn[data-recording="true"] svg,
    .obs-conn-status[data-phase="connecting"] .obs-conn-dot {
      animation: none;
    }
  }
}
