/* ============================================================================
   app-redesign.css — last-layer refresh (mobile shell + polish + animations)
   Loaded DEAD LAST (end of <body>, after chat-polish.css and inline <style>s)
   so it wins the cascade without fighting the fragile 36k-line monolith.

   Scope:
     • Mobile (≤900px): convert the chat to a proper 100dvh flex app-shell with a
       real scroll CONTAINER (#messages) instead of document/body scroll. Pairs
       with mobile-shell.js (keyboard / visualViewport) and the container-aware
       scroll helpers in dashboard.js (isMobileShell()).
     • Cross-device: brand-consistent polish + smooth micro-animations using the
       easing tokens already defined in dashboard-new.css (--ease-*, --duration-*).
     • Mobile perf: tame always-on fixed blur/noise layers for 60fps scrolling.
     • A real global prefers-reduced-motion kill-switch.

   Brand palette (kept): purple #8b5cf6 / #7c3aed, magenta #cb11ab, cyan #06b6d4,
   glass surfaces, light theme. Revert = remove the <link> in dashboard.html.
   ============================================================================ */

/* Local fallbacks so this layer is self-sufficient if a token is missing. */
:root {
  --ar-ease: var(--ease-out-expo, cubic-bezier(0.16, 1, 0.3, 1));
  --ar-ease-back: var(--ease-out-back, cubic-bezier(0.34, 1.56, 0.64, 1));
  --ar-fast: var(--duration-fast, 150ms);
  --ar-normal: var(--duration-normal, 250ms);
  --ar-brand: var(--primary, #8b5cf6);
}

/* ───────────────────────── Cross-device polish ──────────────────────────── */

html[data-page="dashboard"] body {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility;
}

/* Kill the grey tap flash everywhere on touch. */
html[data-page="dashboard"] * {
  -webkit-tap-highlight-color: transparent;
}

/* Accessible, on-brand focus ring (keyboard only — no mouse-click outlines). */
html[data-page="dashboard"] :where(button, a, [role="button"], input, textarea, select, .tab):focus-visible {
  outline: 2px solid var(--ar-brand);
  outline-offset: 2px;
  border-radius: 8px;
}

/* The speed label becomes icon-only on phones, so the button itself must carry
   the state. Fast remains neutral; thoughtful is intentionally unmistakable. */
html[data-page="dashboard"] #chatView #heroModelToggleBtn.is-thoughtful,
html[data-page="dashboard"] #composer.composer-v2 #composerModelToggleBtn.is-thoughtful {
  color: #ffffff !important;
  background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%) !important;
  border-color: rgba(124, 58, 237, 0.72) !important;
  box-shadow: 0 4px 12px rgba(124, 58, 237, 0.28) !important;
}

html[data-page="dashboard"] #chatView #heroModelToggleBtn.is-thoughtful .model-name,
html[data-page="dashboard"] #composer.composer-v2 #composerModelToggleBtn.is-thoughtful .model-name,
html[data-page="dashboard"] #chatView #heroModelToggleBtn.is-thoughtful svg,
html[data-page="dashboard"] #composer.composer-v2 #composerModelToggleBtn.is-thoughtful svg {
  color: #ffffff !important;
  stroke: currentColor !important;
}

/* Smooth, momentum scrolling for every scrollable region. */
html[data-page="dashboard"] #messages,
html[data-page="dashboard"] .modal-body,
html[data-page="dashboard"] .chat-list {
  scroll-behavior: smooth;
}

/* ─────────────── Touch micro-interactions (tap feedback) ─────────────────── */
/* Only on touch devices, so desktop hover behaviour is untouched. */
@media (hover: none), (pointer: coarse) {
  html[data-page="dashboard"] .tab,
  html[data-page="dashboard"] .action-pill,
  html[data-page="dashboard"] .hero-case-card,
  html[data-page="dashboard"] .chat-item,
  html[data-page="dashboard"] .family-switch button,
  html[data-page="dashboard"] #attachBtn,
  html[data-page="dashboard"] #composerModelToggleBtn,
  html[data-page="dashboard"] .send-btn,
  html[data-page="dashboard"] button.icon-btn {
    transition: transform var(--ar-fast) var(--ar-ease), opacity var(--ar-fast) var(--ar-ease);
  }
  html[data-page="dashboard"] .tab:active,
  html[data-page="dashboard"] .action-pill:active,
  html[data-page="dashboard"] .hero-case-card:active,
  html[data-page="dashboard"] .chat-item:active,
  html[data-page="dashboard"] .family-switch button:active,
  html[data-page="dashboard"] #attachBtn:active,
  html[data-page="dashboard"] #composerModelToggleBtn:active,
  html[data-page="dashboard"] .send-btn:active,
  html[data-page="dashboard"] button.icon-btn:active {
    transform: scale(0.96);
  }
}

/* =====================================================================
   MOBILE APP-SHELL  (≤900px) — the core scroll fix
   Body becomes a 100dvh flex column: [ header ] [ main(grows) ].
   Header & composer leave `position:fixed`; #messages is the scroller.
   ===================================================================== */
@media (max-width: 900px) {

  /* Full-height shell; the document itself never scrolls. --app-height is set
     by mobile-shell.js to the visualViewport height while the keyboard is open
     (iOS), otherwise it falls back to the dynamic viewport unit. */
  html[data-page="dashboard"],
  html[data-page="dashboard"] body.hero-page {
    height: 100%;
    width: 100%;
    max-width: 100%;
    overflow: hidden !important;
    overflow-x: clip !important;
    overscroll-behavior: none !important;
  }
  html[data-page="dashboard"] body {
    width: 100% !important;
    max-width: 100% !important;
    height: var(--app-height, 100dvh) !important;
    min-height: var(--app-height, 100dvh) !important;
    max-height: var(--app-height, 100dvh) !important;
    overflow: hidden !important;
    overflow-x: clip !important;
    display: flex !important;
    flex-direction: column !important;
    box-sizing: border-box !important;
    overscroll-behavior-x: none !important;
  }

  /* Header — first flex row, pinned to the top of the shell (not fixed). */
  html[data-page="dashboard"] body .top-header {
    position: sticky !important;
    top: 0 !important;
    left: auto !important;
    right: auto !important;
    flex: 0 0 auto !important;
    width: 100% !important;
    z-index: 1000;
  }

  /* Main — the growing region. Holds the active view + the composer. */
  html[data-page="dashboard"] body .main {
    flex: 1 1 auto !important;
    min-height: 0 !important;
    min-width: 0 !important;
    width: 100% !important;
    max-width: 100% !important;
    height: auto !important;
    max-height: none !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    overflow: hidden !important;
    display: flex !important;
    flex-direction: column !important;
    gap: 0 !important;
  }

  /* The active view grows; chat view delegates scrolling to #messages. */
  html[data-page="dashboard"] body .main > .view.active {
    flex: 1 1 auto !important;
    min-height: 0 !important;
    min-width: 0 !important;
    width: 100% !important;
    max-width: 100% !important;
    height: auto !important;
    max-height: none !important;
  }
  /* Non-chat views scroll themselves inside the shell. */
  html[data-page="dashboard"] body .main > .view.active:not(#chatView) {
    overflow-y: auto !important;
    overflow-x: hidden !important;   /* admin grids are desktop-width; don't break the page */
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
  }
  /* #feedbackView carries an ID-level `min-height:100vh !important` (dashboard-new.css)
     that out-specifies the .view.active reset above and forces it taller than the
     clipped .main → its bottom (submit button / history) becomes unreachable on mobile.
     Reset it here with an ID-bearing selector so it wins the cascade. */
  html[data-page="dashboard"] body .main > #feedbackView.view.active {
    min-height: 0 !important;
  }
  /* #adminFeedbackView .afv-shell's declared bottom padding (64px, split across
     several non-!important rules in admin-feedback.css/theme-overrides.css)
     isn't reliably reaching the true end of scroll — the last feedback card
     ends up flush against the viewport edge. Pin it explicitly (last-loaded
     sheet wins) and add the safe-area inset for notched/gesture-bar phones. */
  html[data-page="dashboard"] #adminFeedbackView .afv-shell {
    padding-bottom: calc(64px + env(safe-area-inset-bottom)) !important;
  }
  /* Промпты use a desktop-width card grid with NO scroll wrapper — make the
     grid + cards fit the phone instead of being clipped off-screen on the right.
     (Other admin views — Боты/Пользователи — already use overflow-x:auto wrappers
     like .bots-owners-bar / .uv-table-wrap, so they scroll fine and aren't touched.) */
  html[data-page="dashboard"] #promptsView .prompts-section,
  html[data-page="dashboard"] #promptsView .prompts-grid,
  html[data-page="dashboard"] #promptsView .prompt-card {
    width: 100% !important;
    max-width: 100% !important;
    min-width: 0 !important;     /* flex items default to min-width:auto → won't shrink; force 0 */
    box-sizing: border-box !important;
  }
  /* The desktop 24px section padding eats the narrow phone width — trim it. */
  html[data-page="dashboard"] #promptsView .prompts-section { padding: 12px !important; }
  html[data-page="dashboard"] #promptsView .prompts-grid {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }

  /* .active only — an INACTIVE chat view must stay display:none, otherwise it
     leaks above other views (Промпты/Боты/…) and pushes their content down. */
  html[data-page="dashboard"] body #chatView.view.active {
    overflow: hidden !important;
    display: flex !important;
    flex-direction: column !important;
  }
  html[data-page="dashboard"] body #chatView .chat-container {
    flex: 1 1 auto !important;
    min-height: 0 !important;
    min-width: 0 !important;
    width: 100% !important;
    max-width: 100% !important;
    height: auto !important;
    max-height: none !important;
    overflow: hidden !important;
    display: flex !important;
    flex-direction: column !important;
    padding: 0 !important;
  }
  /* Loco bar (if shown) stays a fixed-height row at the top of the chat. */
  html[data-page="dashboard"] body #chatView .loco-bar {
    flex: 0 0 auto !important;
  }

  /* THE scroll container. */
  html[data-page="dashboard"] body #chatView #messages {
    flex: 1 1 auto !important;
    min-height: 0 !important;
    height: auto !important;
    max-height: none !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
    scroll-behavior: smooth;
    width: 100% !important;
    max-width: none !important;
    margin: 0 !important;
    padding: 12px 12px 8px !important;
    box-sizing: border-box !important;
  }
  /* Legacy bottom-spacer hacks no longer needed (composer is in flow now). */
  html[data-page="dashboard"] body #chatView #messages::after {
    display: none !important;
    height: 0 !important;
  }

  /* Empty state (hero) becomes the scroll region instead. */
  html[data-page="dashboard"] body #chatView #heroSection {
    flex: 1 1 auto !important;
    min-height: 0 !important;
    height: auto !important;
    max-height: none !important;
    overflow-y: auto !important;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
    /* SHORT-SCREEN FIX (e.g. Galaxy S25 360×780): the hero centres its content
       (justify-content:center); when the content is taller than the screen the
       centred overflow clips the TOP (wordmark) and it can't be scrolled to.
       `safe center` top-aligns when it would overflow, so nothing is cut. */
    justify-content: safe center !important;
    padding-top: 10px !important;
    padding-bottom: 14px !important;
  }
  html[data-page="dashboard"] body #chatView #heroSection.chat-active {
    width: 100% !important;
    max-width: none !important;
    padding: 0 !important;
    margin: 0 !important;
  }
  /* The hero wordmark must never be clipped by its own line-box on small screens. */
  html[data-page="dashboard"] body #chatView #heroSection .matrixe-wordmark {
    line-height: 1.1 !important;
    padding-top: 2px !important;
    flex: 0 0 auto !important;
  }

  /* Composer — normal flow bottom row. The keyboard now pushes layout (Chrome
     interactive-widget) or the shell shrinks to vv.height (iOS), so it always
     stays visible above the keyboard without position:fixed gymnastics. */
  html[data-page="dashboard"] body #composer {
    position: static !important;
    flex: 0 0 auto !important;
    left: auto !important;
    right: auto !important;
    bottom: auto !important;
    top: auto !important;
    width: 100% !important;
    max-width: 100% !important;
    margin: 0 !important;
    gap: 0 !important;
    min-height: 0 !important;
    padding: 5px 8px calc(5px + env(safe-area-inset-bottom, 0px)) !important;
    z-index: 5;
    box-sizing: border-box !important;
    transform: none !important;
  }
  html[data-page="dashboard"] body #composer.composer-v2 .composer-bar {
    width: 100% !important;
    max-width: 100% !important;
    left: auto !important;
    right: auto !important;
    gap: 4px !important;
    min-height: 0 !important;
    padding: 7px 9px 6px !important;
    border-radius: 18px !important;
    box-shadow: none !important;
    backdrop-filter: none !important;
    -webkit-backdrop-filter: none !important;
    box-sizing: border-box !important;
  }
  html[data-page="dashboard"] body #composer.composer-v2 .composer-bar:focus-within {
    box-shadow: none !important;
    border-color: rgba(124, 58, 237, 0.38) !important;
  }
  html[data-page="dashboard"] body #composer.composer-v2 .attached-files-v2:empty {
    display: none !important;
    padding: 0 !important;
  }
  html[data-page="dashboard"] body #composer.composer-v2 .c-input {
    height: 36px !important;
    min-height: 36px !important;
    padding: 0 6px 4px !important;
    font-size: 16px !important;
    line-height: 1.35 !important;
  }

  /* iOS may pan the visual viewport instead of resizing the layout viewport.
     Pin the shell to that visible rectangle while the keyboard is open. */
  html[data-page="dashboard"].keyboard-open body {
    position: fixed !important;
    top: var(--vv-top, 0px) !important;
    left: var(--vv-left, 0px) !important;
    right: auto !important;
    bottom: auto !important;
    width: var(--vv-width, 100%) !important;
  }

  /* ── Sidebar drawer: unify open/active, smooth slide + scrim fade ── */
  html[data-page="dashboard"] #sidebar {
    transition: transform 0.42s var(--ar-ease), box-shadow 0.42s ease !important;
    will-change: transform;
  }
  html[data-page="dashboard"] .sidebar-overlay {
    transition: opacity 0.42s var(--ar-ease), visibility 0.42s !important;
  }
  html[data-page="dashboard"] .sidebar-overlay.active,
  html[data-page="dashboard"] .sidebar-overlay.open {
    opacity: 1 !important;
    visibility: visible !important;
    pointer-events: auto !important;
  }
  html[data-page="dashboard"] .sidebar-overlay:not(.active):not(.open) {
    opacity: 0 !important;
    visibility: hidden !important;
    pointer-events: none !important;
  }

  /* ── Mobile performance: stop always-on per-frame paint cost during scroll ── */
  html[data-page="dashboard"] body .noise-overlay {
    display: none !important;
  }
  html[data-page="dashboard"] body .ambient-background,
  html[data-page="dashboard"] body .ambient-background * {
    animation: none !important;
    will-change: auto !important;
  }

  /* ── Message bubble polish (mobile) ── */
  html[data-page="dashboard"] body #messages .msg {
    max-width: 92% !important;
  }

  /* No horizontal page scroll, ever. */
  html[data-page="dashboard"] body {
    overflow-x: hidden !important;
  }
}

/* Even 320px phones have enough room for the existing four controls in one
   compact row. The older emergency two-row grid doubled composer height. */
@media (max-width: 359px) {
  html[data-page="dashboard"] body #composer.composer-v2 .c-bottom-row {
    display: flex !important;
    grid-template-columns: none !important;
    grid-template-rows: none !important;
    align-items: center !important;
    gap: 3px !important;
  }

  html[data-page="dashboard"] body #composer .family-switch {
    grid-column: auto !important;
    grid-row: auto !important;
    flex: 1 1 auto !important;
    width: auto !important;
    min-width: 0 !important;
  }

  html[data-page="dashboard"] body #composer #attachBtn,
  html[data-page="dashboard"] body #composer #composerModelToggleBtn,
  html[data-page="dashboard"] body #composer #send {
    grid-column: auto !important;
    grid-row: auto !important;
    justify-self: auto !important;
  }

  html[data-page="dashboard"] body #composer .family-opt {
    min-width: 0 !important;
  }
}

/* Small phones: a touch more breathing room economy. */
@media (max-width: 480px) {
  html[data-page="dashboard"] body #composer {
    padding-left: 8px !important;
    padding-right: 8px !important;
  }
  html[data-page="dashboard"] body #messages .msg {
    max-width: 94% !important;
  }
}

/* =====================================================================
   DESKTOP (≥901px) — purple object outlines + brand glow (NO white glow)
   A cohesive "обводка" on the main objects plus a soft brand-purple glow
   at rest that intensifies on hover/focus. Low-alpha at rest = tasteful;
   the composer focus state is the focal moment. Brand purple only.
   ===================================================================== */
@media (min-width: 901px) {
  :root {
    --ar-pl-edge:        rgba(124, 58, 237, 0.16);   /* resting outline      */
    --ar-pl-edge-strong: rgba(124, 58, 237, 0.42);   /* hover/active outline */
    /* soft 2-layer glow — gentle, low-contrast (eye-comfort) */
    --ar-pl-glow-sm: 0 1px 2px rgba(124, 58, 237, 0.05), 0 6px 18px -10px rgba(124, 58, 237, 0.14);
    --ar-pl-glow:    0 1px 3px rgba(124, 58, 237, 0.05), 0 10px 26px -12px rgba(124, 58, 237, 0.20);
    --ar-pl-glow-lg: 0 2px 6px rgba(124, 58, 237, 0.06), 0 16px 38px -14px rgba(139, 92, 246, 0.26);
    --ar-pl-ring:    0 0 0 3px rgba(139, 92, 246, 0.15);
    --ar-tr: var(--ar-normal) var(--ar-ease);
  }

  /* Assistant bubble — purple outline + soft glow, lifts on hover */
  html[data-page="dashboard"] #chatView .msg.assistant .bubble,
  html[data-page="dashboard"] #chatView .msg:not(.user) .bubble {
    border: 1px solid var(--ar-pl-edge) !important;
    box-shadow: var(--ar-pl-glow-sm) !important;
    transition: box-shadow var(--ar-tr), border-color var(--ar-tr), transform var(--ar-tr);
  }
  html[data-page="dashboard"] #chatView .msg.assistant .bubble:hover,
  html[data-page="dashboard"] #chatView .msg:not(.user) .bubble:hover {
    border-color: var(--ar-pl-edge-strong) !important;
    box-shadow: var(--ar-pl-glow) !important;
    transform: translateY(-1px);
  }

  /* User bubble (already brand-purple) — matching aura + subtle inner edge */
  html[data-page="dashboard"] #chatView .msg.user .bubble {
    border: 1px solid rgba(255, 255, 255, 0.16) !important;
    box-shadow: 0 1px 3px rgba(124, 58, 237, 0.10), 0 10px 26px -12px rgba(124, 58, 237, 0.30) !important;
    transition: box-shadow var(--ar-tr), transform var(--ar-tr);
  }
  html[data-page="dashboard"] #chatView .msg.user .bubble:hover {
    box-shadow: var(--ar-pl-glow-lg) !important;
    transform: translateY(-1px);
  }

  /* Composer — the focal object: outline + glow, brighter ring on focus */
  html[data-page="dashboard"] #composer .composer-bar {
    border: 1px solid var(--ar-pl-edge) !important;
    box-shadow: var(--ar-pl-glow-sm) !important;
    transition: box-shadow var(--ar-tr), border-color var(--ar-tr);
  }
  html[data-page="dashboard"] #composer .composer-bar:focus-within {
    border-color: var(--ar-pl-edge-strong) !important;
    box-shadow: var(--ar-pl-ring), var(--ar-pl-glow) !important;
  }

  /* Send button — brand glow, lifts + grows slightly on hover */
  html[data-page="dashboard"] #composer .c-send,
  html[data-page="dashboard"] #composer button[type="submit"] {
    box-shadow: 0 4px 16px -6px rgba(124, 58, 237, 0.38) !important;
    transition: box-shadow var(--ar-fast) var(--ar-ease), transform var(--ar-fast) var(--ar-ease);
  }
  html[data-page="dashboard"] #composer .c-send:hover,
  html[data-page="dashboard"] #composer button[type="submit"]:hover {
    box-shadow: var(--ar-pl-glow-lg) !important;
    transform: translateY(-1px) scale(1.03);
  }

  /* Sidebar — purple-tinted right edge + soft directional glow */
  html[data-page="dashboard"] #sidebar {
    border-right: 1px solid var(--ar-pl-edge) !important;
    box-shadow: 12px 0 44px -22px rgba(124, 58, 237, 0.22) !important;
  }

  /* Chat list items — reserve a transparent outline, light up on hover/active */
  html[data-page="dashboard"] #chatList .chat-item {
    border: 1px solid transparent;
    transition: background-color var(--ar-fast) var(--ar-ease),
                border-color var(--ar-fast) var(--ar-ease),
                box-shadow var(--ar-fast) var(--ar-ease);
  }
  html[data-page="dashboard"] #chatList .chat-item:hover {
    border-color: var(--ar-pl-edge) !important;
    box-shadow: var(--ar-pl-glow-sm) !important;
  }
  html[data-page="dashboard"] #chatList .chat-item.active {
    border-color: var(--ar-pl-edge-strong) !important;
    box-shadow: var(--ar-pl-glow-sm) !important;
  }

  /* Header — thin purple underline (keeps its existing purple drop shadow) */
  html[data-page="dashboard"] .top-header {
    border-bottom: 1px solid var(--ar-pl-edge) !important;
  }

  /* Tabs — purple glow on hover/active */
  html[data-page="dashboard"] .top-header .tab {
    transition: box-shadow var(--ar-fast) var(--ar-ease),
                border-color var(--ar-fast) var(--ar-ease),
                background-color var(--ar-fast) var(--ar-ease);
  }
  html[data-page="dashboard"] .top-header .tab:hover,
  html[data-page="dashboard"] .top-header .tab.active {
    box-shadow: var(--ar-pl-glow-sm) !important;
  }

  /* Cards / modals / hero input — cohesive purple outline + glow */
  html[data-page="dashboard"] .hero-input-card,
  html[data-page="dashboard"] .action-pill,
  html[data-page="dashboard"] .action-card,
  html[data-page="dashboard"] .modal-content {
    border: 1px solid var(--ar-pl-edge) !important;
    box-shadow: var(--ar-pl-glow-sm) !important;
  }
  html[data-page="dashboard"] .hero-input-card:focus-within {
    border-color: var(--ar-pl-edge-strong) !important;
    box-shadow: var(--ar-pl-ring), var(--ar-pl-glow) !important;
  }
  html[data-page="dashboard"] .action-pill:hover,
  html[data-page="dashboard"] .action-card:hover {
    border-color: var(--ar-pl-edge-strong) !important;
    box-shadow: var(--ar-pl-glow) !important;
    transform: translateY(-2px);
    transition: all var(--ar-tr);
  }
}

/* =====================================================================
   SOFT COMFORT (all viewports) — calmer canvas, gentler surfaces, easier
   text. Keeps brand purple + light theme; lowers glare and visual noise.
   Grounded in ui-ux-pro-max: contrast ≥4.5:1, soft layered elevation,
   comfortable line-height, tabular figures, intentional whitespace.
   ===================================================================== */

/* Token tuning (monolith sets these with !important, so match it) */
html[data-page="dashboard"] {
  --text-muted: rgba(15, 23, 42, 0.64) !important;   /* was .56 → now ≥4.5:1, still soft */
  --bg-card: #FFFBF1 !important;                       /* white with a hint of cream (matches canvas) */
}

/* 1. Warm "Vanilla Cream" (#F8E3AB, RAL 060-90-10) page canvas — ALL viewports.
   Cards/bubbles/composer/sidebar stay light so they float over the warm bg.
   NOTE: the monolith paints a radial-gradient wash via body's background-image
   (and a white .ambient-background layer) on top of the color — kill both so
   the cream actually shows, not a washed-out near-white. */
html[data-page="dashboard"],
html[data-page="dashboard"] body {
  background-color: #F9F2DE !important;   /* light, soft vanilla cream */
  background-image: none !important;
}
html[data-page="dashboard"] .ambient-background,
html[data-page="dashboard"] .noise-overlay {
  display: none !important;
}

/* Surfaces: "white with a hint of cream" (#FFFBF1) so cards harmonize with the
   warm cream canvas instead of clashing as stark white. Brand-purple surfaces
   (user bubble, active tab, buttons, send) are intentionally NOT touched. */
html[data-page="dashboard"] #messages .msg.assistant .bubble,
html[data-page="dashboard"] #messages .msg:not(.user) .bubble,
html[data-page="dashboard"] .hero-input-card,
html[data-page="dashboard"] .input-wrapper-hero,
html[data-page="dashboard"] #composer .composer-bar,
html[data-page="dashboard"] .sidebar,
html[data-page="dashboard"] .sidebar-header,
html[data-page="dashboard"] .sidebar-footer,
html[data-page="dashboard"] .action-card,
html[data-page="dashboard"] .prompt-card,
html[data-page="dashboard"] .modal-content {
  background-color: #FFFBF1 !important;
  background-image: none !important;
}
/* Header glass: warm tint so it doesn't read cold-white over the cream. */
html[data-page="dashboard"] header.top-header {
  background-color: rgba(255, 251, 241, 0.82) !important;
}

/* Business UI font — Manrope (self-hosted). Brand wordmark stays Ubuntu Mono. */
html[data-page="dashboard"] body,
html[data-page="dashboard"] body button,
html[data-page="dashboard"] body input,
html[data-page="dashboard"] body textarea,
html[data-page="dashboard"] body select,
html[data-page="dashboard"] body .tab,
html[data-page="dashboard"] body .btn,
html[data-page="dashboard"] body .chat-item,
html[data-page="dashboard"] body .bubble {
  font-family: 'Manrope', 'Inter', system-ui, -apple-system, sans-serif !important;
}
html[data-page="dashboard"] .matrixe-wordmark {
  font-family: 'Ubuntu Mono', monospace !important;   /* preserve brand signature */
}

/* 2. Text comfort: readable measure + relaxed line-height in reading blocks */
html[data-page="dashboard"] #messages .bubble,
html[data-page="dashboard"] #messages .bubble p,
html[data-page="dashboard"] #messages .msg-content {
  line-height: 1.6;
}
/* Tabular figures for data so numbers don't jitter (timestamps, tables) */
html[data-page="dashboard"] .msg-time,
html[data-page="dashboard"] #messages table td,
html[data-page="dashboard"] #messages table th {
  font-variant-numeric: tabular-nums;
  font-feature-settings: "tnum" 1;
}
/* On-brand text selection */
html[data-page="dashboard"] ::selection {
  background: rgba(139, 92, 246, 0.22);
}

/* 3. Softer user bubble — gentle gradient instead of a heavy solid block */
html[data-page="dashboard"] #messages .msg.user .bubble {
  background-image: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 65%) !important;
}

/* 4. Gentle elevation on mobile too (desktop uses the softened --ar-pl-glow*) */
@media (max-width: 900px) {
  html[data-page="dashboard"] #messages .msg.assistant .bubble,
  html[data-page="dashboard"] #composer .composer-bar {
    box-shadow: 0 1px 2px rgba(124, 58, 237, 0.05),
                0 6px 18px -10px rgba(124, 58, 237, 0.16) !important;
  }
}

/* 5. A little more breathing room between consecutive messages (8px rhythm) */
html[data-page="dashboard"] #messages .msg + .msg {
  margin-top: 6px;
}

/* =====================================================================
   CHAT HISTORY (sidebar) — refined, modern, on-brand
   Rounded interactive rows, soft purple hover, clear active state with a
   left accent, brand "Новый чат" button, tidy section labels, hover-reveal
   row actions. Cross-device (drawer on mobile, fixed rail on desktop).
   ===================================================================== */

/* Section title "История чатов" */
html[data-page="dashboard"] .sidebar-header h2 {
  font-size: 13px !important;
  font-weight: 700 !important;
  letter-spacing: 0.04em !important;
  text-transform: uppercase !important;
  color: var(--text-muted) !important;
}

/* "Новый чат" — brand gradient pill (#newChatBtn to win specificity) */
html[data-page="dashboard"] #newChatBtn.btn-new-chat {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed) !important;
  color: #fff !important;
  border: none !important;
  border-radius: 12px !important;
  padding: 10px 14px !important;
  font-weight: 600 !important;
  box-shadow: 0 4px 14px -6px rgba(124, 58, 237, 0.50) !important;
  transition: transform var(--ar-fast) var(--ar-ease),
              box-shadow var(--ar-fast) var(--ar-ease),
              filter var(--ar-fast) var(--ar-ease) !important;
}
html[data-page="dashboard"] #newChatBtn.btn-new-chat:hover {
  transform: translateY(-1px);
  box-shadow: 0 8px 22px -8px rgba(124, 58, 237, 0.55) !important;
  filter: brightness(1.05);
}
html[data-page="dashboard"] #newChatBtn.btn-new-chat svg { stroke: #fff !important; }

/* Date group labels ("Сегодня" / "Вчера" / "Ранее") */
html[data-page="dashboard"] .chat-group-label {
  font-size: 11px !important;
  font-weight: 600 !important;
  letter-spacing: 0.06em !important;
  text-transform: uppercase !important;
  color: rgba(15, 23, 42, 0.42) !important;
  padding: 14px 14px 6px !important;
  margin: 0 !important;
}

/* Chat rows — comfortable rounded items */
html[data-page="dashboard"] #chatList .chat-item {
  padding: 9px 10px !important;
  margin: 2px 8px !important;
  border-radius: 11px !important;
  color: var(--text-main) !important;
  border: 1px solid transparent !important;
  box-shadow: none !important;
  transition: background-color var(--ar-fast) var(--ar-ease),
              border-color var(--ar-fast) var(--ar-ease) !important;
}
html[data-page="dashboard"] #chatList .chat-item:hover {
  background: rgba(139, 92, 246, 0.07) !important;
  border-color: rgba(124, 58, 237, 0.14) !important;
  box-shadow: none !important;
}
html[data-page="dashboard"] #chatList .chat-item.active {
  background: linear-gradient(135deg, rgba(139, 92, 246, 0.15), rgba(124, 58, 237, 0.09)) !important;
  border-color: rgba(124, 58, 237, 0.22) !important;
  box-shadow: inset 3px 0 0 #7c3aed !important;   /* left accent bar */
}
html[data-page="dashboard"] #chatList .chat-item-title {
  font-size: 14px !important;
  font-weight: 500 !important;
  line-height: 1.35 !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}
html[data-page="dashboard"] #chatList .chat-item.active .chat-item-title {
  font-weight: 600 !important;
  color: #6d28d9 !important;
}
html[data-page="dashboard"] #chatList .chat-item-time {
  font-size: 11px !important;
  color: var(--text-muted) !important;
  font-variant-numeric: tabular-nums;
}

/* Row actions: reveal on hover (pointer devices); always shown on touch */
@media (hover: hover) {
  html[data-page="dashboard"] #chatList .chat-item-actions {
    opacity: 0;
    transition: opacity var(--ar-fast) var(--ar-ease);
  }
  html[data-page="dashboard"] #chatList .chat-item:hover .chat-item-actions,
  html[data-page="dashboard"] #chatList .chat-item.active .chat-item-actions {
    opacity: 1;
  }
}
html[data-page="dashboard"] #chatList .chat-item-actions button {
  border-radius: 8px !important;
  transition: background-color var(--ar-fast) var(--ar-ease),
              color var(--ar-fast) var(--ar-ease) !important;
}
html[data-page="dashboard"] #chatList .chat-item-actions button:hover {
  background: rgba(124, 58, 237, 0.12) !important;
  color: #7c3aed !important;
}

/* Logout — subtle, turns danger on hover */
html[data-page="dashboard"] .sidebar-logout-btn {
  border-radius: 10px !important;
  transition: background-color var(--ar-fast) var(--ar-ease),
              color var(--ar-fast) var(--ar-ease) !important;
}
html[data-page="dashboard"] .sidebar-logout-btn:hover {
  background: rgba(239, 68, 68, 0.08) !important;
  color: #dc2626 !important;
}

/* =====================================================================
   HEADER TAB-RAIL ARROWS (desktop ≥901px)
   The top tab strip (.tabs) overflows but didn't signal it. mobile-shell.js
   wraps it (.tabs-nav-wrap) and injects ‹ / › buttons; these styles render
   them as floating brand pills over the strip edges. Hidden on mobile.
   ===================================================================== */
html[data-page="dashboard"] .tabs-nav-wrap {
  position: relative;
  display: flex;
  align-items: center;
  flex: 1 1 auto;   /* grow like the original .tabs did, else the strip collapses */
  min-width: 0;
}
html[data-page="dashboard"] .tabs-nav-wrap > .tabs { min-width: 0; }
html[data-page="dashboard"] .tabs-nav-btn { display: none; }

/* Mobile: the wrapper must NOT affect layout (arrows are desktop-only).
   display:contents removes its box so the tab strip flexes exactly as before. */
@media (max-width: 900px) {
  html[data-page="dashboard"] .tabs-nav-wrap { display: contents !important; }
}

@media (min-width: 901px) {
  /* arrows replace the native scrollbar as the affordance */
  html[data-page="dashboard"] .tabs-nav-wrap > .tabs {
    scrollbar-width: none;
    scroll-behavior: smooth;
  }
  html[data-page="dashboard"] .tabs-nav-wrap > .tabs::-webkit-scrollbar { display: none; }

  html[data-page="dashboard"] .tabs-nav-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index: 6;
    width: 28px;
    height: 28px;
    padding: 0;
    display: grid;
    place-items: center;
    border-radius: 9px;
    border: 1px solid rgba(124, 58, 237, 0.20);
    background: rgba(253, 253, 255, 0.94);
    -webkit-backdrop-filter: blur(6px);
    backdrop-filter: blur(6px);
    color: #7c3aed;
    cursor: pointer;
    box-shadow: 0 2px 10px -3px rgba(124, 58, 237, 0.32);
    transition: background-color var(--ar-fast) var(--ar-ease),
                box-shadow var(--ar-fast) var(--ar-ease),
                opacity var(--ar-fast) var(--ar-ease),
                transform var(--ar-fast) var(--ar-ease);
  }
  html[data-page="dashboard"] .tabs-nav-btn:hover {
    background: #fff;
    box-shadow: 0 4px 14px -4px rgba(124, 58, 237, 0.45);
  }
  html[data-page="dashboard"] .tabs-nav-btn:active { transform: translateY(-50%) scale(0.92); }
  html[data-page="dashboard"] .tabs-nav-left  { left: 0; }
  html[data-page="dashboard"] .tabs-nav-right { right: 0; }
  html[data-page="dashboard"] .tabs-nav-btn.hidden { opacity: 0; pointer-events: none; }
}

/* =====================================================================
   SHORT screens (e.g. Samsung Galaxy S25 ~360×780): the hero is a scroll
   container, so its first child (the "matrixe.ai" wordmark) was rendered flush
   against the scroll edge with a near-0-height title box → the tall glyph
   ascenders got clipped at the top. Give breathing room + a real line-height.
   ===================================================================== */
@media (max-width: 900px) {
  html[data-page="dashboard"] body #chatView #heroSection {
    padding-top: 14px !important;
  }
  html[data-page="dashboard"] .hero-title.matrixe-wordmark,
  html[data-page="dashboard"] .matrixe-wordmark {
    line-height: 1.18 !important;
    overflow: visible !important;
    padding-top: 2px !important;
  }
}
/* Genuinely short viewports (≤820px tall): tighten vertical rhythm a touch so
   the hero content fits without the top being squeezed. */
@media (max-width: 900px) and (max-height: 820px) {
  html[data-page="dashboard"] body #chatView #heroSection { padding-top: 10px !important; }
  html[data-page="dashboard"] #chatView #heroSection .hero-subtitle { margin: 4px 0 10px !important; }
}

/* ═════════════════════ Premium data-table polish (chat answers) ═══════════
   The analytics tables are the product's core surface. Give them scannable
   hover rows, right-aligned numerics, and a crisp framed look so the data
   reads like a real dashboard, not a markdown dump. */
html[data-page="dashboard"] #messages .table-scroll {
  border: 1px solid rgba(124, 58, 237, 0.12) !important;
  border-radius: 14px !important;
  overflow-x: auto !important;
  overflow-y: hidden !important;
  overscroll-behavior-x: contain;
  -webkit-overflow-scrolling: touch;
  box-shadow: 0 1px 2px rgba(31, 36, 48, 0.04),
              0 10px 30px -22px rgba(124, 58, 237, 0.30) !important;
  background: #FFFFFF !important;
}
html[data-page="dashboard"] #messages .table-scroll table {
  /* min-width (not width) so narrow tables fill the frame for a clean dashboard
     look, while wide tables still overflow → .table-scroll scrolls horizontally
     (preserves the mobile horizontal-scroll behaviour for many-column tables). */
  min-width: 100% !important;
  width: auto !important;
  border-collapse: collapse !important;
  margin: 0 !important;
}
html[data-page="dashboard"] #messages .table-scroll thead th {
  position: sticky; top: 0;
  background: linear-gradient(rgba(139, 92, 246, 0.10), rgba(139, 92, 246, 0.045)) !important;
  border-bottom: 1px solid rgba(124, 58, 237, 0.16) !important;
  letter-spacing: 0.04em !important;
  white-space: nowrap !important;
}
/* Zebra + hover so a long table stays readable row-to-row. */
html[data-page="dashboard"] #messages .table-scroll tbody tr:nth-child(even) {
  background: rgba(124, 58, 237, 0.022) !important;
}
html[data-page="dashboard"] #messages .table-scroll tbody tr {
  transition: background-color 0.12s ease !important;
}
html[data-page="dashboard"] #messages .table-scroll tbody tr:hover {
  background: rgba(139, 92, 246, 0.08) !important;
}
html[data-page="dashboard"] #messages .table-scroll tbody td {
  border-bottom: 1px solid rgba(31, 36, 48, 0.055) !important;
}
html[data-page="dashboard"] #messages .table-scroll tbody tr:last-child td {
  border-bottom: 0 !important;
}
/* Numeric columns read right-aligned with tabular figures so digits line up by
   place value (currency / counts). dashboard.js tags such cells `.num` after
   render. The double-ID prefix (#chatView #messages) is required to out-specify
   chat-polish.css's `#chatView .table-scroll … td { text-align:left !important }`
   (1,3,4) — two IDs beat its single ID regardless of load order. */
html[data-page="dashboard"] #chatView #messages .table-scroll td.num,
html[data-page="dashboard"] #chatView #messages .table-scroll th.num {
  text-align: right !important;
  font-variant-numeric: tabular-nums !important;
}

/* ═══════════════ Chart images: frame them to match the data tables ═══════════
   Charts arrive as `![title](/static/chart_*.png)` → bare <img>. Give them the
   same crisp rounded frame + soft shadow as the polished tables so a chart reads
   as a first-class card inside the answer, not a pasted screenshot. (Scoped to
   chart PNGs by src so product thumbnails / uploads stay untouched.) */
html[data-page="dashboard"] #messages .bubble img[src*="/static/chart_"] {
  display: block !important;
  width: 100% !important;
  max-width: 560px !important;
  height: auto !important;
  margin: 12px 0 !important;
  border-radius: 16px !important;
  border: 1px solid rgba(124, 58, 237, 0.12) !important;
  box-shadow: 0 1px 2px rgba(31, 36, 48, 0.04),
              0 14px 36px -24px rgba(124, 58, 237, 0.34) !important;
  background: #FFFFFF !important;
}

/* ═══════════════ Micro-interactions: message entrance + tactile controls ══════
   Subtle motion that makes the product feel "expensive" without being noisy.
   The reduced-motion kill-switch below neutralises all of this for users who
   ask for it. */
@keyframes mxMsgIn {
  from { opacity: 0; transform: translateY(8px); }
  to   { opacity: 1; transform: translateY(0); }
}
/* .mx-enter is added by dashboard.js ONLY for freshly appended messages (never
   on streaming re-renders via replaceMessage) so the bubble doesn't re-flash
   while tokens stream in. */
html[data-page="dashboard"] #messages .msg.mx-enter {
  animation: mxMsgIn 0.34s cubic-bezier(0.22, 1, 0.36, 1) both;
}
/* Tactile press + smooth hover on the primary controls. */
html[data-page="dashboard"] .c-btn,
html[data-page="dashboard"] .family-opt,
html[data-page="dashboard"] .tab,
html[data-page="dashboard"] .copy-btn-unified {
  transition: transform 0.12s cubic-bezier(0.22, 1, 0.36, 1),
              box-shadow 0.18s ease, background-color 0.18s ease,
              border-color 0.18s ease, color 0.18s ease !important;
}
html[data-page="dashboard"] .c-btn:active,
html[data-page="dashboard"] .family-opt:active,
html[data-page="dashboard"] .copy-btn-unified:active {
  transform: translateY(1px) scale(0.97) !important;
}
html[data-page="dashboard"] .c-send:hover {
  box-shadow: 0 8px 22px -8px rgba(124, 58, 237, 0.55) !important;
}
html[data-page="dashboard"] .copy-btn-unified:hover {
  border-color: rgba(124, 58, 237, 0.40) !important;
  color: #7c3aed !important;
}

/* ════════ Desktop: turn the side voids into an intentional branded canvas ═══════
   The chat is a centred reading column — widening it would push text lines past a
   comfortable length, so instead of stretching content we make the cream margins
   feel designed: a soft, barely-there warm/violet ambient anchored to the voids.
   Pure background; zero layout change, so readability + composer stay put. */
@media (min-width: 1180px) {
  html[data-page="dashboard"] body {
    background-image:
      radial-gradient(1120px 640px at 8% -10%, rgba(139, 92, 246, 0.055), transparent 58%),
      radial-gradient(960px 640px at 100% 110%, rgba(124, 58, 237, 0.05), transparent 60%) !important;
  }
}

/* ═══════════════════════ QA-sweep fixes (desktop + mobile) ════════════════════
   Bugs found during the full "act like a real user" QA pass. */

/* [P2] «Пожелания» (#feedbackView) рисовался на холодном --bg-body (#f7f8fb из
   minimal.css → монолит), выбиваясь из тёплого крема остальных вью, и белая
   карточка почти не отделялась. Пускаем крем-холст сквозь и теплим поверхность. */
html[data-page="dashboard"] #feedbackView {
  background: transparent !important;
  --fbv-surface: #FFFBF1;
  --fbv-surface-alt: #FBF6E9;
  --fbv-border: rgba(124, 58, 237, 0.14);
}

/* [P2] «Промпты» (#promptsView, admin): карточка ограничена `max-height:160px` и это
   flex-колонка; когда заголовок переносится на 2 строки, превью (`flex-grow:1`)
   сжимается до 0 высоты — текст есть, но не виден. Снимаем жёсткую высоту карточки и
   даём превью брать натуральную (обрезанную по строкам) высоту. */
html[data-page="dashboard"] #promptsView .prompt-card {
  max-height: none !important;
  height: auto !important;
}
html[data-page="dashboard"] #promptsView .prompt-card .pc-preview {
  display: -webkit-box !important;
  -webkit-box-orient: vertical !important;
  -webkit-line-clamp: 3 !important;
  overflow: hidden !important;
  flex: 0 0 auto !important;
  min-height: 0 !important;
  opacity: 1 !important;
  color: #5b6472 !important;
  -webkit-text-fill-color: #5b6472 !important;
}

/* [P2] Mobile: the Locomotive tab collapses to an icon when another tab is active,
   but its `.loco-tab-badge` ("1") is an inline flex child (margin-left:4px) — inside
   the ~40px icon-only tab the icon + badge don't fit, shoving the car icon off to the
   left ("значок машины уезжает из-за надписи 1"). Pin the badge to the tab's top-right
   corner as a notification dot so the icon stays centred. Scoped to the collapsed
   (:not(.active)) tab on mobile — the expanded/active tab keeps its inline badge. */
@media (max-width: 900px) {
  html[data-page="dashboard"] #locomotiveTab:not(.active) {
    position: relative !important;
    overflow: visible !important;
  }
  html[data-page="dashboard"] #locomotiveTab:not(.active) .loco-tab-badge {
    position: absolute !important;
    top: -3px !important;
    right: -3px !important;
    margin: 0 !important;
    min-width: 14px !important;
    height: 14px !important;
    padding: 0 3px !important;
    font-size: 9px !important;
    line-height: 1 !important;
    box-shadow: 0 0 0 2px #F9F2DE !important; /* cream ring so it reads as a badge */
    pointer-events: none;
  }
}

/* [P2] Mobile: «Редактирование бота» (#botSettingsModalPremium) выглядел криво —
   карточка захардкожена 820px и прижата к низу (верх подрезан), а футер с кнопками
   лежал ВНУТРИ скролл-формы с холодным полупрозрачным фоном (rgba(248,250,252,.6)),
   так что поля просвечивали под кнопками. Центрируем, делаем адаптивную высоту и
   превращаем футер в липкий непрозрачный ivory-бар на всю ширину — кнопки всегда
   видны и ровно по центру снизу. */
@media (max-width: 900px) {
  html[data-page="dashboard"] #botSettingsModalPremium {
    align-items: center !important;      /* было flex-end (прижато вниз) → по центру */
    justify-content: center !important;
    padding: 14px !important;
  }
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-panel {
    max-height: calc(100dvh - 28px) !important;  /* было 820px фикс → адаптивно */
    width: 100% !important;
    max-width: 460px !important;
    margin: 0 auto !important;
  }
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-form {
    -webkit-overflow-scrolling: touch !important;  /* инерционный скролл */
    overscroll-behavior: contain !important;       /* не «пробивать» на страницу */
    padding-bottom: 0 !important;                  /* отступ даёт сам футер */
  }
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-footer {
    position: sticky !important;
    bottom: -20px !important;                       /* прилипает ниже 20px-паддинга формы */
    margin: 12px -20px -20px !important;            /* на всю ширину формы */
    padding: 14px 20px calc(16px + env(safe-area-inset-bottom, 0px)) !important;
    background: #FFFBF1 !important;                 /* непрозрачный ivory (был холодный see-through) */
    border-top: 1px solid rgba(124, 58, 237, 0.14) !important;
    z-index: 3 !important;
  }
  /* Кнопки футера — равной ширины, крупные, удобные под палец. */
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-footer > button {
    flex: 1 1 0 !important;
    min-height: 46px !important;
  }
}

/* ═══════════════ Mobile: плавный/инерционный скролл по всему приложению ══════════
   Момент-скролл (iOS) + гашение «пробоя» скролла на страницу под модалками/шторками
   и в скролл-зонах чата/списков. Делает прокрутку на телефоне мягче и без дёрганья. */
@media (max-width: 900px) {
  html[data-page="dashboard"] #messages,
  html[data-page="dashboard"] .view,
  html[data-page="dashboard"] .modal-content,
  html[data-page="dashboard"] [class*="-form"],
  html[data-page="dashboard"] .table-scroll,
  html[data-page="dashboard"] #sidebar {
    -webkit-overflow-scrolling: touch;
  }
  html[data-page="dashboard"] #messages,
  html[data-page="dashboard"] #sidebar,
  html[data-page="dashboard"] .modal-content {
    overscroll-behavior: contain;
  }
}

/* ═══════════════════════ P3 polish (mobile) ══════════════════════════════════ */
@media (max-width: 900px) {
  /* [P3] Шторка истории чатов была во всю ширину (390px) → scrim не видно, закрыть
     можно было только повторным тапом по бургеру. Сужаем до ~86vw и двигаем строго
     трансформом (закрытая = полностью за экраном), чтобы справа открылась полоска
     scrim — тап по ней закрывает (обработчик клика по #sidebarOverlay уже есть). */
  /* NB: dashboard-mobile.css @≤560px форсит `.sidebar{width:100vw}` селектором
     `aside.sidebar#sidebar` (спец. 1,2,1), поэтому здесь нужна не меньшая специфичность. */
  html[data-page="dashboard"] aside#sidebar.sidebar {
    width: 86vw !important;
    max-width: 340px !important;
    left: 0 !important;
    right: auto !important;   /* иначе left+right тянут шторку на 100% */
    transform: translateX(-100%) !important;
  }
  html[data-page="dashboard"] aside#sidebar.sidebar.open {
    transform: translateX(0) !important;
  }

  /* [P3] Тач-таргеты: пилюли режима и иконки правки/удаления чата были ~26px по
     одной стороне — мелко для пальца. Доводим до удобного минимума. */
  html[data-page="dashboard"] .family-opt {
    min-height: 36px !important;
    display: inline-flex !important;
    align-items: center !important;
  }
  html[data-page="dashboard"] .chat-item-edit,
  html[data-page="dashboard"] .chat-item-delete {
    min-width: 38px !important;
  }
}

/* ═══════════ Реальные баги с телефона (~360px) — скрины пользователя ═══════════ */
@media (max-width: 900px) {
  /* [баг1] Редактор бота: `.bot-editor-grid` держал ФИКСИРОВАННУЮ колонку
     (grid-template-columns ≈ 247px), которая не ужимается на узком экране, из-за чего
     поля (Telegram/MAX/Токен/WB-ключ/…) вылезали за правый край карточки и обрезались
     ~на четверть. Делаем колонку текучей и разрешаем детям/инпутам ужиматься. */
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-grid {
    grid-template-columns: minmax(0, 1fr) !important;
  }
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-grid > *,
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-card,
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-input,
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-form input,
  html[data-page="dashboard"] #botSettingsModalPremium .bot-editor-form select {
    min-width: 0 !important;
    max-width: 100% !important;
    box-sizing: border-box !important;
  }

  /* [баг2] Редактор промпта: `.editor-footer` — 3 кнопки (Удалить/Отмена/Сохранить) +
     padding 32px не влезали в ~360px, «Удалить» уезжала за левый край. Переносим ряд и
     ужимаем паддинг; «Удалить» прижата влево (margin-right:auto), остальные справа. */
  html[data-page="dashboard"] .editor-modal .editor-footer,
  html[data-page="dashboard"] .editor-footer {
    flex-wrap: wrap !important;
    gap: 8px !important;
    padding: 14px 16px calc(14px + env(safe-area-inset-bottom, 0px)) !important;
    justify-content: flex-end !important;
  }
  html[data-page="dashboard"] .editor-footer > #deletePrompt,
  html[data-page="dashboard"] .editor-footer > [id*="delete"],
  html[data-page="dashboard"] .editor-footer > .btn-danger,
  html[data-page="dashboard"] .editor-footer > [class*="delete"] {
    margin-right: auto !important;
  }

  /* [баг3] Карточка промпта: `.prompt-tags` имел `max-height:52px; overflow:hidden` →
     2-й (перенесённый) ряд тегов обрезался снизу. Даём тегам показаться целиком —
     карточка (height:auto) сама вырастает под них. */
  html[data-page="dashboard"] #promptsView .prompt-tags {
    max-height: none !important;
    overflow: visible !important;
  }

  /* [баг4, страховка] Чтобы hero-инпут не «уезжал» вправо при фокусе/клавиатуре — гасим
     любое горизонтальное переполнение внутри чат-холста (clip не ломает fixed/sticky). */
  html[data-page="dashboard"] #chatView,
  html[data-page="dashboard"] #heroSection,
  html[data-page="dashboard"] #chatContainer,
  html[data-page="dashboard"] .main-input-wrapper,
  html[data-page="dashboard"] .hero-input-row,
  html[data-page="dashboard"] .hero-input-card {
    overflow-x: clip !important;
    max-width: 100% !important;
    box-sizing: border-box !important;
  }

  /* [keyboard] iOS can horizontally pan the visual viewport while focusing a
     field. Keep the layout viewport anchored and make the hero controls shrink
     instead of creating implicit grid columns wider than the phone. */
  html[data-page="dashboard"].keyboard-open,
  html[data-page="dashboard"].keyboard-focus,
  html[data-page="dashboard"].keyboard-open body,
  html[data-page="dashboard"].keyboard-focus body {
    overflow-x: clip !important;
    overscroll-behavior-x: none !important;
  }
  html[data-page="dashboard"] #chatView .hero-input-bottom {
    display: grid !important;
    grid-template-columns: minmax(0, 1fr) auto !important;
    align-items: center !important;
    gap: 8px !important;
  }
  html[data-page="dashboard"] #chatView .hero-bottom-left,
  html[data-page="dashboard"] #chatView .hero-bottom-right {
    display: flex !important;
    align-items: center !important;
    min-width: 0 !important;
    max-width: 100% !important;
  }
  html[data-page="dashboard"] #chatView .hero-bottom-left {
    gap: 6px !important;
    overflow: hidden !important;
  }
  html[data-page="dashboard"] #chatView .hero-bottom-right {
    gap: 6px !important;
    justify-content: flex-end !important;
    flex: 0 0 auto !important;
  }
  html[data-page="dashboard"] #chatView .hero-bottom-left .family-switch,
  html[data-page="dashboard"] #composer .family-switch {
    flex: 1 1 auto !important;
    min-width: 0 !important;
    max-width: 100% !important;
    overflow: hidden !important;
  }
  html[data-page="dashboard"] #chatView .hero-bottom-left .family-opt,
  html[data-page="dashboard"] #composer .family-opt {
    flex: 1 1 0 !important;
    min-width: 0 !important;
    padding-left: 9px !important;
    padding-right: 9px !important;
    text-align: center !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
  }
  html[data-page="dashboard"] #chatView .mode-info {
    flex: 0 0 auto !important;
  }
  html[data-page="dashboard"] #chatView #heroModelToggleBtn .model-name {
    display: none !important;
  }
}

html[data-page="dashboard"] .attached-files-v2 {
  flex-wrap: nowrap !important;
  overflow-x: auto !important;
  overflow-y: hidden !important;
  overscroll-behavior-x: contain !important;
  scrollbar-width: thin;
}

html[data-page="dashboard"] .attached-files-v2 .attached-file-item {
  flex: 0 0 auto !important;
}

html[data-page="dashboard"] .attachment-card-meta {
  display: inline-flex;
  align-items: center;
  width: max-content;
  max-width: 100%;
  font-size: 10px;
  line-height: 1;
  font-weight: 700;
  letter-spacing: 0;
  color: rgba(100, 116, 139, 0.9);
}

html[data-page="dashboard"] .msg.user .attachment-card-meta {
  color: rgba(255, 255, 255, 0.78);
}

/* [P3] Стрелки прокрутки ленты вкладок (.tabs-nav-btn ‹ ›, фиолетовые) стояли ниже
   центра ленты (`top:23px; bottom:-5px` → центр на ~14px ниже). Центрируем по вертикали
   авто-полями внутри `.tabs-nav-wrap` (relative, height 46). Обе стрелки. */
html[data-page="dashboard"] .tabs-nav-btn {
  top: 0 !important;
  bottom: 0 !important;
  margin-top: auto !important;
  margin-bottom: auto !important;
}

/* [P2] Тач: кнопки-действия карточек (карандаш/корзина) показывались только на hover
   карточки (`opacity:0` → `card:hover{opacity:1}`). На телефоне hover нестабилен, и часть
   мобильных браузеров/webview рапортует `hover:hover`, из-за чего существующие
   `@media(hover:none)`-фиксы НЕ срабатывали → кнопки «прыгали» и пропадали при наведении/
   тапе (репорт: карандаш «редактировать» в Базе знаний). Делаем их всегда видимыми и
   кликабельными на мобиле — привязка к ШИРИНЕ экрана, а не к hover-медиа. Покрываем и
   аналогичные кнопки в других местах (правка/удаление чата в шторке). */
@media (max-width: 900px) {
  html[data-page="dashboard"] #knowledgeView .knowledge-edit-btn,
  html[data-page="dashboard"] #knowledgeView .knowledge-delete-btn,
  html[data-page="dashboard"] .chat-item-actions,
  html[data-page="dashboard"] .chat-item-edit,
  html[data-page="dashboard"] .chat-item-delete,
  html[data-page="dashboard"] [class*="card"] [class*="edit-btn"],
  html[data-page="dashboard"] [class*="card"] [class*="delete-btn"] {
    opacity: 1 !important;
    visibility: visible !important;
    pointer-events: auto !important;
  }
}

/* [P2] usersView (мобайл): `.um-user-list` имел `display:table-row-group`, но БЕЗ
   `display:table`-родителя → браузер строил анонимную таблицу, которая сайзилась по
   контенту (~344px) и не ужималась под родителя (~298px), карточки юзеров вылезали за
   правый край экрана. Переводим список/карточки в обычные блоки — текут под контейнер. */
@media (max-width: 900px) {
  /* id-селектор нужен, т.к. `#usersView #usersTableBodyDash{display:table-row-group}`
     (спец. 2,0,0) перебивал класс. Монолит и сам задаёт `.um-user-list{display:flex}` —
     возвращаем это как flex-колонку (вертикальный список), чтобы карточки текли под ширину. */
  html[data-page="dashboard"] #usersView #usersTableBodyDash,
  html[data-page="dashboard"] #usersView .um-user-list {
    display: flex !important;
    flex-direction: column !important;
    width: 100% !important;
    max-width: 100% !important;
    min-width: 0 !important;
  }
  html[data-page="dashboard"] #usersView #usersTableBodyDash .um-user-card,
  html[data-page="dashboard"] #usersView .um-user-card {
    display: block !important;
    width: auto !important;
    max-width: 100% !important;
    min-width: 0 !important;
    box-sizing: border-box !important;
  }
}

/* ───────────────────── Global reduced-motion kill-switch ─────────────────── */
@media (prefers-reduced-motion: reduce) {
  html[data-page="dashboard"] *,
  html[data-page="dashboard"] *::before,
  html[data-page="dashboard"] *::after {
    animation-duration: 0.001ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.001ms !important;
    scroll-behavior: auto !important;
  }
}

/* ============================================================================
   [QA-fix mobile] Модалка «Редактор пакета» (#packageEditorModal) — наложение
   кнопок футера на поле «Запросов».
   Корень: базовый .modal-footer в монолите — position:sticky; bottom:0 с
   ПРОЗРАЧНЫМ фоном. На узком экране тело модалки (.modal-body, max-height ~548px)
   переполняется (scrollHeight 589 > clientHeight 549), футер прилипает к низу, и
   поле «Запросов», уезжающее под него, ПРОСВЕЧИВАЕТ сквозь прозрачный футер →
   кнопки «Отмена/Сохранить» визуально ложатся на поле (репорт со скрина).
   Фикс: для ЭТОЙ модалки на мобиле футер — нормальный поток (не sticky) + сплошной
   кремовый фон; кнопки переносятся аккуратно на всю ширину. Scoped на
   #packageEditorModal, чтобы не задеть sticky-футер других модалок (напр. редактор бота).
   ============================================================================ */
@media (max-width: 900px) {
  #packageEditorModal .modal-footer {
    position: static !important;
    background: #FFFBF1 !important;
    flex-wrap: wrap !important;
    gap: 10px !important;
    margin-top: 20px !important;
  }
  /* Группа «Отмена + Сохранить» — на всю ширину, кнопки растягиваются поровну. */
  #packageEditorModal .modal-footer > div {
    margin-left: 0 !important;
    margin-right: 0 !important;
    width: 100% !important;
    gap: 10px !important;
  }
  #packageEditorModal .modal-footer > div > .btn-md {
    flex: 1 1 0 !important;
    margin-right: 0 !important;
  }
  /* «Удалить» — отдельной строкой на всю ширину, по центру. */
  #packageEditorModal #deletePackageBtnSettings {
    width: 100% !important;
    justify-content: center !important;
  }
}

/* ============================================================================
   [QA-fix] Редактор записи знаний / промпта (#kbEditorShell / #editorShell) —
   «серая штука снизу» + кривые кнопки (репорт со скрина, мобилка).
   Корень серого: базовый .editor-footer в монолите задаёт background:
   rgba(0,0,0,0.2) (дизайн под тёмную тему), а light-override в монолите фон НЕ
   трогает (только border-color) → на светлой кремовой модалке футер = серая полоса.
   Красим футер в кремовый (все вьюпорты). Ниже — мобильная раскладка кнопок:
   3 кнопки (Удалить/Отмена/Сохранить) не влезают в ряд ~360px → Сохранить
   переносилась криво. Делаем: Отмена+Сохранить равным рядом сверху, Удалить —
   на всю ширину снизу (как в модалке пакета). ============================================================================ */
html[data-page="dashboard"] #editorShell .editor-footer,
html[data-page="dashboard"] #kbEditorShell .editor-footer {
  background: #FFFBF1 !important;
}
@media (max-width: 900px) {
  html[data-page="dashboard"] #kbEditorShell .editor-footer > #kbEditCancel,
  html[data-page="dashboard"] #kbEditorShell .editor-footer > #kbEditSave {
    flex: 1 1 0 !important;
    margin: 0 !important;
  }
  html[data-page="dashboard"] #kbEditorShell .editor-footer > #kbEditDelete {
    order: 5 !important;
    flex: 1 1 100% !important;
    margin: 0 !important;
    justify-content: center !important;
  }
}

/* ============================================================================
   [QA-fix mobile] Футеры модалок Локомотива (#locoSettingsModal / #locoWizardModal
   / #locoGoLiveModal). Базовый мобильный .modal-footer в монолите — position:sticky;
   bottom:0; background:inherit → при переполнении тела на узком экране футер прилипает
   и может просвечивать/наложиться на контент (тот же класс бага, что у модалки пакета).
   Делаем футер нормальным потоком + сплошной кремовый фон. Scoped на loco-модалки. */
@media (max-width: 900px) {
  #locoSettingsModal .modal-footer,
  #locoWizardModal .modal-footer,
  #locoGoLiveModal .modal-footer {
    position: static !important;
    background: #FFFBF1 !important;
  }
}

/* [QA-fix mobile] iOS zoom-on-focus: инпуты loco-модалок лежат в .modal, а не в .view,
   поэтому глобальный guard `.view input {font-size:16px}` до них не достаёт. Дублируем
   16px для полей настроек/визарда Локомотива. */
@media (max-width: 900px) {
  #locoSettingsModal input,
  #locoSettingsModal select,
  #locoSettingsModal textarea,
  #locoWizardModal input,
  #locoWizardModal select,
  #locoWizardModal textarea,
  #locomotiveView .loco-cogs-input,
  #locomotiveView .loco-custom-input { font-size: 16px !important; }
}

/* ============================================================================
   [QA-fix mobile] ZOOM-ON-FOCUS: любое текстовое поле с font-size < 16px заставляет
   iOS Safari / Chrome Android ЗУМИТЬ страницу при фокусе (viewport-meta разрешает зум) —
   макет съезжает, инпут «улетает вправо», hero обрезается (репорт: композер чата, но
   баг системный). Живой аудит нашёл 15 полей <16px: композер .c-input=15, .um-input=13.5,
   .bot-editor-input=13–14, .glass-select=14, #userSearchInput=13.5. Форсим ≥16px на мобиле.
   app-redesign.css грузится ПОСЛЕДНИМ; для полей за id-правилами (композер) даём
   id-специфичность (1,2,1 бьёт #composer.composer-v2 .c-input = 1,2,0). Viewport-meta НЕ
   трогаем — ручной pinch-zoom для доступности остаётся. Меняем ТОЛЬКО font-size. */
@media (max-width: 900px) {
  html[data-page="dashboard"] #composer .c-input,
  html[data-page="dashboard"] #input,
  html[data-page="dashboard"] #userSearchInput,
  html[data-page="dashboard"] .c-input,
  html[data-page="dashboard"] .um-input,
  html[data-page="dashboard"] .bot-editor-input,
  html[data-page="dashboard"] .glass-input,
  html[data-page="dashboard"] .glass-select,
  /* Админ-модалки задают font-size id-правилами (#userManageModal .um-input и
     #botSettingsModalPremium .bot-editor-input = спец. 1,1,0) — бьём их id-скоупом
     (1,2,1). Плюс select#dailyModeSettings в настройках. */
  html[data-page="dashboard"] #userManageModal input,
  html[data-page="dashboard"] #userManageModal select,
  html[data-page="dashboard"] #userManageModal textarea,
  html[data-page="dashboard"] #botSettingsModalPremium input,
  html[data-page="dashboard"] #botSettingsModalPremium select,
  html[data-page="dashboard"] #botSettingsModalPremium textarea,
  html[data-page="dashboard"] select#dailyModeSettings,
  /* Токен/ключ-поля бота имеют 2-id правило (#botSettingsModalPremium #botTokenInput
     = 2,0,0, моно-шрифт) — бьём 2-id селектором (2,1,1). */
  html[data-page="dashboard"] #botSettingsModalPremium #botTokenInput,
  html[data-page="dashboard"] #botSettingsModalPremium #botWbKeyInput,
  html[data-page="dashboard"] input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="file"]):not([type="color"]):not([type="submit"]):not([type="button"]),
  html[data-page="dashboard"] textarea,
  html[data-page="dashboard"] select {
    font-size: 16px !important;
  }
}

/* [QA-fix users stats] app-redesign.css loads after dashboard-new.css and was
   flattening the main chart card back to a plain sheet. Keep the intended
   premium light-theme chrome for the dynamics chart. */
html[data-page="dashboard"][data-theme="light"] #usersView .uv-chart-card.uv-chart-main,
[data-theme="light"] #usersView .uv-chart-card.uv-chart-main {
  background:
    linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(248, 250, 252, 0.94) 48%, rgba(239, 246, 255, 0.9) 100%) !important;
  border: 1px solid rgba(148, 163, 184, 0.18) !important;
  border-radius: 26px !important;
  box-shadow:
    0 22px 55px rgba(15, 23, 42, 0.12),
    0 8px 22px rgba(37, 99, 235, 0.08) !important;
}
html[data-page="dashboard"][data-theme="light"] #usersView .chart-tab.active,
[data-theme="light"] #usersView .chart-tab.active {
  color: #f8fafc !important;
  background:
    linear-gradient(135deg, #312e81 0%, #4f46e5 52%, #7c3aed 100%) !important;
  box-shadow:
    0 8px 20px rgba(79, 70, 229, 0.24),
    inset 0 1px 0 rgba(255, 255, 255, 0.22) !important;
}

html[data-page="dashboard"] textarea#heroInput.glass-input-large {
  resize: none !important;
  min-height: 24px !important;
  max-height: 200px !important;
  height: 24px;
  line-height: 1.45 !important;
  overflow: hidden;
  white-space: pre-wrap;
}

/* =====================================================================
   GALAXY S25 / NARROW PHONE LAYOUT
   Keep the empty-chat hero scrollable without shrinking sections to zero,
   and give phone-width screens a readable one-column action list.
   ===================================================================== */
@media (max-width: 900px) {
  html[data-page="dashboard"] body #chatView #heroSection:not(.chat-active) {
    justify-content: flex-start !important;
    gap: 14px !important;
  }

  html[data-page="dashboard"] body #chatView #heroSection:not(.chat-active) > * {
    flex: 0 0 auto !important;
  }

  html[data-page="dashboard"] body #chatView #heroSection:not(.chat-active) > .main-input-wrapper,
  html[data-page="dashboard"] body #chatView #heroSection:not(.chat-active) .hero-input-card {
    margin-bottom: 0 !important;
  }

  html[data-page="dashboard"] body #chatView #heroSection:not(.chat-active) > .hero-cases-section {
    height: auto !important;
    min-height: min-content !important;
    overflow: visible !important;
  }

  html[data-page="dashboard"] #chatView .action-pill > span:not(.t-btnflex__icon) {
    min-width: 0 !important;
    max-width: 100% !important;
  }
}

@media (max-width: 480px) {
  html[data-page="dashboard"] #messages .msg.assistant {
    width: 100% !important;
    max-width: 100% !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
  }

  html[data-page="dashboard"] #messages .msg.assistant .bubble {
    flex: 1 1 0 !important;
    min-width: 0 !important;
  }
}

@media (max-width: 480px) {
  html[data-page="dashboard"] #chatView .action-cards-row-top,
  html[data-page="dashboard"] #chatView .action-cards-row-bottom {
    grid-template-columns: minmax(0, 1fr) !important;
    gap: 8px !important;
  }

  html[data-page="dashboard"] #chatView .action-cards-row-top > .action-pill,
  html[data-page="dashboard"] #chatView .action-cards-row-bottom > .action-pill {
    width: 100% !important;
    max-width: none !important;
    min-height: 48px !important;
    height: auto !important;
    padding: 10px 14px !important;
    justify-self: stretch !important;
    justify-content: flex-start !important;
    text-align: left !important;
  }

  html[data-page="dashboard"] #chatView .hero-input-bottom {
    display: grid !important;
    grid-template-columns: 44px minmax(0, 1fr) 42px 44px !important;
    gap: 3px !important;
  }

  html[data-page="dashboard"] #chatView .hero-bottom-left,
  html[data-page="dashboard"] #chatView .hero-bottom-right {
    display: contents !important;
  }

  html[data-page="dashboard"] #chatView .hero-input-bottom .mode-info {
    display: none !important;
  }

  html[data-page="dashboard"] #chatView .family-switch {
    width: auto !important;
    min-width: 0 !important;
  }

  html[data-page="dashboard"] #chatView .hero-bottom-left .family-opt {
    padding-left: 5px !important;
    padding-right: 5px !important;
  }

  html[data-page="dashboard"] #chatView .hero-bottom-left .family-opt:first-of-type {
    flex: 1 1 auto !important;
  }

  html[data-page="dashboard"] #chatView .hero-bottom-left .family-opt:last-of-type {
    flex: 0 0 auto !important;
  }

  html[data-page="dashboard"] #composer.composer-v2 .c-bottom-row {
    gap: 3px !important;
  }

  html[data-page="dashboard"] #composer.composer-v2 .c-bottom-row .c-attach {
    margin: 0 !important;
  }

  html[data-page="dashboard"] #composer .family-opt {
    padding-left: 5px !important;
    padding-right: 5px !important;
  }

  html[data-page="dashboard"] #composer .family-opt:first-of-type {
    flex: 1 1 auto !important;
  }

  html[data-page="dashboard"] #composer .family-opt:last-of-type {
    flex: 0 0 auto !important;
  }

  html[data-page="dashboard"] #chatView .model-toggle-wrapper,
  html[data-page="dashboard"] #chatView #heroModelToggleBtn {
    width: 42px !important;
    min-width: 42px !important;
  }
}

@media (max-width: 359px) {
  html[data-page="dashboard"] #chatView .hero-input-bottom {
    grid-template-columns: 44px minmax(0, 1fr) 44px !important;
    grid-template-rows: auto 44px !important;
  }

  html[data-page="dashboard"] #chatView #heroAttachBtn {
    grid-column: 1 !important;
    grid-row: 2 !important;
  }

  html[data-page="dashboard"] #chatView .family-switch {
    grid-column: 1 / -1 !important;
    grid-row: 1 !important;
  }

  html[data-page="dashboard"] #chatView .model-toggle-wrapper {
    grid-column: 2 !important;
    grid-row: 2 !important;
    justify-self: end !important;
  }

  html[data-page="dashboard"] #chatView #heroSendBtn {
    grid-column: 3 !important;
    grid-row: 2 !important;
  }

  html[data-page="dashboard"] #composer.composer-v2 .c-bottom-row {
    display: grid !important;
    grid-template-columns: 44px minmax(0, 1fr) 44px !important;
    grid-template-rows: auto 44px !important;
    align-items: center !important;
  }

  html[data-page="dashboard"] #composer .family-switch {
    grid-column: 1 / -1 !important;
    grid-row: 1 !important;
    width: 100% !important;
  }

  html[data-page="dashboard"] #composer #attachBtn {
    grid-column: 1 !important;
    grid-row: 2 !important;
  }

  html[data-page="dashboard"] #composer #composerModelToggleBtn {
    grid-column: 2 !important;
    grid-row: 2 !important;
    justify-self: end !important;
  }

  html[data-page="dashboard"] #composer #send {
    grid-column: 3 !important;
    grid-row: 2 !important;
  }
}

/* Final mobile-chat flattening. Keep every control and action intact, but let
   spacing and borders carry the hierarchy instead of stacked card shadows. */
@media (max-width: 900px) {
  html[data-page="dashboard"] body #chatView #heroSection.chat-active #messages {
    padding: 12px 12px 8px !important;
  }

  html[data-page="dashboard"] body #chatView #messages .msg .bubble,
  html[data-page="dashboard"] body #chatView #messages .copy-btn {
    box-shadow: none !important;
  }
}
