/* ==========================================================================
   LeadFlow — единая дизайн-система (v6.2)
   Один файл на всё приложение: и на страницы проектов (shell), и на
   страницы верхнего уровня (page_template). Раньше наборов стилей было два
   и они постепенно расходились.

   Разделы:
     1. Токены (тёмная / светлая тема)
     2. База и типографика
     3. Каркас: сайдбар, топбар, контент
     4. Компоненты: карточки, кнопки, формы, таблицы, бейджи
     5. Прикладные блоки: метрики, графики, канбан
     6. Совместимость со старой разметкой
     7. Адаптив: планшет, телефон, safe-area
   ========================================================================== */

/* ============================ 1. ТОКЕНЫ ================================== */

:root {
  color-scheme: dark;

  /* Alethea: чёрный графит с холодным фиолетовым подтоном. */
  --bg:            #090710;
  --side:          #0d0a15;
  --panel:         #14101e;
  --panel2:        #1b1528;
  --input:         #100c18;
  --line:          #2b223b;
  --line-strong:   #3a2d50;

  --text:          #e9edf4;
  --text-2:        #b4bdcc;
  --muted:         #7c879a;

  /* Фирменный фиолетовый Alethea. */
  --accent:        #a66bff;
  --accent-strong: #8546e8;
  --accent-ink:    #ffffff;
  --accent-soft:   rgba(166, 107, 255, .16);

  --info:          #6fb8ff;
  --info-soft:     rgba(111, 184, 255, .13);
  --warning:       #ffcc33;
  --warning-soft:  rgba(255, 204, 51, .13);
  --danger:        #ff3d6e;
  --danger-soft:   rgba(255, 61, 110, .13);
  --violet:        #c9a6ff;
  --violet-soft:   rgba(201, 166, 255, .14);
  /* Раньше --success был псевдонимом --accent — при мятном акценте это
     случайно совпадало (успех = зелёный = акцент), но с красно-оранжевым
     акцентом статус "Ответил" в канбане (background: var(--accent) в
     .kanban-column.st-replied .status-dot) слился с каждой акцентной
     кнопкой/бордером на странице. Даём success собственный, независимый
     оттенок — тот самый бывший акцент проекта. */
  --success:       #34d399;
  --success-soft:  rgba(52, 211, 153, .13);

  /* Сияние-подложка hero/карточек (см. .hero::before в разделе 4). */
  --aurora-1:      #c49aff;
  --aurora-2:      #6517d8;

  --hero1:         #211533;
  --hero2:         #120d1c;
  --top:           rgba(9, 7, 16, .88);
  --chip:          #211931;

  --radius:        14px;
  --radius-sm:     10px;
  --radius-lg:     18px;
  --radius-pill:   999px;
  --shadow:        0 18px 48px rgba(0, 0, 0, .32);
  --shadow-hover:  0 22px 60px rgba(0, 0, 0, .42);
  --focus-ring:    0 0 0 3px rgba(166, 107, 255, .36);
  --transition:    .18s cubic-bezier(.4, 0, .2, 1);

  --font-display: 'Unbounded', var(--font);

  --side-w:        268px;
  --top-h:         64px;
  --tap:           44px;

  /* Inter грузится с Google Fonts; если сети нет, подхватываются системные
     шрифты — интерфейс остаётся читаемым, а не съезжает на Times. */
  --font: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
          "Helvetica Neue", "Noto Sans", Arial, sans-serif;
  --font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace;

  /* Псевдонимы для старой разметки, чтобы ничего не сломалось */
  --bg-primary:    var(--bg);
  --bg-secondary:  var(--panel);
  --bg-card:       var(--panel);
  --bg-hover:      var(--panel2);
  --card:          var(--panel);
  --surface-1:     var(--panel);
  --surface-2:     var(--panel2);
  --surface-border: var(--line);
  --border:        var(--line);
  --border-color:  var(--line);
  --input-bg:      var(--input);
  --navbar-bg:     var(--side);
  --text-primary:  var(--text);
  --text-secondary: var(--text-2);
  --text-muted:    var(--muted);
  --primary:       var(--accent);
  --primary-dark:  var(--accent-strong);
  --primary-light: var(--accent-soft);
  --accent2:       var(--info);

  --alert-bg-success:   var(--success-soft);
  --alert-text-success: var(--success);
  --alert-bg-info:      var(--info-soft);
  --alert-text-info:    var(--info);
  --alert-bg-warning:   var(--warning-soft);
  --alert-text-warning: var(--warning);
  --alert-bg-danger:    var(--danger-soft);
  --alert-text-danger:  var(--danger);
}

:root[data-accent="blue"], body[data-accent="blue"] {
  --accent:#5b8cff; --accent-strong:#3768d8; --accent-soft:rgba(91,140,255,.16);
  --focus-ring:0 0 0 3px rgba(91,140,255,.36);
}
:root[data-accent="green"], body[data-accent="green"] {
  --accent:#39b98a; --accent-strong:#218765; --accent-soft:rgba(57,185,138,.16);
  --focus-ring:0 0 0 3px rgba(57,185,138,.36);
}
html[data-contrast="high"] body {
  --muted:var(--text-2); --line:var(--line-strong);
}
html[data-contrast="high"] input,
html[data-contrast="high"] select,
html[data-contrast="high"] textarea,
html[data-contrast="high"] button,
html[data-contrast="high"] .btn { border-width:2px; }
@media (prefers-contrast: more) {
  html[data-contrast="system"] body { --muted:var(--text-2); --line:var(--line-strong); }
}
html[data-motion="reduced"] *,
html[data-motion="reduced"] *::before,
html[data-motion="reduced"] *::after {
  animation-duration:.01ms !important; animation-iteration-count:1 !important;
  transition-duration:.01ms !important; scroll-behavior:auto !important;
}

/* Светлая тема. Поддерживаем оба переключателя: data-theme (страницы
   проектов) и класс .light-theme (страницы верхнего уровня). */
body[data-theme="light"],
body.light-theme {
  color-scheme: light;

  --bg:            #f4f6fa;
  --side:          #ffffff;
  --panel:         #ffffff;
  --panel2:        #eef2f7;
  --input:         #ffffff;
  --line:          #dde4ee;
  --line-strong:   #c6d0de;

  --text:          #131a26;
  --text-2:        #3d4757;
  --muted:         #6b7789;

  --accent:        #7138c9;
  --accent-strong: #5b28aa;
  --accent-ink:    #ffffff;
  --accent-soft:   rgba(113, 56, 201, .12);

  --info:          #2563eb;
  --info-soft:     rgba(37, 99, 235, .10);
  --warning:       #b45309;
  --warning-soft:  rgba(180, 83, 9, .10);
  --danger:        #c81e5c;
  --danger-soft:   rgba(200, 30, 92, .10);
  --violet:        #a3298c;
  --violet-soft:   rgba(163, 41, 140, .10);
  --success:       #0d9668;
  --success-soft:  rgba(13, 150, 104, .10);

  --aurora-1:      #9662e8;
  --aurora-2:      #c7a5ff;

  --hero1:         #ffffff;
  --hero2:         #eaf1f8;
  --top:           rgba(255, 255, 255, .88);
  --chip:          #eef2f7;

  --shadow:        0 16px 40px rgba(20, 34, 62, .08);
  --shadow-hover:  0 22px 52px rgba(20, 34, 62, .14);
}

body[data-theme="dark"],
body.dark-theme { color-scheme: dark; }

/* The light theme defines its own accent tokens above. Keep a chosen accent
   stronger than those defaults, including during the early head bootstrap. */
html[data-accent="blue"] body {
  --accent:#5b8cff; --accent-strong:#3768d8; --accent-soft:rgba(91,140,255,.16);
  --focus-ring:0 0 0 3px rgba(91,140,255,.36);
}
html[data-accent="green"] body {
  --accent:#39b98a; --accent-strong:#218765; --accent-soft:rgba(57,185,138,.16);
  --focus-ring:0 0 0 3px rgba(57,185,138,.36);
}
html[data-accent="blue"] body:is(.light-theme,[data-theme="light"]) {
  --accent:#2455bd; --accent-strong:#194296; --accent-soft:rgba(36,85,189,.12);
  --focus-ring:0 0 0 3px rgba(36,85,189,.28);
}
html[data-accent="green"] body:is(.light-theme,[data-theme="light"]) {
  --accent:#117a52; --accent-strong:#095c3b; --accent-soft:rgba(17,122,82,.12);
  --focus-ring:0 0 0 3px rgba(17,122,82,.28);
}

/* ======================= 2. БАЗА И ТИПОГРАФИКА ========================== */

* { box-sizing: border-box; }

/* Любой элемент с атрибутом hidden обязан реально скрываться — по
   умолчанию это обеспечивает браузерное правило [hidden]{display:none}, но
   у него специфичность как у обычного атрибутного селектора: класс с
   собственным display (например .foo{display:flex}) при равной
   специфичности побеждает как более поздний, авторский. На практике это
   уже дважды ломало реальные тумблеры .hidden=true/false в JS: панель
   уведомлений/её бейдж (.notif-panel, .notif-badge) и список файлов при
   импорте архивов аккаунтов (.account-file-list) — все трое продолжали
   рендериться, что бы ни говорил их атрибут hidden. !important здесь не
   локальный хак под один компонент, а гарантия на будущее для всего файла:
   ни один новый .foo{display:...} не сможет тайно перебить hidden.*/
[hidden] { display: none !important; }

html { -webkit-text-size-adjust: 100%; }

body {
  margin: 0;
  background: var(--bg);
  color: var(--text);
  font-family: var(--font);
  font-size: 15px;
  line-height: 1.55;
  -webkit-font-smoothing: antialiased;
  overflow-wrap: break-word;
}

a { color: inherit; text-decoration: none; }
a:focus-visible,
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible,
[tabindex]:focus-visible {
  outline: none;
  box-shadow: var(--focus-ring);
  border-radius: var(--radius-sm);
}

h1, h2, h3, h4 { margin: 0 0 8px; font-weight: 700; letter-spacing: -.02em; }
h1 { font-size: clamp(24px, 3.2vw, 31px); line-height: 1.18; font-family: var(--font-display); font-weight: 600; text-wrap: balance; }
h2 { font-size: 17px; }
h3 { font-size: 15px; }
p  { margin: 0 0 10px; }

.muted, .desc, .form-hint, .empty-text { color: var(--muted); }
small { font-size: 12.5px; }
/* Маска внутри мелкого текста (11.11: эмодзи ⛔ у пометки «отключён от
   рассылки» заменена .ic-ban). Строчный контекст без flex — штрих надо
   посадить по строке вручную, иначе он висит выше текста. */
small .ic { vertical-align: -.16em; }

.eyebrow {
  display: block;
  margin-bottom: 6px;
  background: linear-gradient(90deg, var(--aurora-1), var(--aurora-2));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-size: 11px;
  font-weight: 800;
  letter-spacing: .14em;
  text-transform: uppercase;
}

code, pre, .mono { font-family: var(--font-mono); font-size: 13px; }
code {
  padding: 2px 6px;
  border-radius: 6px;
  background: var(--panel2);
  color: var(--text-2);
}
pre { overflow-x: auto; -webkit-overflow-scrolling: touch; }

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

/* ============================ 3. КАРКАС ================================= */

.app {
  min-height: 100vh;
  min-height: 100dvh;
  display: grid;
  grid-template-columns: var(--side-w) minmax(0, 1fr);
}

.side {
  position: sticky;
  top: 0;
  height: 100vh;
  height: 100dvh;
  display: flex;
  flex-direction: column;
  padding: 18px 14px 14px;
  background: var(--side);
  border-right: 1px solid var(--line);
  overflow-y: auto;
  overscroll-behavior: contain;
}

.brand {
  display: flex;
  align-items: center;
  gap: 11px;
  padding: 6px 10px 18px;
  font-size: 17px;
  font-weight: 700;
  letter-spacing: -.02em;
}
.brand-mark {
  display: grid;
  place-items: center;
  width: 30px; height: 30px; flex: 0 0 30px;
  border-radius: 9px;
  background: linear-gradient(135deg, var(--accent), var(--accent-strong));
  color: var(--accent-ink);
  font-size: 15px;
  font-weight: 800;
}
.brand-wordmark { display: grid; gap: 1px; line-height: 1.05; letter-spacing: .12em; }
.brand-wordmark b { font-size: 11px; font-weight: 800; }
.brand-wordmark small { color: var(--muted); font-size: 8px; letter-spacing: .32em; }
.brand-tag {
  margin-left: auto;
  padding: 3px 8px;
  border-radius: var(--radius-pill);
  background: var(--chip);
  color: var(--muted);
  font-size: 10.5px;
  font-weight: 700;
}

.project {
  display: flex;
  align-items: center;
  gap: 11px;
  padding: 12px;
  margin-bottom: 14px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel);
  transition: border-color var(--transition), background var(--transition);
}
.project:hover { border-color: var(--line-strong); background: var(--panel2); }
.project-mark {
  display: grid;
  place-items: center;
  width: 34px; height: 34px; flex: 0 0 34px;
  border-radius: 10px;
  background: var(--accent-soft);
  color: var(--accent);
  font-weight: 800;
}
.project b { display: block; font-size: 13.5px; }
.project small { color: var(--muted); font-size: 11px; }

.side nav { display: grid; gap: 3px; }
.nav-new{display:inline-block;margin-left:6px;padding:1px 7px;border-radius:99px;
background:var(--accent);color:#fff;font-size:10.5px;font-weight:700;
line-height:1.5;letter-spacing:.4px;vertical-align:1px}
.nav-group {
  padding: 16px 12px 6px;
  color: var(--muted);
  font-size: 10.5px;
  font-weight: 800;
  letter-spacing: .13em;
  text-transform: uppercase;
}
.side nav a {
  position: relative;
  display: flex;
  align-items: center;
  gap: 11px;
  min-height: var(--tap);
  padding: 10px 12px;
  border-radius: var(--radius-sm);
  color: var(--text-2);
  font-size: 14px;
  transition: background .24s ease, color .24s ease, transform .24s cubic-bezier(.2,.8,.2,1);
}
.side nav a i { width: 18px; font-size: 15px; text-align: center; color: var(--muted); }
.side nav a:hover { background: var(--panel2); color: var(--text); }
@media (hover: hover) and (pointer: fine) {
  .side nav a:hover { transform: translateX(2px); }
}
.side nav a.active { background: var(--panel2); color: var(--text); font-weight: 600; }
.side nav a.active i { color: var(--accent); }
.side nav a.active::before {
  content: "";
  position: absolute;
  left: 0; top: 50%;
  width: 3px; height: 22px;
  margin-top: -11px;
  border-radius: 0 3px 3px 0;
  background: var(--accent);
  transform-origin: center;
  animation: lf-nav-indicator-in .48s cubic-bezier(.16,1,.3,1) both;
}
@keyframes lf-nav-indicator-in { from { opacity: .35; transform: scaleY(.24); } to { opacity: 1; transform: scaleY(1); } }
.nav-count {
  margin-left: auto;
  padding: 2px 8px;
  border-radius: var(--radius-pill);
  background: var(--chip);
  color: var(--muted);
  font-size: 11px;
  font-weight: 700;
}

.side .bottom {
  margin-top: auto;
  padding-top: 12px;
  border-top: 1px solid var(--line);
}

.content { min-width: 0; display: flex; flex-direction: column; }

.top {
  position: sticky;
  top: 0;
  z-index: 30;
  display: flex;
  align-items: center;
  gap: 12px;
  height: var(--top-h);
  padding: 0 24px;
  background: var(--top);
  border-bottom: 1px solid var(--line);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
}
.top .crumbs { color: var(--muted); font-size: 12.5px; min-width: 0; }
.top .crumbs b { color: var(--text-2); font-weight: 600; }
.top-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
  min-width: 0;
}

.burger-btn {
  display: none;
  align-items: center;
  justify-content: center;
  width: var(--tap); height: var(--tap);
  padding: 0;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel);
  color: var(--text);
  font-size: 18px;
  cursor: pointer;
}

.icon-btn {
  display: grid;
  place-items: center;
  width: 38px; height: 38px;
  min-height: 38px;
  padding: 0;
  border: 1px solid transparent;
  border-radius: var(--radius-sm);
  background: transparent;
  color: var(--muted);
  font-size: 15px;
  cursor: pointer;
  transition: background var(--transition), color var(--transition);
}
.icon-btn:hover { background: var(--panel2); color: var(--text); filter: none; }

/* ===== Полноэкранный режим блока диалогов (08.11, слово владельца) =====
   По кнопке .dialogs-layout поднимается в fixed на весь вьюпорт: ничего
   лишнего вокруг, только сам блок (список + переписка). Повторный
   клик/Esc возвращает обычный вид. */

/* Окно выбора чатов для обучения. Слово владельца 11.11: «надпись
   Telegram должна быть ОДНА и выше всего — это типа для каждой соцсети,
   чтобы разбить по соцсетям; только у Телеграмма два вида аккаунтов».
   Поэтому два уровня: канал (крупно, одна строка на соцсеть) и, только
   внутри Telegram, тип аккаунта (мельче). */
.lt-ch-row > td, .lt-grp-row > td { padding: 0; }
.lt-ch-head {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 14px;
  background: var(--panel2, var(--panel));
  border-top: 1px solid var(--line);
  border-bottom: 1px solid var(--line);
}
.lt-ch-toggle {
  flex: 0 0 auto;
  width: 26px;
  height: 26px;
  display: grid;
  place-items: center;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  color: var(--text);
  font-size: 11px;
  line-height: 1;
  cursor: pointer;
}
.lt-ch-toggle:hover { background: var(--accent); color: #fff; border-color: transparent; }
.lt-ch-title {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 10px;
  min-width: 0;
}
.lt-ch-title b {
  font-size: 15px;
  letter-spacing: .3px;
  text-transform: uppercase;
  color: var(--accent);
}
.lt-ch-stats { font-size: 12.5px; color: var(--muted); }

.lt-grp-head {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
  padding: 9px 14px 9px 30px;
  background: var(--input, transparent);
}
.lt-grp-head b { font-size: 13.5px; }
.lt-grp-stats { font-size: 12px; color: var(--muted); }
.lt-group-btn { flex: 0 0 auto; }
@media (max-width: 700px) {
  .lt-ch-stats, .lt-grp-stats { flex-basis: 100%; }
  .lt-grp-head { padding-left: 14px; }
}

.dialogs-fs-btn { flex: 0 0 auto; }
.dialogs-layout.dialogs-fs {
  position: fixed;
  inset: 0;
  z-index: 90;
  margin: 0;
  border-radius: 0;
  background: var(--panel, #14161b);
  display: grid;
  grid-template-columns: minmax(280px, 380px) 1fr;
  height: 100vh;
  height: 100dvh;
  max-height: none;
}
.dialogs-layout.dialogs-fs .dialog-list-pane {
  border-right: 1px solid var(--border);
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding-top: env(safe-area-inset-top);
}
.dialogs-layout.dialogs-fs #dialogListScroll { flex: 1 1 auto; overflow-y: auto; }
.dialogs-layout.dialogs-fs .thread-pane {
  height: 100%;
  overflow-y: auto;
  padding-top: env(safe-area-inset-top);
  padding-bottom: env(safe-area-inset-bottom);
}
@media (max-width: 900px) {
  .dialogs-layout.dialogs-fs { grid-template-columns: 1fr; }
  .dialogs-layout.dialogs-fs.thread-open .dialog-list-pane { display: none; }
  .dialogs-layout.dialogs-fs:not(.thread-open) .thread-pane { display: none; }
}

/* Плашка баланса ИИ в шапке (слово владельца 08.11, повтор). */
.balance-chip {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 7px 11px; border-radius: var(--radius-pill);
  background: var(--panel2); border: 1px solid var(--border);
  color: var(--text); text-decoration: none; white-space: nowrap;
  font-size: 13px; line-height: 1;
  /* 11.11 (аудит вёрстки): плашка — не резиновая. Без этого она сжималась
     последней в ряду и рвала собственную подпись, а «₽» уезжал на вторую
     строку. Сжиматься в шапке должен ТЕКСТ пользователя, а не деньги. */
  flex: 0 0 auto;
}
.balance-chip b { font-weight: 700; }
.balance-chip .balance-chip-sub { color: var(--muted); font-size: 11.5px; }
.balance-chip:hover { filter: brightness(1.08); }
.balance-chip.warn { border-color: var(--danger, #e2483d); color: var(--danger, #e2483d); }
.balance-chip.warn .balance-chip-sub { color: var(--danger, #e2483d); opacity: .8; }

.notif-bell-wrap { position: relative; }
.notif-bell-wrap .icon-btn { position: relative; }
.notif-badge {
  position: absolute;
  top: 2px; right: 2px;
  min-width: 15px; height: 15px;
  padding: 0 4px;
  display: grid; place-items: center;
  border-radius: var(--radius-pill);
  background: var(--danger);
  color: #fff;
  font-size: 10px;
  font-weight: 700;
  line-height: 1;
}
.notif-panel {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  width: 340px;
  max-height: 420px;
  display: flex;
  flex-direction: column;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel);
  box-shadow: var(--shadow);
  z-index: 40;
  overflow: hidden;
}
.notif-panel-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  padding: 12px 14px;
  border-bottom: 1px solid var(--line);
}
.notif-list { overflow-y: auto; }
.notif-row {
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 11px 14px;
  border-bottom: 1px solid var(--line);
  cursor: pointer;
  transition: background var(--transition);
}
.notif-row:last-child { border-bottom: none; }
.notif-row:hover { background: var(--panel2); }
/* Непрочитанное — тонкая полоса слева, а не заливка всей строки: в списке
   из десятка уведомлений сплошные цветные блоки читались как «всё
   сломалось» (слово владельца 11.11: премиум-бизнес, не детский вид). */
.notif-row.unread { background: color-mix(in srgb, var(--accent) 4%, transparent); }
.notif-row.unread::before {
  content: "";
  position: absolute;
  inset: 0 auto 0 0;
  width: 2px;
  background: var(--accent);
}
.notif-row-icon {
  flex: 0 0 auto;
  margin-top: 2px;
  color: var(--muted);
  font-size: 15px;
}
.notif-row.unread .notif-row-icon { color: var(--accent); }
.notif-row-body { min-width: 0; font-size: 13px; line-height: 1.4; }
.notif-row-body b { display: block; font-weight: 600; }
.notif-row-body .muted { font-size: 12px; margin-top: 1px; }
.notif-row-title { display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap; min-width: 0; }
.notif-row-title b { min-width: 0; overflow-wrap: anywhere; }
/* Метка направления в списке уведомлений (renderNotifList, main.js):
   общий вид чипа как у .brand-tag/.pill, но компактнее — панель узкая. */
.notif-ws-badge {
  flex: 0 1 auto;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 1px 7px;
  border-radius: var(--radius-pill);
  background: var(--chip);
  color: var(--muted);
  font-size: 10.5px;
  font-weight: 700;
}
.notif-row-time { font-size: 11px; margin-top: 2px; }
@media (max-width: 480px) {
  .notif-panel { position: fixed; top: var(--top-h); left: 10px; right: 10px; width: auto; }
}

.current-admin {
  display: flex;
  align-items: center;
  gap: 9px;
  min-width: 0;
  max-width: 250px;
  padding: 5px 9px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel);
  /* 11.11 (аудит вёрстки, замер шапки на 390px): карточка пользователя —
     ПОСЛЕДНЕЙ в ряду и ужималась сильнее всех. При ширине 390 от неё
     оставалось 75px на аватар 32 + два «шестерёнка/выход» по 30 — имя
     сжималось в 25px (одна буква), а на 320px карточка схлопывалась в 16px
     и аватар вылезал за экран (doc=409 при vw=390). Теперь карточка НЕ
     сжимается ниже своей компактной ширины: ужимается подпись внутри
     (ellipsis), а не сама карточка. */
  flex: 0 0 auto;
}
.current-admin-avatar {
  width: 32px; height: 32px; flex: 0 0 32px;
  border-radius: 50%;
  object-fit: cover;
  background: var(--accent-soft);
  color: var(--accent);
}
.current-admin-meta { min-width: 0; display: grid; gap: 1px; line-height: 1.2; }
.current-admin-meta strong {
  font-size: 12px; font-weight: 600;
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.current-admin-meta span { font-size: 10.5px; color: var(--muted); }
.admin-logout {
  display: grid; place-items: center;
  width: 30px; height: 30px;
  margin-left: 4px;
  border-radius: 8px;
  color: var(--muted);
}
.admin-logout:hover { background: var(--panel2); color: var(--text); }

main, .container {
  width: 100%;
  max-width: 1420px;
  margin: 0 auto;
  /* Слово владельца 10.11: «слишком вытянутое, не вся информация
     помещается». Верхний отступ уменьшен 26→18: на ноутбуке 768px по
     высоте это возвращало половину строки первого блока на экран, ничего
     не сжимая внутри. Нижний оставлен большим (44) — там конец страницы,
     и «воздух» после последней карточки ничего не отнимает. */
  padding: 18px 24px 40px;
}

.nav-overlay {
  position: fixed;
  inset: 0;
  z-index: 60;
  background: rgba(4, 6, 10, .58);
  opacity: 0;
  visibility: hidden;
  transition: opacity var(--transition), visibility var(--transition);
}
.nav-overlay.show { opacity: 1; visibility: visible; }

/* window.prompt() замена (см. window.leadflowPromptConfirm в main.js) —
   не полагается на нативный диалог браузера, который во многих версиях
   Telegram Mini App (WebView) не показывается вовсе. */
.lf-modal-overlay {
  position: fixed; inset: 0; z-index: 200;
  background: rgba(4, 6, 10, .58);
  display: flex; align-items: center; justify-content: center;
  padding: 20px;
}
.lf-modal {
  width: 100%; max-width: 420px;
  padding: 22px; border-radius: var(--radius-lg);
  background: var(--panel); border: 1px solid var(--line); box-shadow: var(--shadow);
}
.lf-modal p { margin: 0 0 14px; font-size: 14px; line-height: 1.5; white-space: pre-wrap; }
.lf-modal-input { width: 100%; margin-bottom: 14px; }
.lf-modal-actions { display: flex; justify-content: flex-end; gap: 8px; }

/* Баннер «Данные изменились» (db_refresh.js). Раньше стили были inline в
   JS с z-index:9999 — поверх ВСЕГО, включая мобильный оверлей треда (65) и
   модалки (200): на телефоне плашка липла к нижнему краю и перекрывала
   composer открытого диалога, игнорируя home-индикатор.

   Слой 55 — выше липкого топбара (40), но ниже подложки сайдбара (60),
   оверлея треда (65), самого сайдбара (70) и модалок (200): баннер про
   данные уровня страницы, и он не должен висеть поверх диалогов, которые
   пользователь ведёт в данный момент. На мобильном /replies открытый тред —
   непрозрачный полноэкранный слой, поэтому баннер просто не виден, пока тред
   открыт; это корректно: тред поллит свои сообщения сам (threadPollTimer),
   а PRAGMA data_version меняется от любой записи в БД — чаще всего именно от
   сообщений этого треда. Закрыл тред — баннер тут как тут. */
.db-changed-notice {
  position: fixed;
  right: 18px;
  bottom: 18px;
  z-index: 55;
  display: flex;
  align-items: center;
  gap: 10px;
  max-width: 420px;
  padding: 12px 14px;
  background: var(--panel);
  border: 1px solid var(--line);
  border-radius: 12px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, .25);
}

/* ========================= 4. КОМПОНЕНТЫ ================================ */

.hero, .hero-card {
  position: relative;
  isolation: isolate;
  overflow: hidden;
  /* Слово владельца 10.11: «слишком вытянутое, не вся информация
     помещается». Шапка страницы занимала 24px отступа сверху и снизу плюс
     18px отрыва от первого блока — четверть экрана ноутбука уходила на три
     строки текста. 20/14 при той же типографике: заголовок читается так же,
     а до первого смыслового блока человек видит на строку больше. */
  padding: 20px;
  margin-bottom: 14px;
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  background: var(--hero1);
}
/* Тлеющее сияние — единственное место, где мы тратим "необычность" на
   весь интерфейс: два размытых пятна цвета аврора-акцента медленно
   дрейфуют за шапкой каждой страницы. Везде остальное — спокойно. */
.hero::before, .hero-card::before {
  content: "";
  position: absolute;
  z-index: -1;
  inset: -40% -20% auto auto;
  width: 60%;
  aspect-ratio: 1;
  border-radius: 50%;
  background: radial-gradient(circle, var(--aurora-1), transparent 70%);
  opacity: .28;
  filter: blur(48px);
  animation: aurora-drift 22s ease-in-out infinite alternate;
}
.hero::after, .hero-card::after {
  content: "";
  position: absolute;
  z-index: -1;
  inset: auto auto -50% -10%;
  width: 50%;
  aspect-ratio: 1;
  border-radius: 50%;
  background: radial-gradient(circle, var(--aurora-2), transparent 70%);
  opacity: .22;
  filter: blur(48px);
  animation: aurora-drift 26s ease-in-out infinite alternate-reverse;
}
@keyframes aurora-drift {
  from { transform: translate(0, 0) scale(1); }
  to   { transform: translate(-6%, 8%) scale(1.15); }
}
@media (prefers-reduced-motion: reduce) {
  .hero::before, .hero-card::before, .hero::after, .hero-card::after { animation: none; }
}
.hero h1, .hero-card h1 { margin-bottom: 6px; font-family: var(--font-display); font-weight: 600; letter-spacing: -.01em; }
.hero p, .hero-card p { color: var(--muted); margin: 0; max-width: 68ch; }
.hero .actions, .hero-card .actions { margin-top: 16px; }

.card, .info-card, .action-card, .stat-card, .info-block, .example-block {
  /* Плотность карточки: 18→16 по вертикали. На странице из шести карточек
     это те же 12px экономии без единого потерянного пикселя содержимого. */
  padding: 16px 18px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel);
}
.card { box-shadow: var(--shadow); }
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin: -2px 0 14px;
}
.card-header h2 { margin: 0; }
.card-body { min-width: 0; }

.section-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 14px;
}
.section-head h2 { margin: 0 0 3px; }
.dashboard-section { margin-top: 16px; }

.grid   { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; }
.grid2  { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, .75fr); gap: 14px; }
.grid3  { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; }
.stats-grid, .metrics-grid, .actions-grid, .security-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
  gap: 14px;
}
/* Поля-«плитки» (настройки направления, каналы платформы): ряд из нескольких
   подписанных полей. Это НЕ .grid2 — тот про «широкая колонка + узкий
   сайдбар» и держит ровно две дорожки. Для одинаковых полей нужна сетка,
   которая сама подбирает число дорожек и НЕ оставляет дыру в последнем ряду:
   11.11 (аудит вёрстки) на странице настроек три лимита вставали «2+1», а
   пять кулдаунов «2+2+1» — одна карточка на всю ширину с пустотой справа.
   auto-fit + minmax(220px) даёт 3+0 и 3+2 на широком экране и 1 колонку на
   телефоне; последнее поле растягивается на свободное место, а не висит
   сиротой в половине ряда. */
.fields-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 12px 14px;
}
.fields-grid > div { min-width: 0; }
.analytics-grid { display: grid; grid-template-columns: minmax(0, 1.45fr) minmax(0, 1fr); gap: 14px; }

.metric, .stat-card {
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 3px;
  /* Слово владельца 10.11: «карточки на пол-экрана с одним числом».
     108px при одной цифре и двух подписях — это запас пустоты, а не
     воздух: карточка с «2» и карточка с «12 483» должны быть одной
     высоты, но не за счёт трети экрана. 88px хватает обеим. */
  min-height: 88px;
}
.metric b, .stat-card .number {
  display: block;
  font-size: clamp(26px, 3.4vw, 32px);
  font-weight: 700;
  line-height: 1.05;
  letter-spacing: -.03em;
}
.metric span, .stat-card .number + div {
  color: var(--muted);
  font-size: 13px;
  font-weight: 500;
}
.metric small { display: block; margin-top: 4px; color: var(--muted); }
.metric::after {
  content: "";
  position: absolute;
  inset: 0 0 auto 0;
  height: 3px;
  background: var(--accent);
  opacity: .8;
}
.metric.is-info::after    { background: var(--info); }
.metric.is-warning::after { background: var(--warning); }
.metric.is-violet::after  { background: var(--violet); }
.metric.is-success::after { background: var(--success); }

.btn, button, .dropbtn, .toggle-btn, .theme-toggle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-height: var(--tap);
  padding: 11px 16px;
  border: 1px solid transparent;
  border-radius: var(--radius-sm);
  background: var(--accent);
  color: var(--accent-ink);
  font-family: inherit;
  font-size: 14px;
  font-weight: 700;
  line-height: 1;
  cursor: pointer;
  text-align: center;
  transition: filter var(--transition), background var(--transition),
              border-color var(--transition), transform var(--transition);
}
.btn:hover, button:hover {
  filter: brightness(1.1) saturate(1.08); transform: translateY(-2px);
  box-shadow: 0 9px 24px color-mix(in srgb, var(--accent) 24%, transparent);
}
.btn:active, button:active { filter: brightness(.98); transform: translateY(0) scale(.985); box-shadow: none; }
.btn:disabled, button:disabled { opacity: .55; cursor: not-allowed; }

.btn.secondary, button.secondary,
.btn-secondary, .btn-outline, .dropbtn, .toggle-btn, .theme-toggle {
  background: var(--panel2);
  border-color: var(--line);
  color: var(--text);
  font-weight: 600;
}
.btn.secondary:hover, button.secondary:hover,
.btn-secondary:hover, .btn-outline:hover { border-color: var(--line-strong); }

/* Product micro-interactions use one restrained spring across the workspace;
   only cards that are actual links lift, never passive data panels. */
a.card, .action-card, .project {
  transition: transform .28s cubic-bezier(.2,.8,.2,1),
    border-color .28s ease, box-shadow .28s ease, background .28s ease;
}
a.card:hover, .action-card:hover {
  transform: translateY(-3px);
  border-color: color-mix(in srgb, var(--accent) 42%, var(--line));
  box-shadow: 0 14px 36px rgba(0,0,0,.2), 0 0 0 1px color-mix(in srgb, var(--accent) 9%, transparent);
}

.btn-primary, .btn-success { background: var(--accent); color: var(--accent-ink); }
.btn.danger, button.danger, .btn-danger {
  background: var(--danger-soft);
  border-color: var(--danger);
  color: var(--danger);
}
.btn-warning { background: var(--warning-soft); border-color: var(--warning); color: var(--warning); }
.btn-sm { min-height: 34px; padding: 7px 11px; font-size: 12.5px; }
.btn-lg { min-height: 52px; padding: 15px 22px; font-size: 16px; }

.actions, .btn-group, .button-group, .form-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}
.actions form { margin: 0; }

.theme-toggle { width: 38px; min-height: 38px; padding: 0; }

label, .label {
  display: block;
  margin-bottom: 4px;
  font-size: 13px;
  font-weight: 600;
  color: var(--text-2);
}
.required::after { content: " *"; color: var(--danger); }

input, textarea, select, .form-control {
  width: 100%;
  min-height: var(--tap);
  padding: 11px 13px;
  margin: 0 0 14px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--input);
  color: var(--text);
  font-family: inherit;
  font-size: 15px;
  transition: border-color var(--transition), box-shadow var(--transition);
}
input:hover, textarea:hover, select:hover { border-color: var(--line-strong); }
input:focus, textarea:focus, select:focus {
  border-color: var(--accent);
  box-shadow: var(--focus-ring);
  outline: none;
}
input::placeholder, textarea::placeholder { color: var(--muted); }
textarea { min-height: 118px; resize: vertical; line-height: 1.6; }
select {
  appearance: none;
  -webkit-appearance: none;
  background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%),
                    linear-gradient(135deg, var(--muted) 50%, transparent 50%);
  background-position: calc(100% - 18px) calc(50% + 1px), calc(100% - 13px) calc(50% + 1px);
  background-size: 5px 5px, 5px 5px;
  background-repeat: no-repeat;
  padding-right: 36px;
}
.form-group { margin-bottom: 4px; }
input[type="checkbox"], input[type="radio"] {
  width: 20px; height: 20px; min-height: 20px;
  margin: 0 8px 0 0; vertical-align: -4px;
  accent-color: var(--accent);
}
input[type="file"] { padding: 9px; }

/* The plan matrix uses a full touch target while keeping a compact checkbox. */
.plan-feature-cell { text-align: center; }
.plan-feature-toggle {
  display: inline-flex;
  width: 44px;
  height: 44px;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.plan-feature-toggle input[type="checkbox"] { margin: 0; }
.plan-feature-toggle:focus-within {
  outline: 2px solid var(--accent);
  outline-offset: 2px;
  border-radius: 6px;
}
.plan-feature-toggle:has(input:disabled) { cursor: default; }

.table-container, .table-wrap, .table-responsive {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  border: 1px solid var(--line);
  border-radius: var(--radius);
}
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th {
  padding: 12px 14px;
  border-bottom: 1px solid var(--line);
  background: var(--panel2);
  color: var(--muted);
  font-size: 11.5px;
  font-weight: 700;
  letter-spacing: .06em;
  text-transform: uppercase;
  text-align: left;
  white-space: nowrap;
}
td {
  padding: 13px 14px;
  border-bottom: 1px solid var(--line);
  text-align: left;
  vertical-align: middle;
}
tbody tr:last-child td { border-bottom: 0; }
tbody tr { transition: background var(--transition); }
tbody tr:hover { background: var(--panel2); }
.muted-cell { color: var(--muted); font-size: 12.5px; }

.pill, .badge, .status-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  border-radius: var(--radius-pill);
  background: var(--accent-soft);
  color: var(--accent);
  font-size: 11.5px;
  font-weight: 700;
  white-space: nowrap;
}
.badge-on, .status-active, .status-ok, .status-completed, .on { background: var(--accent-soft); color: var(--accent); }
.badge-warn, .status-warn, .status-pending, .status-waiting, .status-scheduled { background: var(--warning-soft); color: var(--warning); }
.badge-off, .status-inactive, .status-badge.denied, .off { background: var(--danger-soft); color: var(--danger); }
.status-running { background: var(--info-soft); color: var(--info); }

.status-dot {
  display: inline-block;
  width: 8px; height: 8px;
  border-radius: 50%;
  background: var(--accent);
}
.nav-time {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 7px 12px;
  border: 1px solid var(--line);
  border-radius: var(--radius-pill);
  background: var(--panel);
  color: var(--muted);
  font-size: 12.5px;
  font-weight: 600;
}

/* Плашки-напоминания (слово владельца 11.11: «дизайн всех таких
   напоминаний очень детский, у нас должен быть премиум-бизнес дизайн»).

   Что было «детским» и что изменилось:
   1. ЦВЕТ. Плашка заливалась насыщенным цветом статуса и обводилась им же
      той же насыщенности — как стикер. Теперь заливка — тот же оттенок на
      8%, рамка — на 28%, а цвет статуса держится ОДНОЙ узкой полосой слева.
      Читается статус так же быстро, но страница не пестрит.
   2. ФОРМА. Рамка 1px и радиус из шкалы (--radius-sm) вместо «толстая
      цветная коробка»; текст — обычного цвета, а не цвета статуса (цветной
      абзац текста читается хуже и выглядит игрушечно).
   3. ИЕРАРХИЯ. Появился .alert-title — строка-заголовок, отделённая от
      пояснения. Раньше всё было одной простынёй жирного цвета.
   4. ЭМОДЗИ. Значков-эмодзи в плашках нет и не должно быть: иконка
      ставится маской .ic-* (см. .alert .ic), она наследует цвет статуса. */
.alert {
  --alert-tone: var(--accent);
  position: relative;
  padding: 12px 14px 12px 17px;
  margin-bottom: 12px;
  /* Fallback для движков без color-mix (аудит B5, D-1): рамка и фон
     деградируют в базовые переменные, читаемость сохраняется. */
  border: 1px solid var(--line);
  border: 1px solid color-mix(in srgb, var(--alert-tone) 28%, var(--line));
  border-radius: var(--radius-sm);
  background: var(--panel);
  background: color-mix(in srgb, var(--alert-tone) 8%, var(--panel));
  color: var(--text);
  font-size: 13.5px;
  line-height: 1.5;
}
/* Полоса статуса — единственное место, где цвет звучит в полную силу. */
.alert::before {
  content: "";
  position: absolute;
  inset: 0 auto 0 0;
  width: 3px;
  border-radius: var(--radius-sm) 0 0 var(--radius-sm);
  background: var(--alert-tone);
}
/* Иконка в плашке — маска (.ic-*), не эмодзи: наследует цвет статуса. */
.alert .ic { color: var(--alert-tone); }
.alert-title {
  display: block;
  margin-bottom: 2px;
  font-weight: 600;
  color: var(--text);
}
.alert-success { --alert-tone: var(--success); }
.alert-info    { --alert-tone: var(--info); }
.alert-warning { --alert-tone: var(--warning); }
.alert-danger  { --alert-tone: var(--danger); }
.alert-hidden  { display: none; }

/* Всплывающее подтверждение действия (window.leadflowNotify в main.js).
   Раньше это был браузерный alert(): модальное окно с именем домена,
   системным шрифтом и одной кнопкой «ОК» — самая «детская» поверхность в
   кабинете, и в Telegram WebView оно местами вообще не показывается.
   Теперь — тихая карточка внизу экрана: тонкая цветная полоса статуса,
   обычный текст, закрытие крестиком и само через несколько секунд. */
.lf-toast-stack {
  position: fixed;
  right: 18px;
  bottom: 18px;
  z-index: 210;
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: min(360px, calc(100vw - 32px));
  pointer-events: none;
}
.lf-toast {
  --alert-tone: var(--accent);
  pointer-events: auto;
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 11px 34px 11px 15px;
  /* Fallback рамки для движков без color-mix (аудит B5, D-1). */
  border: 1px solid var(--line);
  border: 1px solid color-mix(in srgb, var(--alert-tone) 28%, var(--line));
  border-left: 3px solid var(--alert-tone);
  border-radius: var(--radius-sm);
  background: var(--panel);
  box-shadow: var(--shadow);
  color: var(--text);
  font-size: 13.5px;
  line-height: 1.45;
  animation: lf-toast-in .48s cubic-bezier(.16, 1, .3, 1) both;
}
.lf-toast .ic { margin-top: 1px; color: var(--alert-tone); font-size: 15px; }
.lf-toast > div { min-width: 0; overflow-wrap: anywhere; }
.lf-toast.is-success { --alert-tone: var(--success); }
.lf-toast.is-warning { --alert-tone: var(--warning); }
.lf-toast.is-danger  { --alert-tone: var(--danger); }
.lf-toast-close {
  position: absolute;
  top: 6px;
  right: 6px;
  display: grid;
  place-items: center;
  width: 22px; height: 22px;
  min-height: 0;
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--muted);
  cursor: pointer;
}
.lf-toast-close:hover { background: var(--panel2); color: var(--text); }
.lf-toast-close .ic { font-size: 11px; color: inherit; margin: 0; }
@keyframes lf-toast-in {
  0% { opacity: 0; transform: translate3d(18px, 12px, 0) scale(.94); filter: blur(5px); }
  68% { opacity: 1; transform: translate3d(-2px, -2px, 0) scale(1.012); filter: blur(0); }
  100% { opacity: 1; transform: translate3d(0, 0, 0) scale(1); filter: none; }
}
@media (max-width: 700px) {
  .lf-toast-stack {
    right: 12px;
    left: 12px;
    bottom: calc(12px + env(safe-area-inset-bottom));
    width: auto;
  }
}

.notice-card { background: var(--panel); border-color: var(--line-strong); }

.empty-state, .table-empty-state, .empty-state-message {
  padding: 40px 20px;
  color: var(--muted);
  text-align: center;
}
.empty-state i { display: block; margin-bottom: 12px; font-size: 34px; opacity: .5; }

.modal {
  position: fixed;
  inset: 0;
  z-index: 200;
  display: none;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background: rgba(4, 6, 10, .62);
}
.modal.open, .modal[open] { display: flex; animation: lf-modal-backdrop-in .24s ease-out both; }
.modal-content {
  width: 100%;
  max-width: 520px;
  max-height: 88vh;
  overflow-y: auto;
  padding: 22px;
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  background: var(--panel);
  box-shadow: var(--shadow-hover);
}

.modal.open .modal-content, .modal[open] .modal-content {
  animation: lf-modal-panel-in .46s cubic-bezier(.16, 1, .3, 1) both;
  transform-origin: 50% 58%;
}
@keyframes lf-modal-backdrop-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes lf-modal-panel-in {
  0% { opacity: 0; transform: perspective(900px) translate3d(0, 18px, -40px) scale(.965); filter: blur(5px); }
  68% { opacity: 1; transform: perspective(900px) translate3d(0, -2px, 0) scale(1.006); filter: blur(0); }
  100% { opacity: 1; transform: perspective(900px) translate3d(0, 0, 0) scale(1); filter: none; }
}

.dropdown { position: relative; }
.dropdown-content {
  position: absolute;
  top: calc(100% + 6px);
  left: 0;
  z-index: 90;
  display: none;
  min-width: 224px;
  padding: 6px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel);
  box-shadow: var(--shadow-hover);
}
.dropdown.open > .dropdown-content,
.dropdown:hover > .dropdown-content { display: block; }
.dropdown.open > .dropdown-content,
.dropdown:hover > .dropdown-content { animation: lf-dropdown-in .2s cubic-bezier(.16, 1, .3, 1) both; transform-origin: 20px 0; }
@keyframes lf-dropdown-in {
  from { opacity: 0; transform: translate3d(0, -6px, 0) scale(.98); filter: blur(3px); }
  to { opacity: 1; transform: translate3d(0, 0, 0) scale(1); filter: none; }
}
.dropdown-content a {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: var(--tap);
  padding: 10px 12px;
  border-radius: 8px;
  color: var(--text-2);
  font-size: 14px;
}
.dropdown-content a:hover { background: var(--panel2); color: var(--text); }

/* Зона перетаскивания/вставки файлов — импорт готовых аккаунтов и другие
   места, где нужно принять один или несколько файлов сразу. */
.account-dropzone {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  text-align: center;
  padding: 28px 20px;
  border: 1.5px dashed var(--line-strong);
  border-radius: var(--radius);
  background: var(--panel2);
  cursor: pointer;
  transition: border-color var(--transition), background var(--transition), box-shadow var(--transition);
}
.account-dropzone:hover,
.account-dropzone:focus-visible { border-color: var(--accent); outline: none; }
.account-dropzone.drag {
  border-color: var(--accent);
  background: var(--accent-soft);
  box-shadow: 0 0 0 3px var(--accent-soft);
}
.account-dropzone-icon {
  display: grid;
  place-items: center;
  width: 44px; height: 44px;
  margin-bottom: 6px;
  border-radius: 50%;
  background: var(--accent-soft);
  color: var(--accent);
  font-size: 19px;
}
.account-dropzone p { margin: 2px 0; color: var(--text-2); font-size: 13.5px; }
.account-dropzone p.small { font-size: 12px; color: var(--muted); }
.account-dropzone b { color: var(--text); }

.account-file-list { margin-top: 12px; display: flex; flex-direction: column; gap: 6px; }
.account-file-summary { font-size: 12.5px; margin-bottom: 2px; }
.account-file-chip {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 10px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel);
}
.account-file-chip-name {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
  font-weight: 600;
}
.account-file-chip-size { font-size: 12px; flex: none; }
.account-file-chip-remove {
  flex: none;
  display: grid;
  place-items: center;
  width: 24px; height: 24px;
  min-height: 0;
  padding: 0;
  border: 0;
  border-radius: 50%;
  background: transparent;
  color: var(--muted);
  font-size: 16px;
  line-height: 1;
  cursor: pointer;
}
.account-file-chip-remove:hover { background: var(--danger-soft); color: var(--danger); }

/* Плитки статистики хаба. Их теперь семь: общий счёт Telegram в компании
   плюс статистика выбранного направления. Своя сетка вместо общего .grid,
   чтобы последняя карточка не оставалась одна после смены ширины.
   Почему не auto-fit 180px: замер в headless Chrome показал, что на
   900px он даёт ровно ЧЕТЫРЕ колонки (по 207px — 180 влезает вчетверо),
   поэтому число колонок задано явно. */
.hub-kpis {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 14px;
}
@media (max-width: 1100px) {
  /* 4+3: семь плиток на две строки. */
  .hub-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
/* На телефоне две компактные колонки; седьмая карточка занимает всю
   последнюю строку вместо того, чтобы висеть одна в половине ширины. */
@media (max-width: 460px) {
  .hub-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  .hub-kpis > .metric:last-child { grid-column: 1 / -1; }
}
/* Полоса-акцент сверху плитки снята ИМЕННО здесь: .metric::after
   (общий компонент) рисует 3px var(--accent) — на странице каналов это
   читалось как «ошибка/тревога» у каждой плитки, хотя числа нейтральны.
   На дашборде те же полосы несут смысл (is-info/is-warning/is-violet
   различают KPI), поэтому общий .metric::after не тронут — правка
   ограничена плитками хаба. */
.hub-kpis .metric::after { content: none; }

/* ---- Хаб аккаунтов (/accounts): сетка карточек каналов ----------------
   11.11 (слово владельца, скриншот «И здесь тоже мне не нравится
   дизайн»): пять каналов были пятью широкими полосами во всю ширину —
   одинаковыми по весу, хотя у одного 25 аккаунтов, а у других ноль, и
   с много воздуха при почти пустом содержимом. Теперь — сетка карточек
   (2–3 в ряд на десктопе, 1 на телефоне), у карточки своя иерархия:
   шапка с иконкой и бейджем, крупные числа, описание, кнопки.
   Все цвета — токены выше; хардкода оттенков в этом блоке нет. */
/* Карточки каналов: колонки фиксированного числа, шаги по одной.
   ПОЧЕМУ НЕ auto-fit (замерено в headless Chrome 11.11): на 1440px
   auto-fit с minmax(272px,1fr) даёт ЧЕТЫРЕ колонки по 274px — шесть
   карточек встают 4+2, и справа в последнем ряду остаётся пустота 580px.
   Ровно тот дефект, о котором скриншот владельца («5-я карточка уехала
   одна, рядом пустота на всю ширину»): auto-fit НЕ растягивает неполный
   последний ряд, он лишь уравнивает ширины внутри ряда.
   Здесь число колонок задано явно и меняется ступенями; каждая ступень
   выбрана так, чтобы шесть карточек делились на неё без остатка
   (6 = 3×2 = 2×3 = 1×6), поэтому последний ряд всегда полный и пустоты
   справа нет ни на одной ширине.
   min(272px, 100%) — страховка от горизонтального скролла на очень
   узком экране: колонка не может стать шире контейнера. */
.hub-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 16px;
  margin-top: 16px;
}
/* Узкий десктоп/планшет: две колонки (6 = 2×3). */
@media (max-width: 1100px) {
  .hub-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
/* Телефон: одна колонка. */
@media (max-width: 680px) {
  .hub-grid { grid-template-columns: minmax(0, 1fr); }
}
/* Растягивание по высоте: карточки в ряду одинаковые (grid stretch —
   поведение по умолчанию, но задано явно, чтобы flex-содержимое ниже
   умело прижать кнопки к низу). */
.hub-grid > .hub-card { align-self: stretch; }

.hub-card {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
  padding: 18px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel);
}
/* Карточка канала, недоступного в наборе направления: приглушена, но
   читаема — это объявление, а не ошибка. */
.hub-card-off { opacity: .75; }

.hub-head {
  display: flex;
  align-items: center;
  /* Перенос вместо обрезки: если название канала и бейдж не помещаются
     в одну строку, бейдж уезжает на свою строку ЦЕЛИКОМ, а не
     вылезает за правый край карточки (дефект скриншота 11.11). */
  flex-wrap: wrap;
  gap: 8px 12px;
  min-width: 0;
}
/* Каналы используют один фиолетовый цвет продукта; Telegram выделен синим.
   22px глиф в 44px квадрате — оптический вес наравне с заголовком. */
.hub-ico {
  display: grid;
  place-items: center;
  flex: 0 0 auto;
  width: 44px;
  height: 44px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--accent-soft);
  color: var(--accent);
  font-size: 22px;
}
.hub-ico.c-tg { background: var(--info-soft); color: var(--info); }
.hub-title {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin: 0;
  min-width: 0;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: -.01em;
}
/* Название канала в шапке: flex-дитя обязано иметь min-width:0, иначе
   длинное слово не даёт шапке сжаться и выдавливает бейдж за край. */
.hub-head h2 {
  flex: 1 1 auto;
  min-width: 0;
  margin: 0;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: -.01em;
  overflow-wrap: anywhere;
}
/* Бейдж статуса в шапке карточки: тот же .badge, но всегда справа от
   названия (margin-left:auto) и с точкой-индикатором внутри.
   flex-shrink:0 — бейдж не сжимается: подпись целиком. Перенос
   (.hub-head flex-wrap) даёт ему отдельную строку, если места нет. */
.hub-head .badge {
  flex: 0 0 auto;
  margin-left: auto;
  gap: 6px;
}
.hub-dot {
  display: inline-block;
  flex: 0 0 auto;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: currentColor;
}
/* «Не подключён» — НЕЙТРАЛЬНЫЙ серый, а не тревожно-жёлтый: отсутствие
   подключения это не сбой, а просто пустой канал. */
.badge-idle {
  background: var(--chip);
  color: var(--muted);
}

/* Мини-статистика: ключевые числа крупно с подписями под ними —
   прежняя плоская строка «25 аккаунт(ов) · 25 активных · 145 в сутки»
   не читалась. */
.hub-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 22px;
}
.hub-stat { min-width: 0; }
.hub-stat b {
  display: block;
  font-size: 26px;
  font-weight: 700;
  line-height: 1.05;
  letter-spacing: -.03em;
  color: var(--text);
}
.hub-stat span {
  display: block;
  margin-top: 3px;
  color: var(--muted);
  font-size: 12.5px;
  font-weight: 500;
}

/* Описание — мелким и приглушённо, максимум две строки: длинные
   подписи каналов не должны раздувать высоту карточки. */
.hub-desc {
  margin: 0;
  color: var(--muted);
  font-size: 13px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.hub-note {
  margin: 0;
  color: var(--muted);
  font-size: 12px;
  line-height: 1.5;
}

/* Нижняя строка — кнопки у правого края; margin-top:auto прижимает её к
   низу карточки, поэтому в ряду кнопки стоят на одной линии.
   Слово владельца 11.11 (скриншот): «Пул» и «Добавить» были разной
   ширины и вразнобой. Одинаковая высота (общая база .btn уже даёт
   min-height:var(--tap)), зазор 8px и прижатие вправо — одна строка
   действий, а не две разные кнопки. */
.hub-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
  justify-content: flex-end;
  gap: 8px;
  margin-top: auto;
}
.hub-actions .btn { min-height: var(--tap); }

@media (max-width: 560px) {
  /* Телефон (390px): кнопки в полную ширину, ни одна не сжата.
     Сетка карточек здесь уже одна колонка — правило для неё задано
     выше, при @media 680px, и не дублируется. */
  .hub-actions { justify-content: stretch; }
  .hub-actions .btn { flex: 1 1 0; }
}

/* ====================== 5. ПРИКЛАДНЫЕ БЛОКИ ============================= */

.kanban {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(268px, 1fr));
  gap: 12px;
}
.kanban-column {
  min-width: 0;
  padding: 13px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel2);
}
.kanban-column h2 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 2px;
  font-size: 14px;
}
.kanban-column > .muted { font-size: 12px; }

/* Разделы CRM (crm_ai_final_fixes.py) — сворачиваемые <details>/<summary>,
   появились позже последнего прохода по адаптиву и не имели собственных
   стилей: <summary> не наследует .kanban-column h2, поэтому статус-точка,
   подпись и счётчик рисовались браузером как попало, без раскладки и без
   курсора-указателя на кликабельном элементе. */
.kanban-column > summary {
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 44px;
  margin-bottom: 2px;
  padding: 4px 2px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  list-style: none;
  -webkit-tap-highlight-color: transparent;
}
.kanban-column > summary::-webkit-details-marker { display: none; }
.kanban-column > summary::marker { content: ""; }
.kanban-column > summary:focus-visible {
  outline: 2px solid var(--accent);
  outline-offset: 2px;
  border-radius: 6px;
}
.kanban-column .col-hint { margin: 2px 0 8px; }
.crm-section-body { min-height: 24px; }
.crm-pager {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}
.lead-card {
  padding: 13px;
  margin-top: 10px;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: var(--panel);
  transition: border-color var(--transition), transform var(--transition);
}
.lead-card:hover { border-color: var(--line-strong); transform: translateY(-1px); }
.lead-card b { font-size: 14px; }
.lead-card p { margin: 4px 0; font-size: 13px; }
.lead-card .lead-birthday-meta { color: var(--muted); font-size: 12px; }
.lead-card form { display: flex; gap: 8px; margin-top: 10px; }
.lead-card form select { margin: 0; }
.lead-card form button { flex: 0 0 auto; }
.lead-card a.muted { display: inline-block; margin-top: 8px; font-size: 12.5px; }

.chart-card, .chart-container { min-width: 0; }
.chart-row { display: flex; gap: 8px; align-items: stretch; }
.chart-y-axis {
  position: relative;
  flex: none;
  width: 34px;
  height: 250px;
  margin: 10px 0;
}
.chart-y-axis span {
  position: absolute;
  right: 4px;
  transform: translateY(-50%);
  font-size: 10px;
  color: var(--muted);
  text-align: right;
  white-space: nowrap;
}
.svg-chart { flex: 1; min-width: 0; height: 250px; padding: 10px 0; }
.svg-chart svg { width: 100%; height: 100%; overflow: visible; }
.gridline { stroke: var(--line); stroke-width: .6; stroke-dasharray: 3 5; fill: none; }
.line {
  fill: none;
  stroke-width: 2.2;
  vector-effect: non-scaling-stroke;
  stroke-linecap: round;
  stroke-linejoin: round;
}
.lead-line { stroke: var(--accent); }
.sent-line { stroke: var(--info); }
.recv-line { stroke: var(--warning); }
.chart-legend {
  display: flex; flex-wrap: wrap; gap: 12px;
  color: var(--muted); font-size: 12px;
}
.chart-legend span { display: inline-flex; align-items: center; gap: 6px; }
.chart-legend span::before {
  content: ""; width: 8px; height: 8px;
  border-radius: 50%; background: var(--muted);
}
.chart-legend .lead-dot::before { background: var(--accent); }
.chart-legend .sent-dot::before { background: var(--info); }
.chart-legend .recv-dot::before { background: var(--warning); }
.chart-legend .pending-dot::before { background: var(--success); }
.chart-labels {
  display: grid;
  grid-template-columns: repeat(14, minmax(0, 1fr));
  gap: 2px;
  color: var(--muted);
  font-size: 10px;
  text-align: center;
}

.stage-chart { display: grid; gap: 13px; padding-top: 4px; }
.stage-row {
  display: grid;
  grid-template-columns: minmax(88px, .9fr) minmax(88px, 2fr) minmax(56px, auto);
  gap: 10px;
  align-items: center;
}
.stage-row span { color: var(--muted); font-size: 12.5px; }
/* Задача J (03.11, скрин владельца): значение ряда — строка («в пакете»,
   «—», «7,0 ₽»), а третья колонка была 36px под чистые числа — текст
   переносился столбиком ПО БУКВАМ. Колонка теперь auto (min 56px), а
   b — nowrap: короткая метка НЕ рвётся никогда; если место кончится,
   grid сожмёт дорожку бара (2fr), не текст. Мутация «вернуть 36px»
   красится пином ширины. */
.stage-row b { text-align: right; font-size: 13px; white-space: nowrap; }
.stage-track {
  height: 9px;
  border-radius: var(--radius-pill);
  background: var(--input);
  overflow: hidden;
}
.stage-track i { display: block; height: 100%; border-radius: inherit; background: var(--accent); }

.state-restricted td { background: rgba(251, 191, 36, .09); }
.state-frozen td     { background: rgba(249, 115, 22, .10); }
.state-blocked td,
.state-banned td     { background: rgba(248, 113, 113, .11); }

.user-avatar {
  width: 38px; height: 38px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
}

.account-cell { display: flex; align-items: center; gap: 10px; }
.account-avatar {
  width: 34px; height: 34px;
  border-radius: 50%;
  object-fit: cover;
  flex: none;
  display: block;
}
.account-avatar-fallback {
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--input);
  color: var(--muted);
  font-weight: 600;
  font-size: 13px;
}
/* Telegram Premium — золотое кольцо вокруг аватарки, как в самом Telegram,
   вместо неприметной текстовой пометки (см. /accounts). */
.account-avatar-premium {
  outline: 2px solid #f5b400;
  outline-offset: 2px;
}
.premium-star { font-size: 12px; }
/* Premium-отметка аккаунта — маска .ic-star внутри .premium-star (11.11:
   эмодзи ⭐ заменена иконкой). Цвет золотой сохраняем — это смысл знака. */
.premium-star { color: #f5b301; }
.premium-star .ic { width: .95em; height: .95em; vertical-align: -.1em; }
/* Реально забаненный/заблокированный аккаунт (см. /accounts и
   app.services.account_watchdog) — красное кольцо приоритетнее золотого
   Premium-кольца выше, если вдруг совпали оба. */
.account-avatar-banned {
  outline: 2px solid var(--danger);
  outline-offset: 2px;
}
/* Спам-блок/ограничение (временное, не полный бан) — оранжевое кольцо,
   чтобы визуально не путать с реальным банном (красное кольцо выше). См.
   /accounts и app.services.account_watchdog: 'restricted'/'frozen' —
   мягкий статус, 'blocked'/'banned' — необратимый. */
.account-avatar-restricted {
  outline: 2px solid #f59e0b;
  outline-offset: 2px;
}
/* --- Таблица аккаунтов (/accounts): компактные действия ------------------
   11.11 (слово владельца, второй скриншот): справа висел СТОЛБИК из четырёх
   крупных кнопок («Прогрев», «Отключить от рассылки», «Прокси», «Удалить
   безвозвратно») — он распирал строку по высоте, и таблица читалась как
   список. Что изменено:
     • действия в ОДНУ строку, компактные (.acct-act), во всю ширину не
       растягиваются;
     • «Удалить безвозвратно» (необратимое) убрано в меню «⋯» и краснеет
       только при открытии;
     • аватар 38px, приглушённая подпись, тонкие разделители строк.
   Разметку строки собирает /accounts в app/main.py. */
.acct-table td { padding: 10px 12px; vertical-align: middle; }
.acct-table { width: 100%; table-layout: fixed; }
.acct-table th, .acct-table td { overflow-wrap: anywhere; }
.acct-table th:first-child, .acct-table td:first-child { width: 3%; }
.acct-table th:nth-child(2) { width: 21%; }
.acct-table th:nth-child(3) { width: 29%; }
.acct-table th:nth-child(4) { width: 10%; }
.acct-table th:nth-child(5) { width: 14%; }
.acct-table th:nth-child(6) { width: 19%; }
.acct-table th:last-child { width: 4%; }
.acct-table tbody tr { border-bottom: 1px solid var(--line); }
.acct-table tbody tr:last-child { border-bottom: 0; }
.acct-table .account-cell { gap: 12px; }
/* Аватар: аккуратный круг 36-40px, по центру строки (было 34px). */
.acct-table .account-avatar { width: 38px; height: 38px; font-size: 14px; }
/* Имя/телефон — основная строка, остальное приглушено и мельче. */
.acct-table .account-cell b { font-size: 13.5px; }
.acct-table .account-cell .muted { font-size: 11.5px; line-height: 1.3; }

/* Общий счёт компании виден рядом с пулом выбранного направления: список
   аккаунтов остаётся изолированным, а число не выглядит общим для компании. */
.account-company-summary {
  display: flex;
  align-items: center;
  gap: 22px;
  margin: 14px 0;
  padding: 14px 18px;
}
.account-company-summary > div:first-child { flex: 1 1 auto; min-width: 180px; }
.account-company-summary > div:first-child > b { font-size: 14px; }
.account-company-summary p { margin: 4px 0 0; font-size: 12px; }
.account-company-summary-count {
  display: grid;
  justify-items: end;
  gap: 2px;
  min-width: 68px;
}
.account-company-summary-count strong { font-size: 20px; line-height: 1.1; }
.account-company-summary-count span { color: var(--muted); font-size: 11px; }
@media (max-width: 560px) {
  .account-company-summary { gap: 14px; padding: 12px; }
  .account-company-summary > div:first-child { flex-basis: 100%; }
  .account-company-summary-count { justify-items: start; }
}
/* Селекты типа и направления: узкие, чтобы не распирали строку. */
.acct-select {
  min-height: 32px;
  max-width: 150px;
  padding: 5px 8px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--input);
  color: var(--text);
  font-size: 12.5px;
}
.acct-select:focus {
  outline: none;
  border-color: var(--accent);
  box-shadow: var(--focus-ring);
}
/* «Сегодня / состояние»: счётчик крупнее, служебная строка — мельче и
   приглушённо, в одну строку (просьба владельца). */
.acct-stat { min-width: 0; white-space: normal; }
.acct-stat-main {
  display: block;
  color: var(--text);
  font-size: 14px;
  font-weight: 700;
  font-variant-numeric: tabular-nums;
}
.acct-stat-sub {
  display: block;
  min-width: 0;
  margin-top: 2px;
  color: var(--muted);
  font-size: 11.5px;
  font-variant-numeric: tabular-nums;
  overflow-wrap: anywhere;
}
/* Ряд действий: одна линия, малый зазор, без растягивания на всю ячейку.
   Раньше это был .actions — он тянется и переносит детей, отсюда столбик. */
.acct-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  justify-content: flex-start;
}
.acct-act {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  min-height: 32px;
  padding: 5px 9px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: transparent;
  color: var(--text-2);
  font-size: 12px;
  font-weight: 600;
  line-height: 1.15;
  text-decoration: none;
  white-space: nowrap;
  cursor: pointer;
  transition: background var(--transition), border-color var(--transition),
              color var(--transition);
}
.acct-act:hover {
  background: var(--panel2);
  border-color: var(--line-strong);
  color: var(--text);
}
.acct-act .ic { font-size: 13px; opacity: .85; }
/* Состояние переключателя: «в рассылке» — акцентом, «отключён» — тихо. */
.acct-act.is-on { border-color: var(--accent); color: var(--accent); }
.acct-act.is-on .ic { opacity: 1; }
.acct-act.is-warn { color: var(--muted); }
.acct-act.is-warn:hover { border-color: var(--warning); color: var(--warning); }
/* «⋯» — редкие и опасные действия. details/summary: работает без JS,
   закрывается кликом по самой кнопке; меню всплывает над строкой. */
.acct-more { position: relative; display: inline-flex; }
.acct-more-mobile-item { display: none; }
.acct-more > summary {
  list-style: none;
  width: 32px;
  height: 32px;
  min-height: 32px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  cursor: pointer;
}
.acct-more > summary::-webkit-details-marker { display: none; }
.acct-more > summary::marker { content: ''; }
.acct-more > summary:hover { background: var(--panel2); border-color: var(--line-strong); }
.acct-more[open] > summary { background: var(--panel2); border-color: var(--line-strong); color: var(--text); }
.acct-more-menu {
  position: absolute;
  top: calc(100% + 6px);
  right: 0;
  z-index: 20;
  min-width: 210px;
  padding: 6px;
  border: 1px solid var(--line-strong);
  border-radius: var(--radius-sm);
  background: var(--panel);
  box-shadow: var(--shadow);
}
.acct-more-menu .acct-more-mobile-item {
  display: flex;
  width: 100%;
  justify-content: flex-start;
  border-color: transparent;
  padding: 8px 10px;
}
.account-header-actions { align-items: center; flex-wrap: wrap; gap: 8px; }
.account-header-more { flex: 0 0 auto; }
.account-header-more > summary { display: grid; place-items: center; font-size: 22px; }
.account-header-more .acct-more-menu { min-width: 240px; max-width: calc(100vw - 32px); }
/* Menus must not be clipped by decorative heroes or scroll wrappers. */
.hero:has(.account-header-more[open]) { overflow: visible; z-index: 30; }
.hero:has(.account-header-more[open])::before,
.hero:has(.account-header-more[open])::after { display: none; }
.table-wrap:has(.acct-more[open]),
.table-container:has(.pool-row-more[open]),
.card:has(.acct-more[open]),
.card:has(.pool-row-more[open]) { overflow: visible; }
.acct-more[open], .pool-row-more[open] { z-index: 35; }
.acct-more-menu, .pool-row-more-menu { overflow-wrap: anywhere; }
.acct-table .acct-actions { justify-content: flex-end; min-width: 52px; }
.acct-table .acct-more-menu .acct-act { min-height: 38px; white-space: normal; }
.acct-state-note {
  display: block;
  max-width: 24rem;
  margin-top: 7px;
  color: var(--muted);
  line-height: 1.45;
  white-space: normal;
  font-size: 12px;
  overflow-wrap: anywhere;
}
.acct-error-details { margin-top: 5px; color: var(--muted); }
.acct-error-details summary { width: fit-content; cursor: pointer; font-size: 12px; }
.acct-error-details small { display: block; max-width: min(36rem, 100%); margin-top: 5px; overflow-wrap: anywhere; word-break: break-word; }
/* Dense account registries become product cards before the table runs out
   of horizontal room. This keeps the same controls and data while making
   tablet and narrow desktop layouts readable without sideways scrolling. */
@media (max-width: 1600px) {
  .acct-table thead { display: none; }
  .acct-table, .acct-table tbody, .acct-table tr, .acct-table td {
    display: block; width: 100%; white-space: normal;
  }
  .acct-table { table-layout: auto; }
  .acct-table tbody tr {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    grid-template-areas:
      "account account"
      "status status"
      "type workspace"
      "activity activity"
      "actions actions";
    align-items: start;
    gap: 10px 14px;
    position: relative;
    margin: 0 0 12px;
    padding: 14px;
    border: 1px solid var(--line);
    border-radius: 16px;
    background: var(--panel);
    box-shadow: 0 5px 18px rgba(0,0,0,.08);
  }
  .acct-table tbody tr:hover { background: var(--panel); }
  /* Ячейка — элемент grid, поэтому оставляем ширину трека. Наследованные
     width:100% из общего правила таблиц распирали карточку и накладывали
     подписи/значения на соседние столбцы. */
  .acct-table td { min-width: 0; width: auto; padding: 7px 0; border: 0; }
  .acct-table td::before {
    content: attr(data-label);
    display: block;
    margin-bottom: 4px;
    color: var(--muted);
    font-size: 10px;
    font-weight: 700;
    letter-spacing: .07em;
    text-transform: uppercase;
  }
  .acct-table td[data-label='Аккаунт'] {
    grid-area: account;
    display: flex;
    align-items: center;
    min-height: 48px;
    padding: 0 46px 0 0;
  }
  .acct-table td[data-label='Аккаунт']::before { display: none; }
  .acct-table td[data-label='Статус'] {
    grid-area: status;
    padding: 10px 0;
    border-top: 1px solid var(--line);
    border-bottom: 1px solid var(--line);
  }
  .acct-table td[data-label='Тип'] { grid-area: type; }
  .acct-table td[data-label='Направление'] { grid-area: workspace; }
  .acct-table td[data-label='Выбор'] {
    position: absolute;
    top: 14px;
    left: 14px;
    width: auto;
    padding: 0;
    z-index: 1;
  }
  .acct-table td[data-label='Выбор']::before { display: none; }
  .acct-table td[data-label='Аккаунт'] { padding-left: 42px; }
  .acct-table td[data-label='Активность'] { grid-area: activity; align-self: center; }
  .acct-table td[data-label='Действия'] {
    grid-area: actions;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    align-self: end;
  }
  .acct-table .acct-stat-main { font-size: 15px; }
  .acct-table .acct-stat-sub { font-size: 11px; line-height: 1.35; }
  .acct-table td[data-label='Тип'] .acct-select,
  .acct-table td[data-label='Направление'] .acct-select { min-height: 40px; }
  .acct-table .acct-more > summary {
    width: auto;
    min-width: 42px;
    height: 40px;
    padding: 0 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 14px;
  }
  .acct-table .acct-more > summary::after {
    content: 'Действия';
    font-size: 12px;
    font-weight: 650;
    line-height: 1;
  }
  .acct-table .acct-more[open] .acct-more-menu { grid-column: 1 / -1; }
  .acct-table .acct-state-note { max-width: 100%; }
  .acct-table-wrap { overflow: visible; border: 0; }
}
.state-restricted td, .state-frozen td, .state-blocked td, .state-banned td {
  background: transparent;
}
.state-restricted, .state-frozen, .state-blocked, .state-banned {
  box-shadow: inset 3px 0 0 var(--warning);
}
.state-blocked, .state-banned { box-shadow: inset 3px 0 0 var(--danger); }
/* Опасное действие: красным ТОЛЬКО при открытии меню (требование
   владельца) — в закрытом виде его вообще не видно. */
.acct-more-danger {
  display: flex;
  align-items: center;
  gap: 7px;
  width: 100%;
  min-height: 34px;
  padding: 7px 10px;
  border: 1px solid transparent;
  border-radius: var(--radius-sm);
  background: transparent;
  color: var(--danger);
  font-size: 12.5px;
  font-weight: 600;
  text-align: left;
  cursor: pointer;
}
.acct-more-danger:hover { background: var(--danger-soft); border-color: var(--danger); }
.pool-row-more { position: relative; display: inline-block; }
.pool-row-more > summary {
  display: grid;
  place-items: center;
  width: 38px;
  height: 38px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: 22px;
  line-height: 1;
}
.pool-row-more > summary:hover,
.pool-row-more[open] > summary { background: var(--panel2); border-color: var(--line-strong); }
.pool-row-more > summary::-webkit-details-marker { display: none; }
.pool-row-more > summary::marker { content: ''; }
.pool-row-more-menu {
  display: none;
  position: absolute;
  top: calc(100% + 6px);
  right: 0;
  z-index: 25;
  flex-direction: column;
  align-items: stretch;
  gap: 8px;
  width: min(370px, calc(100vw - 32px));
  padding: 10px;
  border: 1px solid var(--line-strong);
  border-radius: var(--radius-md);
  background: var(--panel);
  box-shadow: var(--shadow);
}
.pool-row-more[open] > .pool-row-more-menu { display: flex; }
.pool-row-more-menu form { display: flex !important; flex-direction: column; gap: 8px !important; margin: 0 !important; }
.pool-row-more-menu .pool-secret-field {
  display: grid;
  gap: 4px;
  width: 100%;
  margin: 0;
  color: var(--text-2);
  font-size: 12px;
  font-weight: 600;
}
.pool-row-more-menu .pool-secret-field input { font-weight: 400; }
.pool-row-more-menu .pool-secret-hint { margin: 0; line-height: 1.4; }
.pool-row-more-menu input { width: 100%; min-width: 0 !important; }
.pool-row-more-menu button { width: 100%; min-height: 40px; white-space: normal; }
.credential-chip { display: inline-flex; align-items: center; gap: 5px; margin: 2px 4px 2px 0; }
.credential-chip > span { color: var(--muted); font-size: 11px; }
.credential-chip code { overflow-wrap: anywhere; }
.channel-health-summary { white-space: normal; }
.channel-health-details { margin-top: 5px; }
.channel-health-details summary { width: fit-content; cursor: pointer; color: var(--muted); font-size: 12px; }
.channel-health-details small { display: block; max-width: 28rem; margin-top: 5px; overflow-wrap: anywhere; }
.user-avatar.fallback, .fallback {
  display: grid;
  place-items: center;
  background: var(--accent-soft);
  color: var(--accent);
  font-weight: 700;
}

/* ============ 6. СОВМЕСТИМОСТЬ СО СТАРОЙ РАЗМЕТКОЙ ====================== */

.navbar {
  position: sticky; top: 0; z-index: 30;
  background: var(--top);
  border-bottom: 1px solid var(--line);
  backdrop-filter: blur(16px);
}
.navbar-content {
  display: flex; align-items: center; gap: 12px;
  max-width: 1420px; margin: 0 auto; padding: 0 20px;
  min-height: var(--top-h);
}
.navbar-brand { display: flex; align-items: center; gap: 9px; font-weight: 700; }
.logo-icon { font-size: 19px; }
.nav-links { display: flex; align-items: center; gap: 4px; }
.nav-links a {
  display: inline-flex; align-items: center; gap: 7px;
  min-height: 38px; padding: 8px 12px;
  border-radius: var(--radius-sm);
  color: var(--text-2); font-size: 14px;
}
.nav-links a:hover { background: var(--panel2); color: var(--text); }
.nav-links a.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.nav-right { display: flex; align-items: center; gap: 8px; margin-left: auto; }

.footer {
  padding: 26px 20px calc(26px + env(safe-area-inset-bottom));
  border-top: 1px solid var(--line);
  color: var(--muted);
  font-size: 12.5px;
  text-align: center;
}
.footer p { margin: 0; }

.title { font-size: 17px; font-weight: 700; }
.number { font-weight: 700; }
.row { display: flex; flex-wrap: wrap; gap: 12px; }
.item { min-width: 0; }
.icon { display: inline-grid; place-items: center; }
.arrow { color: var(--muted); }
.account-list { display: grid; gap: 10px; }
.account-name { font-weight: 600; }
.info-list { margin: 12px 0 20px; padding-left: 20px; color: var(--muted); line-height: 1.8; }
.info-note { padding: 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel2); line-height: 1.6; }
.distribution-example, .example-block { background: var(--panel2); }
.stats-today .number { color: var(--accent); }
.stats-total .number { color: var(--info); }
.import-result { min-height: 22px; margin: 0 0 10px; }
.faq-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 18px; }
.delete-faq { color: var(--text); }

.green, .primary  { color: var(--accent); }
.indigo, .purple, .pink { color: var(--violet); }
.teal             { color: var(--info); }
.orange           { color: var(--warning); }
.red              { color: var(--danger); }
.secondary        { color: var(--text-2); }
.bg-success-light { background: var(--accent-soft); }
.bg-info-light    { background: var(--info-soft); }
.bg-warning-light { background: var(--warning-soft); }
.bg-danger-light  { background: var(--danger-soft); }

/* Ссылка внизу сайдбара */
.side-foot {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: var(--tap);
  padding: 10px 12px;
  border-radius: var(--radius-sm);
  font-size: 13.5px;
}
.side-foot:hover { background: var(--panel2); color: var(--text); }

/* Страховка от горизонтального скролла: длинные ссылки и токены
   в карточках раньше растягивали страницу на телефоне. */
body { overflow-x: hidden; }
.card, .lead-card, .info-note, .hero { min-width: 0; }
img, svg, video, canvas { max-width: 100%; height: auto; }

/* ============================ 7. АДАПТИВ ================================ */

@media (max-width: 1240px) {
  :root { --side-w: 236px; }
  .grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  .analytics-grid, .grid2 { grid-template-columns: minmax(0, 1fr); }
  main, .container { padding: 16px 18px 36px; }
}

/* Планшет и телефон: сайдбар превращается в выезжающую панель */
@media (max-width: 900px) {
  .app { grid-template-columns: minmax(0, 1fr); }

  .side {
    position: fixed;
    top: 0; left: 0; bottom: 0;
    z-index: 70;
    width: min(84vw, 310px);
    height: 100dvh;
    padding-top: calc(16px + env(safe-area-inset-top));
    padding-bottom: calc(16px + env(safe-area-inset-bottom));
    box-shadow: var(--shadow-hover);
    transform: translateX(-102%);
    transition: transform var(--transition);
    will-change: transform;
  }
  .side.open { transform: translateX(0); }

  .burger-btn { display: inline-flex; }

  .top {
    padding: 0 14px;
    padding-top: env(safe-area-inset-top);
    height: calc(var(--top-h) + env(safe-area-inset-top));
  }
  .top .crumbs { display: none; }

  main, .container { padding: 18px 14px calc(34px + env(safe-area-inset-bottom)); }

  .navbar-content { flex-wrap: wrap; padding: 0 14px; }
  .nav-links {
    order: 5;
    width: 100%;
    overflow-x: auto;
    padding-bottom: 8px;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }
  .nav-links::-webkit-scrollbar { display: none; }
  .nav-links a { flex: 0 0 auto; white-space: nowrap; }
}

/* Телефон */
@media (max-width: 700px) {
  body { font-size: 16px; }

  /* На iOS поле со шрифтом меньше 16px заставляет Safari зумить страницу. */
  input, textarea, select, .form-control { font-size: 16px; min-height: 50px; }
  textarea { min-height: 132px; }
  .btn, button { min-height: 50px; font-size: 15.5px; }
  /* Кнопка «назад к списку» треда /replies — компактный чип: 50px в полосе
     561-700px избыточны и не совпадают с шапкой ≤560px, где она уже
     зафиксирована на 44px — унифицируем тап-цель на всех мобильных. Класс
     (0,1,0) специфичнее button (0,0,1) и перебивает глобальное правило в
     этой полосе; блок ≤560px сохраняет собственное правило 44px с
     паддингом. */
  .thread-back-btn { min-height: 44px; }
  /* Keep every mobile button at the same minimum touch size. Compact visual
     styling stays compact through padding and type size, not a smaller target. */
  .btn-sm { min-height: 44px; font-size: 13px; }
  .icon-btn, .theme-toggle {
    min-height: 44px;
    min-width: 44px;
    width: 44px;
    height: 44px;
  }

  h1 { font-size: clamp(25px, 7vw, 32px); }
  h2 { font-size: 18px; }

  .hero, .hero-card { padding: 20px 17px; border-radius: 16px; }
  .card, .info-card, .action-card, .stat-card { padding: 17px 15px; border-radius: 15px; }

  .grid, .grid2, .grid3, .stats-grid, .metrics-grid,
  .actions-grid, .security-grid, .analytics-grid, .kanban {
    grid-template-columns: minmax(0, 1fr);
  }
  /* Компактные числа остаются парой, чтобы на телефоне не приходилось
     прокручивать четыре одинаково короткие метрики по одной за раз. */
  .grid:has(> .metric) { grid-template-columns: repeat(2, minmax(0, 1fr)); }

  /* Каждое действие на всю ширину: попасть пальцем в узкую кнопку тяжело. */
  .actions > *, .btn-group > *, .form-actions > * { flex: 1 1 100%; }
  .actions form, .btn-group form { width: 100%; }
  .actions form button { width: 100%; }
  /* Верхние быстрые действия на страницах не занимают полэкрана колонкой:
     две крупные кнопки в строке, одиночный хвост — во всю ширину. */
  .hero > .actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
  .hero > .actions > * { width: 100%; min-width: 0; min-height: 44px; }
  .hero > .actions > :last-child:nth-child(odd) { grid-column: 1 / -1; }

  .section-head, .faq-head { flex-direction: column; gap: 10px; }

  .current-admin { max-width: 172px; padding: 4px 7px; }
  .current-admin-meta span { display: none; }
  .nav-time { display: none; }

  /* 11.11 (аудит вёрстки, замер 390/360/320): в шапку телефона не влезают
     сразу пять элементов — «бургер», баланс, колокольчик, тема и карточка
     пользователя. До этой правки ряд ПЕРЕПОЛНЯЛСЯ: страница получала
     горизонтальный скролл (замер на 390: документ 409px при экране 390,
     лишние 19px — иконка «выход», вылезшая за край), а имя пользователя
     сжималось до 25px — одна буква вместо имени.
     Теперь шапка на телефоне ПЕРЕНОСИТСЯ на вторую строку вместо того,
     чтобы выпихивать содержимое за экран. Ничего не скрыто: все пять
     элементов остаются на месте и работают, меняется только раскладка. */
  .top { flex-wrap: wrap; height: auto; row-gap: 6px;
         min-height: calc(var(--top-h) + env(safe-area-inset-top));
         padding-bottom: calc(6px + env(safe-area-inset-bottom)); }
  /* Действия больше не «всё или ничего»: они занимают остаток строки после
     «бургера» и переносят ВНУТРИ себя только то, что действительно не
     влезло (карточку пользователя). Без этого весь блок уезжал на вторую
     строку целиком и шапка занимала три ряда вместо двух. */
  .top-actions { flex: 1 1 0; min-width: 0; flex-wrap: wrap;
                 justify-content: flex-end; row-gap: 6px; }
  /* Карточка пользователя на телефоне — СВОЕЙ строкой на всю ширину.
     Причина та же, что выше: в один ряд с балансом ей остаётся 140px, а
     нужно ~215 (аватар + имя + «настройки» + «выход»). Ужималось имя —
     до одной буквы. Отдельная строка отдаёт ей всю ширину: имя читается,
     обе ссылки («настройки аккаунта» и «выйти») остаются на месте и
     полноразмерны — ни одна функция не спрятана. */
  .current-admin { flex: 1 1 100%; max-width: none; justify-content: flex-start; }
  .current-admin-meta { flex: 1 1 auto; }
  .current-admin-meta strong { max-width: none; }
  .admin-logout { flex: 0 0 auto; }
  /* Плашка баланса на телефоне — только сумма: подпись «≈ N отв.» уходила
     на вторую строку внутри самой плашки и рвала её. Число ответов живёт
     в подсказке (title) и на /billing, куда плашка ведёт. */
  .balance-chip .balance-chip-sub { display: none; }

  .stage-row { grid-template-columns: minmax(74px, 1fr) minmax(60px, 1.6fr) minmax(48px, auto); }
  .svg-chart { height: 210px; }
  .chart-y-axis { height: 210px; width: 26px; }
  .chart-y-axis span { font-size: 9px; right: 2px; }
  .chart-labels { grid-template-columns: repeat(7, minmax(0, 1fr)); font-size: 9.5px; }

  .modal-content { max-height: 92dvh; border-radius: 16px; }
  .lead-card form { flex-direction: column; }
  .lead-card form button { width: 100%; }

  /* Разделы CRM на телефоне: крупнее заголовок-переключатель, счётчик
     не должен уезжать за край экрана, пагинация — на всю ширину, чтобы
     не промахнуться пальцем мимо «Ещё 10 →». */
  .kanban-column > summary { min-height: 48px; font-size: 15px; }
  .kanban-column .nav-count { flex-shrink: 0; }
  .crm-pager { flex-direction: column; align-items: stretch; }
  .crm-pager > a, .crm-pager > button { width: 100%; text-align: center; }

  /* Таблицы превращаются в карточки: горизонтальный скролл на телефоне
     неудобен, а данные всё равно читаются построчно. Ячейкам нужен
     атрибут data-label — его проставляет /static/js/main.js. */
  .mobile-cards thead { display: none; }
  .mobile-cards table,
  .mobile-cards tbody,
  .mobile-cards tr,
  .mobile-cards td { display: block; width: 100%; white-space: normal; }
  .mobile-cards .table-container,
  .mobile-cards .table-wrap,
  .mobile-cards .table-responsive { border: 0; overflow: visible; }
  .mobile-cards tr {
    margin: 0 0 10px;
    padding: 13px;
    border: 1px solid var(--line);
    border-radius: 13px;
    background: var(--panel);
  }
  .mobile-cards tr:hover { background: var(--panel); }
  .mobile-cards td { padding: 6px 0; border: 0; }
  .mobile-cards td::before {
    content: attr(data-label);
    display: block;
    margin-bottom: 2px;
    color: var(--muted);
    font-size: 11.5px;
    font-weight: 600;
  }
  /* Табличные действия внутри мобильных карточек остаются компактной
     строкой. Общий `.mobile-cards td { display:block }` раньше перебивал
     flex у `.row-actions`, и кнопки перемещения этапа вставали столбиком. */
  .mobile-cards td.row-actions { display: block; }
  .mobile-cards td.row-actions form {
    display: inline-flex;
    vertical-align: middle;
    margin: 0 6px 0 0;
  }
  .mobile-cards td.row-actions button {
    width: auto;
    min-height: 42px;
    flex: 0 0 auto;
  }
  .mobile-cards td:empty { display: none; }
  /* Таблица аккаунтов на телефоне становится карточками. Рабочие действия
     доступны в раскрывающемся меню ⋮, чтобы длинная строка кнопок не
     распирала карточку; удаление остаётся там же с отдельным опасным стилем. */
  /* Общий адаптер таблиц задаёт td width:100%. У .acct-table сетка в две
     колонки, поэтому сбрасываем эту ширину более специфичным селектором:
     иначе каждая ячейка растягивалась на всю карточку и визуально становилась
     длинным вертикальным списком с пустой правой половиной. */
  .mobile-cards .acct-table td { min-width: 0; width: auto; }
  .acct-table .acct-actions { justify-content: flex-start; }
  .acct-table .acct-actions > .acct-more { display: block; }
  .acct-table .acct-more > summary { display: grid; place-items: center; font-size: 24px; line-height: 1; }
  .account-header-more > summary { width: 44px; height: 44px; min-height: 44px; }
  .acct-table .acct-more-menu .acct-more-mobile-item { display: flex; }
  .acct-table .acct-select { max-width: 100%; width: 100%; }
  /* Меню в карточке раскрывается В ПОТОКЕ, а не всплывающим слоем:
     absolute-меню внутри карточки наезжало на следующую строку. */
  .acct-table .acct-more { position: static; }
  .acct-table .acct-more-menu {
    position: static;
    min-width: 0;
    margin-top: 6px;
    box-shadow: none;
  }
  .acct-table .acct-more-menu .acct-more-danger { justify-content: flex-start; }
  .pool-row-more > summary { display: grid; place-items: center; font-size: 24px; line-height: 1; }
  .pool-row-more {
    position: static;
    display: grid;
    width: 100%;
    min-width: 0;
  }
  .pool-row-more > summary { justify-self: end; }
  .pool-row-more-menu { display: none; }
  .pool-row-more[open] .pool-row-more-menu {
    display: flex;
    position: static;
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
    width: 100%;
    box-sizing: border-box;
    margin-top: 8px;
    padding: 10px;
    border: 1px solid var(--line);
    border-radius: var(--radius-sm);
    background: var(--panel2);
  }
  .pool-row-more-menu form { display: flex !important; flex-direction: column; gap: 8px !important; width: 100%; }
  .pool-row-more-menu input { width: 100%; min-width: 0 !important; }
  .pool-row-more-menu button { width: 100%; min-height: 40px; }
  .table-container.mobile-cards td code { overflow-wrap: anywhere; word-break: break-word; }
  /* Пулы WA/IG/MAX/VK на телефоне: вместо длинного вертикального списка
     полей — компактная карточка с ключом/состоянием сверху, короткими
     показателями в две колонки и меню действий внизу. Табличный desktop
     остаётся без изменений. */
  #pool-card .mobile-cards tbody tr {
    position: relative;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    align-items: start;
    gap: 4px 12px;
    padding: 12px 13px;
  }
  #pool-card .mobile-cards td {
    min-width: 0;
    margin: 0;
    overflow-wrap: anywhere;
  }
  #pool-card .mobile-cards td::before {
    margin-bottom: 3px;
    font-size: 10px;
    letter-spacing: .045em;
  }
  #pool-card .mobile-cards td:first-child {
    position: absolute;
    top: 10px;
    right: 10px;
    display: grid;
    place-items: center;
    width: 44px;
    height: 44px;
    padding: 0;
  }
  #pool-card .mobile-cards td:first-child::before,
  #pool-card .mobile-cards td:last-child::before { display: none; }
  #pool-card .mobile-cards td:nth-child(2),
  #pool-card .mobile-cards td:nth-child(3),
  #pool-card .mobile-cards td:nth-last-child(2),
  #pool-card .mobile-cards td:last-child { grid-column: 1 / -1; }
  #pool-card .mobile-cards td:nth-child(2) {
    min-height: 46px;
    padding-right: 46px;
    font-size: 15px;
    font-weight: 650;
  }
  #pool-card .mobile-cards td:last-child {
    display: block;
    padding-top: 3px;
  }
  /* Ячейка-галочка и «Действия» без подписи-заголовка читались бы как
     безымянные блоки; подписи из thead уже подставлены main.js. */
  .acct-table td { padding: 6px 0; }
}

/* Узкий телефон */
@media (max-width: 420px) {
  main, .container { padding: 15px 11px calc(30px + env(safe-area-inset-bottom)); }
  .hero, .hero-card { padding: 17px 14px; }
  .card { padding: 15px 13px; }
  .metric b, .stat-card .number { font-size: 27px; }
  .brand-tag { display: none; }
  /* 11.11 (аудит вёрстки): прежние 140px/84px обрезали имя пользователя до
     одной-двух букв, ради экономии 84px, которых всё равно не хватало —
     шапка всё равно переполнялась. На узком экране карточка пользователя
     идёт отдельной строкой на всю ширину (правило в блоке ≤700px выше),
     поэтому потолок здесь только мешает: снимаем. */
  .current-admin { max-width: none; }
  .current-admin-meta strong { max-width: none; }
  th, td { padding: 11px 10px; }
}

/* Учёт «чёлки» и жестовой панели */
@supports (padding: max(0px)) {
  .top {
    padding-left: max(14px, env(safe-area-inset-left));
    padding-right: max(14px, env(safe-area-inset-right));
  }
  main, .container {
    padding-left: max(14px, env(safe-area-inset-left));
    padding-right: max(14px, env(safe-area-inset-right));
  }
}

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: .01ms !important;
    animation-delay: 0ms !important;
    transition-duration: .01ms !important;
    scroll-behavior: auto !important;
  }
}

@media (prefers-contrast: more) {
  :root { --line: #3a445a; --muted: #9aa5b8; }
}

@media print {
  .side, .top, .navbar, .nav-overlay, .actions, .footer, .burger-btn { display: none !important; }
  .app { display: block; }
  body { background: #fff; color: #000; }
  .card, .hero { border: 1px solid #ccc; box-shadow: none; }
}

/* Значение выставляет инлайн-бутстрап в <head> до первой отрисовки —
   без него у пользователей светлой темы мигал тёмный фон. */
html[data-boot-theme="light"] { background: #f4f6fa; }
html[data-boot-theme="dark"]  { background: #0a0c10; }

/* V65 navigation separation and icon polish */
.side nav a { display:flex; align-items:center; gap:12px; }
.side nav a > i { width:20px; min-width:20px; text-align:center; font-size:16px; }
.side nav a > span { min-width:0; }
.side-foot { display:flex; align-items:center; gap:10px; }
.side-foot > i { width:18px; text-align:center; }
.theme-toggle i { pointer-events:none; }

/* V67: consistent icon system */
.btn i,.secondary i,button i,.hero h1>i,.hero h2>i,.card h2>i,.eyebrow i,.empty-state>i,.row-actions i{display:inline-flex;align-items:center;justify-content:center;width:1.15em;min-width:1.15em;margin-right:.38em;vertical-align:-.08em;}
.icon-btn i,.burger-btn i,.admin-logout i,.row-actions .icon-btn i{margin:0;width:1em;min-width:1em;}
.hero .btn,.actions .btn,.actions button{display:inline-flex;align-items:center;gap:.4rem;}
.nav-group:before{content:"";display:inline-block;width:6px;height:6px;border-radius:50%;background:currentColor;opacity:.55;margin-right:8px;vertical-align:middle;}

/* ==========================================================================
   V68 — дашборд из утверждённого макета: KPI со спарклайнами, превью
   канбана, живая лента, панели CRM. Токены те же, новых цветов нет.
   ========================================================================== */

/* --- KPI-карточки --- */
.kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.kpi { gap: 6px; min-height: 104px; justify-content: flex-start; padding-top: 18px; }
.kpi-label { font-size: 12px; }
.kpi-row {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 12px;
  min-width: 0;
}
.kpi-row b { flex: 0 0 auto; }
.spark { width: 96px; height: 34px; flex: 1 1 auto; max-width: 120px; }

.delta {
  align-self: flex-start;
  padding: 3px 9px;
  border-radius: var(--radius-pill);
  font-size: 11px;
  font-weight: 700;
}
.delta-up   { background: var(--success-soft); color: var(--success); }
.delta-down { background: var(--warning-soft); color: var(--warning); }
.delta-flat { background: var(--chip);         color: var(--muted); }

/* --- Превью канбана на дашборде --- */
.kanban-preview { grid-template-columns: repeat(auto-fit, minmax(0, 1fr)); gap: 10px; }
.kanban-preview .kanban-column { padding: 11px; }
.mini-lead {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: var(--tap);
  padding: 9px 10px;
  margin-top: 8px;
  border: 1px solid var(--line);
  border-radius: 11px;
  background: var(--panel);
  min-width: 0;
  transition: border-color var(--transition), transform var(--transition);
}
.mini-lead:hover { border-color: var(--line-strong); transform: translateY(-1px); }
.mini-lead > span:last-child { min-width: 0; display: grid; line-height: 1.25; }
.mini-lead b { font-size: 13px; }
.mini-lead b, .mini-lead small {
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.mini-lead small { font-size: 11px; }
.mini-lead-mark {
  display: grid;
  place-items: center;
  width: 26px; height: 26px; flex: 0 0 26px;
  border-radius: 50%;
  background: var(--chip);
  color: var(--text-2);
  font-size: 11px;
  font-weight: 700;
}

/* --- Живая лента --- */
.feed { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; }
.feed-item {
  position: relative;
  display: flex;
  gap: 12px;
  padding: 9px 0;
  min-width: 0;
}
.feed-item + .feed-item { border-top: 1px solid var(--line); }
.feed-item > span:last-child { min-width: 0; display: grid; gap: 2px; line-height: 1.3; }
.feed-item b { font-size: 13px; font-weight: 600; }
.feed-item small { font-size: 11.5px; overflow-wrap: anywhere; }
.feed-dot {
  width: 8px; height: 8px; flex: 0 0 8px;
  margin-top: 7px;
  border-radius: 50%;
  background: var(--accent);
}

.rules-note {
  margin-top: 14px;
  padding: 13px;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: var(--panel2);
}
.rules-note b { display: block; margin-bottom: 4px; font-size: 13px; }
.rules-note p { margin: 0; font-size: 12.5px; }

/* --- Панели CRM --- */
.crm-toolbar {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  align-items: end;
}
.crm-toolbar > div { min-width: 0; }
.crm-toolbar input, .crm-toolbar select { margin-bottom: 0; }
.crm-toolbar button { width: 100%; }

.crm-add {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
  gap: 12px;
  align-items: end;
}
.crm-add input, .crm-add select { margin-bottom: 0; }
.crm-add button { width: 100%; }

.lead-card-links {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid var(--line);
}
.lead-card-links form { margin: 0; }

.row-actions { display: flex; flex-wrap: wrap; gap: 6px; }
.row-actions form { margin: 0; }
.row-actions button { min-width: 38px; }

/* --- Адаптив нового блока --- */
@media (max-width: 1240px) {
  .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 900px) {
  .kanban-preview { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 700px) {
  .kpi-grid { grid-template-columns: minmax(0, 1fr); }
  .kpi { min-height: 0; }
  .spark { max-width: 130px; }
  .crm-toolbar, .crm-add { grid-template-columns: minmax(0, 1fr); }
  .lead-card-links { display: grid; grid-template-columns: minmax(0, 1fr); }
  .lead-card-links form, .lead-card-links button { width: 100%; }
  .row-actions button { flex: 1 1 auto; min-height: 42px; }
}

/* Состояния аккаунтов должны отличаться не только эмодзи, но и цветом
   бейджа — требование «ограничен / заморожен / заблокирован визуально
   отличаются друг от друга». */
.state-restricted .pill { background: var(--warning-soft); color: var(--warning); }
.state-frozen     .pill { background: rgba(249, 115, 22, .14); color: #fb923c; }
.state-blocked    .pill,
.state-banned     .pill { background: var(--danger-soft);  color: var(--danger); }
.state-inactive   .pill { background: var(--chip);         color: var(--muted); }
.state-waiting_code .pill { background: var(--info-soft);  color: var(--info); }
body[data-theme="light"] .state-frozen .pill,
body.light-theme .state-frozen .pill { color: #c2410c; }

/* --- Статусы лидов (v6.8): цвет колонки и подпись --- */
.chips { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.chips .nav-count { margin-left: 4px; }

/* --- Чипсы-фильтры: ЕДИНЫЙ компонент (слово владельца 10.11) ----------------
   «Дизайн всех этих кнопок на всех страницах мне не нравится»: ряды фильтров
   выглядели голым текстом. Причина найдена: <a class="btn-sm"> НЕ получает
   кнопочную базу — правило `.btn, button, …` перечисляет ТЕГИ и класс `.btn`,
   но не класс `.btn-sm`, поэтому чипсы-ссылки были без фона и рамки (а
   кнопки-<button> в том же ряду — с фоном, отсюда разнобой).
   Второй источник: контейнеры .tabs/.tab вообще не имели стилей в shared CSS.
   Канон: один вид плашки в двух видах контейнера — .chips (фильтры-ссылки,
   кнопки и .pill, включая чипсы каналов диалогов) и .period-switch (кнопки
   периода в /replies). Активное состояние понимается И классом .active, И
   исторической формой «нет .secondary»: разметку и JS-переключение не
   трогали, поэтому обе конвенции работают одинаково.
   Специфичность намеренно (0,2,0): правила телефона ниже
   (.period-switch .btn-sm — тап-цель 44px) обязаны её перебивать.

   11.11 (слово владельца, скриншот «3 дня / 7 дней / 30 дней / Все»): ряд
   ОБЯЗАН читаться одним цельным набором. Что было не так и что закрыто:
     • «Все» уезжало на вторую строку и рядом висел пустой квадратик
       (кнопка «на весь экран» без зазора от чипсов — шапка списка была
       голым блочным потоком, см. .dialog-list-header ниже);
     • в /replies активная кнопка заливалась ПЛОТНЫМ --accent с тёмным
       текстом, хотя здесь — мягкая заливка: два вида одной кнопки в
       пределах одного продукта. Правило .period-switch .btn-sm.active
       (оставшееся ниже) теперь приведено к общему виду;
     • горизонтальные паддинги были привязаны к ширине текста («3 дня» и
       «30 дней» — разная ширина), отсюда рваный ряд.
   Размер: min-height 36px и паддинг 7px/14px — здесь намеренно СОХРАНЕНЫ.
   Пины зонной вёрстки (test_dialogs_mobile_layout) держат этот литерал и
   сверяют арифметику тап-целей; единообразие ряда даёт не высота, а
   min-width + tabular-цифры + один gap, см. ниже. */
.chips > .btn-sm,
.chips > .pill,
.period-switch > .btn-sm {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 36px;
  min-width: 72px;
  padding: 7px 14px;
  border: 1px solid var(--line);
  border-radius: var(--radius-pill);
  /* Неактивный чипс — тихая обводка на ПРОЗРАЧНОМ фоне (просьба владельца
     к скриншоту): заливка --panel2 на карточке --panel давала «серые
     кнопки», которые спорили с активной оранжевой. */
  background: transparent;
  color: var(--muted);
  font-size: 13px;
  font-weight: 600;
  line-height: 1.15;
  /* Цифры одинаковой ширины: без этого «3 дня», «7 дней» и «30 дней»
     получают разную ширину глифов, и ряд из четырёх пилюль читается
     рваным даже при равных паддингах (жалоба владельца на скриншоте). */
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  cursor: pointer;
  transition: background var(--transition), border-color var(--transition),
              color var(--transition), filter var(--transition);
}
/* Наведение — до активного состояния: у обоих (0,3,0), побеждает позднее. */
.chips > .btn-sm:hover,
.chips > .pill:hover,
.period-switch > .btn-sm:hover {
  background: var(--chip);
  border-color: var(--line-strong);
  color: var(--text);
}
/* A semantic <button.pill> inherits the global button lift/shadow. Filter
   chips must stay in one steady row just like their link siblings. */
.chips > button.pill:hover {
  transform: none;
  box-shadow: none;
}
/* Активный чипс: сплошная оранжевая заливка (--accent) с тёмным текстом
   (--accent-ink) — ровно как на утверждённом скриншоте владельца.
   Прежде здесь была мягкая --accent-soft, и на /replies активная кнопка
   периода вдобавок перебивалась своим правилом на плотную заливку:
   один компонент выглядел двумя разными способами. Теперь вид ОДИН и
   задан здесь — именно этот блок читают все страницы с рядами фильтров.
   На тёмном фоне --accent (#ff5e33) даёт достаточный контраст с
   --accent-ink (#2a0f08), поэтому текст активной пилюли читается, а не
   «светится». Неактивные — тихая обводка на прозрачном фоне (см. ниже). */
.chips > .btn-sm:not(.secondary),
.chips > .pill:not(.secondary),
.period-switch > .btn-sm.active {
  background: var(--accent);
  border-color: var(--accent);
  color: var(--accent-ink);
  font-weight: 700;
}
.chips > .btn-sm:not(.secondary):hover,
.chips > .pill:not(.secondary):hover,
.period-switch > .btn-sm.active:hover { filter: brightness(1.12); }
/* Счётчик внутри чипса: на активном инвертируется, иначе тонет в заливке. */
.chips > .btn-sm .nav-count,
.chips > .pill .nav-count { background: var(--chip); color: var(--muted); }
.chips > .btn-sm:not(.secondary) .nav-count,
.chips > .pill:not(.secondary) .nav-count {
  background: var(--accent);
  color: var(--accent-ink);
  font-weight: 700;
}

/* --- Таб-бар страницы: ЕДИНЫЙ компонент (.tabs / .tab) ----------------------
   Классы макетов 27-30, 16-knowledge, команды, аналитики жили в разметке с
   прошлых волн, но стилей в shared CSS не имели — вкладки рисовались голыми
   ссылками. Один вид с чипсами: та же плашка, тот же акцент в активной. */
.tabs { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 10px 0; }
.tabs > .tab {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  min-height: 36px;
  padding: 7px 14px;
  border: 1px solid var(--line);
  border-radius: var(--radius-pill);
  background: var(--panel2);
  color: var(--muted);
  font-size: 13px;
  font-weight: 600;
  line-height: 1.15;
  text-decoration: none;
  white-space: nowrap;
  transition: background var(--transition), border-color var(--transition),
              color var(--transition), filter var(--transition);
}
.tabs > .tab:hover {
  background: var(--chip);
  border-color: var(--line-strong);
  color: var(--text);
}
.tabs > .tab.active {
  background: var(--accent-soft);
  border-color: var(--accent);
  color: var(--accent);
  font-weight: 700;
}
.tabs > .tab.active:hover { filter: brightness(1.12); }
.tabs > .tab .ic { opacity: .85; }

/* Чипсы «только одна дата» (фильтр дней рождения в CRM): это НЕ выбор одного
   из многих — второй чипс не «неактивен», а просто другое действие, поэтому
   историческую форму «нет .secondary = активен» здесь отключаем: иначе
   «ДР на этой неделе» при выбранном «сегодня» рисовался бы как выбранный. */
.chips.crm-birth-chips > .btn-sm,
.chips.crm-birth-chips > .btn-sm:not(.secondary) {
  background: var(--panel2);
  border-color: var(--line);
  color: var(--text);
  font-weight: 600;
}
.chips.crm-birth-chips > .btn-sm:hover,
.chips.crm-birth-chips > .btn-sm:not(.secondary):hover {
  background: var(--chip);
  border-color: var(--line-strong);
  filter: none;
}

/* Пометки лида (теги на карточке): это МЕТКИ, а не фильтр — вид выбранного
   чипса (акцентная заливка) читался бы как «эта пометка включена».
   Возвращаем им роль читаемой метки: нейтральная плашка, обычный текст. */
.chips.lead-tag-chips > .pill,
.chips.lead-tag-chips > .pill:not(.secondary) {
  background: var(--chip);
  border-color: var(--line);
  color: var(--text-2);
  font-weight: 600;
  cursor: default;
}
.col-hint { margin: 0 0 8px; font-size: 11.5px; line-height: 1.35; }
.lead-meta { margin: 6px 0 0; font-size: 11.5px; }

.kanban-column.st-new        .status-dot { background: var(--muted); }
.kanban-column.st-contacted  .status-dot { background: var(--info); }
.kanban-column.st-replied    .status-dot { background: var(--success); }
.kanban-column.st-interested .status-dot { background: var(--violet); }
.kanban-column.st-no_answer .status-dot { background: var(--muted); }
.kanban-column.st-processed  .status-dot { background: var(--accent-strong); }
.kanban-column.st-rejected   .status-dot { background: var(--danger); }

.ws-card {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
  transition: border-color var(--transition), transform var(--transition);
}
.ws-card:hover { border-color: var(--line-strong); transform: translateY(-1px); }
.ws-card > span:last-child { min-width: 0; display: grid; line-height: 1.3; }
.ws-card b { font-size: 14px; }
.ws-card small { font-size: 11.5px; }

@media (max-width: 700px) {
  /* Телефон: чипсы переносятся по строке (flex-wrap), а НЕ жёсткой сеткой в
     2 колонки — в сетке длинная подпись («Обычные аккаунты · 12») не влезала
     в половину ширины и вылезала за плашку. Тап-цель ≥44px: база компонента
     36px на телефоне мала (iOS HIG). */
  .chips { display: flex; }
  .chips > .btn-sm,
  .chips > .pill,
  .period-switch > .btn-sm,
  .tabs > .tab { min-height: 44px; padding: 9px 15px; font-size: 13.5px; }
}

/* --- Настройка 2FA --- */
.twofa-qr {
  display: flex;
  justify-content: center;
  padding: 16px;
  margin: 12px 0;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: #ffffff;
}
.twofa-qr img, .twofa-qr svg { width: 190px; height: 190px; }
#twofaCodesList {
  margin: 8px 0 0;
  padding: 12px;
  border-radius: var(--radius-sm);
  background: var(--input);
  font-size: 14px;
  line-height: 1.9;
  letter-spacing: .04em;
  white-space: pre-wrap;
}

/* Инициалы вместо аватарки, пока она не загрузилась или её нет. */
.current-admin-avatar.fallback {
  display: grid;
  place-items: center;
  font-size: 12.5px;
  font-weight: 700;
  line-height: 1;
}

/* --- Живой прогресс рассылки (v7.3) --- */
.progress-cell { min-width: 150px; }
.progress-track {
  height: 8px;
  margin-bottom: 6px;
  border-radius: var(--radius-pill);
  background: var(--input);
  overflow: hidden;
}
.progress-track i {
  display: block;
  height: 100%;
  border-radius: inherit;
  background: var(--accent);
  /* Плавно, чтобы шаг опроса не выглядел рывком. */
  transition: width .6s ease;
}

/* Причина, по которой задача стоит. */
.task-reason {
  margin-top: 6px;
  max-width: 34ch;
  color: var(--warning);
  font-size: 11.5px;
  line-height: 1.35;
}

.live-badge {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 7px 12px;
  border: 1px solid var(--line);
  border-radius: var(--radius-pill);
  color: var(--muted);
  font-size: 12px;
}
.live-badge .status-dot { background: var(--accent); }
.live-badge.stale { opacity: .55; }
.live-badge.stale .status-dot { background: var(--muted); }

@media (max-width: 700px) {
  .task-reason { max-width: none; }
  .progress-cell { min-width: 0; }
}

/* ---- Диалоги: два столбца в стиле Telegram Web (app/dialogs.py) ---- */
.dialogs-layout {
  display: grid;
  grid-template-columns: 320px 1fr;
  height: calc(100dvh - 300px);
  min-height: 480px;
}
.dialog-list-pane {
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--line);
  overflow: hidden;
  min-width: 0;
}
.dialog-list-header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  padding: 12px 14px;
  border-bottom: 1px solid var(--line);
}
/* Чипсы периода — первая строка шапки на всю ширину, кнопка «на весь
   экран» и поиск — вторая (flex-basis с переносом; порядок детей в
   разметке НЕ менялся, его пинят test_dialogs_mobile_layout и
   test_dialogs_search_p3). Прежде здесь был голый блочный поток: кнопка
   .icon-btn прилипала к последней пилюле без зазора и читалась как
   «пустой квадратик» рядом с «Все» — а на узких экранах «Все» из-за
   этого уезжало на отдельную строку. */
.dialog-list-header > .period-switch { flex: 1 1 100%; }
/* Второй элемент шапки (поле поиска) в shared-статике НЕ упоминается:
   пин test_dialogs_search_p3 запрещает даже имя класса здесь (ruling 00+13,
   прецедент f3488b1/a4b584d), а его оформление живёт page-scoped в
   app/dialogs.py (extra_head, min-height 44px). Раскладку второй строки
   держит правило ниже — через дочерний селектор шапки без имени класса. */
.dialog-list-header > input[type="search"] { flex: 1 1 220px; min-width: 0; }
/* Переключатель типа аккаунта под поиском (11.11, скриншот владельца
   «под поиском кнопка Все»). Третья строка шапки: «Все · Обычные ·
   Главные» — сегмент склеенных кнопок того же вида, что .ai-mode-switch
   в шапке треда (radius только по краям, активная — акцентом), поэтому
   новый элемент не заводит четвёртый стиль кнопок на странице.
   flex-basis 100% — чтобы группа заняла свою строку целиком и не
   вклинивалась между полем поиска и кнопкой «на весь экран». */
.account-switch { display: inline-flex; gap: 0; flex: 1 1 100%; margin-top: 8px; }
.account-switch .btn-sm { border-radius: 0; margin-left: -1px; min-height: 36px; }
.account-switch .btn-sm:first-child { border-radius: var(--radius-sm) 0 0 var(--radius-sm); margin-left: 0; }
.account-switch .btn-sm:last-child { border-radius: 0 var(--radius-sm) var(--radius-sm) 0; }
.account-switch .btn-sm.active { background: var(--accent-soft); color: var(--accent);
  border-color: var(--accent); z-index: 1; position: relative; }
/* Ряд периода: 8px между пилюлями (было 6px — «единые отступы 8-10px» из
   просьбы владельца) и НИКАКОГО переноса, пока ширина реально позволяет:
   пилюли ужимаются до min-width вместо того, чтобы рвать ряд. */
.period-switch { display: flex; gap: 8px; flex-wrap: wrap; }
/* Активная кнопка периода наследует ОБЩИЙ вид чипса из блока выше
   (сплошная --accent). Прежнее правило плотной заливки удалено — именно
   оно делало /replies непохожей на остальные страницы с фильтрами. */
/* #dialogsListWrap — обычный div вокруг .dialog-list-scroll + .dialog-pager
   (см. app/dialogs.py), сам по себе не flex-контейнер, из-за чего flex:1
   у .dialog-list-scroll ниже не имел вообще никакого эффекта: список
   просто рос на всю высоту содержимого (обрезаясь снаружи через
   .dialog-list-pane { overflow:hidden }), а не скроллился внутри себя. */
#dialogsListWrap { display: flex; flex-direction: column; flex: 1; min-height: 0; overflow: hidden; }
.dialog-list-scroll { flex: 1; min-height: 0; overflow-y: auto; }
.dialog-row {
  display: flex;
  gap: 10px;
  padding: 12px 14px;
  border-bottom: 1px solid var(--line);
  cursor: pointer;
}
.dialog-row:hover { background: var(--panel2); }
.dialog-row.active { background: var(--panel2); box-shadow: inset 3px 0 0 var(--accent); }
.dialog-row-body { min-width: 0; flex: 1; }
.dialog-row-top { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
.dialog-row-top b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dialog-row-name-wrap { display: flex; align-items: baseline; gap: 6px; min-width: 0; overflow: hidden; }
.dialog-time { flex: none; font-size: 11px; color: var(--muted); }
.dialog-manager-tag {
  flex: none;
  padding: 2px 7px;
  border-radius: var(--radius-pill);
  background: var(--accent-soft);
  color: var(--accent);
  font-size: 10.5px;
  font-weight: 700;
  white-space: nowrap;
}
.dialog-row .preview {
  margin-top: 3px;
  color: var(--muted);
  font-size: 12.5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.dialog-pager {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 10px 14px;
  border-top: 1px solid var(--line);
}

.thread-pane { display: flex; flex-direction: column; min-width: 0; overflow: hidden; }
.thread-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 24px;
}
.thread-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 14px;
  border-bottom: 1px solid var(--line);
}
.thread-header .account-cell { flex: 1; min-width: 0; }
.thread-header-actions { display: flex; gap: 6px; flex: none; }
.thread-back-btn {
  display: none;
  flex: none;
  align-items: center;
  gap: 6px;
  border: none;
  background: none;
  color: var(--text);
  cursor: pointer;
  font: inherit;
  padding: 6px;
}
/* Задача C (03.11, скрин владельца «кривой визуал» шапки): опасная
   кнопка удаления — иконка-квадрат (ic-trash), не текстовая в ряд.
   Тап-цель и опасная айдентика (danger) сохранены; текст — в
   title/aria-label + модальный confirm (dialogs.js deleteConversation). */
.thread-delete-btn { display: inline-flex; align-items: center; justify-content: center;
  width: 34px; padding: 6px; }
.thread-delete-btn .ic { width: 16px; height: 16px; }

.thread-composer { position: relative; }
/* Быстрые ответы по «/» (см. dialogs.js, /api/quick-replies): список над
   полем ввода. Тап-цели ≥44px — на мобильном выбор тапом, не только
   стрелками. */
.qr-popup {
  position: absolute;
  left: 12px;
  right: 12px;
  bottom: calc(100% + 4px);
  z-index: 80;
  max-height: 240px;
  overflow-y: auto;
  background: var(--card, #fff);
  border: 1px solid var(--line);
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0,0,0,.14);
}
.qr-item {
  display: flex;
  align-items: baseline;
  gap: 10px;
  min-height: 44px;
  padding: 8px 12px;
  cursor: pointer;
}
.qr-item.selected, .qr-item:hover { background: var(--accent-soft, rgba(99,102,241,.12)); }
/* Меню действий сообщения (копировать/ответить, dialogs.js) — fixed у
   пузыря, тап-цели ≥44px (HIG-конвенция файла); z-index выше qr-popup
   (80), меню показывается по явному жесту. */
/* Закреплённое сообщение (локальный pin, см. /api/conversations/{id}/pin):
   полоска под шапкой треда; тап-цель отмены не меньше 44px. */
/* Модалка пересылки (dialogs.js openForwardPicker): затемнение на весь
   экран, карточка с поиском и списком диалогов; тап-цели >=44px. */
.forward-picker {
  position: fixed;
  inset: 0;
  z-index: 190;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background: rgba(0,0,0,.45);
}
.forward-card {
  width: 100%;
  max-width: 420px;
  max-height: 80dvh;
  display: flex;
  flex-direction: column;
  background: var(--bg, #fff);
  border: 1px solid var(--line);
  border-radius: 14px;
  box-shadow: 0 16px 48px rgba(0,0,0,.28);
  overflow: hidden;
}
.forward-head {
  padding: 14px 16px 8px;
  font-weight: 600;
}
.forward-preview {
  display: block;
  font-weight: 400;
  font-size: 12.5px;
  color: var(--muted, #666);
  margin-top: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.forward-search { margin: 8px 16px; }
.forward-list {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 0 8px 8px;
}
.forward-target {
  display: block;
  width: 100%;
  min-height: 44px;
  padding: 10px 12px;
  border: none;
  border-radius: 10px;
  background: none;
  color: var(--text);
  font: inherit;
  text-align: left;
  cursor: pointer;
}
.forward-target:hover { background: var(--accent-soft, rgba(99,102,241,.12)); }
.forward-foot {
  display: flex;
  justify-content: flex-end;
  padding: 10px 16px;
  border-top: 1px solid var(--line);
}
.forward-toast {
  position: fixed;
  left: 50%;
  bottom: 32px;
  transform: translateX(-50%);
  z-index: 195;
  padding: 10px 18px;
  border-radius: 999px;
  background: var(--text, #222);
  color: var(--bg, #fff);
  font-size: 14px;
  box-shadow: 0 8px 24px rgba(0,0,0,.3);
}
/* ── inbox-ux Р1-Р6 (SPEC-inbox-ux, макет pages/13-inbox.html) ───────────
   Классы перенесены из mockups.css (визуальный источник истины — решение
   владельца «весь дизайн из макетов 2.0»). Устаревшая .draft-bar (полоса
   над композером) удалена: черновик ИИ теперь draft-card ВНУТРИ ленты
   (Р1) — экономия ~37px постоянного хрома треда, жалоба «из-за различных
   окон неудобно». Тап-цели кнопок карточки не меньше 44px (HIG-конвенция
   файла, перенесена с .draft-bar-insert). */
.plat { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px;
        border-radius: var(--radius-pill); font-size: 10.5px; font-weight: 800;
        letter-spacing: .02em; white-space: nowrap; }
.plat::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
.plat > .ic { width: 13px; height: 13px; vertical-align: middle; }
.plat.plat-icon::before { display: none; }
.plat-icon > span:not(.ic) { display: inline-flex; align-items: center; gap: 3px; }
.p-tg { background: rgba(111, 184, 255, .14); color: var(--info); }
.p-wa { background: rgba(52, 211, 153, .14); color: var(--success); }
.p-ig { background: rgba(217, 79, 149, .15); color: var(--violet); }
.p-mx { background: rgba(255, 204, 51, .13); color: var(--warning); }
.p-tt { background: rgba(255, 59, 92, .14); color: var(--danger); }
.p-vk { background: rgba(0, 119, 255, .14); color: var(--info); }
/* «Каналы по факту доступности» (дизайн-нота fc049b88): выключенный канал —
   ТОТ ЖЕ .plat-бейдж, приглушённый (серый, не красный: «выключен» — норма,
   не ошибка; .badge-off :877 — danger, не этот случай). Пометка «выключен»
   внутри бейджа. plat-unkn — сбой чтения (пунктир, мягкая деградация).
   channel-status — строка бейджей на карточке направления. */
.plat-off { background: transparent; color: var(--muted); opacity: .45;
            border: 1px solid var(--line); }
.plat-off::before { background: var(--muted); }
.plat-off small { font-weight: 500; margin-left: 2px; }
.plat-unkn { background: transparent; color: var(--muted);
             border: 1px dashed var(--line); }
.plat-unkn small { font-weight: 500; }
.channel-status { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 10px; }
.channel-status .muted.small { align-self: center; }

/* R5: метка «требует менеджера» в строке списка (P1-E сервис
   manager_request.py, метки в списке раньше не было). */
.dialog-esc-tag { display: inline-flex; align-items: center; gap: 4px; margin-left: 6px;
  padding: 2px 8px; border-radius: var(--radius-pill); font-size: 11px; font-weight: 600; }
.dialog-esc-tag.esc-human { background: var(--warning-soft); color: var(--warning); }
.dialog-esc-tag.esc-distrust { background: var(--danger-soft); color: var(--danger); }

/* R1: черновик ИИ — карточка последним child ленты (макет .draft-card). */
.draft-card { align-self: flex-end; max-width: 72%; margin: 6px 0 10px; padding: 12px 14px;
  border: 1.5px dashed var(--accent); border-radius: var(--radius-lg) var(--radius-sm) var(--radius-lg) var(--radius-lg);
  background: var(--accent-soft); }
.draft-head { display: flex; align-items: center; gap: 7px; margin-bottom: 6px;
  font-size: 11.5px; color: var(--accent); }
.draft-head b { font-size: 11.5px; letter-spacing: .04em; text-transform: uppercase; }
.draft-head .muted { font-size: 11px; margin-left: auto; }
.draft-card p { margin: 0 0 10px; font-size: 13.5px; color: var(--text);
  white-space: pre-wrap; word-break: break-word; }
.draft-card .actions { gap: 6px; }
/* HIG 44px перенесён с .draft-bar-insert/.draft-bar-hide: три кнопки
   карточки — такие же тап-цели, как у прежней полосы. */
.draft-card .actions .btn-sm { min-height: 44px; }

/* ИСТОРИЧЕСКАЯ НОТА (pin-inversion, STEP-UI-1 08.10): здесь жили классы
   полосы шагов сценария thread-step-strip, step-strip-expand, step-chip и
   родственные (script_progress коммит 3 → inbox-ux Р6 перенос из
   mockups.css). Виджет удалён по буквальной жалобе владельца №1 («не надо
   в диалогах выводить эти шаги»); data-слой script_progress сохранён
   целиком — см. ноту в app/dialogs.py на месте удалённой функции. */

/* Р7 (inbox часть 2): 3-позиционный переключатель режима ИИ диалога —
   классы макета 13-inbox .ai-mode-switch (mockups.css :209-214) перенесены
   Р6-приёмом части 1. Сегмент склеенных кнопок: radius только по краям,
   активная позиция — акцентом (как period-switch). */
.ai-mode-switch { display: inline-flex; gap: 0; }
.ai-mode-switch .btn-sm { border-radius: 0; margin-left: -1px; }
.ai-mode-switch .btn-sm:first-child { border-radius: var(--radius-sm) 0 0 var(--radius-sm); margin-left: 0; }
.ai-mode-switch .btn-sm:last-child { border-radius: 0 var(--radius-sm) var(--radius-sm) 0; }
.ai-mode-switch .btn-sm.active { background: var(--accent-soft); color: var(--accent);
  border-color: var(--accent); z-index: 1; position: relative; }

/* inbox part 3 T1: follow-up-состояние рядом с режимами AI — пилюля макета
   13-inbox (mockups.css :443-447 перенесён Р6-приёмом). Прежний серый
   inline-span «follow-up: активен» заменён состояниями fu-active/fu-closed.
   11.11: добавлено ТРЕТЬЕ состояние fu-idle — «дожим этому диалогу не
   придёт». Прежняя пара состояний показывала «активен» всем 803 активным
   диалогам, хотя планировщик взял бы 621; владелец читал пилюлю как
   обещание дожима. Нейтральный (не зелёный, не синий) тон — это НЕ
   статус «всё хорошо», а «здесь ничего не произойдёт». */
.fu-state { display: inline-flex; align-items: center; gap: 5px; margin-left: 8px;
  padding: 4px 10px; border-radius: var(--radius-pill); font-size: 11.5px; font-weight: 600; }
.fu-state.fu-active { background: var(--info-soft); color: var(--info); }
.fu-state.fu-closed { background: var(--success-soft); color: var(--success); }
.fu-state.fu-idle { background: var(--panel2, var(--line-soft)); color: var(--muted); }
.thread-pin-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-bottom: 1px solid var(--line);
  background: var(--accent-soft, rgba(99,102,241,.08));
  font-size: 13px;
}
.thread-pin-icon { flex: none; display: inline-flex; align-items: center; }
/* Маска значка закрепа (11.11: эмодзи 📌 заменена .ic-pin): центрируем её
   флексом, иначе штрих садится на базовую линию и «прыгает» в полосе. */
.thread-pin-icon .ic { font-size: 13px; }
.thread-pin-text {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--text);
}
.thread-pin-unpin {
  flex: none;
  min-height: 44px;
  min-width: 44px;
  border: none;
  border-radius: 8px;
  background: none;
  color: var(--muted, #666);
  font-size: 20px;
  line-height: 1;
  cursor: pointer;
}
/* Само закреплённое сообщение в ленте — лёгкая метка, не спорящая с
   выбором/цитированием. */
.msg-bubble.pinned { box-shadow: inset 3px 0 0 var(--accent, #6366f1); }
.msg-reactions { display: flex; flex-wrap: wrap; gap: 4px; margin: 5px 28px 1px 0; }
.msg-reaction-chip {
  display: inline-flex; align-items: center; gap: 3px; min-height: 24px;
  padding: 1px 7px; border: 1px solid var(--line); border-radius: 999px;
  background: var(--panel); color: var(--text); font-size: 12px; line-height: 1;
}
.msg-reaction-chip.chosen { border-color: var(--accent); background: var(--accent-soft); }
.msg-actions {
  position: fixed;
  z-index: 90;
  display: flex;
  flex-wrap: wrap;
  max-width: min(350px, calc(100vw - 16px));
  gap: 4px;
  padding: 4px;
  background: var(--card, #fff);
  border: 1px solid var(--line);
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0,0,0,.18);
}
.msg-reaction-picker { display: flex; flex: 0 0 100%; justify-content: space-between; gap: 2px; }
.msg-reaction-option {
  display: grid; place-items: center; min-width: 38px; min-height: 40px;
  padding: 3px; border: 0; border-radius: 8px; background: transparent;
  font-size: 20px; cursor: pointer;
}
.msg-reaction-option:hover, .msg-reaction-option.selected { background: var(--accent-soft); }
.msg-action {
  min-height: 44px;
  padding: 8px 14px;
  border: none;
  border-radius: 8px;
  background: none;
  color: var(--text);
  font: inherit;
  cursor: pointer;
  white-space: nowrap;
}
.msg-action:hover { background: var(--accent-soft, rgba(99,102,241,.12)); }
.msg-action.danger { color: var(--danger, #e54868); }
.msg-action.danger:hover { background: color-mix(in srgb, var(--danger, #e54868) 12%, transparent); }
.message-edit-bar { border-left-color: var(--warning, #d99b25); }
/* Цитата «Ответить» над композером: кто/что цитируется + кнопка отмены. */
.reply-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 12px;
  padding: 8px 10px;
  border-left: 3px solid var(--accent, #6366f1);
  background: var(--accent-soft, rgba(99,102,241,.08));
  border-radius: 8px;
  font-size: 13px;
  color: var(--text);
}
.reply-bar-quote { flex: none; font-size: 15px; }
.reply-bar-text {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.reply-bar-text b { margin-right: 4px; }
.reply-bar-cancel {
  flex: none;
  min-height: 44px;
  min-width: 44px;
  border: none;
  border-radius: 8px;
  background: none;
  color: var(--muted, #666);
  font-size: 20px;
  line-height: 1;
  cursor: pointer;
}
.qr-shortcut { font-weight: 600; white-space: nowrap; }
.qr-text { color: var(--muted, #666); font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.thread-scroll {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.msg-bubble {
  max-width: 70%;
  padding: 9px 13px 16px;
  border-radius: var(--radius);
  font-size: 14px;
  line-height: 1.4;
  position: relative;
  white-space: pre-wrap;
  word-break: break-word;
}
.msg-bubble.msg-entering { animation: lf-message-arrive .38s cubic-bezier(.16, 1, .3, 1) both; animation-delay: var(--bubble-delay, 0ms); }
@keyframes lf-message-arrive {
  0% { opacity: 0; transform: translate3d(0, 9px, 0) scale(.975); filter: blur(3px); }
  68% { opacity: 1; transform: translate3d(0, -1px, 0) scale(1.006); filter: blur(0); }
  100% { opacity: 1; transform: none; filter: none; }
}
.msg-in { align-self: flex-start; background: var(--panel2); border: 1px solid var(--line); border-bottom-left-radius: 4px; }
.msg-out { align-self: flex-end; background: var(--accent-soft); border-bottom-right-radius: 4px; }
.msg-time {
  position: absolute;
  right: 10px;
  bottom: 4px;
  font-size: 10px;
  color: var(--muted);
}
.dialog-unknown-banner {
  padding: 10px 12px;
  border-top: 1px solid var(--line);
  background: var(--warning-soft);
  color: var(--warning);
  font-size: 12.5px;
  line-height: 1.4;
}
/* Маска знака вопроса в плашке (11.11: эмодзи ❓ заменена .ic-*). Баннер —
   обычный блок, поэтому выравниваем штрих по тексту вручную: у .ic по
   умолчанию vertical-align -.14em, для строки 1.4 этого мало. */
.dialog-unknown-banner .ic { vertical-align: -.18em; margin-right: 2px; }
.thread-composer {
  display: flex;
  gap: 8px;
  padding: 12px;
  border-top: 1px solid var(--line);
}
.thread-composer textarea {
  flex: 1;
  resize: none;
  min-height: 42px;
  max-height: 140px;
}
.thread-composer button { flex: none; align-self: flex-end; }
.thread-attach-btn {
  display: inline-grid;
  flex: none;
  place-items: center;
  align-self: flex-end;
  width: 44px;
  min-height: 44px;
  border: 1px solid var(--line);
  border-radius: 12px;
  color: var(--muted);
  cursor: pointer;
}
.thread-attach-btn:hover { color: var(--accent); border-color: var(--accent); }
.thread-attach-name {
  align-self: center;
  max-width: 150px;
  overflow: hidden;
  color: var(--muted);
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.thread-attach-clear {
  align-self: center;
  min-width: 28px;
  min-height: 28px;
  padding: 0;
  border: 0;
  background: transparent;
  color: var(--muted);
  font-size: 20px;
}
@media (max-width: 600px) {
  .thread-composer { flex-wrap: wrap; }
  .thread-attach-name {
    order: -1;
    flex: 1 1 calc(100% - 42px);
    max-width: none;
  }
  .thread-attach-clear { order: -1; }
  .thread-composer textarea { flex-basis: calc(100% - 108px); }
}
.msg-attachment-preview {
  display: block;
  width: 300px;
  max-width: 100%;
  aspect-ratio: 4 / 3;
  margin-top: 4px;
  border-radius: var(--radius-sm);
  background: var(--panel);
  object-fit: contain;
}
video.msg-attachment-preview {
  aspect-ratio: 16 / 9;
  background: #111;
}
.msg-attachment-preview[hidden] { display: none; }
.msg-attachment {
  display: flex;
  align-items: center;
  gap: 10px;
  width: fit-content;
  max-width: 100%;
  min-height: 44px;
  margin-top: 4px;
  padding: 8px 10px;
  border: 1px solid var(--line);
  border-radius: 10px;
  color: var(--accent);
  white-space: normal;
}
.msg-attachment:hover { background: var(--accent-soft); }
.msg-attachment:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.msg-attachment > .ic { flex: none; font-size: 17px; }
.msg-attachment-details { display: grid; min-width: 0; gap: 2px; }
.msg-attachment-name { font-weight: 600; overflow-wrap: anywhere; }
.msg-attachment-size { color: var(--muted); font-size: 12px; }
.msg-text { white-space: pre-wrap; overflow-wrap: anywhere; }

@media (max-width: 760px) {
  /* Открытый диалог — полноэкранный слой поверх страницы, как в мобильном
     Telegram. Раньше тред просто показывался вместо списка там же, где
     стоял — а это ниже hero и метрик (~600px контента), поэтому тап по
     строке на телефоне выглядел как «ничего не произошло»: переписка
     открывалась под сгибом экрана. fixed-слой от этого не зависит;
     скролл body на это время блокирует dialogs.js (класс .dialogs-lock).
     z-index: над .nav-overlay (60, подложка сайдбара), но под сайдбаром
     (70) и всеми модалками (.modal/.lf-modal-overlay, 200) — подтверждение
     удаления диалога должно оставаться поверх треда.
     Вложенный .thread-scroll скроллится сам (-webkit-overflow-scrolling
     на нём), поэтому overscroll-behavior: contain — жест «дотянуть до
     конца и потащить дальше» не прокручивает заблокированную страницу. */
  .dialogs-layout.thread-open .thread-pane {
    position: fixed;
    inset: 0;
    z-index: 65;
    display: flex;
    background: var(--bg);
    overscroll-behavior: contain;
  }
  /* Оверлей накрывает весь экран включая топбар, поэтому «чёлку»
     обходит сам заголовок треда, а хоум-бар — панель ввода (на всех
     ≤760px, не только на узких: iPad portrait тоже с home-индикатором). */
  .dialogs-layout.thread-open .thread-header {
    padding-top: calc(12px + env(safe-area-inset-top));
  }
  .thread-composer {
    padding-bottom: calc(12px + env(safe-area-inset-bottom));
  }
  .dialogs-layout { grid-template-columns: 1fr; }
  /* Пока тред открыт полноэкранным слоем, страница под ним не должна
     скроллиться (класс вешает dialogs.js при thread-open на ≤760px). */
  body.dialogs-lock { overflow: hidden; }
  /* Список — на всю высоту под липким топбаром (--top-h): прежний
     фиксированный вычитаемый offset (260px «на глаз») угадать невозможно —
     высота hero/метрик/падающего меню у всех разная, и на маленьком
     экране список оказывался то 200px, то уезжал за сгиб. min-height
     базы (480px) на телефоне перебиваем: 480 > вьюпорт 640px минус
     топбар — composer уходил за сгиб. */
  .dialogs-layout:not(.thread-open) {
    height: calc(100dvh - var(--top-h) - env(safe-area-inset-top) - 16px);
    min-height: 0;
  }
  .dialogs-layout:not(.thread-open) .dialog-list-pane { display: flex; }
  .dialogs-layout:not(.thread-open) .thread-pane { display: none; }
  .thread-back-btn { display: inline-flex; }
  /* На iOS поле со шрифтом < 16px зумит страницу при фокусе. Глобальное
     правило input/textarea { font-size: 16px } живёт в @media 700px — в
     зазоре 700–760px composer оставался 15px и ловил зум, поэтому 16px
     продублирован здесь, на весь диапазон ≤760px. */
  .thread-composer textarea { font-size: 16px; }
  .thread-scroll { -webkit-overflow-scrolling: touch; }
  /* Баннер «Данные изменились» (db_refresh.js, базовое правило — в разделе
     fixed-слоёв): на телефоне не угловая плашка 420px, а компактная полоса
     у нижнего края с обходом home-индикатора. Кнопка тап-цель не задаём
     явно — её держат глобальные button { min-height: var(--tap) } (44px)
     и ≤700px { min-height: 50px }; ID-селектор здесь их бы ПЕРЕБИЛ вниз
     (урок .krow-check). Пока тред открыт, баннер под его непрозрачным
     оверлеем (z-index 55 < 65) — не перекрывает composer. */
  .db-changed-notice {
    left: 10px;
    right: 10px;
    bottom: calc(10px + env(safe-area-inset-bottom));
    max-width: none;
    padding: 10px 12px;
    font-size: 13px;
  }
}

@media (max-width: 560px) {
  /* Шапка треда: клиент + три действия не влезают в одну строку на 360px
     (кнопки flex-wrap не переносятся, если не задать явно) — действия
     уезжают отдельным рядом на всю ширину и переносятся чипами. */
  .thread-header { flex-wrap: wrap; row-gap: 8px; padding: 10px 12px; }
  /* 44px, не 40px (iOS HIG): эти правила специфичнее глобального
     .btn, button { min-height: 50px } из @media ≤700px и до фикса
     УМЕНЬШАЛИ тап-цель относительно него — тот же урок специфичности,
     что у .krow-check. */
  .thread-back-btn { min-height: 44px; padding: 6px 10px 6px 4px; }
  .thread-header .account-cell { flex: 1 1 0; }
  .thread-header-actions { flex: 1 1 100%; flex-wrap: wrap; }
  .thread-header-actions .btn-sm { flex: 1 1 auto; min-height: 44px; padding-left: 8px; padding-right: 8px; }

  /* Шапка списка: тап-цели ≥40px (кнопки периода) + компактный заголовок. */
  .dialog-list-header { padding: 8px 10px; }
  .period-switch { gap: 4px; }
  .period-switch .btn-sm { flex: 1; min-height: 44px; padding: 6px 4px; }
  /* 11.11 (скриншот владельца «Все уехало на вторую строку»): на телефоне
     четыре пилюли периода делят строку ПОРОВНУ, а не «сколько влезло».
     flex: 1 выше уже растягивает их, но при переносе последняя оставалась
     одна на второй строке и ползла на всю ширину. Сетка из двух колонок
     даёт ровный прямоугольник 2×2 на 390px — без горизонтального скролла
     и без сироты-пилюли. Ниже 420px это же правило продолжает работать. */
  .dialog-list-header > .period-switch {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 6px;
  }
  .dialog-list-header > .period-switch .btn-sm { width: 100%; min-width: 0; }
  /* Поиск — вторая строка целиком; кнопка «на весь экран» уходит вправо
     в той же строке, отделённая зазором (тот самый «пустой квадратик»
     рядом с «Все» больше не прилипает к чипсам). */
  .dialog-list-header > input[type="search"] { flex: 1 1 100%; order: 2; }
  /* Переключатель типа аккаунта — третья строка, кнопки делят ширину
     поровну и держат тап-цель 44px (iOS HIG): на 390px три подписи
     «Все / Обычные / Главные» в один ряд 36px-кнопками были бы мелкими
     для пальца. */
  .account-switch { flex: 1 1 100%; order: 3; margin-top: 6px; }
  .account-switch .btn-sm { flex: 1 1 0; min-height: 44px; padding: 6px 4px; min-width: 0; }
  .dialog-list-header > .dialogs-fs-btn {
    margin-left: auto;
    border-color: var(--line);
    border-radius: var(--radius-sm);
    background: transparent;
  }
  .dialog-row { padding: 10px 12px; }
  .dialog-pager { flex-wrap: wrap; padding: 8px 10px; }
  .dialog-pager .btn-sm { min-height: 44px; flex: 0 1 auto; }
  .dialog-pager span { flex: 1; text-align: center; font-size: 12px; }

  /* Пузыри: 70% от 360px — ~250px, длинный текст превращался в узкую
     колонку. 85% ближе к мобильным мессенджерам; word-break из базового
     правила .msg-bubble добивает непереносимые слова (URL и т.п.). */
  .msg-bubble { max-width: 85%; }
  /* R1: draft-card в ленте на телефоне шире (макет .draft-card ≤700px →
     max-width 92%); три кнопки карточки переносятся чипами. */
  .draft-card { max-width: 92%; }
  .draft-card .actions { flex-wrap: wrap; }
  .draft-card .actions .btn-sm { min-height: 44px; }
  .thread-scroll { padding: 12px 10px; }
  /* padding-bottom обязан включать env() и здесь: этот блок (≤560px) идёт
     ПОСЛЕ блока ≤760px, где .thread-composer получает padding-bottom с
     safe-area; шортхенд «padding: 10px» затёр бы его — на узком iPhone
     хоум-бар снова налез бы на поле ввода. */
  .thread-composer { padding: 10px 10px calc(10px + env(safe-area-inset-bottom)); }
  .thread-composer textarea { min-height: 44px; }
  .thread-composer button { min-height: 44px; padding: 10px 14px; }

  /* Hero/metrics страницы диалогов: на телефоне шапка с h1, абзацем и
     двумя кнопками в 50px + две метровые карточки по 108px съедали ~600px
     — список диалогов начинался за сгибом. Скоуп-классы (page-hero-compact
     / page-metrics-compact) навешаны только на /replies (app/dialogs.py),
     другие страницы с обычным hero не затрагиваются. */
  .page-hero-compact { padding: 14px 15px; }
  .page-hero-compact h1 { font-size: 21px; }
  .page-hero-compact p.muted { display: none; }
  .page-hero-compact .actions { margin-top: 12px !important; gap: 8px; }
  .page-hero-compact .actions > * { min-height: 44px; font-size: 13.5px; }
  .page-metrics-compact { gap: 8px; }
  .page-metrics-compact .metric {
    min-height: 0;
    padding: 10px 12px;
    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    align-items: baseline;
    gap: 3px 8px;
  }
  .page-metrics-compact .metric b { font-size: 15px; }
  .page-metrics-compact .metric span { min-width: 0; font-size: 12px; overflow-wrap: anywhere; }
  .page-metrics-compact .metric small { grid-column: 1 / -1; min-width: 0; margin-top: 0; overflow-wrap: anywhere; }

  /* Денежный KPI технического контура бывает семизначным. Сохраняем
     двухколоночную сетку, но не разрываем копейки и знак рубля посередине. */
  .technical-kpis .metric:last-child b {
    font-size: clamp(19px, 5.4vw, 23px);
    white-space: nowrap;
    letter-spacing: -.045em;
  }

  /* Плашка «вопрос без AI-ответа» над composer'ом — компактнее, чтобы
     вместе с клавиатурой не съела весь тред. */
  .dialog-unknown-banner { padding: 8px 10px; font-size: 12px; }

  /* Чекбоксы выбора записей базы знаний (/workspaces/{slug}/knowledge):
     базовые 20px пальцем не попасть. Область тапа — 44px: видимый квадрат
     28px плюс прозрачная рамка 8px со всех сторон.

     Селектор обязан быть input[type="checkbox"].krow-check: базовое
     правило (style.css:780) имеет специфичность (0,1,1) и голый класс
     (0,1,0) его width/height не перебил бы. box-sizing: content-box —
     потому что глобальный * { border-box } (style.css:173) включил бы
     рамку ВНУТРЬ 28px (контент схлопнулся бы до 12px, суммарно 28px, а
     не 44px); с content-box рамка добавляется снаружи: 28+8+8 = 44.
     background-clip: padding-box — чтобы accent-фон чекбокса не красил
     прозрачную рамку. */
  input[type="checkbox"].krow-check {
    box-sizing: content-box;
    width: 28px; height: 28px; min-height: 28px;
    border: 8px solid transparent;
    background-clip: padding-box;
  }
}

/* ── P1-C: онбординг (шаги 05/06, чеклист 09) ─────────────────────────── */

/* Чекбоксы каналов шага 06: крупные строки-цели (тап-цель ≥44px по HIG),
   disabled-каналы («скоро») приглушены, но видны — намерение владельца
   сохраняется и будет предложено в Фазе 2. */
.onboarding-channel {
  display: flex; align-items: center; gap: 12px;
  min-height: 44px; padding: 8px 10px;
  border: 1px solid var(--line, rgba(0,0,0,.08)); border-radius: 12px;
  margin-top: 8px; cursor: pointer;
}
.onboarding-channel input[type="checkbox"] {
  width: 22px; height: 22px; min-height: 22px; flex: 0 0 auto;
}
.onboarding-channel.disabled { opacity: .55; cursor: not-allowed; }
.onboarding-channel span { display: flex; flex-direction: column; }

/* Чеклист «Запуск за 15 минут» на дашборде: блок виден, пока есть
   незавершённые шаги. */
.onboarding-card { margin-top: 14px; }
.onboarding-steps {
  list-style: none; margin: 0; padding: 0;
  display: grid; gap: 8px;
}
.onboarding-step { display: block; }
.onboarding-step a {
  display: flex; align-items: center; gap: 12px;
  min-height: 44px; padding: 8px 12px;
  border: 1px solid var(--line, rgba(0,0,0,.08)); border-radius: 12px;
  text-decoration: none; color: inherit;
}
.onboarding-step a span:first-of-type { font-weight: 600; }
.onboarding-step a small { margin-left: auto; }
.onboarding-check {
  display: inline-flex; align-items: center; justify-content: center;
  width: 24px; height: 24px; flex: 0 0 auto;
  border: 2px solid var(--line, rgba(0,0,0,.15)); border-radius: 50%;
  font-size: 14px; line-height: 1;
}
.onboarding-step.done .onboarding-check {
  border-color: var(--accent, #4f7cff); background: var(--accent, #4f7cff);
  color: #fff;
}
.onboarding-step.done a small { color: var(--accent, #4f7cff); }/* Чеклист «Запуск за 15 минут» на дашборде — строение макета 09
   (ревериф 28.10, D4): onboard-check сетка нумерованных onboard-step
   (кружок span.n + текст b + справа pill «готово»/btn-sm). Порт
   mockups.css:228-239 на переменные дерева. Прежние ul.onboarding-steps
   классы сняты (генератор их больше не выдаёт). */
.onboard-check { display: grid; gap: 8px; }
.onboard-step { display: grid; grid-template-columns: 26px minmax(0,1fr) auto; gap: 11px;
  align-items: center; padding: 11px 14px; border: 1px solid var(--line);
  border-radius: var(--radius); background: var(--panel2); }
.onboard-step .n { display: grid; place-items: center; width: 26px; height: 26px;
  border-radius: 50%; background: var(--input); color: var(--text-2);
  font-size: 12.5px; font-weight: 800; }
/* Выполненный шаг: вместо галочки-глифа «✓» (эмодзи-класс, заменено 11.11)
   стоит маска .ic-check. Размер — 14px: штрих маски совпадает по весу с
   цифрой шага, иначе иконка выглядела крупнее соседних номеров. */
.onboard-step .n .ic { width: 14px; height: 14px; }
.onboard-step b { font-size: 13.5px; display: block; }
.onboard-step.done { border-color: var(--success); }
.onboard-step.done .n { background: var(--success-soft); color: var(--success); }
.onboard-step.now { border-color: var(--accent); background: var(--accent-soft); }
.onboard-step.now .n { background: var(--accent); color: var(--accent-ink); }
/* ПАРТИЯ №4, нога cc/0f (макет 09-dashboard, ГО координатора 28.10):
   «Дальше по желанию» — карточки-ссылки next-steps. Классы .next-steps/
   .next-step/.next-step-ic/.next-step-body/.next-step-arrow + вечная
   карточка «скоро» (.next-step-soon). Reels — честная заглушка §D.7
   (descoped), НЕ ссылка. Все CSS-переменные уже существуют в дереве
   (--line/--radius/--panel2/--accent/--accent-soft/--muted). */
.next-steps { display: grid; gap: 10px; }
.next-step { display: grid; grid-template-columns: 40px minmax(0,1fr) auto; gap: 13px;
  align-items: center; padding: 13px 15px; border: 1px solid var(--line);
  border-radius: var(--radius); background: var(--panel2); text-decoration: none;
  color: var(--text); transition: border-color var(--transition), background var(--transition); }
.next-step:hover { border-color: var(--accent); background: var(--panel); }
.next-step-ic { display: grid; place-items: center; width: 40px; height: 40px;
  border-radius: var(--radius-sm); background: var(--accent-soft); color: var(--accent); }
.next-step-ic .ic { font-size: 1.1rem; }
.next-step-body { min-width: 0; }
.next-step-body b { display: block; font-size: 13.5px; }
.next-step-body small { display: block; color: var(--muted); font-size: 12px; margin-top: 2px; }
.next-step-arrow { color: var(--muted); font-size: .85rem; }
.next-step-soon { opacity: .55; cursor: default; }
.next-step-soon:hover { border-color: var(--line); background: var(--panel2); }

/* Косметика 08 (ревериф строения, ГО координатора 28.10): секционный
   подзаголовок над списком направлений — порт .subhead из макетного
   mockups.css:202-204 (у crm_ai_final_fixes он page-scoped; общим классом
   закрываем страницу 08 без дублирования page-стилей). */
.subhead { display: flex; align-items: center; gap: 10px; margin: 20px 0 10px; flex-wrap: wrap; }
.subhead h2 { margin: 0; font-size: 17px; }
.subhead .muted { font-size: 12.5px; }
/* Sticky cabinet header must not cover a section title reached from an
   in-page tab, especially on phones where the account controls wrap to a
   second row. */
.tab-anchor { scroll-margin-top: calc(var(--top-h) + 16px); }
@media (max-width: 900px) {
  .tab-anchor {
    scroll-margin-top: calc(var(--top-h) + 56px + env(safe-area-inset-top));
  }
}

/* ── Функции направления (конструктор, 09.11) ────────────────────────────
   Слово владельца: «карточки подписки сильно большие». Прежде функция была
   отдельной карточкой в сетке 2-3 колонки: заголовок, цена строкой ниже,
   кнопка и длинное предупреждение о сгорании В КАЖДОЙ карточке — список из
   11 функций занимал почти экран и больше. Теперь одна строка на функцию:
   название занимает свободное место, цена прижата вправо, переключатель
   (или кнопка) стоит на фиксированном месте. Пояснения (сгорание, оплата,
   минимальный набор) — ОДИН раз под сеткой (.feature-note), а не в каждой
   строке.

   Классы новые, потому что прежние .feature-card/.feature-grid жили только
   inline-стилями в app/constructor_features.py, то есть общей формы у них
   не было вовсе. Переменные — существующие токены дерева, новых цветов не
   вводим. */
.feature-block { min-width: 0; }
.feature-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; }
.feature-card {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto auto;
  align-items: center;
  column-gap: 10px;
  row-gap: 2px;
  min-height: 44px;              /* тап-цель по HIG, как у чекбоксов каналов */
  padding: 8px 11px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel2);
  min-width: 0;
  cursor: pointer;
  transition: border-color var(--transition), background var(--transition);
}
.feature-card {
  transition: transform .28s cubic-bezier(.2,.8,.2,1), border-color .26s ease,
    background .26s ease, box-shadow .28s ease;
}
@media (hover: hover) and (pointer: fine) {
  .feature-card:hover {
    transform: translateY(-2px);
    border-color: color-mix(in srgb, var(--accent) 36%, var(--line));
    box-shadow: 0 10px 26px rgba(0,0,0,.16);
  }
}
/* Выбранная функция — акцентная рамка и мягкая заливка (слово владельца:
   «выбранные функции визуально отличаются»). Признак — data-on: его ставит
   сервер для минимального набора, клиентский пересчёт обновляет сам. */
.feature-card[data-on="1"] { border-color: var(--accent); background: var(--accent-soft); }
.feature-card .feature-name {
  grid-column: 1; grid-row: 1;
  font-weight: 600; font-size: 13.5px; min-width: 0; overflow-wrap: anywhere;
}
.feature-card .feature-price {
  grid-column: 2; grid-row: 1;
  color: var(--muted); font-size: 12.5px; font-weight: 600; white-space: nowrap;
}
.feature-card .feature-state {
  grid-column: 1; grid-row: 2;
  color: var(--muted); font-size: 12px;
}
.feature-card input[type="checkbox"],
.feature-card form {
  grid-column: 3; grid-row: 1;
}
.feature-card form { margin: 0; display: inline-flex; }
.feature-card input[type="checkbox"] {
  width: 20px; height: 20px; min-height: 20px;
  margin: 0; accent-color: var(--accent);
}
.feature-card input[type="checkbox"]:disabled { opacity: .55; cursor: default; }
/* Один поясняющий текст под сеткой вместо повторов в каждой строке. */
.feature-note {
  margin: 10px 0 0;
  padding: 9px 12px;
  border-left: 3px solid var(--line-strong);
  border-radius: var(--radius-sm);
  background: var(--input);
  color: var(--muted);
  font-size: 12.5px;
  line-height: 1.5;
}

@media (max-width: 700px) {
  /* Узкий экран: цена и состояние уходят под название (одна колонка),
     переключатель/кнопка остаются справа и не переносятся — иначе
     название обрезается «…», а кнопка уезжает на новую строку. */
  .feature-card { grid-template-columns: minmax(0, 1fr) auto; }
  .feature-card input[type="checkbox"],
  .feature-card form { grid-column: 2; grid-row: 1 / span 3; align-self: center; }
}

/* ── Окно создания направления (09.11) ───────────────────────────────────
   Слово владельца: кнопка «Создать» на странице направлений открывает ОКНО
   с формой и тут же настройкой набора функций. Прежний отдельный адрес
   /workspaces/new остался запасной страницей: та же форма и тот же
   обработчик — окно лишь показывает её поверх списка.

   Почему нативный <dialog>, а не div с классом .modal: браузер сам держит
   фокус внутри окна, закрывает по Esc и возвращает фокус на кнопку. И, что
   важнее для формы с вводом, db_refresh.js уже считает `dialog[open]`
   признаком «человек занят» и НЕ перезагружает страницу, пока окно открыто
   (иначе тихое автообновление стёрло бы набранное название посреди работы). */
.ws-create-dialog {
  width: min(640px, calc(100vw - 24px));
  max-width: 640px;
  max-height: 90dvh;
  margin: auto;
  padding: 0;
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  background: var(--panel);
  color: var(--text);
  box-shadow: var(--shadow-hover);
  overflow: hidden;
}
.ws-create-dialog::backdrop { background: rgba(4, 6, 10, .62); }

/* First-use legal/risk acknowledgement uses the same modal language as the
   rest of the product instead of the browser's unstyled native dialog. */
.risk-ack-dialog {
  width: min(620px, calc(100vw - 24px));
  max-height: min(760px, calc(100dvh - 24px));
  overflow: auto;
  margin: auto;
  padding: clamp(20px, 4vw, 30px);
  border: 1px solid var(--line-strong);
  border-radius: var(--radius-lg);
  background: var(--panel);
  color: var(--text);
  box-shadow: 0 28px 90px rgba(0, 0, 0, .48);
}
.risk-ack-dialog::backdrop {
  background: rgba(4, 6, 10, .7);
  backdrop-filter: blur(4px);
}
.risk-ack-dialog h2 { margin: 0 0 12px; }
.risk-ack-dialog ul {
  margin: 0 0 18px;
  padding-left: 22px;
  color: var(--text-2);
}
.risk-ack-dialog li + li { margin-top: 9px; }
.risk-ack-dialog label {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 14px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel2);
}
.risk-ack-dialog input[type="checkbox"] {
  flex: 0 0 auto;
  width: 20px;
  min-height: 20px;
  margin: 2px 0 0;
}
@media (max-width: 560px) {
  .risk-ack-dialog { width: calc(100vw - 16px); max-height: calc(100dvh - 16px); }
  .risk-ack-dialog .actions > button { flex: 1 1 100%; width: 100%; }
}
.ws-create-dialog[open] { display: flex; flex-direction: column; }
.ws-create-box { display: flex; flex-direction: column; min-height: 0; max-height: inherit; width: 100%; }
.ws-create-form { display: flex; flex-direction: column; min-height: 0; }
.ws-create-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  padding: 16px 18px 10px;
  border-bottom: 1px solid var(--line);
}
.ws-create-head h2 { margin: 0 0 2px; font-size: 18px; }
.ws-create-head p { margin: 0; color: var(--muted); font-size: 12.5px; }
.ws-create-body { padding: 12px 18px 0; overflow-y: auto; min-height: 0; flex: 1 1 auto; }
.ws-create-body > label { margin-top: 10px; }
.ws-create-body input[name="name"] { margin-bottom: 10px; }
.ws-create-body textarea { min-height: 72px; }
.ws-create-foot {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  padding: 11px 18px;
  border-top: 1px solid var(--line);
  background: var(--panel);
}
.ws-create-foot .actions { margin: 0; }
.ws-create-foot .ws-create-sum { font-size: 13px; }
@media (max-width: 700px) {
  .ws-create-dialog {
    width: 100%;
    max-width: 100%;
    max-height: 94dvh;
    margin: auto auto 0;
    border-radius: 16px 16px 0 0;
    border-bottom: 0;
  }
  .ws-create-head { padding: 14px 15px 9px; }
  .ws-create-body { padding: 10px 15px 0; }
  .ws-create-foot { padding: 10px 15px calc(10px + env(safe-area-inset-bottom)); }
  .ws-create-foot .actions { width: 100%; }
  .ws-create-foot .ws-create-sum { width: 100%; }
}

/* ── «Как ИИ понимает сценарий» (10.11, перенос по каналам 11.11) ─────────
   Слово владельца 11.11 (скриншот): «этот блок надо перенести для каждой
   соц. сети, в настройках ИИ на её странице» + замечания к дизайну.

   Что было криво на скриншоте и что поправлено:
   1. Вместо иконок стояли «◻◻» — квадраты выпавших глифов. Здесь только
      маски проекта .ic-* (иконки без внешних шрифтов); в разметке блока
      эмодзи нет вовсе, поэтому и выпадать нечему.
   2. «Показать полностью» было крупной оранжевой кнопкой и спорило с
      кнопкой проверки. Раскрытие текста — не действие страницы: теперь это
      тихая текстовая ссылка .air-more.
   3. Метка времени — мелкая приглушённая подпись, а не второй заголовок.
   4. Бейдж модели прижат к правому краю шапки и выровнен по базовой линии
      заголовка.
   5. Заголовки секций — обычный текст (11px, uppercase, muted) с иконкой;
      списки — строки-плашки с аккуратными отступами.

   Префикс .air- (AI Review): .card/.pill переиспользуются как есть, новое
   заводится только там, где действительно нужно. */

.ai-review {
  margin-bottom: 18px;
  background: linear-gradient(135deg, var(--panel), color-mix(in srgb, var(--accent) 6%, var(--panel)));
}

/* Шапка: заголовок слева, бейдж модели справа. Baseline, а не center —
   заголовок крупнее бейджа, и по центру бейдж «висел» бы выше строки. */
.ai-review .air-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 10px 14px;
  flex-wrap: wrap;
  margin-bottom: 6px;
}
.ai-review .air-head h2 {
  display: flex; align-items: center; gap: 9px;
  font-size: 19px; margin: 0;
}
.ai-badge {
  background: var(--panel2);
  color: var(--text-2);
  border: 1px solid var(--line);
  font-size: 11.5px;
  font-weight: 700;
  white-space: nowrap;
}
.ai-badge.air-badge { background: var(--panel2); color: var(--text-2); border: 1px solid var(--line); }
.air-intro { margin: 6px 0 14px; font-size: 13px; max-width: 74ch; }

/* Две карточки в ряд на широком экране (обычные / главный аккаунт),
   в одну колонку на телефоне. minmax(0,1fr) — длинный текст не растягивает
   грид шире контейнера. */
.air-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.air-card {
  min-width: 0;
  padding: 16px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel2);
}
.air-card.is-running { border-color: var(--accent); }

/* Заголовок карточки и время под ним: время — тихая подпись, не второй
   заголовок (замечание владельца к «11.11 00:21 МСК»). */
.air-card-head { margin-bottom: 12px; }
.air-card-head h3 { margin: 0; font-size: 15px; font-weight: 700; }
.air-when {
  display: block;
  margin-top: 3px;
  color: var(--muted);
  font-size: 11.5px;
  font-variant-numeric: tabular-nums;
}

/* Блок = плашка со своей подложкой и подписью. Так «Понимание»,
   «Уточнения» и «Улучшения» читаются как разные вещи, а не как один
   сплошной текст. */
.air-block + .air-block { margin-top: 10px; }
.air-block {
  padding: 12px 13px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel);
}
.air-label {
  margin-bottom: 7px;
  color: var(--muted);
  font-size: 11px; font-weight: 800;
  letter-spacing: .08em; text-transform: uppercase;
}

/* Главный блок: понимание — крупнее остального текста и на мягкой
   акцентной подложке (акцент тот же, что одобрен в .hero-card). */
.air-understand {
  background: linear-gradient(135deg,
    color-mix(in srgb, var(--accent) 7%, transparent), transparent 70%);
  border-color: color-mix(in srgb, var(--accent) 24%, var(--line));
}
.air-text {
  margin: 0;
  font-size: 14.5px;
  line-height: 1.6;
  color: var(--text);
  overflow-wrap: anywhere;
}
/* Четыре строки по умолчанию: длинный разбор не превращает страницу в
   полотно. Раскрытие — ссылка «Показать полностью» (airExpand в
   ai_review_card.py), она же снимает класс.
   «По умолчанию» — буквально: обрезка стоит здесь, а не приходит из JS.
   Так текст не «прыгает» на первой отрисовке, а если скрипт не доехал,
   человек всё равно может раскрыть текст кнопкой. Скрипт (airMeasure)
   снимает обрезку и кнопку там, где четыре строки вмещают текст целиком. */
.air-text.is-clamped,
.air-text.air-clampable {
  display: -webkit-box;
  -webkit-line-clamp: 4;
  line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
/* Кнопка, у которой раскрывать нечего, скрыта скриптом (см. airFit). */
.air-more[hidden] { display: none; }
/* Раскрытие — ТЕКСТОВАЯ ссылка, а не кнопка: через общий селектор
   `button { background: var(--accent) }` это была крупная оранжевая
   плашка, которая спорила с кнопкой проверки (замечание владельца).
   Гасим кнопочную базу целиком: фон, рамку, высоту, вес. */
.air-more {
  display: inline;
  margin: 8px 0 0;
  padding: 0;
  min-height: 0;
  border: 0;
  background: none;
  box-shadow: none;
  color: var(--accent);
  font-family: inherit;
  font-size: 12.5px;
  font-weight: 700;
  line-height: 1.4;
  text-align: left;
  cursor: pointer;
}
.air-more:hover { filter: none; text-decoration: underline; }
.air-more:active { transform: none; }
.air-more:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }

/* Списки: строка-плашка на пункт, текст переносится по словам. Никаких
   эмодзи-маркеров — иконок здесь нет вовсе (частые иконки на каждый пункт
   превращали список в рябь); акцент даёт сама плашка. */
.air-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
.air-item {
  display: flex; align-items: flex-start; gap: 9px;
  padding: 8px 10px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--input);
  font-size: 13px;
  line-height: 1.5;
  overflow-wrap: anywhere;
}
/* Предложения — то, что можно улучшить: акцентная подсветка, чтобы
   отличались от нейтральных «уточнений». */
.air-tips { border-color: color-mix(in srgb, var(--accent) 26%, var(--line)); }
.air-tips .air-item { border-color: color-mix(in srgb, var(--accent) 18%, var(--line)); }

/* ── «Уточнить»: вопрос ИИ + поле ответа владельца (слово владельца 11.11).
   Вопрос и кнопка в одну строку (кнопка не сжимается), поле раскрывается
   ПОД вопросом и не сдвигает соседние пункты: список — grid, поэтому
   раскрытие «толкает» только свою строку. */
.air-ask-item { display: block; }
.air-ask-row {
  display: flex; align-items: flex-start; gap: 10px;
}
.air-ask-q { flex: 1 1 auto; min-width: 0; }
.air-ask-btn {
  flex: 0 0 auto;
  padding: 3px 9px;
  border: 1px solid var(--line);
  border-radius: 999px;
  background: var(--panel);
  color: var(--text-2);
  font-size: 11.5px;
  font-weight: 700;
  cursor: pointer;
  white-space: nowrap;
}
.air-ask-btn:hover { filter: brightness(1.06); }
.air-ask-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
/* Отвеченный вопрос: зелёная рамка + сам ответ под вопросом. Человек должен
   видеть, что он уже ответил, иначе ответит второй раз. */
.air-ask-item.is-answered { border-color: color-mix(in srgb, var(--success) 34%, var(--line)); }
.air-ask-answer {
  margin: 6px 0 0;
  font-size: 12.5px;
  line-height: 1.5;
  color: var(--text-2);
  overflow-wrap: anywhere;
}
.air-ask-answer-label { color: var(--success); font-weight: 700; }
.air-answer { margin-top: 9px; }
.air-answer[hidden] { display: none; }
.air-answer textarea {
  width: 100%;
  box-sizing: border-box;
  min-height: 64px;
  padding: 9px 10px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel);
  color: var(--text);
  font: inherit;
  font-size: 13px;
  line-height: 1.5;
  resize: vertical;
}
.air-answer textarea:focus-visible {
  outline: 2px solid var(--accent); outline-offset: 1px;
}
.air-answer-acts {
  display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
  margin-top: 8px;
}
.air-answer-note { font-size: 12px; color: var(--muted); }
.air-answer-note.is-bad { color: var(--danger); }
.air-askadmin { display: none; }

/* Пусто / ошибка — компактная плашка, а не пустая половина карточки.
   Технический текст ошибки остаётся в логе (_ai_review_worker). */
.air-ok, .air-fail {
  display: flex; align-items: center; gap: 9px; flex-wrap: wrap;
  padding: 11px 12px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--success-soft);
  color: var(--success);
  font-size: 13px;
}
.air-ok .ic { color: var(--success); }
.air-fail {
  background: var(--danger-soft);
  border-color: color-mix(in srgb, var(--danger) 32%, var(--line));
  color: var(--text-2);
}
.air-fail .ic { color: var(--danger); }
.air-fail .air-run { margin-left: auto; }
/* Пояснение под причиной сбоя и строка «разбор сделала резервная
   модель» (11.11). Отдельная строка на всю ширину плашки: именно её
   человек читает, чтобы понять, ЧТО делать, — поэтому она не должна
   сжиматься в один ряд с кнопкой. */
.air-fail-hint {
  flex-basis: 100%;
  color: var(--muted);
  font-size: 12.5px;
  line-height: 1.45;
}
.air-alt-model {
  display: flex; align-items: flex-start; gap: 8px;
  margin: 0 0 12px; padding: 9px 11px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--input);
  color: var(--muted); font-size: 12.5px; line-height: 1.45;
}
.air-empty { margin: 0; font-size: 13px; }

.air-wait {
  display: flex; align-items: center; gap: 9px;
  margin: 0 0 12px;
  color: var(--muted); font-size: 12.5px;
}
/* Спиннер — свой, а не иконка: .ic-* в icons.css не трогаем (иначе
   пришлось бы бампать ICONS_VERSION ради одного символа). */
.air-spinner {
  flex: 0 0 auto;
  width: 13px; height: 13px;
  border: 2px solid color-mix(in srgb, var(--accent) 30%, transparent);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: air-spin .9s linear infinite;
}
@keyframes air-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
  .air-spinner { animation-duration: 3s; }
}
.air-foot { margin-top: 14px; }
.air-foot .air-run { min-height: 40px; }

@media (max-width: 900px) {
  .air-grid { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 700px) {
  .ai-review { padding: 15px 14px; }
  .ai-review .air-head h2 { font-size: 17px; }
  /* Бейдж модели на телефоне уходит ПОД заголовок (иначе он выдавливал
     заголовок в две строки и обрезался справа). */
  .ai-review .air-badge { order: 3; }
  .air-card { padding: 13px; }
  .air-text { font-size: 14px; }
  /* Кнопка проверки — на всю ширину: палец должен попадать без прицела. */
  .air-foot .air-run { width: 100%; }
  .air-fail .air-run { margin-left: 0; width: 100%; }
  /* Вопрос и «Уточнить» на телефоне — в две строки: кнопка справа от
     длинного вопроса выдавливала текст в узкую колонку и рвала слова. */
  .air-ask-row { flex-wrap: wrap; }
  .air-ask-btn { width: 100%; margin-top: 6px; }
  .air-answer-acts .btn-sm { flex: 1 1 auto; }
}

/* ============ 21. МОНИТОРИНГ: карточки и таблица инцидентов ============= */
/* Слово владельца 10.11: «слишком вытянутое и бесполезно вытянутое, и при
   этом не вся информация помещается». Три причины и три правки:

   1. ВЫСОТА. Сетка по умолчанию растягивает элементы строки (stretch), и
      карточка «Аккаунты» тянулась под высоту соседней таблицы — пустота на
      сотни пикселей. align-self:start возвращает карточке её собственную
      высоту; в ряду они друг на друга больше не влияют.
   2. ШИРИНА. Широкая колонка .grid2 (1.25fr) отдана инцидентам — там
      длинные тексты; узкая (0.75fr) — короткой карточке аккаунтов. Плюс
      min-width:0: без него grid-элемент не даёт содержимому сжиматься, и
      таблица выходила за правый край карточки.
   3. ЧИТАЕМОСТЬ. Имя аккаунта — одна строка с многоточием (полное в
      title), причина переносится, а не обрезается, одинаковые записи
      собраны в одну строку со счётчиком «×N» (рендер — renderIncidents в
      app/main.py). */

/* Карточка в ряду — по собственной высоте, не по высоте соседа. */
.mon-card { align-self: start; min-width: 0; }
/* Потолок высоты: очень длинный список не должен уводить карточку за
   экран — прокрутка внутри карточки, а не на странице целиком. Селектор
   БЕЗ «>»: таблица лежит не прямо в карточке, а в контейнере-приёмнике
   (#mIncidents: <section class="card"><div id="mIncidents">…) — с дочерним
   комбинатором правило не срабатывало. */
.mon-card .table-container { max-height: 460px; overflow-y: auto; }

/* «Всё хорошо» / «инцидентов нет»: компактная плашка вместо абзаца,
   оставлявшего под собой полкарточки пустоты. */
.mon-empty {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel2);
}
.mon-empty-ic {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex: 0 0 auto;
  width: 34px;
  height: 34px;
  border-radius: 50%;
  background: var(--success-soft);
  color: var(--success);
  font-size: 17px;
}
.mon-empty b { display: block; font-size: 14px; line-height: 1.3; }
.mon-empty .muted { display: block; font-size: 12.5px; line-height: 1.35; margin-top: 2px; }

/* --- Таблица инцидентов --- */
/* table-layout:fixed — таблица НЕ раздувается под длинный текст: ширины
   колонок берутся из первой строки, а не из самого длинного содержимого.
   Раньше именно это выпихивало таблицу за правый край карточки. */
.mon-incidents { table-layout: fixed; }
/* Ширины — по ЗАМЕРУ реального содержимого (headless-проба 10.11):
   пилюля «Предупреждение» = 127px + 28px отступов ячейки = 155px;
   дата «2026-11-09 20:14» = 120px. Колонки уже этого заставляли пилюлю
   вылезать в соседнюю ячейку, а дату — распирать таблицу на 12px за
   контейнер. Отсюда 158px и 124px с запасом.
   Остальное отдано «Что случилось» — единственной растущей колонке. */
.mon-incidents th:nth-child(1), .mon-incidents td:nth-child(1) { width: 158px; }
.mon-incidents th:nth-child(2), .mon-incidents td:nth-child(2) { width: 30%; }
.mon-incidents th:nth-child(4), .mon-incidents td:nth-child(4) { width: 124px; }
/* Заголовки в этой таблице обрезаются, а не распирают колонку: «Важность»
   и «Что случилось» в узкой шапке иначе уносят её за край. Полные слова —
   в title ячейки. */
.mon-incidents th {
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Аккаунт — одна строка с многоточием; полное имя в атрибуте title.
   Вложенный b (а не сама ячейка) — потому что в мобильной раскладке
   .mobile-cards td становится блоком, и обрезка должна остаться на тексте. */
.mon-incidents .mon-acc { min-width: 0; }
.mon-incidents .mon-acc b {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/* «Что случилось» — переносится, а не обрезается (жалоба владельца:
   «Too many request… by SendMessage» не влезало). anywhere — чтобы
   длинный токен без пробелов тоже переносился, а не выпихивал таблицу. */
.mon-incidents .mon-what {
  min-width: 0;
  white-space: normal;
  overflow-wrap: anywhere;
  line-height: 1.4;
}
.mon-reason { color: var(--text-2); }
/* Счётчик одинаковых: три «Милена — Too many requests» → одна строка ×3. */
.mon-times {
  display: inline-block;
  margin-left: 8px;
  padding: 2px 8px;
  border-radius: var(--radius-pill);
  background: var(--chip);
  color: var(--muted);
  font-size: 11px;
  font-weight: 700;
  white-space: nowrap;
  vertical-align: 1px;
}
.mon-when { white-space: nowrap; }

/* Полный исходный текст — «подробнее» в той же ячейке: строка остаётся
   короткой, но ничего не теряется. */
.mon-more { margin-top: 4px; }
.mon-more > summary {
  display: inline-block;
  color: var(--accent);
  font-size: 11.5px;
  font-weight: 700;
  cursor: pointer;
  list-style: none;
}
.mon-more > summary::-webkit-details-marker { display: none; }
.mon-more > summary::after { content: " ›"; }
.mon-more[open] > summary::after { content: " ⌄"; }
.mon-more > span {
  display: block;
  margin-top: 3px;
  font-size: 12px;
  overflow-wrap: anywhere;
}

@media (max-width: 900px) {
  /* Одна колонка: карточки идут друг под другом — растягивать нечего. */
  .mon-card { align-self: stretch; }
  .mon-card .table-container { max-height: none; overflow-y: visible; }
}

@media (max-width: 700px) {
  /* На телефоне таблицы превращаются в карточки (раздел 7, .mobile-cards):
     фиксированные ширины колонок там только мешают. Правила продублированы
     ниже отдельным блоком БЕЗ зависимости от .mobile-cards: та раскладка
     навешивается скриптом (js/main.js, labelTables), а страница обязана
     читаться и до его срабатывания, и при отключённом JS. */
  .mon-incidents { table-layout: auto; }
  .mon-incidents th, .mon-incidents td,
  .mon-incidents th:nth-child(1), .mon-incidents td:nth-child(1),
  .mon-incidents th:nth-child(2), .mon-incidents td:nth-child(2),
  .mon-incidents th:nth-child(4), .mon-incidents td:nth-child(4) { width: auto; }
  .mon-incidents .mon-acc b { white-space: normal; overflow: visible; text-overflow: clip; }
  .mon-when { white-space: normal; }
}

/* Узкий экран (телефон) — БЕЗ зависимости от .mobile-cards: шапка с
   nowrap-заголовками и пилюля «Предупреждение» (141px) иначе распирают
   таблицу шире карточки и дают горизонтальный скролл (замер 10.11: 456px
   таблицы при карточке 332px). Здесь таблица сжимается и переносит текст. */
@media (max-width: 700px) {
  .mon-incidents th { white-space: normal; overflow: visible; text-overflow: clip; }
  .mon-incidents .pill { white-space: normal; }
}

/* ==========================================================================
   KB-НАБОР — вид для трёх страниц кабинета (слово владельца 11.11 12:46):

     · настройки направления (Р-10): «дизайн устарел, обнови дизайн»,
       «здесь дизайн кривой, кнопки выполняют не ту функцию»;
     · карточки каналов (№O);
     · таблица аккаунтов (№N).

   ЭТАЛОН ВКУСА — страница «Умный разбор» (app/smart_analysis_page.py, слово
   владельца «стиль страницы с умным разбором сильно лучше остальных»):
   мягкая подложка шапки, карточки-плитки с крупной цифрой и подписью под
   ней, секции с иконкой-квадратом в заголовке, спокойные разделители и
   приглушённые подписи. Здесь тот же язык, но БЕЗ правки чужих файлов:
   страницы живут в занятых файлах (workspaces.py / channels_hub.py /
   main.py), поэтому вид отдан классам, а не правкой разметки.

   ГРАНИЦЫ (жёстко):
   1. Блок ДОПИСАН В КОНЕЦ файла. Ни одно правило выше не тронуто.
   2. Пространство имён — .kb-*. Другие агенты дописывают сюда же .prem-*
      и .fit-*; пересечений нет по построению (общий префикс невозможен).
   3. Ни один селектор этого блока не повторяет уже существующий: блок
      только ДОБАВЛЯЕТ вид новым классам и не переопределяет общие
      .card/.btn/.acct-* — иначе поехали бы чужие страницы.
   4. Доступ к функциям не сокращается. Здесь нет ни одного display:none
      на содержимом и ни одного скрытия колонки: единственное исключение —
      ::-webkit-details-marker у кнопки «⋯», где прячется СИСТЕМНЫЙ
      треугольник, а само меню раскрывается нажатием как и раньше.
      Всё, что было видно, остаётся видно.
   ========================================================================== */

/* ---------------------- 1. Лист настроек направления --------------------- */
/* Раньше страница была ОДНОЙ гигантской карточкой: тринадцать <h2> одного
   веса подряд, между ними поля вразнобой, а «Сохранить» — одна кнопка в
   самом низу, до которой на длинной странице надо было долистать. Глаз не
   находил границ разделов, а кнопка сохранения терялась.

   Теперь каждая тема — своя секция .kb-sec с заголовком-строкой (квадрат с
   иконкой, название, справа состояние), поля — равной сеткой .kb-grid, а
   сохранение — постоянная полоса .kb-save-bar внизу экрана: кнопка всегда
   на виду, независимо от того, до какой секции человек долистал. */

.kb-sheet { display: grid; gap: 14px; min-width: 0; }

/* Шапка-лист: те же токены, что у .hero, но собственная мягкая подложка —
   страница настроек перестаёт быть «просто списком карточек». */
.kb-sheet-head {
  position: relative;
  overflow: hidden;
  min-width: 0;
  padding: 24px 26px;
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  background: linear-gradient(135deg, var(--hero1),
    color-mix(in srgb, var(--accent) 7%, var(--hero2)));
}
.kb-sheet-head h1 { margin: 4px 0 6px; font-size: 28px; }
.kb-sheet-lead {
  margin: 0;
  max-width: 74ch;
  color: var(--muted);
  font-size: 13.5px;
  line-height: 1.55;
}
/* Строка фактов в шапке: чипы «что здесь настроено сейчас». Это ответ на
   «устаревший дизайн» без выдуманных полей — только то, что страница и так
   знает: имя, лимит на аккаунт, режим ИИ. */
.kb-sheet-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 14px;
}
.kb-tag {
  display: inline-flex;
  align-items: baseline;
  gap: 6px;
  max-width: 100%;
  padding: 5px 11px;
  border: 1px solid var(--line);
  border-radius: var(--radius-pill);
  background: var(--chip);
  color: var(--text-2);
  font-size: 12px;
  font-weight: 600;
  line-height: 1.35;
  overflow-wrap: anywhere;
}
.kb-tag b { color: var(--text); font-weight: 700; }
.kb-tag.is-on { border-color: var(--accent); color: var(--accent); }
.kb-tag.is-off { border-color: var(--line-strong); color: var(--muted); }

/* Секция настроек. */
.kb-sec {
  min-width: 0;
  padding: 20px 22px;
  border: 1px solid var(--line);
  border-radius: 16px;
  background: var(--panel);
}
.kb-sec > * { min-width: 0; }

.kb-sec-head {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 10px 12px;
  margin-bottom: 12px;
  min-width: 0;
}
/* Квадрат-подложка иконки — тот же приём, что .hub-ico и .sa-card h2 .ic:
   34px, приглушённый фон, акцентный глиф. */
.kb-sec-ic {
  display: grid;
  place-items: center;
  flex: 0 0 auto;
  width: 34px;
  height: 34px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--chip);
  color: var(--accent);
  font-size: 15px;
}
.kb-sec-title {
  flex: 1 1 auto;
  min-width: 0;
  margin: 0;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: -.01em;
  overflow-wrap: anywhere;
}
/* Правая часть заголовка — состояние секции (вкл/выкл, «изменено»…).
   margin-left:auto прижимает к краю, но при нехватке места уезжает на
   свою строку ЦЕЛИКОМ, а не обрезается. */
.kb-sec-side {
  flex: 0 0 auto;
  margin-left: auto;
  align-self: center;
}
.kb-sec-note {
  margin: 0 0 14px;
  max-width: 78ch;
  color: var(--muted);
  font-size: 12.8px;
  line-height: 1.6;
}

/* Сетка однотипных полей: подбирает число дорожек сама — одинокого поля в
   половине ряда не бывает (тот же принцип, что у .fields-grid, но со своим
   воздухом и без наследования чужого потолка ширины). */
.kb-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
  gap: 12px 14px;
}
.kb-grid > * { min-width: 0; }
/* Поле: подпись над контролом, мелкая подсказка под ним. Сами input/
   select/textarea здесь не стилизуются — их общий вид задан базой
   (раздел 4), и переопределять его значило бы менять соседние страницы. */
.kb-field { min-width: 0; }
.kb-field > label { margin-bottom: 5px; }
.kb-field-hint {
  margin: 5px 0 0;
  color: var(--muted);
  font-size: 11.8px;
  line-height: 1.45;
}
/* Строка с одной галочкой: подпись справа от флажка, по центру строки. */
.kb-check {
  display: flex;
  align-items: flex-start;
  gap: 9px;
  min-width: 0;
  font-size: 13px;
  line-height: 1.5;
}
.kb-check > span { min-width: 0; overflow-wrap: anywhere; }

/* Полоса сохранения. Живёт внизу и не уезжает: на длинной странице
   настроек кнопка «Сохранить» перестаёт быть «где-то в конце».
   Не fixed — sticky, потому что страница живёт в обычном потоке, а
   fixed в мини-приложении Telegram перекрывает нижние элементы. */
.kb-save-bar {
  position: sticky;
  bottom: 0;
  z-index: 5;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px 14px;
  min-width: 0;
  padding: 12px 16px;
  border: 1px solid var(--line-strong);
  border-radius: 14px;
  background: color-mix(in srgb, var(--panel) 92%, var(--bg));
  box-shadow: 0 -10px 24px rgba(0, 0, 0, .22);
}
.kb-save-hint {
  flex: 1 1 220px;
  min-width: 0;
  margin: 0;
  color: var(--muted);
  font-size: 12px;
  line-height: 1.45;
}
.kb-save-bar .kb-save-act { flex: 0 0 auto; margin-left: auto; }

/* Переключатель режима ИИ на три положения: «ИИ отвечает сам / черновики /
   выключен». Это и есть ответ на «кнопка выполняет не ту функцию»: одна
   кнопка-переключатель не могла выразить среднее положение и затирала его
   при каждом нажатии. Вид — сегмент склеенных кнопок (как .ai-mode-switch
   в диалогах). */
.kb-mode {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 0;
  max-width: 100%;
}
.kb-mode-opt {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  min-height: var(--tap);
  margin: 0 0 0 -1px;
  padding: 9px 14px;
  border: 1px solid var(--line);
  background: var(--panel);
  color: var(--text-2);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
}
.kb-mode-opt:first-child {
  margin-left: 0;
  border-radius: var(--radius-sm) 0 0 var(--radius-sm);
}
.kb-mode-opt:last-child {
  border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
}
.kb-mode-opt input[type="radio"] {
  width: 16px;
  height: 16px;
  min-height: 16px;
  margin: 0;
}
/* Выбранное положение помечается ДВУМЯ независимыми способами, и это не
   дубль, а страховка: сервер ставит класс is-active на нужном варианте
   (нужен и до срабатывания скриптов, и в браузере без :has), а :has()
   подсвечивает вариант, который человек выбрал только что, — до
   перезагрузки страницы. Прошлый вид опирался на data-атрибут, который
   забывали обновлять, и подсветка врала. */
.kb-mode-opt.is-active,
.kb-mode-opt:has(input[type="radio"]:checked) {
  border-color: var(--accent);
  background: var(--accent-soft);
  color: var(--accent);
}
.kb-mode-opt:hover { border-color: var(--line-strong); }
.kb-mode-opt:focus-within { box-shadow: var(--focus-ring); }

/* Плашка-пояснение внутри секции (например «эта настройка общая на все
   направления»). Тон спокойный: это объяснение, а не ошибка. */
.kb-callout {
  display: flex;
  align-items: flex-start;
  gap: 9px;
  min-width: 0;
  margin: 0 0 12px;
  padding: 11px 13px;
  border: 1px solid var(--line);
  border-left: 3px solid var(--accent);
  border-radius: 10px;
  background: color-mix(in srgb, var(--accent) 5%, var(--panel));
  color: var(--text-2);
  font-size: 12.8px;
  line-height: 1.55;
}
.kb-callout > span { min-width: 0; overflow-wrap: anywhere; }

/* --------------------------- 2. Карточки каналов ------------------------- */
/* Сетка карточек хаба. Число колонок ступенями, а не auto-fit: карточек
   шесть, и ступени выбраны так, чтобы последний ряд был полон (6 = 3×2 =
   2×3 = 1×6) — справа не остаётся пустоты, на которую жаловался владелец. */
.kb-ch-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 16px;
  margin-top: 16px;
}
@media (max-width: 1100px) { .kb-ch-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 680px)  { .kb-ch-grid { grid-template-columns: minmax(0, 1fr); } }

.kb-ch {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
  padding: 18px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: var(--panel);
  transition: border-color var(--transition), box-shadow var(--transition);
}
.kb-ch:hover { border-color: var(--line-strong); box-shadow: var(--shadow); }
/* Канал, который не входит в набор функций направления: приглушён, но
   читаем — это объявление, а не ошибка. */
.kb-ch-off { opacity: .75; }

.kb-ch-head {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px 12px;
  min-width: 0;
}
.kb-ch-ico {
  display: grid;
  place-items: center;
  flex: 0 0 auto;
  width: 44px;
  height: 44px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--chip);
  color: var(--accent);
  font-size: 20px;
}
.kb-ch-name {
  flex: 1 1 auto;
  min-width: 0;
  margin: 0;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: -.01em;
  overflow-wrap: anywhere;
}
/* Бейдж состояния: не сжимается, при нехватке места переносится целиком.
   Подпись короткая — длинная форма обрезалась на «нет аккаунто…». */
.kb-ch-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  flex: 0 0 auto;
  margin-left: auto;
  padding: 4px 10px;
  border-radius: var(--radius-pill);
  background: var(--chip);
  color: var(--muted);
  font-size: 11.5px;
  font-weight: 700;
  white-space: nowrap;
}
.kb-ch-badge::before {
  content: "";
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: currentColor;
}
.kb-ch-badge.is-on   { background: var(--accent-soft); color: var(--accent); }
.kb-ch-badge.is-idle { background: var(--chip);        color: var(--muted); }
.kb-ch-badge.is-off  { background: var(--chip);        color: var(--muted); opacity: .85; }

/* Ключевые числа крупно: «25 аккаунтов · 20 активных» читаются с одного
   взгляда, в отличие от прежней серой строки вполсилы. */
.kb-ch-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 22px;
}
.kb-ch-stat { min-width: 0; }
.kb-ch-stat b {
  display: block;
  font-size: 25px;
  font-weight: 700;
  line-height: 1.05;
  letter-spacing: -.03em;
  color: var(--text);
  font-variant-numeric: tabular-nums;
}
.kb-ch-stat span {
  display: block;
  margin-top: 3px;
  color: var(--muted);
  font-size: 12.5px;
  font-weight: 500;
}
.kb-ch-desc {
  margin: 0;
  color: var(--muted);
  font-size: 13px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.kb-ch-note {
  margin: 0;
  color: var(--muted);
  font-size: 12px;
  line-height: 1.5;
}
/* Кнопки прижаты к низу карточки: в ряду они стоят на одной линии. */
.kb-ch-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
  justify-content: flex-end;
  gap: 8px;
  margin-top: auto;
}
.kb-ch-actions .btn { min-height: var(--tap); }
@media (max-width: 560px) {
  .kb-ch-actions { justify-content: stretch; }
  .kb-ch-actions .btn { flex: 1 1 0; }
}

/* ------------------------- 3. Таблица аккаунтов -------------------------- */
/* Было: строка распиралась по высоте столбиком крупных кнопок справа,
   ячейки без общей рамки, состояния помечались заливкой всей строки в
   тревожный оттенок. Стало: таблица в своей рамке, шапка липнет при
   прокрутке, действия — одной тихой строкой, состояние читается цветом
   подписи, а не заливкой строки.

   ВАЖНО: ни одна колонка не скрывается — «из дизайна не должен пропасть
   доступ ни к одной функции». На телефоне таблица по-прежнему превращается
   в карточки штатным .mobile-cards (js/main.js), и правила ниже этому не
   мешают: телефонный блок повторяет те же отступы. */
.kb-tbl-wrap {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  min-width: 0;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--panel);
}
.kb-tbl {
  width: 100%;
  border-collapse: collapse;
  font-size: 13.5px;
}
.kb-tbl thead th {
  position: sticky;
  top: 0;
  z-index: 1;
  padding: 11px 12px;
  background: var(--panel2);
  color: var(--muted);
  font-size: 11px;
  font-weight: 700;
  letter-spacing: .06em;
  text-transform: uppercase;
  text-align: left;
  white-space: nowrap;
}
.kb-tbl td {
  padding: 10px 12px;
  border-top: 1px solid var(--line);
  vertical-align: middle;
  text-align: left;
}
.kb-tbl tbody tr:first-child td { border-top: 0; }
.kb-tbl tbody tr:hover { background: var(--panel2); }

/* Ячейка «кто это»: фото, имя/телефон, служебные подписи. */
.kb-acct {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}
.kb-acct-photo {
  flex: 0 0 auto;
  width: 38px;
  height: 38px;
  border-radius: 50%;
  object-fit: cover;
  display: grid;
  place-items: center;
  background: var(--panel2);
  color: var(--muted);
  font-size: 14px;
  font-weight: 800;
}
.kb-acct-txt { min-width: 0; }
.kb-acct-txt b {
  display: block;
  font-size: 13.5px;
  overflow-wrap: anywhere;
}
.kb-acct-id {
  display: block;
  margin-top: 2px;
  color: var(--muted);
  font-size: 11.5px;
  font-variant-numeric: tabular-nums;
  overflow-wrap: anywhere;
}

/* Числа дня и здоровья: цифры одной ширины, чтобы столбец не «плясал». */
.kb-acct-stat { white-space: nowrap; }
.kb-acct-stat b {
  display: block;
  font-size: 13.5px;
  font-variant-numeric: tabular-nums;
}
.kb-acct-stat small {
  display: block;
  margin-top: 2px;
  color: var(--muted);
  font-size: 11.5px;
  line-height: 1.35;
  white-space: normal;
}

/* Действия — одна тихая строка. Опасное действие уходит в меню «⋯»
   (в разметке это <details>), поэтому строка не растёт в столбик. */
.kb-acct-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
  justify-content: flex-end;
}
.kb-acct-act {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  min-height: 32px;
  padding: 6px 10px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel2);
  color: var(--text);
  font-size: 12.5px;
  font-weight: 600;
  text-decoration: none;
  cursor: pointer;
  transition: border-color var(--transition), color var(--transition);
}
.kb-acct-act:hover { border-color: var(--line-strong); }
.kb-acct-act:focus-visible { outline: none; box-shadow: var(--focus-ring); }
.kb-acct-act .ic { font-size: 13px; opacity: .85; }
/* Включено — акцент; выключено — тихо; опасное — краснеет только при
   наведении и в раскрытом меню. */
.kb-acct-act.is-on { border-color: var(--accent); color: var(--accent); }
.kb-acct-act.is-off { color: var(--muted); }
.kb-acct-act.is-danger { color: var(--muted); justify-content: flex-start; }
.kb-acct-act.is-danger:hover {
  border-color: var(--danger);
  color: var(--danger);
  background: var(--danger-soft);
}

/* Раскрывающееся меню «ещё действия»: тот же механизм <details>, что в
   таблице сейчас, но вид спокойнее и без наезда на соседнюю строку. */
.kb-acct-more { position: relative; display: inline-flex; }
.kb-acct-more > summary {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  min-height: 32px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel2);
  color: var(--muted);
  cursor: pointer;
  list-style: none;
}
.kb-acct-more > summary::-webkit-details-marker { display: none; }
.kb-acct-more > summary::marker { content: ''; }
.kb-acct-more > summary:hover { border-color: var(--line-strong); color: var(--text); }
.kb-acct-more[open] > summary { border-color: var(--line-strong); color: var(--text); }
.kb-acct-more-menu {
  position: absolute;
  right: 0;
  top: calc(100% + 4px);
  z-index: 20;
  min-width: 210px;
  padding: 4px;
  border: 1px solid var(--line-strong);
  border-radius: var(--radius-sm);
  background: var(--panel);
  box-shadow: var(--shadow);
}

/* Тон строки вместо заливки: строка с проблемой помечается полосой слева,
   остальное остаётся читаемым. Цвета — токены статусов. */
.kb-row-warn td { box-shadow: inset 3px 0 0 var(--warning); }
.kb-row-bad td  { box-shadow: inset 3px 0 0 var(--danger); }
.kb-row-mute td { opacity: .72; }

/* Пустое состояние таблицы: объяснение, а не пустая рама. */
.kb-empty {
  padding: 26px 18px;
  border: 1px dashed var(--line);
  border-radius: 12px;
  color: var(--muted);
  text-align: center;
  font-size: 13px;
  line-height: 1.55;
}

/* --------------------------- 4. Телефон ---------------------------------- */
@media (max-width: 760px) {
  .kb-sheet-head { padding: 20px 17px; border-radius: 16px; }
  .kb-sheet-head h1 { font-size: 23px; }
  .kb-sec { padding: 16px 15px; border-radius: 14px; }
  .kb-grid { grid-template-columns: minmax(0, 1fr); }
  /* Полоса сохранения на телефоне — на всю ширину, кнопка тоже: палец не
     должен целиться в узкую кнопку у края. */
  .kb-save-bar { padding: 10px 12px; gap: 8px; }
  .kb-save-bar .kb-save-act { margin-left: 0; width: 100%; }
  .kb-save-bar .kb-save-act > button { width: 100%; }
  /* Таблица: те же отступы, что у карточной раскладки .mobile-cards, —
     так блок kb-набора не спорит с уже работающим телефонным видом. */
  .kb-tbl td { padding: 6px 0; border-top: 0; }
  .kb-tbl thead th { padding: 8px 6px; }
  .kb-acct-actions { justify-content: flex-start; }
  .kb-acct-more { position: static; }
  .kb-acct-more-menu {
    position: static;
    min-width: 0;
    margin-top: 6px;
    box-shadow: none;
  }
}

/* ==========================================================================
   УПЛОТНЕНИЕ ВЁРСТКИ И ЕДИНЫЙ ВИД ОКОН (.fit-*) — задачи владельца №63 и №71

   СЛОВО ВЛАДЕЛЬЦА (задача №63 реестра): «Слишком вытянутое, не вся
   информация помещается». Замер живого рендера (headless Chrome, 1440×900,
   12.11) показал, о чём речь: настройки направления — 4977px высоты,
   аналитика компании — 3116px, база знаний — 3003px, «Доступ к
   приложению» — 2832px, «AI и сценарий» — 2762px, лиды — 2669px. На
   экране ноутбука это 3–5 экранов прокрутки, и до половины блоков человек
   не доходит вовсе.

   СЛОВО ВЛАДЕЛЬЦА (задача №71): «Окно не вписывается в дизайн».
   Модальные окна в продукте сделаны ЧЕТЫРЬМЯ разными способами: нативный
   <dialog class="ws-create-dialog"> (создание направления), нативный
   <dialog class="crm-lead-dialog"> (карточка лида), div с inline-стилями
   (окно выбора чатов для обучения, #ltModal) и div .forward-picker (пересылка
   сообщения). Отсюда разные скругления (14 / 18 / 16), разные отступы
   шапки, разные затемнения подложки (.45 / .58 / .62) и разные слои
   (60 / 190 / 200). Человек видит четыре «разных продукта».

   ПОЧЕМУ ОТДЕЛЬНЫЙ БЛОК, А НЕ ПРАВКА СУЩЕСТВУЮЩИХ ПРАВИЛ. В style.css
   одновременно пишут три агента (`.prem-*` — дизайн-мелочи, `.kb-*` — база
   знаний, `.fit-*` — уплотнение). Правка чужих правил = тихая поломка их
   работы и их пинов. Поэтому здесь ТОЛЬКО ДОБАВЛЕНИЕ: ни одно правило выше
   не изменено байт-в-байт (это стережёт tests/test_fit_density_unified_modals.py).

   ЧТО ЗДЕСЬ ЕСТЬ:
     1. Плотность: сетки в 2–3 колонки вместо одной простыни (.fit-split,
        .fit-cols), компактные отступы внутри карточки (.fit-dense),
        сжатая шапка страницы (.fit-hero-tight).
     2. Окна: один набор классов на ВСЕ окна (.fit-modal + .fit-modal-box/
        -head/-body/-foot), одинаковые скрипт- и div-окна (.fit-overlay).
     3. Телефон: при ≤900px любая многоколоночная сетка схлопывается в одну
        колонку, окно поднимается снизу листом (как уже делает окно
        создания направления).

   ГЛАВНОЕ ОГРАНИЧЕНИЕ ВЛАДЕЛЬЦА: «из дизайна не должен пропасть доступ ни
   к одной функции». Поэтому здесь НЕТ правил `display: none`, `overflow:
   hidden` на содержимом и обрезки текста: уплотнение — это отступы и число
   колонок, а не спрятанные блоки. Ни один элемент не исчезает.
   ========================================================================== */

/* ── 1. ПЛОТНОСТЬ: МНОГОКОЛОНОЧНЫЕ СЕТКИ ──────────────────────────────────
   .fit-split кладётся на ОБЁРТКУ нескольких карточек: её прямые дети встают
   в 2 колонки вместо вертикальной простыни.

   minmax(min(340px, 100%), 1fr) — не «магия»: min() не даёт дорожке стать
   ШИРЕ контейнера на узком экране (иначе 340px внутри 300px даёт
   горизонтальный скролл, который владелец запретил отдельно: «наоборот, всё
   должно влезать»). При 900px и выше это ровно две колонки. */
.fit-split { display: grid; gap: 14px; align-items: start;
  grid-template-columns: repeat(auto-fit, minmax(min(340px, 100%), 1fr)); }
/* Три неширокие карточки в один ряд (плитки каналов, короткие сводки). */
.fit-cols { display: grid; gap: 14px; align-items: start;
  grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr)); }
/* Две колонки с ЯВНЫМ приоритетом: важное слева и шире, справочное справа. */
.fit-split-wide { display: grid; gap: 14px; align-items: start;
  grid-template-columns: minmax(0, 1.35fr) minmax(0, .65fr); }
/* Карточки внутри сетки не тянут за собой вертикальный отступ: зазор даёт
   gap, а не margin-bottom каждой карточки (иначе двойной воздух 14+14). */
.fit-split > *, .fit-cols > *, .fit-split-wide > * { margin-top: 0; margin-bottom: 0;
  min-width: 0; }
/* Растянуть карточку на всю ширину сетки (заголовок раздела, широкая
   таблица на 9 колонок — её в две колонки ставить нельзя). */
.fit-split > .fit-full, .fit-cols > .fit-full { grid-column: 1 / -1; }

/* ── 2. ПЛОТНОСТЬ: ОТСТУПЫ ВНУТРИ КАРТОЧКИ ───────────────────────────────
   .fit-dense — «эта карточка про плотность». Трогает ТОЛЬКО ритм: зазоры,
   отступы подписей и полей. Размер шрифта, высоту строки и содержимое НЕ
   меняет: читаемость важнее сэкономленных пикселей (урок замера 11.11 — на
   узком экране человеческие подписи стали длиннее и страница выросла).
   Правила ограничены потомками .fit-dense, поэтому на другие страницы
   не протекают. */
.fit-dense > h2 { margin-top: 16px; }
.fit-dense > h2:first-child { margin-top: 0; }
.fit-dense > p { margin: 0 0 8px; }
.fit-dense > label { margin-bottom: 2px; }
.fit-dense input, .fit-dense select, .fit-dense textarea { margin-bottom: 10px; }
.fit-dense .fields-grid { gap: 8px 12px; }
.fit-dense .grid, .fit-dense .grid2, .fit-dense .grid3,
.fit-dense .stats-grid, .fit-dense .metrics-grid { gap: 10px; }
/* Компактные строки таблицы — для длинных списков (журналы, история
   кредитов; замер: таблица на 20 строк отдавала ~100px только на отступы). */
.fit-dense td, .fit-dense th { padding-top: 9px; padding-bottom: 9px; }
.fit-dense .card-header { margin-bottom: 10px; }

/* ── 3. ПЛОТНОСТЬ: ШАПКА СТРАНИЦЫ ─────────────────────────────────────────
   Владелец просил «важное выше»: шапка — не самое важное на странице, а
   занимает 130–400px (база знаний — 404px из-за ряда кнопок и поиска).
   .fit-hero-tight сжимает саму шапку, не убирая из неё ни одной кнопки. */
.fit-hero-tight.hero, .fit-hero-tight.hero-card { padding: 16px 18px; margin-bottom: 12px; }
.fit-hero-tight.hero h1, .fit-hero-tight.hero-card h1 { font-size: 26px; }
.fit-hero-tight .actions { margin-top: 12px; }

/* ── 4. ЕДИНЫЙ ВИД ОКОН ───────────────────────────────────────────────────
   ЭТАЛОН — страница «Умный разбор» (app/smart_analysis_page.py), которую
   владелец назвал лучшей: мягкая подложка, скругление 18px (--radius-lg),
   шапка с eyebrow, спокойные отступы. Окна приводятся к тем же числам.

   Одна геометрия на ВСЕ окна продукта:
     скругление      18px (--radius-lg)   было 14 / 16 / 18
     шапка           16px 18px 10px       было 14/16/18 вразнобой
     тело            0 18px 18px          было 0 18px 18px и 18px и 12px
     подвал          11px 18px            было 11px 18px и «как получится»
     подложка        rgba(4,6,10,.62)     было .45 / .58 / .62
     слой            200                  было 60 / 190 / 200
   Разметка при этом НЕ переписывается: окно получает класс .fit-modal
   (нативный <dialog>) или .fit-overlay (div-обёртка), внутри — .fit-modal-box
   с шапкой .fit-modal-head, телом .fit-modal-body и подвалом .fit-modal-foot.

   ПОЧЕМУ нативный <dialog>, а не div: браузер сам держит фокус внутри окна,
   закрывает по Esc и возвращает фокус на кнопку, а db_refresh.js уже считает
   dialog[open] признаком «человек занят» и не перезагружает страницу под
   открытым окном. Для окон, которые рисует JS (пересылка), остаётся
   .fit-overlay с той же геометрией. */
.fit-modal {
  width: min(640px, calc(100vw - 24px));
  max-width: 640px;
  max-height: 90dvh;
  margin: auto;
  padding: 0;
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  background: var(--panel);
  color: var(--text);
  box-shadow: var(--shadow-hover);
  overflow: hidden;
}
.fit-modal::backdrop { background: rgba(4, 6, 10, .62); }
.fit-modal[open] { display: flex; flex-direction: column; }
/* Широкая форма (карточка лида с таблицами, импорт базы знаний). */
.fit-modal.fit-modal-wide { width: min(920px, calc(100vw - 24px)); max-width: 920px; }
/* Узкая — подтверждения и короткие вводы. */
.fit-modal.fit-modal-narrow { width: min(440px, calc(100vw - 24px)); max-width: 440px; }

.fit-modal-box {
  display: flex;
  flex-direction: column;
  min-height: 0;
  max-height: inherit;
  width: 100%;
  background: var(--panel);
  border: 1px solid var(--line);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-hover);
  overflow: hidden;
}
/* Внутри нативного <dialog> рамку и тень держит сам .fit-modal: двойная
   рамка даёт «окно в окне» — ровно та чужая деталь, на которую жаловался
   владелец. */
.fit-modal > .fit-modal-box { border: 0; border-radius: 0; box-shadow: none; }

.fit-modal-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  padding: 16px 18px 10px;
  border-bottom: 1px solid var(--line);
}
.fit-modal-head h2 { margin: 0 0 2px; font-size: 18px; }
.fit-modal-head p { margin: 0; color: var(--muted); font-size: 12.5px; }
.fit-modal-body {
  padding: 12px 18px 0;
  overflow-y: auto;
  min-height: 0;
  flex: 1 1 auto;
}
.fit-modal-body > label { margin-top: 10px; }
.fit-modal-foot {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  padding: 11px 18px;
  border-top: 1px solid var(--line);
  background: var(--panel);
}
.fit-modal-foot .actions { margin: 0; }
/* Тело без шапки/подвала (короткое подтверждение) — полный отступ. */
.fit-modal-body.fit-modal-body-solo { padding: 18px; }

/* Крестик закрытия — квадратная тап-цель 34px, тихая до наведения. Не
   меньше 34: на телефоне палец должен попадать с первого раза. */
.fit-modal-x {
  flex: 0 0 auto;
  display: grid;
  place-items: center;
  width: 34px;
  height: 34px;
  margin: -4px -6px 0 0;
  border-radius: 10px;
  border: 0;
  background: transparent;
  color: var(--muted);
  font-size: 17px;
  cursor: pointer;
}
.fit-modal-x:hover { background: var(--panel2); color: var(--text); }

/* DIV-окно (рисуется JS или собственной разметкой страницы) — та же
   геометрия, что у нативного <dialog>, только слоем и центровкой. */
.fit-overlay {
  position: fixed;
  inset: 0;
  z-index: 200;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: rgba(4, 6, 10, .62);
}
.fit-overlay[hidden] { display: none; }
.fit-overlay > .fit-modal-box { max-width: 640px; max-height: 90dvh; }
.fit-overlay > .fit-modal-box.fit-modal-wide { max-width: 920px; }
/* Узкое div-окно (подтверждения, короткий ввод). Без этого правила
   .fit-modal-narrow имеет смысл только внутри <dialog>: у div-коробки
   ширину держит max-width самой .fit-modal-box (640), и класс-модификатор
   молча ничего бы не делал. */
.fit-overlay > .fit-modal-box.fit-modal-narrow { max-width: 440px; }

/* ── 5. ТЕЛЕФОН ───────────────────────────────────────────────────────────
   Порог 900px, а не 700: две колонки по 340px перестают помещаться раньше,
   чем наступает «телефонная» ширина, и на планшете 768px карточки вставали
   бы сжатыми в половину. Ниже 900px ЛЮБАЯ многоколоночная сетка — одна
   колонка: это и есть пин «при узком экране колонки схлопываются».
   Окно на телефоне поднимается снизу листом (та же форма, что у окна
   создания направления) и обходит home-индикатор через safe-area. */
@media (max-width: 900px) {
  .fit-split, .fit-cols, .fit-split-wide { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 700px) {
  .fit-modal,
  .fit-modal.fit-modal-wide,
  .fit-modal.fit-modal-narrow {
    width: 100%;
    max-width: 100%;
    max-height: 94dvh;
    margin: auto auto 0;
    border-radius: 18px 18px 0 0;
    border-bottom: 0;
  }
  .fit-modal-head { padding: 14px 15px 9px; }
  .fit-modal-body { padding: 10px 15px 0; }
  .fit-modal-body.fit-modal-body-solo { padding: 15px; }
  .fit-modal-foot { padding: 10px 15px calc(10px + env(safe-area-inset-bottom)); }
  .fit-modal-foot .actions { width: 100%; }
  /* div-окно на телефоне — тот же лист снизу. */
  .fit-overlay { align-items: flex-end; padding: 0; }
  .fit-overlay > .fit-modal-box,
  .fit-overlay > .fit-modal-box.fit-modal-wide {
    max-width: 100%;
    max-height: 94dvh;
    border-radius: 18px 18px 0 0;
    border-bottom: 0;
  }
  .fit-hero-tight.hero, .fit-hero-tight.hero-card { padding: 14px 15px; }
}

/* ==========================================================================
   ДОПИСАНО ВОЛНОЙ T9 (.fit-*, часть вторая) — плотность таблиц и карточек,
   окна на телефоне. НИ ОДНО правило выше не тронуто (это стерегут пины
   tests/test_fit_density_unified_modals.py и test_fit_registry_pages_p33.py).

   ЧТО БЫЛО ПРОСТОРНЫМ (замер по самому style.css, без браузера):
     1. Таблицы. Ячейка несла padding 13px/12px по вертикали, шапка th —
        12px, а содержимое ячеек запрещено переносить (`th { white-space:
        nowrap }`), плюс .progress-cell с min-width:150px. На широком столе
        колонки распирало, и таблица 15+ колонок уезжала за правый край
        карточки → горизонтальная прокрутка (владелец: «наоборот, всё
        должно влезать»).
     2. Карточки. Высоту задавала каждая карточка по себе: ряд из трёх
        карточек вставал «лесенкой» (высокая тянула ряд, короткая висела с
        дырой снизу).
     3. Окна. Общая геометрия .fit-modal уже есть выше, но на телефоне не
        было гарантии, что содержимое прокручивается ВНУТРИ окна (шапка и
        подвал на месте), а кнопка закрытия остаётся видимой при узком окне.

   ПОЧЕМУ ТОЛЬКО КЛАССЫ .fit-*, А НЕ ПРАВКА БАЗЫ. В style.css одновременно
   пишут три агента (.prem-*, .kb-* — свои namespace'ы). Правка общих
   `th`/`td`/`.card` сломала бы их пины молча. Поэтому плотность включается
   ДОПОЛНИТЕЛЬНЫМ классом на контейнере: нет класса — прежний вид байт-в-байт.
   Ни одного `!important` (в чужой каскад не лезем) и ни одного
   `overflow-x: hidden` на body (это маскирует переполнение, а не лечит).

   КЛАССЫ ЭТОЙ ЧАСТИ:
     .fit-table      — таблица без горизонтальной прокрутки: fixed-layout +
                       переносимый текст; узкие числа не переносятся.
     .fit-table-wrap — обёртка таблицы: max-width 100%, перенос строки.
     .fit-num        — ячейка-число: nowrap (число не рвётся по цифрам).
     .fit-eq         — ряд карточек РАВНОЙ высоты (растягиваются по ряду).
     .fit-modal-fluid— окно, вписанное в ширину телефона (≤100vw), прокрутка
                       внутри тела, кнопка закрытия видна (шапка не уезжает).
   ========================================================================== */

/* ── 1. ТАБЛИЦА БЕЗ ГОРИЗОНТАЛЬНОЙ ПРОКРУТКИ ───────────────────────────────
   fixed-layout берёт ширины из первой строки, а не из самой длинной ячейки:
   иначе одна длинная строка распирает таблицу и выпихивает её за карточку.
   width:100% + max-width:100% + box-sizing:border-box — таблица ровно по
   контейнеру, ни пикселем шире. width:100% контейнера, а не фиксированные
   px: на 1280px таблица укладывается без скролла. */
.fit-table { table-layout: fixed; width: 100%; max-width: 100%;
  box-sizing: border-box; border-collapse: collapse; }
/* Шапку в плотном режиме РАЗРЕШЕНО переносить: база держит `th { white-space:
   nowrap }`, из-за чего широкие подписи («Статус доставки») выдавливали
   соседние колонки. Перенос подписи на две строки дешевле горизонтального
   скролла. Это отмена теперь только для .fit-table, чужие таблицы не тронуты. */
/* Переносимый текст в ячейках: длинные email/токены/URL не выпирают за
   колонку, а переносятся по любому символу — требование задачи. */
.fit-table th, .fit-table td { white-space: normal; word-break: break-word;
  overflow-wrap: anywhere; }
/* Компактные строки: 13px/12px → 10px/11px. Замер: на 20 строках это те же
   ~2×3px×20 ≈ 120px высоты без потери читаемости (шрифт и line-height не
   тронуты — урок замера 11.11: ужимать межстрочный нельзя). */
.fit-table th { padding-top: 10px; padding-bottom: 10px; }
.fit-table td { padding-top: 10px; padding-bottom: 10px; }
/* Обёртка таблицы: ровно по контейнеру, углы и рамка как у общей
   .table-container, но БЕЗ обязательного overflow-x: auto — на плотной
   таблице скролл не нужен, а лишний слой прокрутки мешает. */
.fit-table-wrap { max-width: 100%; width: 100%; box-sizing: border-box;
  overflow-wrap: anywhere; }

/* Число в ячейке не рвётся: «1 250» и «2026-11-09 20:14» читаются как одно
   значение. Это единственное nowrap-исключение, и оно узкое (сами цифры). */
.fit-num { white-space: nowrap; }

/* ── 2. КАРТОЧКИ РАВНОЙ ВЫСОТЫ ────────────────────────────────────────────
   Ряд карточек выравнивается по самой высокой: короткие тянутся до неё, и
   «лесенки» из трёх карточек больше нет. align-items:stretch (а не start) —
   именно он растягивает детей сетки по высоте ряда. Высота НЕ задана px:
   фиксированные высоты карточек ломают перенос длинного текста. */
.fit-eq { display: grid; align-items: stretch;
  grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr)); }
/* height:100% НЕ ставим: при авто-размерах ряда это кольцевое значение,
   браузер его игнорирует, а читатель принял бы за механизм равной высоты.
   Механизм — align-items: stretch на .fit-eq. */
.fit-eq > * { min-width: 0; margin-top: 0; margin-bottom: 0;
  max-width: 100%; box-sizing: border-box; }
/* Внутренность карточки в ряду тоже тянется — иначе «равная высота» ломается
   изнутри (тело короче коробки и низ пустой). */
.fit-eq > .card, .fit-eq > .info-card, .fit-eq > .stat-card { display: flex;
  flex-direction: column; }
.fit-eq > .card > .card-body { flex: 1 1 auto; min-width: 0; }

/* ── 3. ОКНО НА ТЕЛЕФОНЕ (ширина ≤100vw, прокрутка внутри) ────────────────
   .fit-modal выше задаёт геометрию; .fit-modal-fluid — гарантия ВПИСАННОГО
   окна на любом экране БЕЗ нового медиа-запроса (хвост блока пин держит на ≤2
   медиа-запросах, и чужие трогать нельзя): ширина min(100%, 100vw-16px)
   сама меньше вьюпорта. .fit-modal — flex-колонка с max-height; тело
   прокручивается внутри, а шапка с крестиком и подвал — flex-соседи тела,
   поэтому видны всегда, на любой высоте. Ни одной px-ширины >360px. */
.fit-modal.fit-modal-fluid { max-width: 100%;
  width: min(100%, calc(100vw - 16px)); }
.fit-modal.fit-modal-fluid > .fit-modal-box { max-width: 100%; min-width: 0; }
.fit-modal-fluid .fit-modal-head { flex-wrap: wrap; align-items: center; }
.fit-modal-fluid .fit-modal-head h2 { min-width: 0; overflow-wrap: anywhere; }
.fit-modal-fluid .fit-modal-body { overflow-y: auto; max-width: 100%;
  overflow-wrap: anywhere; }
.fit-modal-fluid .fit-modal-foot { flex-wrap: wrap; }
/* Крестик закрытия не сжимается длинным заголовком и стоит в своём углу:
   flex:0 0 auto держит размер, margin-left:auto — не даёт заголовку его
   оттеснить. */
.fit-modal-fluid .fit-modal-x { flex: 0 0 auto; margin-left: auto; }

/* ── КОНЕЦ ВОЛНЫ T9 ── */

/* ── W21: плашка уведомлений (.lf-toast) — премиум-доводка ──────────────────
   Волна 11.11 заменила нативный alert() на карточку внизу экрана, но её
   оформление осталось на том же базовом уровне: плоский нейтральный фон
   (var(--panel)), generic-тень уровня всей страницы (var(--shadow) —
   0 18px 48px, габарит модального окна) и полоса статуса, собранная из
   border-left: 3px — грубый приём, из-за которого карточка читается как
   системный виджет, а не элемент кабинета.
   Премиум-язык статусных поверхностей проекта — .alert (доводка 11.11,
   эталонные страницы crm_ai_final_fixes.py / billing_page.py): тон
   состояния живёт в мягкой заливке 8% и в ОДНОЙ скруглённой полосе
   слева, рамка держит 28% тона, текст остаётся обычного цвета. Плашка
   .lf-toast — та же статусная поверхность (те же тоны success /
   warning / danger / info через --alert-tone), поэтому здесь тот же
   приём дословно. Правило стоит НИЖЕ базового блока — каскад переопределяет
   фон, полосу и тень, не трогая раскладку, иконки и мобильный слой. */

.lf-toast {
  /* Заливка 8% тона вместо нейтральной панели: статус читается сразу,
     но карточка не кричит — как у .alert. Fallback (аудит B5, D-1):
     старые WebView (iOS <16.2 / Android <111) не знают color-mix —
     без предшествующего объявления фон оставался бы базовым, а тон
     терялся. Простое объявление var(--panel) ПЕРЕД color-mix даёт
     читаемую плашку на любом движке; новые перекрывают её тоном. */
  background: var(--panel);
  background: color-mix(in srgb, var(--alert-tone) 8%, var(--panel));
  /* Скругление карточечного уровня: плашка — плавающая
     карточка, а не виджет операционной системы. */
  border-radius: var(--radius-lg);
  /* Тень по габариту плашки: базовый var(--shadow) рассчитан на окна и
     панели во весь экран и распирает маленькую карточку. Здесь мягкая
     тень той же формы, что у карточек кабинета. */
  box-shadow: 0 4px 20px rgba(0, 0, 0, .18);
  /* Правый запас больше базового: крестик закрытия (22px у правого края)
     не должен нависать над текстом в две строки. */
  padding: 13px 38px 13px 17px;
}

/* Полоса статуса — ОДНА скруглённая полоса ::before, как у .alert:
   базовый border-left: 3px даёт квадратный обрезанный угол на новом
   радиусе, границу глушим и рисуем полосу поверх неё. */
.lf-toast { border-left: 0; }
.lf-toast::before {
  content: "";
  position: absolute;
  inset: 0 auto 0 0;
  width: 3px;
  border-radius: var(--radius-lg) 0 0 var(--radius-lg);
  background: var(--alert-tone);
}

/* ── W16: ссылка-кнопка — тот же канон, что у <button> ────────────────────
   Базовое правило кнопок перечисляет ТЕГ button и класс .btn, но НЕ
   .btn-sm: мелкая кнопка-ССЫЛКА (пагеры «← Назад / Ещё», «Открыть»,
   «Изменить набор», «Подробный журнал →», seller-табы) рендерилась
   голым текстом — от .secondary ей доставался только цвет шрифта
   (color: var(--text-2)), без фона, рамки и высоты. Тег-версия в том же
   ряду при этом выглядела кнопкой — два вида одной мелкой кнопки.

   Здесь якоря получают ПОЛНЫЙ канон тега: базовая плашка, варианты
   secondary/danger, размер .btn-sm, тап-цель на телефоне. Совпадение
   по классу ловится атрибутным селектором [class*="btn-sm"], чтобы
   собрать и чистые «btn-sm», и составные «btn-sm secondary» (вида
   «a.btn-sm.secondary» в разметке десятки, переименовывать их все —
   чужие файлы).

   ЧТО НЕ МЕНЯЕТСЯ: чипсы .chips / .period-switch и табы .tabs. Их
   контейнерные правила специфичнее (0,2,0 против 0,1,1) и задают вид
   целиком — заливку, рамку, радиус, кегль и вес; ни background, ни
   border, ни min-height в базовом правиле якоря их не перебивает.
   Счётчик .nav-count не тронут: правило ниже не пишет color/background/
   font-weight. Ссылки ДРУГИХ классов (.tab, .mkt-btn, .pill вне чипсов)
   селектором не задеты — у них свои слои оформления. */
a.btn,
a[class*="btn-sm"],
a.btn-primary, a.btn-success, a.btn-outline, a.btn-secondary,
a.btn-warning, a.btn-danger {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-height: var(--tap);
  padding: 11px 16px;
  border: 1px solid transparent;
  border-radius: var(--radius-sm);
  background: var(--accent);
  color: var(--accent-ink);
  font-family: inherit;
  font-size: 14px;
  font-weight: 700;
  line-height: 1.2;
  cursor: pointer;
  text-align: center;
  transition: filter var(--transition), background var(--transition),
              border-color var(--transition);
}
a.btn:hover,
a[class*="btn-sm"]:hover,
a.btn-primary:hover, a.btn-success:hover, a.btn-outline:hover,
a.btn-secondary:hover, a.btn-warning:hover, a.btn-danger:hover {
  filter: brightness(1.07);
}
/* secondary — тихая кнопка рядом с главной (тот же рецепт, что у
   .btn.secondary тега: панель, рамка, обычный вес). */
a.btn.secondary, a.btn-secondary, a[class*="btn-sm"].secondary {
  background: var(--panel2);
  border-color: var(--line);
  color: var(--text);
  font-weight: 600;
}
a.btn.secondary:hover, a.btn-secondary:hover,
a[class*="btn-sm"].secondary:hover { border-color: var(--line-strong); }
/* danger — разрушительное действие (тот же рецепт .btn.danger).
   Специфичность на класс выше базы — побеждает независимо от порядка. */
a.btn.danger, a.btn-danger, a[class*="btn-sm"].danger {
  background: var(--danger-soft);
  border-color: var(--danger);
  color: var(--danger);
}
/* Размер мелкой кнопки-ссылки — тот же, что у .btn-sm тега. */
a[class*="btn-sm"] { min-height: 34px; padding: 7px 11px; font-size: 12.5px; }
/* Телефон: обычная кнопка 50px, компактная — минимум 44px. Визуально
   компактность задаётся паддингом/кеглем, а не уменьшением тап-цели. */
@media (max-width: 700px) {
  a.btn, a[class*="btn-sm"],
  a.btn-primary, a.btn-success, a.btn-outline, a.btn-secondary,
  a.btn-warning, a.btn-danger { min-height: 50px; font-size: 15.5px; }
  a[class*="btn-sm"] { min-height: 44px; font-size: 13px; }
}

/* Alethea: годовая зимняя палитра без изменения каркаса приложения.
   Сезонный атрибут ставится до загрузки CSS из общего boot-скрипта. */
html[data-season="winter"] body {
  --accent: #b894ff;
  --accent-strong: #8a52ec;
  --accent-soft: rgba(184, 148, 255, .19);
  --aurora-1: #e2d4ff;
  --aurora-2: #791cff;
}
html[data-season="winter"] { --seasonal-brand-mark: url('/static/brand/alethea-mark-winter.png'); }
html[data-season="winter"] .page-hero > .wrap::after { mix-blend-mode: screen; }
.brand-mark[src*="alethea-mark-winter"],
.login-mark[src*="alethea-mark-winter"],
.mark[src*="alethea-mark-winter"],
.alethea-entry__mark[src*="alethea-mark-winter"] { mix-blend-mode: screen; }
.alethea-winter-snow {
  position: fixed; inset: 0; z-index: 38; overflow: hidden; pointer-events: none;
  opacity: .24;
  background-image: radial-gradient(2px 2px at 18px 28px, #fff 55%, transparent 60%),
    radial-gradient(1px 1px at 74px 116px, #e8dcff 55%, transparent 60%),
    radial-gradient(1.5px 1.5px at 132px 69px, #fff 55%, transparent 60%);
  background-size: 170px 150px, 220px 190px, 260px 240px;
  animation: alethea-snowfall 22s linear infinite;
}
@keyframes alethea-snowfall { to { background-position: 0 450px, 40px 520px, -30px 600px; } }

/* Короткая заставка один раз при входе в приложение за вкладку; элементы
   кабинета под ней сохраняют исходные позиции. */
.alethea-entry { display: none; }
.alethea-entry.is-active {
  position: fixed; inset: 0; z-index: 10000; display: grid; place-items: center;
  isolation: isolate; overflow: hidden; color: #f8f4ff;
  background: radial-gradient(ellipse at 50% 44%, #24103e 0, #100a1c 42%, #07060a 100%);
  animation: alethea-entry-fade-in .55s cubic-bezier(.16,1,.3,1) both;
}
.alethea-entry.is-active::before, .alethea-entry.is-active::after {
  content: ""; position: absolute; inset: -20%; z-index: -1; pointer-events: none;
}
.alethea-entry.is-active::before {
  background: conic-gradient(from 15deg at 50% 48%, transparent 0 18%, #7c24ff22 24%, transparent 31% 51%, #d8c4ff18 57%, transparent 65% 100%);
  filter: blur(22px); animation: alethea-entry-nebula 9s linear infinite;
}
.alethea-entry.is-active::after {
  inset: 0; opacity: .22;
  background-image: linear-gradient(rgba(205,178,255,.11) 1px, transparent 1px),
    linear-gradient(90deg, rgba(205,178,255,.11) 1px, transparent 1px);
  background-size: 76px 76px;
  mask-image: radial-gradient(ellipse at center, #000 0, transparent 72%);
  transform: perspective(700px) rotateX(64deg) scale(1.8) translateY(30%);
  transform-origin: center bottom; animation: alethea-entry-grid 4.4s cubic-bezier(.2,.8,.2,1) both;
}
.alethea-entry__halo {
  position: absolute; width: min(78vw, 760px); aspect-ratio: 1; border-radius: 50%;
  background: radial-gradient(circle, #a66bff48 0, #7b2cff18 32%, transparent 68%);
  filter: blur(12px); opacity: 0; transform: scale(.25);
  animation: alethea-entry-halo 3.9s cubic-bezier(.16,1,.3,1) .1s both;
}
.alethea-entry__orbit {
  position: absolute; width: min(76vw, 720px); aspect-ratio: 1;
  border: 1px solid rgba(198, 161, 255, .72); border-radius: 50%;
  box-shadow: 0 0 58px #7b2cff75, inset 0 0 42px #7b2cff3d;
  transform: perspective(900px) rotateX(68deg) rotateZ(-42deg) scale(.48);
  animation: alethea-entry-orbit 3.45s cubic-bezier(.16,1,.3,1) both;
}
.alethea-entry__orbit::before {
  content: ""; position: absolute; inset: 12%; border: 1px solid rgba(232, 220, 255, .38);
  border-radius: 50%; transform: rotate(55deg) scaleY(.38); box-shadow: 0 0 30px #d8c4ff2a;
}
.alethea-entry__orbit::after {
  content: ""; position: absolute; inset: -12%; border: 1px solid rgba(166,107,255,.28);
  border-radius: 50%; transform: rotate(-28deg) scaleY(.58);
}
.alethea-entry__mark {
  position: relative; z-index: 1; display: block;
  width: clamp(230px, 40vw, 410px); aspect-ratio: 1; object-fit: contain;
  color: #f7efff; font: 600 clamp(64px, 12vw, 108px)/1 'Unbounded', sans-serif;
  filter: drop-shadow(0 0 18px #be8bffb8) drop-shadow(0 0 58px #7c24ff91);
  opacity: 0; transform: perspective(900px) translateZ(-180px) scale(.48) rotateY(-16deg);
  animation: alethea-entry-mark 1.5s .18s cubic-bezier(.16,1,.3,1) forwards;
}
.alethea-entry__wordmark {
  position: absolute; z-index: 3; top: calc(50% + clamp(142px, 23vw, 222px)); opacity: 0; text-align: center;
  font-size: 14px; font-weight: 800; letter-spacing: .42em; transform: translateY(18px);
  text-shadow: 0 0 24px #a66bff80;
  animation: alethea-entry-title .9s .92s cubic-bezier(.16,1,.3,1) forwards;
}
.alethea-entry__wordmark small {
  display: block; margin-top: 8px; color: #cbb4f2; font-size: 9px;
  font-weight: 500; letter-spacing: .5em;
}
.alethea-entry__flight { position: absolute; z-index: 2; inset: 0; overflow: hidden; pointer-events: none; }
.alethea-entry__flight i {
  position: absolute; top: 50%; left: 50%; display: block;
  width: 2px; height: clamp(48px, 10vh, 104px); border-radius: 99px;
  background: linear-gradient(to bottom, transparent, #fff 42%, #d8c4ff 68%, #7b2cff);
  box-shadow: 0 0 14px #d8c4ff, 0 0 38px #7b2cff, 0 0 64px #7b2cff8c;
  opacity: 0;
  transform: translate(-50%, -50%) rotate(var(--angle)) translateY(0) scaleY(.1);
  animation: alethea-entry-flight 1.75s var(--flight-delay) cubic-bezier(.08,.68,.2,1) both;
}
.alethea-entry__flight i.flight-pass-two {
  width: 2px; height: clamp(48px, 10vh, 110px);
  background: linear-gradient(to bottom, transparent, #fff 40%, #d8c4ff 62%, #7b2cff);
  box-shadow: 0 0 15px #d8c4ff, 0 0 38px #7b2cff;
  animation-duration: 1.45s;
}
.alethea-entry.is-leaving { animation: alethea-entry-fade-out .65s ease both; }
.alethea-entry.is-accelerating .alethea-entry__orbit { animation: alethea-entry-warp 1.5s cubic-bezier(.08,.68,.2,1) both; }
.alethea-entry.is-accelerating .alethea-entry__halo { animation: alethea-entry-warp-halo 1.5s cubic-bezier(.08,.68,.2,1) both; }
@keyframes alethea-entry-flight {
  0% { opacity: 0; transform: translate(-50%, -50%) rotate(var(--angle)) translateY(0) scaleY(.08); }
  18% { opacity: .9; }
  100% { opacity: 0; transform: translate(-50%, -50%) rotate(var(--angle)) translateY(calc(0px - var(--distance))) scaleY(3.6); }
}
@keyframes alethea-entry-mark { 64% { opacity: 1; transform: perspective(900px) translateZ(0) scale(1.08) rotateY(0); } to { opacity: 1; transform: perspective(900px) translateZ(0) scale(1) rotateY(0); } }
@keyframes alethea-entry-orbit { 0% { transform: perspective(900px) rotateX(68deg) rotateZ(-42deg) scale(.48); opacity: .1; } 55% { opacity: 1; } 100% { transform: perspective(900px) rotateX(68deg) rotateZ(318deg) scale(1); opacity: 1; } }
@keyframes alethea-entry-warp { to { transform: perspective(900px) rotateX(68deg) rotateZ(400deg) scale(2.6); opacity: 0; } }
@keyframes alethea-entry-halo { 18% { opacity: .9; } 65% { opacity: .6; transform: scale(1); } 100% { opacity: .35; transform: scale(1.16); } }
@keyframes alethea-entry-warp-halo { to { opacity: 0; transform: scale(2.2); } }
@keyframes alethea-entry-nebula { to { transform: rotate(360deg) scale(1.06); } }
@keyframes alethea-entry-grid { 0% { opacity: 0; transform: perspective(700px) rotateX(64deg) scale(1.8) translateY(44%); } 30%, 75% { opacity: .22; } 100% { opacity: 0; transform: perspective(700px) rotateX(64deg) scale(1.1) translateY(-12%); } }
@keyframes alethea-entry-title { to { opacity: 1; transform: translateY(0); } }
@keyframes alethea-entry-fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes alethea-entry-fade-out { to { opacity: 0; visibility: hidden; } }
@media (prefers-reduced-motion: reduce) {
  .alethea-winter-snow, .alethea-entry__orbit, .alethea-entry__halo,
  .alethea-entry__mark, .alethea-entry__wordmark, .alethea-entry__flight i,
  .alethea-entry.is-active::before, .alethea-entry.is-active::after { animation: none !important; }
  .alethea-entry.is-active { animation: none; }
  .alethea-entry__orbit { opacity: .68; transform: perspective(900px) rotateX(68deg) rotateZ(-24deg) scale(.82); }
  .alethea-entry__halo { opacity: .38; transform: scale(1); }
  .alethea-entry__mark { opacity: 1; transform: perspective(900px) translateZ(0) scale(1) rotateY(0); }
  .alethea-entry__wordmark { opacity: 1; transform: none; }
  .alethea-entry__flight i, .alethea-entry.is-active::after { display: none; }
}

/* Платформенный расход: компании — рабочие карточки с быстрыми действиями,
   а не десятиколоночная бухгалтерская таблица. */
.pu-companies .card-header { align-items: center; gap: 18px; flex-wrap: wrap; }
.pu-companies .card-header h2 { margin: 0; }
.pu-companies .card-header p { margin: 4px 0 0; }
.pu-company-search { display: grid; gap: 5px; width: min(320px, 100%); }
.pu-company-search span { color: var(--muted); font-size: 12px; font-weight: 600; }
.pu-company-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(430px, 100%), 1fr)); gap: 12px; }
.pu-company-card { min-width: 0; padding: 16px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); }
.pu-company-card[hidden] { display: none; }
.pu-company-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 14px; }
.pu-company-head h3 { margin: 0 0 4px; font-size: 17px; }
.pu-company-head .pill { flex: 0 0 auto; }
.pu-company-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
.pu-company-stat { min-width: 0; display: grid; gap: 5px; padding: 10px 11px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel2); }
.pu-company-stat > span { color: var(--muted); font-size: 11.5px; line-height: 1.35; }
.pu-company-stat > b { overflow-wrap: anywhere; font-size: 14px; font-variant-numeric: tabular-nums; }
.pu-company-actions { margin-top: 12px; }
.pu-company-actions form { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel2); }
.pu-company-actions label { display: grid; gap: 5px; color: var(--muted); font-size: 12px; font-weight: 600; }
.pu-company-actions input { width: 100%; min-width: 0; }
.pu-credit-actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
.pu-credit-actions > button { min-height: 44px; }
.pu-credit-presets { display: flex; gap: 5px; flex-wrap: wrap; }
.pu-credit-presets button { min-height: 44px; padding: 5px 9px; border: 1px solid var(--line); border-radius: var(--radius-pill); background: var(--panel); color: var(--text-2); font-size: 12px; cursor: pointer; }
.pu-credit-presets button:hover { color: var(--accent); border-color: var(--accent); }
.pu-company-card > details { margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--line); }
.pu-company-card > details > summary { min-height: 40px; color: var(--text-2); cursor: pointer; }
.pu-company-card .table-container { max-width: 100%; overflow-x: auto; }
@media (max-width: 700px) {
  .pu-company-list { grid-template-columns: minmax(0, 1fr); }
  .pu-company-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  .pu-credit-actions > button { flex: 1 0 100%; }
  .pu-company-search { width: 100%; }
}

/* Alethea mark supplied by the owner: use the original image consistently. */
.brand-mark { display:block; width:38px; height:38px; flex:0 0 38px; object-fit:contain; border-radius:0; background:transparent; }
.login-mark { border-radius:0; background:transparent; }
.alethea-entry__mark { display:block; object-fit:contain; border-radius:0; mix-blend-mode:normal; box-shadow:none; }
/* Platform company directory: replace the database-like 12-column grid
   with scannable company cards. The data and operations remain intact; the
   action set is tucked behind one explicit control. */
.platform-company-list { overflow: visible; }
.platform-company-list table,
.platform-company-list tbody,
.platform-company-list tr,
.platform-company-list td { display: block; width: 100%; }
.platform-company-list table { min-width: 0; }
.platform-company-list thead { display: none; }
.platform-company-list tbody tr {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 0 16px;
  margin: 12px;
  padding: 16px 18px;
  border: 1px solid var(--line);
  border-radius: 16px;
  background: var(--panel);
  box-shadow: 0 6px 20px rgba(0,0,0,.08);
}
.platform-company-list tbody tr:hover { background: var(--panel); }
.platform-company-list td {
  min-width: 0;
  padding: 10px 4px;
  border: 0;
  overflow-wrap: anywhere;
}
.platform-company-list td::before {
  content: attr(data-label);
  display: block;
  margin-bottom: 5px;
  color: var(--muted);
  font-size: 10px;
  font-weight: 700;
  letter-spacing: .07em;
  text-transform: uppercase;
}
.platform-company-list td[data-label='Компания'] {
  grid-column: span 2;
  align-self: center;
  font-size: 17px;
}
.platform-company-list td[data-label='Управление'] {
  grid-column: span 4;
  align-self: center;
  justify-self: stretch;
}
.platform-company-list td[data-label='Компания']::before,
.platform-company-list td[data-label='Управление']::before { display: none; }
.platform-company-list td[data-label='Набор функций'],
.platform-company-list td[data-label='Подписка'],
.platform-company-list td[data-label='Бесплатные ответы ИИ'],
.platform-company-list td[data-label='Последняя активность'],
.platform-company-list td[data-label='Оплачено'] { grid-column: span 1; }
.company-row-actions { position: relative; }
.company-row-actions > summary {
  display: inline-flex;
  min-width: 128px;
  min-height: 40px;
  align-items: center;
  justify-content: center;
  padding: 8px 14px;
  border: 1px solid var(--line);
  border-radius: var(--radius-sm);
  background: var(--panel2);
  color: var(--text);
  font-weight: 650;
  list-style: none;
  cursor: pointer;
}
.company-row-actions > summary::-webkit-details-marker { display: none; }
.company-row-actions[open] > summary { border-color: var(--accent); color: var(--accent); }
.company-row-actions-menu {
  position: absolute;
  z-index: 30;
  top: calc(100% + 7px);
  right: 0;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 7px;
  width: min(290px, calc(100vw - 48px));
  max-height: min(65vh, 520px);
  overflow: auto;
  padding: 10px;
  border: 1px solid var(--line-strong);
  border-radius: 14px;
  background: var(--panel);
  box-shadow: var(--shadow);
}
.company-row-actions-menu > a,
.company-row-actions-menu > form,
.company-row-actions-menu > span { width: 100%; }
.company-row-actions-menu form button,
.company-row-actions-menu form select { width: 100%; min-height: 40px; }
.company-row-actions-menu form { display: flex; flex-direction: column; gap: 6px; }
@media (max-width: 1100px) {
  .platform-company-list tbody tr { grid-template-columns: repeat(3, minmax(0, 1fr)); }
  .platform-company-list td[data-label='Компания'],
  .platform-company-list td[data-label='Управление'] { grid-column: span 3; }
  .platform-company-list td[data-label='Компания'] { grid-column: span 2; }
  .platform-company-list td[data-label='Управление'] { grid-column: span 1; }
  .platform-company-list td[data-label='Набор функций'],
  .platform-company-list td[data-label='Подписка'],
  .platform-company-list td[data-label='Бесплатные ответы ИИ'],
  .platform-company-list td[data-label='Последняя активность'],
  .platform-company-list td[data-label='Оплачено'] { grid-column: span 1; }
}
@media (max-width: 600px) {
  .platform-company-list tbody tr { grid-template-columns: repeat(2, minmax(0, 1fr)); margin: 9px; padding: 13px; gap: 0 10px; }
  .platform-company-list td[data-label='Компания'] { grid-column: span 2; font-size: 16px; }
  .platform-company-list td[data-label='Управление'] { grid-column: span 2; justify-self: stretch; }
  .platform-company-list td[data-label='Набор функций'],
  .platform-company-list td[data-label='Подписка'],
  .platform-company-list td[data-label='Бесплатные ответы ИИ'],
  .platform-company-list td[data-label='Направления'],
  .platform-company-list td[data-label='Диалогов за неделю'],
  .platform-company-list td[data-label='Лиды'],
  .platform-company-list td[data-label='Диалогов всего'],
  .platform-company-list td[data-label='Расход ИИ за 30 дней'],
  .platform-company-list td[data-label='Последняя активность'],
  .platform-company-list td[data-label='Оплачено'] { grid-column: span 1; }
  .company-row-actions > summary { width: 100%; }
  .company-row-actions-menu { position: static; width: 100%; max-height: none; margin-top: 7px; box-shadow: none; }
}
/* Dense account pools become cards at desktop widths too: wide tables with
   long Telegram error text were forcing important controls off-screen. */
@media (min-width: 1601px) {
  .acct-table, .acct-table tbody, .acct-table tr, .acct-table td { display: block; width: 100%; }
  .acct-table { table-layout: auto; }
  .acct-table thead { display: none; }
  .acct-table tbody tr {
    display: grid;
    grid-template-columns: 28px minmax(150px, 1.1fr) minmax(180px, 1.4fr)
      minmax(95px, .65fr) minmax(120px, .85fr) minmax(145px, 1fr) 44px;
    align-items: center;
    gap: 10px 16px;
    margin: 0 0 12px;
    padding: 14px 16px;
    border: 1px solid var(--line);
    border-radius: 16px;
    background: var(--panel);
    box-shadow: 0 5px 18px rgba(0,0,0,.08);
  }
  .acct-table tbody tr:hover { background: var(--panel); }
  .acct-table td { min-width: 0; width: auto; padding: 6px 0; border: 0; overflow-wrap: anywhere; }
  .acct-table td::before {
    content: attr(data-label);
    display: block;
    margin-bottom: 4px;
    color: var(--muted);
    font-size: 10px;
    font-weight: 700;
    letter-spacing: .07em;
    text-transform: uppercase;
  }
  .acct-table td[data-label='Выбор']::before,
  .acct-table td[data-label='Действия']::before { display: none; }
  .acct-table td[data-label='Тип'] .acct-select,
  .acct-table td[data-label='Направление'] .acct-select { width: 100%; max-width: 100%; }
  .acct-table .acct-state-note { max-width: 100%; }
  .account-avatar-wrap { position: relative; display: inline-grid; width: 38px; height: 38px; flex: 0 0 38px; }
  .account-avatar-wrap > .account-avatar { position: absolute; inset: 0; }
}

/* Keep dense channel controls in their own row so the client identity never
   collides with AI mode, follow-up and transfer actions. */
.thread-header { flex-wrap: wrap; }
.thread-header .account-cell { flex: 1 1 320px; }
.thread-header-actions {
  display: flex;
  flex: 1 1 100%;
  min-width: 0;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}
.thread-header-actions > * { max-width: 100%; }
.thread-header-actions .fu-state { margin-left: 0; white-space: normal; }

/* Mobile shell and messenger layout. Desktop keeps the dense admin controls;
   on a phone the header is one compact row and account actions live in menu. */
.mobile-account-actions { display: none; }
.thread-more-btn { display: none; }
.thread-send-btn .ic { display: none; }

@media (max-width: 700px) {
  .top {
    min-height: calc(64px + env(safe-area-inset-top));
    height: calc(64px + env(safe-area-inset-top));
    padding: env(safe-area-inset-top) 10px 0;
    flex-wrap: nowrap;
    gap: 6px;
  }
  .burger-btn, .top .icon-btn {
    width: 44px;
    height: 44px;
    min-height: 44px;
    padding: 0;
    border-radius: 14px;
  }
  .top .crumbs { min-width: 0; flex: 1 1 auto; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
  .top-actions { flex: 0 0 auto; flex-wrap: nowrap; gap: 4px; }
  .balance-chip { min-height: 44px; padding: 0 10px; }
  .balance-chip-sub { display: none; }
  .current-admin { flex: 0 0 44px; width: 44px; min-height: 44px; padding: 0; border: 0; background: transparent; }
  .current-admin-avatar { width: 44px; height: 44px; flex-basis: 44px; }
  .current-admin-meta, .current-admin > .admin-logout, .current-admin > form { display: none; }
  .mobile-account-actions { display: grid; border-bottom: 1px solid var(--line); margin-bottom: 8px; padding-bottom: 8px; }
  .mobile-account-actions form { margin: 0; }
  .mobile-account-actions .side-foot { width: 100%; border: 0; background: transparent; font: inherit; text-align: left; }
  .notif-panel { position: fixed; top: calc(64px + env(safe-area-inset-top)); left: 10px; right: 10px; width: auto; max-height: calc(100dvh - 84px - env(safe-area-inset-top)); }
}

@media (max-width: 480px) {
  .top .crumbs { display: none; }
  .balance-chip { max-width: 76px; }
}

@media (max-width: 760px) {
  .dialogs-layout.thread-open .thread-pane { height: 100dvh; }
  .dialogs-layout.thread-open .thread-header {
    position: relative;
    flex-wrap: nowrap;
    min-height: calc(60px + env(safe-area-inset-top));
    padding: env(safe-area-inset-top) 8px 0;
    gap: 6px;
    background: color-mix(in srgb, var(--panel) 96%, transparent);
    backdrop-filter: blur(18px);
    z-index: 12;
  }
  .thread-back-btn { width: 44px; min-width: 44px; height: 44px; min-height: 44px; padding: 0; justify-content: center; font-size: 0; border-radius: 50%; }
  .thread-back-btn .ic { font-size: 18px; }
  .thread-header .account-cell { flex: 1 1 auto; min-width: 0; }
  .thread-header .account-cell .account-meta { min-width: 0; }
  .thread-header .account-cell .account-meta > * { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
  .thread-more-btn {
    display: inline-grid;
    flex: 0 0 44px;
    place-items: center;
    width: 44px;
    height: 44px;
    min-height: 44px;
    border: 0;
    border-radius: 50%;
    background: transparent;
    color: var(--text);
  }
  .thread-header-actions {
    display: none;
    position: absolute;
    top: calc(100% + 6px);
    left: 8px;
    right: 8px;
    z-index: 30;
    max-height: min(65dvh, 460px);
    overflow-y: auto;
    padding: 10px;
    border: 1px solid var(--line);
    border-radius: 18px;
    background: var(--panel);
    box-shadow: var(--shadow);
  }
  .thread-header.tools-open .thread-header-actions { display: flex; }
  .thread-header-actions > * { flex: 1 1 100%; width: 100%; min-height: 44px; }
  .thread-delete-btn { width: 100%; }
  .thread-scroll {
    padding: 12px 8px 18px;
    background-color: var(--bg);
    background-image: radial-gradient(circle at 20% 20%, color-mix(in srgb, var(--accent) 7%, transparent) 0 1px, transparent 1.5px);
    background-size: 28px 28px;
  }
  .msg-bubble { max-width: 88%; padding: 9px 12px 18px; border-radius: 16px; }
  .msg-in { border-bottom-left-radius: 5px; }
  .msg-out { border-bottom-right-radius: 5px; }
  .thread-composer {
    display: grid !important;
    grid-template-columns: 44px minmax(0, 1fr) 44px;
    grid-template-rows: auto;
    align-items: end;
    gap: 6px;
    padding: 8px 8px calc(8px + env(safe-area-inset-bottom));
    background: var(--panel);
  }
  .thread-attach-btn { grid-column: 1; grid-row: 2; width: 44px; height: 44px; min-height: 44px; border-radius: 50%; }
  .thread-attach-name:not(:empty) { display: block; grid-column: 1 / 3; grid-row: 1; max-width: none; padding: 4px 8px; }
  .thread-attach-name:empty { display: none; }
  .thread-attach-clear:not([hidden]) { display: block; grid-column: 3; grid-row: 1; justify-self: end; }
  .thread-composer textarea {
    grid-column: 2;
    grid-row: 2;
    width: 100%;
    min-height: 44px;
    max-height: 132px;
    padding: 11px 14px;
    border-radius: 22px;
    line-height: 1.35;
  }
  .thread-send-btn {
    grid-column: 3;
    grid-row: 2;
    width: 44px;
    height: 44px;
    min-height: 44px;
    padding: 0;
    border-radius: 50%;
    display: grid;
    place-items: center;
  }
  .thread-send-btn > .thread-send-label { display: none !important; }
  .thread-send-btn .ic { display: inline-block; width: 19px; height: 19px; }
}

/* Birthday template form: two short controls on the first line, full-width
   message below, then the default flag and save action. */
.crm-birthday-form { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: end; }
.crm-birthday-form > div:nth-child(3) { grid-column: 1 / -1; }
.crm-birthday-form > div:nth-child(3) textarea { min-height: 120px; resize: vertical; }
.crm-birthday-form > div:nth-child(4) { align-self: center; }
.crm-birthday-form > div:nth-child(5) { justify-self: end; width: min(100%, 250px); }
.crm-birthday-form > div:nth-child(5) button { width: 100%; }

/* One shared accent for non-Telegram channels; Telegram keeps its own blue.
   This makes the cards read as one product family with a clear TG exception. */
.acp-mark { background: var(--accent-soft) !important; color: var(--accent) !important; }
.acp-mark.c-tg { background: var(--info-soft) !important; color: var(--info) !important; }

/* Section heads inside flush table cards need real inset spacing. The old
   negative card-header margin was designed for padded cards and clipped
   titles against the border on owner screens. */
.card[style*="padding:0"] > .card-header {
  margin: 0;
  padding: 14px 16px;
  border-bottom: 1px solid var(--line);
}
.card[style*="padding:0"] > .card-header h2 { margin: 0; line-height: 1.3; }

/* Page entrance: a brief, staggered focus shift for the first visible blocks.
   This only affects the initial paint after JS opts in; the server HTML stays
   visible by default and reduced-motion users get no movement or blur. */
body.lf-page-motion #main > .lf-page-arrive-item {
  animation: lf-content-arrive .72s cubic-bezier(.16,1,.3,1) both;
  animation-delay: var(--lf-page-stagger, 0ms);
  will-change: opacity, transform, filter;
}
/* Dashboard metric/card grids get a second, finer beat after their section
   enters. Scope this to grids that are part of the initial page entrance so
   long result lists and live-updating tables never animate item-by-item. */
body.lf-page-motion #main > .lf-page-arrive-item:is(.grid,.grid3,.stats-grid,.metrics-grid) > * {
  animation: lf-grid-card-arrive .78s cubic-bezier(.16,1,.3,1) both;
  animation-delay: calc(var(--lf-page-stagger, 0ms) + var(--lf-grid-stagger, 0ms));
  transform-origin: 50% 65%;
}
body.lf-page-motion #main > .lf-page-arrive-item:is(.grid,.grid3,.stats-grid,.metrics-grid) > :nth-child(2) { --lf-grid-stagger: 75ms; }
body.lf-page-motion #main > .lf-page-arrive-item:is(.grid,.grid3,.stats-grid,.metrics-grid) > :nth-child(3) { --lf-grid-stagger: 150ms; }
body.lf-page-motion #main > .lf-page-arrive-item:is(.grid,.grid3,.stats-grid,.metrics-grid) > :nth-child(4) { --lf-grid-stagger: 225ms; }
body.lf-page-motion #main > .lf-page-arrive-item:is(.grid,.grid3,.stats-grid,.metrics-grid) > :nth-child(n+5) { --lf-grid-stagger: 300ms; }
@keyframes lf-grid-card-arrive {
  0% { opacity: 0; filter: blur(7px); transform: perspective(900px) translate3d(0,24px,-42px) rotateX(5deg) scale(.97); }
  72% { opacity: 1; filter: blur(0); transform: perspective(900px) translate3d(0,-2px,0) rotateX(-.6deg) scale(1.008); }
  100% { opacity: 1; filter: none; transform: perspective(900px) translate3d(0,0,0) rotateX(0) scale(1); }
}
@keyframes lf-content-arrive {
  from { opacity: 0; filter: blur(6px); transform: translate3d(0,18px,0) scale(.994); }
  72% { opacity: 1; filter: blur(0); }
  to { opacity: 1; filter: none; transform: translate3d(0,0,0) scale(1); }
}
.login-wrap > .login-card {
  animation: lf-auth-arrive .9s cubic-bezier(.16,1,.3,1) both;
}
.login-wrap > .login-card > .login-story,
.login-wrap > .login-card > .login-panel {
  animation: lf-auth-column-arrive .82s cubic-bezier(.16,1,.3,1) both;
}
.login-wrap > .login-card > .login-panel { animation-delay: 110ms; }
@keyframes lf-auth-arrive {
  from { opacity: 0; filter: blur(10px); transform: translate3d(0,24px,0) scale(.985); }
  to { opacity: 1; filter: none; transform: translate3d(0,0,0) scale(1); }
}
@keyframes lf-auth-column-arrive {
  from { opacity: 0; transform: translate3d(0,14px,0); }
  to { opacity: 1; transform: translate3d(0,0,0); }
}
@media (prefers-reduced-motion: reduce) {
  body.lf-page-motion #main > .lf-page-arrive-item {
    animation: none;
    will-change: auto;
  }
  body.lf-page-motion #main > .lf-page-arrive-item:is(.grid,.grid3,.stats-grid,.metrics-grid) > * { animation: none; }
  .login-wrap > .login-card,
  .login-wrap > .login-card > .login-story,
  .login-wrap > .login-card > .login-panel { animation: none; }
  .feature-card, .feature-card:hover { transition: none; transform: none; }
}

/* Apply the user's motion preference to every workspace component, including
   older page-specific animations that predate the shared motion system. */
.ws-global-ai-mode .card-header { align-items: center; justify-content: space-between; gap: 12px; }
.ws-global-ai-mode .card-header h2 { margin: 0; }
.ws-ai-mode-options { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; margin-top: 16px; }
.ws-ai-mode-option {
  display: flex; align-items: flex-start; gap: 11px; min-width: 0; padding: 14px;
  border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel2);
  cursor: pointer; transition: border-color .18s ease, background-color .18s ease, transform .18s ease;
}
.ws-ai-mode-option:hover { border-color: var(--accent); transform: translateY(-1px); }
.ws-ai-mode-option:has(input:checked) { border-color: var(--accent); background: var(--accent-soft); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent); }
.ws-ai-mode-option input { flex: 0 0 18px; width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--accent); }
.ws-ai-mode-option span { display: grid; gap: 4px; min-width: 0; }
.ws-ai-mode-option b { color: var(--text); font-size: 14px; }
.ws-ai-mode-option small { color: var(--muted); font-size: 12px; line-height: 1.45; }
.ws-ai-mode-option:has(input:disabled) { cursor: progress; opacity: .65; }
.ws-ai-mode-feedback { margin: 12px 0 0; font-size: 12.5px; }
@media (max-width: 760px) { .ws-ai-mode-options { grid-template-columns: 1fr; } }
@media (prefers-reduced-motion: reduce) { .ws-ai-mode-option { transition: none; } }

@media (prefers-reduced-motion: reduce) {
  html:focus-within { scroll-behavior: auto !important; }
  *, *::before, *::after {
    animation-duration: .01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: .01ms !important;
    scroll-behavior: auto !important;
  }
}
