/* Стили ERP: без внешних библиотек, работает на телефоне.
   Цвета и размеры собраны в переменные — меняются в одном месте. Вид — задание 36
   (docs/design/36/spec.md): спокойный, чернильные кнопки, один синий для ссылок и фокуса. */

:root {
  --bg: #f5f5f7;
  --surface: #ffffff;
  --surface-2: #f7f7f8;
  --border: #e8e8ed;
  --border-strong: #d2d2d7;
  --text: #1d1d1f;
  --text-2: #515154;
  --muted: #66666b;
  --placeholder: #66666b;

  --primary: #1d1d1f;
  --primary-hover: #000000;
  --primary-soft: #ececf0;
  --on-primary: #ffffff;
  --link: #0b5cc4;
  --danger: #c0282a;
  --danger-hover: #a02022;
  /* Заливка значка «Удалить» (задание 87): белый крестик на ней читается в обеих темах (≥ 4,5:1). */
  --danger-solid: #c0282a;
  --danger-solid-hover: #a02022;
  --on-danger: #ffffff;
  --success: #1a7a3c;
  --warning: #9a4a00;
  --info: #1d4ed8;

  --side-bg: #f5f5f7;
  --side-text: #4a4a4f;
  --side-hover: #e8e8ed;
  /* Фирменные константы: чёрная плашка знака и буква на ней, одинаковы в обеих темах. */
  --logo-plate: #000000;
  --logo-mark: #ffffff;

  --radius: 12px;
  --radius-sm: 8px;
  --shadow: 0 1px 2px rgba(0, 0, 0, .04), 0 2px 8px rgba(0, 0, 0, .04);
  --shadow-lg: 0 12px 40px rgba(0, 0, 0, .14);
  /* Двойное сплошное кольцо фокуса: зазор цветом поверхности и синее, видно на любом фоне. */
  --focus: 0 0 0 2px var(--surface), 0 0 0 4px var(--link);
  --row-hover: #f7f7f8;
  --input-hover: #a1a1a6;
  --input-bg: var(--surface);
  /* Поле только для чтения: в тёмной теме обычное поле уже --surface-2, поэтому своя переменная. */
  --input-readonly-bg: var(--surface-2);
  --danger-border: #f0b4b4;
  --backdrop: rgba(0, 0, 0, .4);
  --login-glow: #e8e8ed;
  --step-here: var(--link);

  /* Плотность таблиц — три числа; набор «воздух» выбран владельцем 2026-11-01. */
  --cell-y: 10px;
  --cell-x: 12px;
  --table-font: 14px;

  --b-gray-bg: #ececf0;   --b-gray: #4f4f55;
  --b-green-bg: #e2f5e8;  --b-green: #146a2f;
  --b-red-bg: #fde7e7;    --b-red: #a21f21;
  --b-yellow-bg: #fcefd2; --b-yellow: #744400;
  --b-blue-bg: #e2edfb;   --b-blue: #0f4b99;
  --b-violet-bg: #ebe5fa; --b-violet: #5a2ab0;

  --m-success-bg: #eef9f1; --m-success-border: #bfe6cb;
  --m-warning-bg: #fdf4df; --m-warning-border: #f1d890;
  --m-error-bg: #fdeeee;   --m-error-border: #f3c2c2;
  --m-info-bg: #edf3fc;    --m-info-border: #c3d7f5;
  --side-w: 248px;
  color-scheme: light;
}

/* Тема как в системе: тёмная, пока сотрудник не нажал кнопку. Объявления — точная копия блока
   явного выбора ниже (theme.js ставит data-theme только после нажатия). */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #0f0f10;
    --surface: #1a1a1c;
    --surface-2: #222225;
    --border: #2a2a2e;
    --border-strong: #3c3c42;
    --text: #f2f2f4;
    --text-2: #b9b9c0;
    --muted: #a0a0a9;
    --placeholder: #a0a0a9;
    --primary: #f2f2f4;
    --primary-hover: #ffffff;
    --primary-soft: #2a2a2e;
    --on-primary: #111113;
    --link: #86b7ff;
    --danger: #ff8080;
    --danger-hover: #ff9a9a;
    --danger-solid: #d63a3a;
    --danger-solid-hover: #e24a4a;
    --on-danger: #ffffff;
    --success: #62d48c;
    --warning: #f6c75a;
    --info: #8ab4f8;
    --side-bg: #0f0f10;
    --side-text: #c6c6cd;
    --side-hover: #1f1f22;
    --logo-plate: #000000;
    --logo-mark: #ffffff;
    --shadow: 0 1px 2px rgba(0, 0, 0, .5);
    --shadow-lg: 0 12px 40px rgba(0, 0, 0, .6);
    --row-hover: #202023;
    --input-hover: #55555c;
    --input-bg: var(--surface-2);
    --input-readonly-bg: var(--bg);
    --danger-border: #7a3030;
    --backdrop: rgba(0, 0, 0, .6);
    --login-glow: #1a1a1c;
    --b-gray-bg: #2a2a2e;   --b-gray: #cfcfd6;
    --b-green-bg: #12311d;  --b-green: #7fdc9f;
    --b-red-bg: #3b1717;    --b-red: #ffa0a0;
    --b-yellow-bg: #3a2b0b; --b-yellow: #f6c75a;
    --b-blue-bg: #15274b;   --b-blue: #a3c7ff;
    --b-violet-bg: #2b2053; --b-violet: #cbbaff;
    --m-success-bg: #122a1b; --m-success-border: #1f4a2e;
    --m-warning-bg: #2e230c; --m-warning-border: #5a4514;
    --m-error-bg: #2f1515;   --m-error-border: #5c2626;
    --m-info-bg: #13223d;    --m-info-border: #22406d;
    color-scheme: dark;
  }
}

/* Явный выбор «Тёмная» сильнее системы. */
:root[data-theme="dark"] {
  --bg: #0f0f10;
  --surface: #1a1a1c;
  --surface-2: #222225;
  --border: #2a2a2e;
  --border-strong: #3c3c42;
  --text: #f2f2f4;
  --text-2: #b9b9c0;
  --muted: #a0a0a9;
  --placeholder: #a0a0a9;
  --primary: #f2f2f4;
  --primary-hover: #ffffff;
  --primary-soft: #2a2a2e;
  --on-primary: #111113;
  --link: #86b7ff;
  --danger: #ff8080;
  --danger-hover: #ff9a9a;
  --danger-solid: #d63a3a;
  --danger-solid-hover: #e24a4a;
  --on-danger: #ffffff;
  --success: #62d48c;
  --warning: #f6c75a;
  --info: #8ab4f8;
  --side-bg: #0f0f10;
  --side-text: #c6c6cd;
  --side-hover: #1f1f22;
  --logo-plate: #000000;
  --logo-mark: #ffffff;
  --shadow: 0 1px 2px rgba(0, 0, 0, .5);
  --shadow-lg: 0 12px 40px rgba(0, 0, 0, .6);
  --row-hover: #202023;
  --input-hover: #55555c;
  --input-bg: var(--surface-2);
  --input-readonly-bg: var(--bg);
  --danger-border: #7a3030;
  --backdrop: rgba(0, 0, 0, .6);
  --login-glow: #1a1a1c;
  --b-gray-bg: #2a2a2e;   --b-gray: #cfcfd6;
  --b-green-bg: #12311d;  --b-green: #7fdc9f;
  --b-red-bg: #3b1717;    --b-red: #ffa0a0;
  --b-yellow-bg: #3a2b0b; --b-yellow: #f6c75a;
  --b-blue-bg: #15274b;   --b-blue: #a3c7ff;
  --b-violet-bg: #2b2053; --b-violet: #cbbaff;
  --m-success-bg: #122a1b; --m-success-border: #1f4a2e;
  --m-warning-bg: #2e230c; --m-warning-border: #5a4514;
  --m-error-bg: #2f1515;   --m-error-border: #5c2626;
  --m-info-bg: #13223d;    --m-info-border: #22406d;
  color-scheme: dark;
}

* { box-sizing: border-box; }

html { -webkit-text-size-adjust: 100%; background: var(--bg); color: var(--text); }

body {
  margin: 0;
  font: 15px/1.5 -apple-system, "Segoe UI Variable Text", "Segoe UI", system-ui, Roboto, Arial, sans-serif;
  color: var(--text);
  background: var(--bg);
}

/* Ссылки в тексте — синие с тонким приглушённым подчёркиванием (не только цветом). Без color-mix —
   запасной цвет подчёркивания --input-hover. */
a {
  color: var(--link);
  text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 3px;
  text-decoration-color: var(--input-hover);
}
@supports (color: color-mix(in srgb, red 50%, blue)) {
  a { text-decoration-color: color-mix(in srgb, var(--link) 45%, transparent); }
}
a:hover { text-decoration-color: currentColor; }
.menu a, .brand, .brand-mini, .button, .pages a, .logout .link, th a.sort-link { text-decoration: none; }

/* Фокус с клавиатуры — кольцо без скругления: кнопки и поля сохраняют свои углы. 4 px — только у
   строчных ссылок, кнопок-ссылок и summary; :where() оставляет специфичность (0,1,0), поэтому
   .button, .menu a, .pages a сохраняют свои 8 px.
   Правило: у фокусируемого элемента любое правило box-shadow сильнее (0,1,0) обязано повторить
   var(--focus) в своём :focus-visible — иначе выделение перебьёт кольцо. */
:focus-visible { outline: none; box-shadow: var(--focus); }
:where(a:not(.button), button.link, summary):focus-visible { border-radius: 4px; }
.table-wrap:focus-visible { box-shadow: var(--shadow), var(--focus); }

/* --- Раскладка: меню слева, содержимое справа --------------------------------------------- */

.layout { min-height: 100vh; }
/* На компьютере флажок ящика меню ничего не делает — display: none убирает его из порядка Tab;
   на узком экране он возвращается (блок ≤ 900 px) невидимым, но фокусируемым. */
.nav-toggle { display: none; position: absolute; opacity: 0; pointer-events: none; }

.sidebar {
  position: fixed;
  inset: 0 auto 0 0;
  width: var(--side-w);
  display: flex;
  flex-direction: column;
  gap: 1px;
  padding: calc(20px + env(safe-area-inset-top, 0px)) 12px calc(16px + env(safe-area-inset-bottom, 0px));
  background: var(--side-bg);
  color: var(--side-text);
  border-right: 1px solid var(--border);
  overflow-y: auto;
  scrollbar-width: thin; /* меню выше 768–800 px: широкая полоса Windows отнимала бы ширину пунктов */
  z-index: 30;
}

.brand {
  display: flex; align-items: center; gap: 10px;
  padding: 2px 10px 18px;
  color: var(--text); font-weight: 600; font-size: 16px; letter-spacing: -.01em;
}
.brand:hover { text-decoration: none; }
/* Знак логотипа — на чёрной плашке (решение владельца 2026-11-01). Плашка и буква — фирменные
   константы, росчерк задан внутри svg. Кольцо 1 px снаружи — чтобы в тёмной теме чёрный квадрат не
   сливался с фоном; span не фокусируемый (фокус — на ссылке), правило кольца фокуса не задето. */
.brand-logo {
  display: grid; place-items: center; flex: none;
  width: 30px; height: 30px; border-radius: var(--radius-sm);
  background: var(--logo-plate); color: var(--logo-mark);
  box-shadow: 0 0 0 1px var(--border-strong);
}
.brand-logo svg { display: block; width: 24px; height: 24px; }

.menu { display: flex; flex-direction: column; gap: 1px; flex: 1; }
.menu-group {
  margin: 18px 12px 6px;
  font-size: 12px; font-weight: 500;
  color: var(--muted);
}
.menu a {
  display: flex; align-items: center; gap: 12px;
  min-height: 40px; padding: 8px 12px; border-radius: var(--radius-sm);
  color: var(--side-text); font-size: 14px; font-weight: 450;
}
.menu a svg {
  width: 20px; height: 20px; flex: none;
  fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round;
}
.menu a:hover { background: var(--side-hover); color: var(--text); text-decoration: none; }
/* Открытый раздел: белая плашка, жирная подпись и чернильная полоска слева. */
.menu a.active { background: var(--surface); color: var(--text); font-weight: 600; box-shadow: inset 3px 0 0 var(--primary), var(--shadow); }
.menu a.active:focus-visible { box-shadow: inset 3px 0 0 var(--primary), var(--focus); }

.logout {
  display: flex; align-items: center; gap: 10px;
  margin: 12px 0 0; padding: 14px 10px 0;
  border-top: 1px solid var(--border);
  color: var(--text);
}
.logout .avatar {
  display: grid; place-items: center; flex: none;
  width: 30px; height: 30px; border-radius: 50%;
  background: var(--primary); color: var(--on-primary); font-weight: 600; font-size: 13px;
}
.logout .who { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; }
.logout .link { color: var(--muted); font-size: 13px; }
.logout .link:hover { color: var(--text); }

main {
  margin-left: var(--side-w);
  padding: 32px 32px 64px;
  max-width: calc(1280px + var(--side-w));
}

.mobile-top, .nav-backdrop { display: none; }

/* Полоска загрузки вверху, пока HTMX ждёт ответ сервера */
.loading-bar {
  position: fixed; top: 0; left: 0; height: 2px; width: 0;
  background: var(--link); z-index: 100; opacity: 0;
  transition: width .4s ease, opacity .3s;
}
.loading-bar.htmx-request { width: 70%; opacity: 1; }

/* Переключатель темы внизу меню */
.theme-switch {
  display: flex; gap: 2px; margin: 12px 6px 0; padding: 3px;
  background: var(--b-gray-bg); border: 0; border-radius: 10px;
}
.theme-switch button {
  flex: 1 1 0; min-width: 0; min-height: 34px; padding: 5px 2px; gap: 6px;
  flex-direction: row;
  background: transparent; border: 0; border-radius: var(--radius-sm);
  color: var(--side-text); font-size: 12.5px; font-weight: 500; line-height: 1.2;
}
.theme-switch button:hover { background: var(--side-hover); color: var(--text); }
/* Нажатая кнопка темы: белая плашка, полужирное начертание и тонкая рамка — не только цветом. */
.theme-switch button[aria-pressed="true"] { background: var(--surface); color: var(--text); font-weight: 600; box-shadow: inset 0 0 0 1px var(--border-strong), var(--shadow); }
.theme-switch button[aria-pressed="true"]:focus-visible { box-shadow: var(--focus); }
.theme-switch svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; flex: none; }

/* Короткий ноутбук (1280×800, 1366×768): меню плотнее, чтобы тема и «Выйти» были видны без прокрутки.
   На экране выше 900 px пункты те же 40 px, что в макете. */
@media (min-width: 901px) and (max-height: 900px) {
  .sidebar { padding-top: 12px; padding-bottom: 10px; }
  .brand { padding-bottom: 8px; }
  .menu-group { margin: 8px 12px 4px; }
  .menu a { min-height: 36px; padding-block: 6px; }
  .theme-switch { margin-top: 8px; }
  .theme-switch button { min-height: 30px; padding-block: 3px; }
  .logout { margin-top: 8px; padding-top: 8px; }
}

/* --- Заголовки и блоки --------------------------------------------------------------------- */

h1 {
  display: flex; flex-wrap: wrap; align-items: center; gap: 12px;
  font-size: 28px; font-weight: 650; letter-spacing: -.02em; line-height: 1.2;
  margin: 0 0 20px;
}
h2 { font-size: 18px; font-weight: 600; letter-spacing: -.01em; margin: 32px 0 12px; }
h3 { font-size: 15px; font-weight: 600; }

.box {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 20px 24px;
  margin-bottom: 16px;
}

.muted { color: var(--muted); }
.neg { color: var(--danger); }

/* --- Таблицы ------------------------------------------------------------------------------- */

.table-wrap {
  overflow: auto;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  margin-bottom: 16px;
}
/* Плотность — переменными --cell-y, --cell-x и --table-font. */
table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: var(--table-font); }
th, td { padding: var(--cell-y) var(--cell-x); border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; }
/* Шапка таблицы не закреплена (.table-wrap без max-height); position: relative — опора для ручки
   ширины столбца (tables.js). */
th {
  position: relative;
  background: var(--surface-2);
  font-size: 12.5px; font-weight: 600;
  color: var(--text-2); white-space: nowrap;
}
th small { display: block; font-size: 11.5px; font-weight: 400; color: var(--muted); line-height: 1.3; }
tbody tr:last-child td { border-bottom: 0; }
tbody tr:hover td { background: var(--row-hover); }
td.num, th.num { text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; }
tr.total td { font-weight: 600; background: var(--surface-2); border-top: 1px solid var(--border-strong); }
/* Ссылки в таблицах — цветом текста с тонким подчёркиванием, под мышью синие: номера в каждой
   строке не пестрят. Кнопка в ячейке остаётся кнопкой. */
td a { font-weight: 500; white-space: nowrap; }
td a:not(.button) { color: var(--text); text-decoration-color: var(--input-hover); }
td a:not(.button):hover { color: var(--link); text-decoration-color: currentColor; }
/* Пустое состояние: единственная ячейка на всю ширину — по центру, с воздухом. */
tbody > tr > td[colspan]:only-child { padding: 36px 16px; text-align: center; color: var(--muted); }

/* Таблицы просмотра от 9 колонок (журнал документов, документы заявки) и «Связанные документы»: поля ячеек по бокам чуть уже,
   иначе на 1280 px последняя колонка «Состояние» обрезана краем рамки. Высота строки та же. */
.table-wrap > table:not(.lines-input):has(> thead > tr > th:nth-child(9)),
.table-wrap > table.related { --cell-x: 8px; }

table.mini { font-size: 13px; }
table.mini th { position: static; font-size: 12px; }
table.mini td, table.mini th { padding: 3px 8px; border-bottom: 0; }
table.mini tr:hover td { background: transparent; }

/* --- Поля ввода ---------------------------------------------------------------------------- */

input:not([type=checkbox]):not([type=radio]):not([type=hidden]), select, textarea {
  padding: 4px 12px; min-height: 32px;  /* задание 86: «уменьшить и поля», «ещё меньше» — как кнопки, 32 px */
  border: 1px solid var(--border-strong);
  border-radius: var(--radius-sm);
  background: var(--input-bg);
  /* Подпись поля — 13 px полужирная; значение — не мельче 14 px и обычным начертанием. */
  font: inherit; font-size: max(14px, 1em); font-weight: 400;
  color: var(--text);
  transition: border-color .15s, box-shadow .15s;
}
/* Состояния — тем же селектором: короткий (input:hover) слабее правила выше, и рамка не менялась бы. */
input:not([type=checkbox]):not([type=radio]):not([type=hidden]):hover, select:hover, textarea:hover { border-color: var(--input-hover); }
input:not([type=checkbox]):not([type=radio]):not([type=hidden]):focus, select:focus, textarea:focus { outline: none; border-color: var(--link); box-shadow: var(--focus); }
input:not([type=checkbox]):not([type=radio]):not([type=hidden]):disabled, select:disabled, textarea:disabled { background: var(--input-readonly-bg); color: var(--muted); cursor: not-allowed; }
input[type=checkbox], input[type=radio] { accent-color: var(--primary); width: 18px; height: 18px; }
/* Подсказка в пустом поле (серая ставка НДС и др., задание 28): свой цвет с контрастом AA —
   иначе Safari и Firefox рисуют её слишком бледно; Firefox ещё и добавляет прозрачность. */
input::placeholder, textarea::placeholder { color: var(--placeholder); opacity: 1; }

.filters { display: flex; flex-wrap: wrap; gap: 10px 14px; align-items: flex-end; margin-bottom: 16px; }
.filters label { display: flex; flex-direction: column; gap: 5px; font-size: 13px; font-weight: 500; color: var(--text-2); min-width: 0; }
.filters input, .filters select { min-width: 140px; max-width: 100%; }
.filters label:has(> input[type=checkbox]) { flex-direction: row; align-items: center; gap: 8px; min-height: 32px; }
.filters input[type=checkbox] { min-width: 0; margin: 0; flex: none; }
.filters input[type=search] { min-width: 240px; } /* подсказка «Название или артикул» целиком */
.filters .grow { flex: 1 1 220px; }
.filters .grow input { width: 100%; }
.filters button { align-self: flex-end; }

.form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px 16px; }
.form-grid label, .request-col label, .request-markup label, dialog label {
  display: flex; flex-direction: column; gap: 5px; font-size: 13px; font-weight: 500; color: var(--text-2);
}
.form-grid label.wide { grid-column: 1 / -1; }
small { font-size: 12.5px; } /* иначе «smaller» внутри подписи 13 px даёт 10,8 px */
label small { font-weight: 400; }
small.neg { display: block; margin-top: 3px; }
/* «+ новый поставщик» под полем — у левого края поля, а не по центру колонки. */
label > button.link { align-self: flex-start; text-align: left; }

/* Поля строк позиций. :where — специфичность (0,1,1), как у блока 27а в конце файла: он ниже и
   поэтому сильнее. С обычным :not(…) это правило перебило бы ширины в ch, и край суммы обрезался бы. */
.lines-input input:where(:not([type=checkbox])), .lines-input select { width: 100%; min-width: 84px; padding: 4px 10px; }
/* Ячейка товара — по классу: первой колонкой на экранах ввода стала ручка порядка строк. */
.lines-input td.cell-item select { min-width: 200px; }
/* Числа в полях строк — вправо, как и в заголовке столбца. */
.lines-input td.num input:not([type=checkbox]) { text-align: right; font-variant-numeric: tabular-nums; }
.lines-input td { vertical-align: top; }
.lines-input tbody tr:hover td { background: transparent; }
td.line-items { padding-top: 0; }

.wide { grid-column: 1 / -1; }

/* --- Кнопки -------------------------------------------------------------------------------- */

button, .button {
  display: inline-flex; align-items: center; justify-content: center; gap: 6px;
  min-height: 32px;  /* задание 86: «кнопки слишком большие», «ещё меньше» — 32 px, как поля */
  padding: 4px 12px;
  border: 1px solid var(--primary);
  border-radius: var(--radius-sm);
  background: var(--primary);
  color: var(--on-primary);
  font: inherit; font-size: 13.5px; font-weight: 550;
  cursor: pointer;
  text-decoration: none;
  transition: background .15s, border-color .15s, box-shadow .15s;
}
button:hover, .button:hover { background: var(--primary-hover); border-color: var(--primary-hover); text-decoration: none; }
button.secondary, .button.secondary { background: var(--surface); color: var(--text); border-color: var(--border-strong); }
button.secondary:hover, .button.secondary:hover { background: var(--surface-2); border-color: var(--input-hover); }
button.danger, .button.danger { background: var(--surface); color: var(--danger); border-color: var(--danger-border); }
button.danger:hover, .button.danger:hover { background: var(--m-error-bg); color: var(--danger); border-color: var(--danger); }
button:disabled, button:disabled:hover { opacity: .45; cursor: not-allowed; }
button:not(.secondary):not(.danger):not(.link):disabled:hover { background: var(--primary); border-color: var(--primary); }

button.link {
  display: inline; min-height: 0;
  background: none; border: 0; padding: 0;
  color: var(--link); font-size: 13.5px; font-weight: 500;
  cursor: pointer;
}
button.link:hover { background: none; text-decoration: underline; }

.actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0; }
.actions form { margin: 0; }

/* --- Значки состояния ---------------------------------------------------------------------- */

.badge {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 2px 9px; border-radius: 6px;
  font-size: 12.5px; font-weight: 500; white-space: nowrap; letter-spacing: 0; text-transform: none;
  line-height: 1.5;
}
.badge::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: currentColor; opacity: .85; }
.badge-draft { background: var(--b-gray-bg); color: var(--b-gray); }
.badge-posted { background: var(--b-green-bg); color: var(--b-green); }
.badge-cancelled { background: var(--b-red-bg); color: var(--b-red); text-decoration: line-through; }
.badge-fulfill-none { background: var(--b-gray-bg); color: var(--b-gray); }
.badge-fulfill-partial { background: var(--b-yellow-bg); color: var(--b-yellow); }
.badge-fulfill-drafted { background: var(--b-blue-bg); color: var(--b-blue); }
.badge-fulfill-full { background: var(--b-green-bg); color: var(--b-green); }
/* Итог полосы шагов заявки — в списке заявок и в шапке карточки (задание 43а). */
.badge-outcome-done { background: var(--b-green-bg); color: var(--b-green); }
.badge-outcome-in_progress { background: var(--b-blue-bg); color: var(--b-blue); }
.badge-outcome-own_done { background: var(--b-gray-bg); color: var(--b-gray); }

/* --- Сообщения: мягкая плашка, значок контуром слева --------------------------------------- */
/* Значок стоит поверх левого отступа (absolute), а не отдельной колонкой flex: в сообщениях бывают
   ссылки и список причин, во flex они рассыпались бы в ряд. */

.messages { list-style: none; padding: 0; margin: 0 0 16px; }
/* Блок htmx-error (задание 62) — вид предупреждения без классов msg: скрытый блок есть на каждой
   странице, а тесты ищут показанные сообщения по msg и msg-warning. */
.htmx-error, .msg {
  position: relative;
  padding: 12px 16px 12px 46px; margin-bottom: 8px;
  border-radius: var(--radius-sm);
  border: 1px solid transparent;
  font-size: 14.5px; line-height: 1.45;
}
.htmx-error::before, .msg::before {
  content: "i"; position: absolute; top: 13px; left: 16px;
  display: grid; place-items: center;
  width: 20px; height: 20px; border-radius: 50%;
  border: 1.5px solid currentColor; font-size: 12px; font-weight: 700; line-height: 1;
}
.msg-success { background: var(--m-success-bg); border-color: var(--m-success-border); }
.msg-success::before { content: "\2713"; color: var(--success); }
.htmx-error, .msg-warning { background: var(--m-warning-bg); border-color: var(--m-warning-border); }
.htmx-error::before, .msg-warning::before { content: "!"; color: var(--warning); }
.msg-error { background: var(--m-error-bg); border-color: var(--m-error-border); }
/* Ошибка — «×» в кружке, предупреждение — «!»: различаются значком, а не только цветом. */
.msg-error::before { content: "\00d7"; color: var(--danger); font-size: 14px; }
.msg-info { background: var(--m-info-bg); border-color: var(--m-info-border); }
.msg-info::before { content: "i"; color: var(--info); }

/* --- Шапка документа: подпись — значение, по две пары в ряд --------------------------------- */

dl.head {
  display: grid; grid-template-columns: max-content minmax(0, 1fr) max-content minmax(0, 1fr);
  gap: 10px 28px; margin: 0; align-items: baseline;
}
dl.head dt { color: var(--muted); font-size: 13.5px; }
/* Цифры одной ширины: суммы в «Оплате заказа» и остатки читаются столбиком (задание 27).
   Без nowrap — в dd живут названия и ссылки; само число не рвётся за счёт неразрывного пробела. */
dl.head dd { margin: 0; font-weight: 500; font-variant-numeric: tabular-nums; min-width: 0; overflow-wrap: anywhere; }
dl.head dd .muted { font-weight: 400; }

/* --- Листание страниц ---------------------------------------------------------------------- */

.pages { display: flex; gap: 8px; align-items: center; margin: 12px 0; flex-wrap: wrap; color: var(--text-2); font-size: 13.5px; }
/* Кнопка — там, где отбор идёт телом запроса и листает форма («Контрагенты», задание 48); вид тот же. */
.pages a, .pages button {
  display: inline-flex; align-items: center; min-height: 32px; padding: 4px 12px;
  border: 1px solid var(--border-strong); border-radius: var(--radius-sm);
  background: var(--surface); color: var(--text); font-size: inherit; font-weight: 500;  /* кнопка — 13,5 px, как ссылка (задание 86) */
}
.pages a:hover, .pages button:hover { background: var(--surface-2); border-color: var(--border-strong); text-decoration: none; }

/* --- Страница входа ------------------------------------------------------------------------ */

body.login-page {
  min-height: 100vh; display: grid; place-items: center; padding: 16px;
  background: var(--bg);
}
.login {
  width: 100%; max-width: 380px; margin: 0;
  background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
  box-shadow: var(--shadow-lg); padding: 32px;
}
.login .brand { color: var(--text); padding: 0 0 20px; }
.login h1 { font-size: 20px; margin-bottom: 16px; }
.login form { display: flex; flex-direction: column; gap: 14px; }
.login label { display: flex; flex-direction: column; gap: 5px; font-size: 13px; font-weight: 500; color: var(--text-2); }
.login button { min-height: 42px; margin-top: 4px; }

/* --- Окна быстрого создания ---------------------------------------------------------------- */

dialog {
  border: 1px solid var(--border); border-radius: var(--radius);
  background: var(--surface); color: var(--text);
  padding: 20px 24px; max-width: 440px; width: 92vw;
  box-shadow: var(--shadow-lg);
}
dialog::backdrop { background: var(--backdrop); backdrop-filter: blur(2px); }
dialog form { display: flex; flex-direction: column; gap: 12px; }
dialog h3 { margin: 0 0 4px; font-size: 17px; }

/* --- Новая сделка: ряды «общее», «продажа», «закупка» -------------------------------------- */

.deal-head h3 {
  font-size: 13px;
  color: var(--text-2); margin: 20px 0 8px;
}
.deal-head h3:first-child { margin-top: 0; }
.deal-row { display: flex; flex-wrap: wrap; gap: 12px 16px; align-items: flex-start; }
.deal-row label { display: flex; flex-direction: column; gap: 5px; font-size: 13px; font-weight: 500; color: var(--text-2); flex: 1 1 200px; min-width: 0; }
.deal-row input, .deal-row select { width: 100%; }
.deal-row > label:first-child { flex-grow: 2; }
.new-contract {
  flex: 3 1 420px; display: flex; flex-wrap: wrap; gap: 8px 12px;
  background: var(--surface-2); border: 1px dashed var(--border-strong); border-radius: var(--radius-sm); padding: 10px;
}
.new-contract label { flex: 1 1 130px; }
.new-contract select { padding-inline: 8px 4px; }

/* --- Телефон и узкий экран: меню выезжает слева, верхняя полоса светлая -------------------- */

@media (max-width: 900px) {
  /* z-index 21 — выше закреплённой ячейки с курсором (td.cell-item:focus-within — 20), чтобы при
     прокрутке строка не рисовалась поверх полосы. */
  .mobile-top {
    position: sticky; top: env(safe-area-inset-top, 0px); z-index: 21;
    display: flex; align-items: center; gap: 8px;
    min-height: 52px; padding: 4px 10px;
    background: var(--surface); color: var(--text);
    border-bottom: 1px solid var(--border);
  }
  .burger { display: grid; place-items: center; width: 44px; height: 44px; border-radius: 10px; cursor: pointer; color: var(--text); }
  .burger:hover { background: var(--side-hover); }
  /* Флажок #nav-toggle в порядке Tab (Space открывает ящик), кольцо фокуса — на «☰». */
  .nav-toggle { display: block; }
  .nav-toggle:focus-visible ~ .layout .burger { box-shadow: var(--focus); }
  .brand-mini { display: flex; align-items: center; gap: 8px; color: var(--text); font-weight: 600; font-size: 16px; }
  /* Та же плашка .brand-logo, на полосе телефона — 26 px, svg 20 px. */
  .brand-mini .brand-logo { width: 26px; height: 26px; }
  .brand-mini .brand-logo svg { width: 20px; height: 20px; }
  .brand-mini:hover { text-decoration: none; }

  .sidebar { width: min(var(--side-w), 86%); transform: translateX(-100%); transition: transform .2s ease; border-right: 0; }
  .sidebar:focus-visible { box-shadow: var(--shadow-lg), var(--focus); }
  /* Тень — только у открытого ящика: у закрытого она легла бы серой полосой на левый край экрана. */
  .nav-toggle:checked ~ .layout .sidebar { transform: none; box-shadow: var(--shadow-lg); }
  .nav-toggle:checked ~ .layout .nav-backdrop {
    display: block; position: fixed; inset: 0; z-index: 25; background: var(--backdrop);
  }

  main { margin-left: 0; padding: 16px; max-width: none; }
  h1 { font-size: 22px; }
  dl.head { grid-template-columns: max-content minmax(0, 1fr); }
}

@media (max-width: 600px) {
  .table-wrap { --cell-y: 8px; --cell-x: 10px; }
  /* Таблица шире экрана: текст по центру её ширины оказался бы за краем. */
  tbody > tr > td[colspan]:only-child { text-align: left; }
  .box { padding: 14px 16px; }
  dl.head { grid-template-columns: 1fr; gap: 2px; }
  dl.head dt { margin-top: 10px; }
  .filters > *, .filters .grow { flex: 1 1 100%; }
  .filters button { width: 100%; }
  /* Таблица выходит на всю ширину экрана: прокручивается только она, не страница. */
  .table-wrap { margin-left: -16px; margin-right: -16px; border-radius: 0; border-left: 0; border-right: 0; }
  /* Поля строк: то же (0,1,1), что в общем правиле, чтобы блок 27а оставался сильнее. */
  .lines-input input:where(:not([type=checkbox])), .lines-input select { min-width: 92px; }
}

@media print {
  .sidebar, .mobile-top, .actions, .filters, .loading-bar { display: none !important; }
  main { margin: 0; padding: 0; }
  .table-wrap { max-height: none; box-shadow: none; }
}


/* Продажа и покупка (задание 10): метка. Цветной полосы у блока больше нет: сторону задаёт сам экран
   или бейдж в заголовке (задание 36). */
.side { display: inline-block; padding: 1px 8px; border-radius: 6px; font-size: 12.5px; font-weight: 500;
  vertical-align: middle; }
.side-sale { background: var(--b-green-bg); color: var(--b-green); }
.side-purchase { background: var(--b-blue-bg); color: var(--b-blue); }
.section-sale, .section-purchase { border-left: 0; padding-left: 0; }
h1 .side, h2 .side { margin-left: 0; }
/* «Где товар» на «Товар пришёл» / «Отгрузить»: варианты — кнопками в одну строку (замечание 2026-10-29). */
.place-field { display: flex; flex-direction: column; gap: 5px; flex: 2 1 320px; min-width: 0; }
.place-label { font-size: 13px; font-weight: 500; color: var(--text-2); }
.place-choice { display: flex; flex-wrap: wrap; gap: 8px; }
.deal-row .place-choice label {
  flex: none; flex-direction: row; align-items: center; gap: 8px;
  padding: 4px 12px; border: 1px solid var(--border-strong); border-radius: var(--radius-sm);
  background: var(--surface); color: var(--text); font-size: 14px; font-weight: normal; cursor: pointer;
}
.deal-row .place-choice input { width: auto; margin: 0; }
.deal-row .place-choice label:has(input:checked) { border-color: var(--primary); background: var(--primary-soft);
  color: var(--primary); font-weight: 600; }
.deal-row .place-choice label:hover { border-color: var(--input-hover); }
.deal-row .place-choice label:has(input:focus-visible) { box-shadow: var(--focus); }
@media (max-width: 600px) {
  .place-field { flex-basis: 100%; }
  .deal-row .place-choice label { flex: 1 1 140px; }
}
.place-only { align-items: center; padding: 8px 0; }
/* Склад скрыт, пока не выбрано «На склад»: display у .deal-row label иначе перебивает hidden. */
.deal-row label[hidden] { display: none; }
.side-intra { background: var(--b-yellow-bg); color: var(--b-yellow); }

/* Заявка (задание 16): шапка в три колонки, итоги справа, поиск товара в строке. */
.request-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 12px; }
.request-status { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 10px; font-size: 14px; }
.request-header { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(240px, 100%), 1fr)); gap: 20px 24px; }
.request-col { display: flex; flex-direction: column; gap: 12px; }
/* Заявка (задание 88): поля шапки идут по сетке подряд, по три в ряд (Организация, Контрагент,
   Объект; Склад, вид и валюта договора) — у новой заявки нет пустой третьей колонки. Колонки-обёртки
   остаются в разметке (#org-fields обновляется запросом при смене организации). */
#request-form > .request-header > .request-col { display: contents; }
/* Не больше трёх в ряд (иначе на широком экране 5 + 1): ячейка не уже трети шапки; на узком — 240 px, меньше колонок. */
#request-form > .request-header { grid-template-columns: repeat(auto-fill, minmax(max(min(240px, 100%), calc((100% - 48px) / 3 - 1px)), 1fr)); }
.request-col label > span { font-size: 15px; font-weight: 500; color: var(--text); }
.request-col label > span.muted { font-weight: 400; color: var(--muted); font-size: 13.5px; }
.request-col label > input, .request-col label > select { font-weight: 400; }
.request-col label small.muted { font-weight: 400; font-size: 12.5px; }
.request-markup { display: flex; flex-wrap: wrap; gap: 16px 32px; }
.request-markup label { flex: 0 1 300px; min-width: 0; }
.request-markup label small { font-weight: 400; font-size: 12.5px; }
/* Итоги — на плашке --surface-2, числа крупнее. */
.request-totals {
  margin-left: auto; max-width: 420px; display: flex; flex-direction: column; gap: 6px;
  padding: 14px 18px; background: var(--surface-2); border-radius: var(--radius);
}
.request-totals div { display: flex; justify-content: space-between; align-items: baseline; gap: 24px; font-variant-numeric: tabular-nums; }
.request-totals div > span { color: var(--text-2); }
/* Сумма итога — одной строкой (задание 27: «13 440 000,00 UZS» не рвётся перед валютой);
   если не влезает, переносится подпись слева, а не число. */
.request-totals strong { font-size: 17px; font-weight: 600; white-space: nowrap; font-variant-numeric: tabular-nums; }
.request-totals .grand { border-top: 1px solid var(--border-strong); padding-top: 10px; margin-top: 4px; }
.request-totals .grand > span { color: var(--text); font-weight: 600; }
.request-totals .grand strong { font-size: 20px; font-weight: 650; }
.request-totals .msg { margin: 0 0 8px; }
.stock-popup { text-align: left; font-size: 0.9em; }
.request-date { display: flex; align-items: center; gap: 10px; font-size: 15px; font-weight: 500; color: var(--text-2); }
.combo { position: relative; }
.request-comment { margin-top: 16px; }
.request-comment label { display: flex; flex-direction: column; gap: 5px; font-size: 13px; font-weight: 500; color: var(--text-2); }
.request-comment textarea { width: 100%; max-width: 640px; }

/* Выпадающий список найденного (задание 28): товар в строке, «Поставщик», «Контрагент».
   Открывается поверх страницы у самого поля — строки таблицы не сдвигаются, а прокрутка таблицы
   и узкая ячейка его не обрезают. Место, ширину и высоту ставит core/combo.js.
   Предкам таблицы и полей поиска не ставить transform, translate, rotate, scale, filter,
   backdrop-filter, perspective, contain, container-type, content-visibility, а также will-change
   с ними, и position вместе с z-index: иначе список привяжется к такому предку или окажется под
   закреплёнными ячейками. */
.combo-results {
  position: fixed; z-index: 15;
  overflow-y: auto; overscroll-behavior: contain;
  padding: 4px 0;
  background: var(--surface); border: 1px solid var(--border-strong);
  border-radius: var(--radius-sm); box-shadow: var(--shadow-lg);
  text-align: left; white-space: normal;
}
.combo-results:empty { display: none; }
.combo-results:focus-visible { box-shadow: var(--shadow-lg), var(--focus); }
/* Пункт списка — строка во всю ширину: название слева, артикул или ИНН справа. Вид кнопки
   перебит целиком; выделен только пункт с .is-active (стрелки или мышь), не :hover. */
.combo-results .combo-option,
.combo-results .combo-create {
  display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
  width: 100%; min-height: 40px; padding: 9px 12px;
  background: transparent; border: 0; border-radius: 0;
  color: var(--text); font-size: 14.5px; font-weight: 400; line-height: 1.35;
  text-align: left; white-space: normal; overflow-wrap: anywhere;
  cursor: pointer; transition: none;
}
.combo-results .combo-option:hover,
.combo-results .combo-create:hover { background: transparent; }
.combo-option > span { flex: 1 1 auto; min-width: 0; }
.combo-option small {
  flex: none; white-space: nowrap; font-size: 12.5px; color: var(--text-2); font-variant-numeric: tabular-nums;
}
/* «+ Создать …» — последним пунктом, синим, с чертой над ним, если выше есть пункты. */
.combo-results .combo-create { color: var(--link); font-weight: 550; }
.combo-results * + .combo-create { border-top: 1px solid var(--border); }
/* Выделенный пункт — серый фон и чернильная полоса слева, как у открытого пункта меню. */
.combo-results .combo-option.is-active,
.combo-results .combo-create.is-active { background: var(--primary-soft); box-shadow: inset 3px 0 0 var(--primary); }
.combo-results .combo-option.is-active:focus-visible,
.combo-results .combo-create.is-active:focus-visible { box-shadow: inset 3px 0 0 var(--primary), var(--focus); }
/* Выделенный «+ Создать» — обычным цветом: на серой подложке он читается лучше синего. */
.combo-results .combo-create.is-active { color: var(--text); }
/* Подписи без действия: «Не найдено.», «Показаны первые 20…», «…пока нет»; ошибка — красным. */
.combo-results > small { display: block; padding: 8px 12px; font-size: 13px; line-height: 1.4; color: var(--text-2); }
.combo-results > small.neg { color: var(--danger); margin-top: 0; }

/* Таблица позиций компактнее остальных: до 14 колонок с полями. */
.lines-input th, .lines-input td { padding: calc(var(--cell-y) - 2px) calc(var(--cell-x) - 2px); }
/* Поле товара в строке — самое широкое: после выбора в нём «артикул — название», а похожие товары
   различаются концом названия (задание 28). Ширину столбца по-прежнему можно поменять вручную —
   тогда поле сжимается до столбца (правило ниже, для table.cols-fixed). */
table.request-lines td.cell-item > input[type=search] { min-width: 220px; }
table.cols-fixed.request-lines td.cell-item > input[type=search] { min-width: 0; }
/* Колонка «Наименование» закреплена слева на любой ширине: при прокрутке вправо название строки
   остаётся на месте. Ячейка с colspan не закрепляется — иначе накрыла бы соседей. */
table.request-lines > thead > tr > th[data-col="item"],
table.request-lines > tbody > tr > td.cell-item:not([colspan]) {
  position: sticky; left: 0; z-index: 2; background: var(--surface); box-shadow: inset -1px 0 0 var(--border);
}
table.request-lines > thead > tr > th[data-col="item"] { z-index: 3; background: var(--surface-2); }
.lines-input tbody tr:hover td.cell-item { background: var(--surface); }
/* Закреплённая ячейка — свой контекст наложения: выпадающий список товара (combo.js оставляет его
   внутри ячейки, position: fixed) рисовался бы под закреплёнными ячейками следующих строк. Пока в
   ячейке курсор, она поднимается выше остальных (и выше шапки — список может открыться вверх). */
table.request-lines > tbody > tr > td.cell-item:focus-within { z-index: 20; }
/* В остальных таблицах закреплена первая колонка (номер, товар, «когда»). */
.table-wrap > table:not(.lines-input) > thead > tr > th:first-child,
.table-wrap > table:not(.lines-input) > tbody > tr > td:first-child:not([colspan]) {
  position: sticky; left: 0; z-index: 2; background: var(--surface); box-shadow: inset -1px 0 0 var(--border);
}
.table-wrap > table:not(.lines-input) > thead > tr > th:first-child { z-index: 3; background: var(--surface-2); }
.table-wrap > table:not(.lines-input) > tbody > tr:hover > td:first-child:not([colspan]) { background: var(--row-hover); }
.table-wrap > table:not(.lines-input) > tbody > tr.total > td:first-child:not([colspan]) { background: var(--surface-2); }
.table-wrap > table:not(.lines-input) > tbody > tr.current > td:first-child:not([colspan]) { background: var(--primary-soft); }
/* Строка итога в подвале таблицы (tfoot): подпись «Итого» тоже закреплена слева — на телефоне при
   прокрутке вбок видно, что это за число (задание 44а). Подпись — отдельная первая ячейка без colspan. */
.table-wrap > table:not(.lines-input) > tfoot > tr > :first-child:not([colspan]) {
  position: sticky; left: 0; z-index: 2; background: var(--surface-2); box-shadow: inset -1px 0 0 var(--border);
}
tfoot tr:last-child > * { border-bottom: 0; }
/* Числа без поля («На складе / всего», «Сумма с НДС», «Доступно / Остаток», маржа) — на одной линии
   с текстом в полях строки. */
table.lines-input.request-lines > tbody > tr > td.num:not(:has(input, select)) { padding-top: 13px; }
/* Подписи под числами в ячейке — своей строкой. Подпись внутри блока ячейки (сейчас — «сумма вручную» /
   «изменено вручную» в .vat-pair) переносится, а не раздувает столбец (задание 27; подсказки последней
   закупки под остатком больше нет — задание 89). «средняя …» и «= …» под полями — прямые дети ячейки. */
td.num small.muted { display: block; font-size: 12.5px; margin-top: 3px; white-space: nowrap; }
td.num small.muted:empty { display: none; }
table.request-lines td.num > div > small.muted { display: block; white-space: normal; }
@media (max-width: 600px) {
  /* Закреплённые колонки на телефоне. Ширину ячейки задают width + min-width (один width в тесной
     таблице сжимается до min-content): «Наименование» 168 px, прокрутке остаётся ≈ 150–200 px. В
     таблицах просмотра первая колонка естественной ширины; в «Строках» карточки название
     переносится по словам, колонке — не уже 168 px. */
  table[data-cols="document_lines"] > thead > tr > th:first-child,
  table[data-cols="document_lines"] > tbody > tr > td:first-child:not([colspan]) { min-width: 168px; }
  table.request-lines > thead > tr > th[data-col="item"],
  table.request-lines > tbody > tr > td.cell-item { width: 168px; min-width: 168px; }
  table.request-lines td.cell-item > input[type=search] { min-width: 0; width: 100%; }
  table.lines-input.request-lines > tbody > tr > td.num:not(:has(input, select)) { padding-top: 15px; }
  .request-totals { max-width: none; }
  .request-totals div { gap: 12px; }
  .request-comment textarea { max-width: none; }
  /* «Не оплачено: 1 000 000 000,00 из …» — на телефоне переносится, а не уводит страницу вбок. */
  .request-status .badge { white-space: normal; max-width: 100%; }
  /* «Сохранить» и «Закрыть» прилипают к низу экрана, во всю ширину (с учётом выреза телефона). */
  #request-form > .actions {
    position: sticky; bottom: 0; z-index: 5; margin: 8px -16px 0;
    padding: 10px 16px calc(10px + env(safe-area-inset-bottom, 0px));
    background: var(--bg); border-top: 1px solid var(--border);
  }
  #request-form > .actions > button, #request-form > .actions > .button { flex: 1 1 auto; }
}

/* Под таблицей позиций: «+ Строка» и пояснение о пределе строк (задание 28). */
.lines-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: -4px 0 8px; }
.lines-actions button.secondary.add-row { min-height: 32px; padding: 4px 12px; font-size: 13.5px; }
/* Подсказка под таблицей (задание 29): первая фраза видна, остальное — по «Подробнее». */
.lines-hint { font-size: 13.5px; line-height: 1.5; margin: 0 0 16px; max-width: 90ch; }
.lines-hint details { display: block; margin-top: 2px; }
.lines-hint summary { display: inline-block; cursor: pointer; color: var(--link); font-weight: 500; list-style: none; }
.lines-hint summary::-webkit-details-marker { display: none; }
.lines-hint details[open] > summary { color: var(--muted); }
/* После hex-escape парсер CSS съедает один пробел как завершитель: " \2014 свернуть" дало бы
   «—свернуть», поэтому неразрывный пробел тоже escape-ом. */
.lines-hint details[open] > summary::after { content: " \2014\00a0свернуть"; }
.lines-hint details > span { display: block; margin-top: 4px; }
/* Пояснение под итогами («правила НДС нет …») — мелко, серым, с переносом. */
.request-totals > small { display: block; font-size: 12.5px; line-height: 1.4; }
@media print {
  .combo-results, .lines-actions { display: none; }
}

/* Окно «Откуда брать» у строки заявки (Р-27).
   Шапка и полоса с кнопками закреплены, прокручивается только середина.
   Окно лежит внутри строки таблицы позиций, поэтому правила .lines-input здесь перебиты. */
.src-summary { margin-top: 6px; display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: baseline; font-size: 13px; }
.src-summary small { font-size: 12.5px; overflow-wrap: anywhere; }
/* Ошибки мест под названием (задание 89) — кнопки окна «Откуда брать»: красные, как текст ошибки. */
.src-summary button.link.neg { color: var(--danger); font-size: 12.5px; text-align: left; overflow-wrap: anywhere; }
dialog.src-dialog {
  width: min(1000px, calc(100vw - 32px)); max-width: none;
  max-height: calc(100vh - 48px); max-height: calc(100dvh - 48px);
  padding: 0; overflow: hidden; text-align: left; white-space: normal;
  border: 1px solid var(--border); border-radius: var(--radius);
  background: var(--surface); color: var(--text); box-shadow: var(--shadow-lg);
}
dialog.src-dialog[open] { display: flex; flex-direction: column; }
.src-dialog::backdrop { background: var(--backdrop); backdrop-filter: blur(2px); }

.src-top {
  display: flex; align-items: flex-start; gap: 12px;
  padding: 16px 24px 12px; border-bottom: 1px solid var(--border);
}
.src-top h3 { flex: 1; min-width: 0; margin: 0; font-size: 17px; overflow-wrap: anywhere; }
.src-top .src-item { color: var(--text-2); font-weight: 550; }
dialog.src-dialog .src-close {
  flex: none; min-height: 0; width: 32px; height: 32px; padding: 0; margin: -4px -8px 0 0;
  background: transparent; border: 0; border-radius: var(--radius-sm);
  color: var(--muted); font-size: 22px; line-height: 1; font-weight: 400;
}
dialog.src-dialog .src-close:hover { background: var(--surface-2); color: var(--text); }

.src-body { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 16px 24px 20px; }
.src-body h4 { margin: 20px 0 2px; font-size: 15px; font-weight: 600; }
.src-note { margin: 0 0 10px; font-size: 13px; }
.src-label {
  margin: 0 0 6px; font-size: 12.5px; font-weight: 600;
  color: var(--text-2);
}

/* Где есть товар: склады слева, итог и быстрые кнопки справа */
.src-where { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 16px 24px; align-items: start; }
.src-stock:empty { min-height: 80px; }
.src-stock-table { border: 1px solid var(--border); border-radius: var(--radius-sm); font-size: 13.5px; }
.src-dialog .src-stock-table th { position: static; padding: 6px 10px; font-size: 12px; }
.src-dialog .src-stock-table td { padding: 6px 10px; }
.src-dialog .src-stock-table thead th:first-child { border-top-left-radius: var(--radius-sm); }
.src-dialog .src-stock-table thead th:last-child { border-top-right-radius: var(--radius-sm); }
.src-dialog .src-stock-table tbody tr.src-own td,
.src-dialog .src-stock-table tbody tr.src-own:hover td { background: var(--primary-soft); font-weight: 600; }
.src-own-mark {
  margin-left: 4px; padding: 0 6px; border-radius: 6px;
  background: var(--b-blue-bg); color: var(--b-blue); font-size: 11.5px; font-weight: 500; white-space: nowrap;
}
.src-need {
  margin: 0 0 14px; padding: 10px 14px;
  border: 1px solid var(--border); border-left: 4px solid var(--border-strong); border-radius: var(--radius-sm);
  background: var(--surface-2); font-size: 15.5px; line-height: 1.6;
}
/* «не хватает 1 300,000» — одной фразой; строка переносится по точкам между частями (задание 27). */
.src-need strong { font-variant-numeric: tabular-nums; white-space: nowrap; }
.src-need.short { border-left-color: var(--danger); background: var(--m-error-bg); }
.src-need.ok { border-left-color: var(--success); background: var(--m-success-bg); }
.src-need .pos, .pos { color: var(--success); }
.src-quick { display: flex; flex-wrap: wrap; gap: 8px; }
.src-quick button { min-height: 32px; padding: 4px 10px; font-size: 13px; }

/* Как покрыть: одна доля — одна строка */
.src-table {
  --src-cols: minmax(150px, 1.5fr) minmax(96px, .8fr) minmax(130px, 1.3fr)
              minmax(128px, 1.1fr) minmax(76px, .6fr) minmax(128px, 1.1fr) 28px;
  border: 1px solid var(--border); border-radius: var(--radius-sm);
}
.src-table.is-empty { border-style: dashed; }
.src-head, .source-row {
  display: grid; grid-template-columns: var(--src-cols); gap: 8px; align-items: start; padding: 8px 10px;
}
.source-row[hidden], .src-table.is-empty .src-head { display: none; }
.src-head {
  background: var(--surface-2); border-bottom: 1px solid var(--border);
  border-radius: var(--radius-sm) var(--radius-sm) 0 0;
  font-size: 12px; font-weight: 600; color: var(--text-2);
  line-height: 1.3;
}
.src-head .num, .src-f-num { text-align: right; }
.source-row + .source-row { border-top: 1px solid var(--border); }
dialog.src-dialog .source-row label { display: flex; flex-direction: column; gap: 2px; min-width: 0; font-size: 12px; }
dialog.src-dialog .source-row label input,
dialog.src-dialog .source-row label select { width: 100%; min-width: 0; padding: 4px 8px; }
dialog.src-dialog .source-row .src-f-num input { text-align: right; font-variant-numeric: tabular-nums; }
/* Заблокированная доля (Р-37): список «Откуда» не меняется — вид поля только для чтения. */
.source-row[data-locked] select { background: var(--input-readonly-bg); color: var(--text-2); }
.src-cap {
  position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap;
}
.src-f-drop { display: flex; justify-content: center; padding-top: 6px; }
dialog.src-dialog .src-drop { font-size: 18px; line-height: 1; color: var(--muted); }
dialog.src-dialog .src-drop:hover { color: var(--danger); text-decoration: none; }
.src-errors { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 2px; font-size: 12.5px; }
/* Доля недоступной фирмы (Р-37, задание 37б): подсказка — единственное объяснение прочерков, поэтому
   цвет темнее обычного серого (контраст AA) и размер как у плотных таблиц. Значение ячейки без поля —
   отступы и размер как у соседних полей. */
.src-locked { grid-column: 1 / -1; font-size: 13px; line-height: 1.35; color: var(--text-2); }
dialog.src-dialog .source-row .src-value { padding: 4px 8px; font-size: 14px; font-weight: 400; font-variant-numeric: tabular-nums; }
dialog.src-dialog .source-row .src-value:not(.muted) { color: var(--text); }
.src-empty { margin: 0; padding: 12px 14px; font-size: 13px; }
.src-add { margin-top: 10px; }

/* Поле не нужно для этого вида доли: прячем (значение остаётся в форме), в ячейке — прочерк */
.source-row[data-kind="own"] .src-f-group > :not(.src-cap),
.source-row[data-kind="stock"] .src-f-supplier > :not(.src-cap) { display: none; }
.source-row[data-kind="own"] .src-f-group::after,
.source-row[data-kind="stock"] .src-f-supplier::after { content: "—"; padding: 4px 8px; font-size: 14px; color: var(--muted); }

/* Закреплённая полоса внизу: счёт и кнопки видны всегда */
.src-foot {
  display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 16px;
  padding: 12px 24px; border-top: 1px solid var(--border); background: var(--surface-2);
  border-radius: 0 0 var(--radius) var(--radius);
}
.src-foot .actions { margin: 0; }
.src-count { margin: 0; font-weight: 600; font-variant-numeric: tabular-nums; }
.src-count.neg { color: var(--danger); }

/* Ноутбук поуже: таблица долей превращается в карточки по две колонки. Точка перехода — сумма минимумов
   --src-cols + зазоры и отступы окна: 888 px, на сенсорном экране минимумы шире — 972 px. */
@media (max-width: 888px), (pointer: coarse) and (max-width: 972px) {
  .src-where { grid-template-columns: 1fr; }
  .src-head { display: none; }
  .source-row { grid-template-columns: 1fr 1fr; gap: 8px 12px; padding: 12px; }
  .src-cap { position: static; width: auto; height: auto; overflow: visible; clip: auto; white-space: normal; }
  .src-f-source { grid-column: 1 / -1; }
  .src-head .num, .src-f-num { text-align: left; }
  .src-f-drop { grid-column: 1 / -1; justify-content: flex-end; padding-top: 0; }
  dialog.src-dialog .src-drop { font-size: 13px; }
  /* В карточке поля идут столбиком: объяснение — над ними, а не под «убрать». */
  .src-locked { order: -1; }
  .source-row[data-kind="own"] .src-f-group,
  .source-row[data-kind="stock"] .src-f-supplier { display: none; }
  .source-row[data-locked] .src-f-none { display: none; }
}
/* Телефон: окно почти на весь экран, поля в одну колонку, кнопки во всю ширину */
@media (max-width: 600px) {
  dialog.src-dialog { width: calc(100vw - 16px); max-height: calc(100vh - 16px); max-height: calc(100dvh - 16px); }
  .src-top { padding: 12px 14px 10px; }
  .src-body { padding: 12px 14px 16px; }
  .src-foot { padding: 10px 14px; }
  .src-foot .actions, .src-foot .actions button { flex: 1 1 auto; }
  .source-row { grid-template-columns: 1fr; }
}

/* Метка строки заявки: хватает ли склада (под «Доступно / Остаток») */
.line-need { margin-top: 4px; font-size: 12.5px; white-space: normal; }
.line-need .need-short { color: var(--danger); font-weight: 600; text-align: right; }
.line-need .need-covered { color: var(--muted); }
.line-need .need-ok { color: var(--success); font-weight: 600; }

/* Закуп на склад: поля фирмы-закупщика — колонки той же сетки шапки */
.request-header-part { display: contents; }
/* Новый договор закупки — свёрнут, раскрывается по нажатию (поля те же, что и раньше). */
/* В колонке шапки — без растяжки: flex-basis 420px у .new-contract в колонке становился высотой
   (пустое пространство на «Закупе на склад», замечание владельца 2026-10-29). Свёрнутый — просто ссылка. */
.request-col details.new-contract { flex: none; display: block; background: none; border: 0; padding: 0; }
.request-col .new-contract-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
.request-col .new-contract-fields label { flex: none; }
.new-contract summary { cursor: pointer; color: var(--link); width: fit-content; }
.new-contract summary:hover { text-decoration: underline; }
.new-contract-fields { display: flex; flex-direction: column; gap: 8px; margin-top: 8px;
  padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface-2); }

/* Полоса шагов процесса (задание 19): кружки и линия, без рамок. Пройдено — зелёный кружок с ✓,
   частично — жёлтый с номером, текущий — единственная чернильная заливка, этап открытого документа —
   синее кольцо и подпись, не нужен / нет доступа — пунктирный контур и приглушённое название.
   Под этапами — главный шаг и его кнопка. */
.process { padding: 20px 24px; }
.process-title { margin-bottom: 14px; font-size: 13px; font-weight: 500; color: var(--muted); }
.steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 0;
  grid-template-columns: repeat(auto-fit, minmax(128px, 1fr)); }
.step { position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 8px;
  min-width: 0; padding: 0 12px 0 0; }
.step::before { content: ""; position: absolute; top: 13px; left: 26px; right: 0; height: 2px; background: var(--border-strong); }
.step:last-child::before { display: none; }
.step-no { position: relative; z-index: 1; flex: none; display: inline-flex; align-items: center; justify-content: center;
  width: 26px; height: 26px; border-radius: 50%; background: var(--surface); border: 1.5px solid var(--border-strong);
  color: var(--muted); font-size: 12px; font-weight: 650; line-height: 1; }
.step-body { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
.step-title { font-size: 13.5px; font-weight: 500; line-height: 1.3; overflow-wrap: anywhere; color: var(--text-2); }
.step-state { font-size: 12px; color: var(--muted); line-height: 1.35; }
/* Переход к документам этапа (замечание 2026-10-29). */
a.step-link { color: inherit; text-decoration: underline dotted; text-decoration-color: var(--muted);
  text-underline-offset: 3px; }
/* Нажимается весь этап, а не только надпись (удобно на телефоне). */
a.step-link::after { content: ""; position: absolute; inset: 0; border-radius: inherit; }
a.step-link:hover, a.step-link:focus-visible { color: var(--link); outline: none; }
.step-docs { display: flex; flex-wrap: wrap; gap: 2px 8px; font-size: 12px; }
.step-docs a { color: var(--link); }
.step-docs a, .step-docs strong { white-space: nowrap; }
.step-docs strong { color: var(--text); }
.step-state:empty { display: none; }
/* «этот документ» на ноутбуке — отдельной строкой под состоянием: на всех этапах в одном месте и
   без висящей точки «0 из 1 ·». На телефоне — в строку через точку (см. @media ниже). */
.step-here-mark { display: block; font-weight: 600; }
.step-done .step-no { background: var(--success); border-color: var(--success); color: var(--surface); }
.step-done .step-title { color: var(--text); }
.step-partial .step-no { background: var(--b-yellow-bg); border-color: var(--b-yellow); color: var(--b-yellow); }
.step-partial .step-state { color: var(--b-yellow); }
/* «Не нужен» и «нет доступа» — без прозрачности: текст под opacity падал ниже 4,5:1. */
.step-skip .step-no, .step-no_access .step-no { border-style: dashed; background: transparent; }
.step-skip .step-title, .step-no_access .step-title { color: var(--muted); }
.step-current .step-no { background: var(--primary); border-color: var(--primary); color: var(--on-primary); }
.step-current .step-title { color: var(--text); font-weight: 650; }
/* Этап открытого документа — только синее кольцо и подпись «этот документ»; цвет своего состояния
   он сохраняет. Заливкой выделен только текущий шаг (решение владельца 2026-10-30). */
.step-here .step-no { box-shadow: 0 0 0 3px var(--surface), 0 0 0 5px var(--step-here); }
.step-here .step-here-mark { color: var(--step-here); }
.step-next { margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--border);
  display: flex; flex-wrap: wrap; align-items: center; gap: 10px 20px; }
.step-next-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; max-width: 72ch; }
.step-next-text strong { font-size: 16px; }
.step-note { color: var(--text-2); }
.step-all-done { color: var(--success); font-size: 16px; }
.step-next form { margin: 0; }
.step-next button, .step-next .button { min-height: 42px; padding: 9px 22px; font-size: 15px; }
.process-hidden { margin: 12px 0 0; font-size: 13.5px; }
.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; }

/* Ряд кнопок карточки, когда главный шаг уже есть в полосе: те же кнопки, но скромнее. */
.actions-caption { align-self: center; font-size: 13.5px; color: var(--muted); }
.actions-minor button:not(.danger):not(.secondary):not(.link),
.actions-minor .button:not(.danger):not(.secondary) {
  background: var(--surface); color: var(--text); border-color: var(--border-strong); }
.actions-minor button:not(.danger):not(.secondary):not(.link):hover,
.actions-minor .button:not(.danger):not(.secondary):hover {
  background: var(--surface-2); border-color: var(--input-hover); }

/* Связанные документы: строка открытого документа — серым фоном и чернильной полоской слева.
   Второе правило — в одном box-shadow с волоском закреплённой первой ячейки, иначе закрепление
   (специфичность выше) полоску перебивает. */
table.related tr.current td { background: var(--primary-soft); }
table.related tr.current td:first-child { box-shadow: inset 3px 0 0 var(--primary); }
.table-wrap > table.related > tbody > tr.current > td:first-child:not([colspan]) { box-shadow: inset 3px 0 0 var(--primary), inset -1px 0 0 var(--border); }
table.related td:first-child, table.related td strong { white-space: nowrap; }

/* Экран заявки: заголовок над полосой шагов, дата — первой строкой формы. */
.request-head { margin-bottom: 16px; }
.request-head h1 { margin: 0; }
.request-date-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; margin-bottom: 12px; }

/* Телефон: этапы — списком сверху вниз, кнопка шага — во всю ширину. */
@media (max-width: 600px) {
  .steps { grid-template-columns: 1fr; gap: 6px; }
  .step { flex-direction: row; align-items: flex-start; gap: 10px; padding: 2px 0 8px; }
  .step::before { top: 14px; bottom: -8px; left: 12px; right: auto; width: 2px; height: auto; }
  .step-body { flex-direction: row; flex-wrap: wrap; align-items: baseline; gap: 0 8px; padding-top: 4px; }
  /* «частично · этот документ»: точка — у состояния, подпись — одним блоком; если строка не
     влезает, подпись переносится целиком, а не рвётся между словами. */
  .step-here-mark { display: inline-block; }
  .step-state > span:not(.sr-only):has(+ .step-here-mark)::after { content: " · "; color: var(--muted); font-weight: normal; }
  .step-next { align-items: stretch; }
  .step-next form, .step-next .button, .step-next button { width: 100%; }
  .actions-minor > *, .actions-minor form > button { flex: 1 1 auto; }
  .actions-caption { flex: 1 1 100%; }
}

/* «Связанные документы» деревом — что из чего создано (замечание владельца 2026-10-29). */
.related .tree-cell { white-space: nowrap; }
.related .tree { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; color: var(--muted);
  margin-right: 4px; letter-spacing: 0; }
table.related tr.current .tree { color: var(--text); }
.related .tree-start { font-size: 11.5px; padding: 1px 7px; border-radius: 999px; background: var(--b-blue-bg); color: var(--b-blue); font-weight: 500; }
.related-hint { margin-top: -4px; font-size: 13.5px; }

/* --- Таблица позиций (задание 24): порядок строк и ширина столбцов (скрипт core/tables.js) --- */

/* Первая узкая колонка экранов ввода: ручка ⋮⋮ (перетащить мышью) и кнопки ↑ ↓. */
th.row-tools, td.row-tools { width: 1%; padding-left: 8px; padding-right: 2px; white-space: nowrap; }
.row-tools-in { display: flex; align-items: center; gap: 2px; }
.row-handle {
  display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 32px;
  border-radius: 5px; color: var(--muted); font-size: 15px; line-height: 1; letter-spacing: -3px;
  cursor: grab; user-select: none; -webkit-user-select: none;
}
.row-handle:hover { background: var(--surface-2); color: var(--text); }
.row-handle:active { cursor: grabbing; }
.row-move { display: flex; flex-direction: column; gap: 2px; }
.row-move button {
  min-height: 0; width: 24px; height: 15px; padding: 0;  /* 2 × 15 + 2 = 32, как поле (задание 86) */
  background: transparent; border: 1px solid transparent; border-radius: 5px;
  color: var(--muted); font-size: 12px; font-weight: 600; line-height: 1;
}
.row-move button:hover { background: var(--surface-2); border-color: var(--border-strong); color: var(--text); }
.row-move button[aria-disabled="true"],
.row-move button[aria-disabled="true"]:hover { opacity: .3; cursor: default; background: transparent; border-color: transparent; color: var(--muted); }
/* Перетаскивание: сама строка бледнеет, место вставки — чернильная черта. */
tbody[data-reorder] > tr.is-dragging > td { opacity: .4; }
tbody[data-reorder] > tr.drop-before > td { box-shadow: inset 0 2px 0 var(--primary); }
tbody[data-reorder] > tr.drop-after > td { box-shadow: inset 0 -2px 0 var(--primary); }
/* Закреплённая ячейка товара сильнее правил выше: черта и волосок — в одном box-shadow. */
table.request-lines > tbody[data-reorder] > tr.drop-before > td.cell-item:not([colspan]) { box-shadow: inset 0 2px 0 var(--primary), inset -1px 0 0 var(--border); }
table.request-lines > tbody[data-reorder] > tr.drop-after > td.cell-item:not([colspan]) { box-shadow: inset 0 -2px 0 var(--primary), inset -1px 0 0 var(--border); }
/* Строка, которую только что переставили, на секунду подсвечена — видно, куда встала. */
tbody[data-reorder] > tr.row-moved > td { animation: row-moved 1s ease-out; }
@keyframes row-moved { from { background: var(--primary-soft); } to { background: transparent; } }
@media (prefers-reduced-motion: reduce) { tbody[data-reorder] > tr.row-moved > td { animation: none; } }

/* «Удалить» строки (задание 87): красный квадрат с белым крестиком ровно по центру. В формах ввода
   это сам флажок формы (поле …-delete, только CSS), в листе инвентаризации — кнопка .line-delete.
   Крестик — две линии толщиной 2 px фоном самого элемента: два linear-gradient в квадрате --del-x
   по центру. Цвет — из переменной; символа «×» нет (у него смещён центр), псевдоэлементов на
   <input> тоже (в Firefox они ненадёжны). */
.lines-input td:last-child > input[name$="-delete"],
table.stocktake-sheet .line-delete {
  --del-ink: var(--on-danger);
  /* «давай поменьше сделаем кнопку» (владелец 2026-11-26): 30 → 24 px, крестик 12 → 10 px. */
  --del-x: 10px;
  appearance: none; -webkit-appearance: none;
  width: 24px; height: 24px; min-width: 0; min-height: 0; padding: 0; cursor: pointer;
  border: 1px solid var(--danger-solid); border-radius: 6px;
  background-color: var(--danger-solid);
  background-image:
    linear-gradient(45deg, transparent calc(50% - 1.25px), var(--del-ink) calc(50% - .75px), var(--del-ink) calc(50% + .75px), transparent calc(50% + 1.25px)),
    linear-gradient(-45deg, transparent calc(50% - 1.25px), var(--del-ink) calc(50% - .75px), var(--del-ink) calc(50% + .75px), transparent calc(50% + 1.25px));
  background-size: var(--del-x) var(--del-x);
  background-position: center; background-repeat: no-repeat;
}
.lines-input td:last-child > input[name$="-delete"] { display: block; margin: 4px 0 0; }  /* по середине поля 32 px */
.lines-input td:last-child > input[name$="-delete"]:hover,
table.stocktake-sheet .line-delete:hover { background-color: var(--danger-solid-hover); border-color: var(--danger-solid-hover); }
/* Отмечено — видно только в строке, которую сервер вернул с ошибкой: «наоборот», красный крестик на поверхности. */
.lines-input td:last-child > input[name$="-delete"]:checked { --del-ink: var(--danger); background-color: var(--surface); border-color: var(--danger); }
.lines-input td:last-child > input[name$="-delete"]:checked:hover { background-color: var(--m-error-bg); border-color: var(--danger); }
/* Запасная пустая строка внизу (data-spare ставит core/tables.js): квадрата не видно, ширина столбца та же. */
tbody[data-grow] > tr[data-spare] > td:last-child > input[name$="-delete"] { visibility: hidden; }
/* Отмеченная строка уходит с экрана (задание 87); из документа её удалит «Сохранить». Вес правила
   больше, чем у карточки строки на телефоне (table.pos-lines > tbody > tr { display: block }).
   Строка с ошибкой (data-row-errors, ставит шаблон) остаётся видна и зачёркнута — с текстом ошибки. */
.lines-input tbody > tr:has(> td:last-child > input[name$="-delete"]:checked):not([data-row-errors]),
.lines-input tbody > tr:has(> td:last-child > input[name$="-delete"]:checked):not([data-row-errors]) + tr[data-row-part] { display: none; }
.lines-input tbody tr:has(td:last-child > input[name$="-delete"]:checked) td:not(:last-child),
.lines-input tbody tr:has(td:last-child > input[name$="-delete"]:checked) td:not(:last-child) :is(input, select, button.link, a, small, span) { color: var(--muted); text-decoration: line-through; }
/* Полоса «Удалено строк: N. Вернуть» под таблицей — её создаёт core/tables.js. */
.lines-removed { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; margin: 8px 0; font-size: 13px; color: var(--text-2); }
.lines-removed[hidden], .lines-removed [hidden] { display: none; }
.lines-removed button.link { font-size: 13px; }
/* Телефон: число — первой строкой, «Вернуть последнюю · Вернуть все» — второй, без висящей точки. */
@media (max-width: 600px) { .lines-removed > [data-removed-count] { flex-basis: 100%; } }

/* Ширина столбцов: ручка у правой границы заголовка (тонкая черта, синяя под мышью). */
table.mini th[data-col] { position: relative; }
.col-resizer {
  position: absolute; top: 0; right: 0; bottom: 0; z-index: 2; width: 9px;
  cursor: col-resize; touch-action: none;
}
.col-resizer::after {
  content: ""; position: absolute; top: 25%; bottom: 25%; right: 3px; width: 2px; border-radius: 1px;
  background: var(--border-strong); opacity: .55;
}
th:last-child > .col-resizer::after { opacity: 0; }
th:hover > .col-resizer::after { opacity: 1; }
.col-resizer:hover::after, .col-resizer.is-active::after { top: 0; bottom: 0; background: var(--link); opacity: 1; }
html.cols-resizing, html.cols-resizing * { cursor: col-resize !important; user-select: none; -webkit-user-select: none; }
/* Ширина задана вручную: длинные заголовки переносятся, не влезающее в ячейку — обрезается «…»,
   поля ввода сжимаются до ширины столбца. */
table.cols-fixed > thead > tr > th { white-space: normal; overflow-wrap: break-word; }
table.cols-fixed > tbody > tr > td { overflow: hidden; text-overflow: ellipsis; overflow-wrap: break-word; }
table.cols-fixed td input, table.cols-fixed td select, table.cols-fixed td textarea,
table.cols-fixed td.cell-item select { min-width: 0; max-width: 100%; }
.cols-reset { display: flex; justify-content: flex-end; margin: -6px 0 6px; }
.cols-reset .link { font-size: 12.5px; }
/* Заголовок мини-таблицы позиций в карточке заявки — тихий, чтобы не спорить с таблицей документов. */
table.mini > thead th { background: transparent; color: var(--muted); font-weight: 500; }

@media print {
  .row-tools, .col-resizer, .cols-reset, .lines-removed { display: none !important; }
}

/* --- Справочники «Товары» и «Договоры» (задание 25) ---------------------------------------- */

/* Кнопка в заголовке («+ Новый товар») — обычного размера: иначе она берёт шрифт заголовка. */
h1 > .button { font-size: 13.5px; letter-spacing: normal; }

/* Столбец с сортировкой выглядит как обычный заголовок; синим — под мышью и тот, по которому
   сейчас отсортировано (со стрелкой ↑ ↓). */
th a.sort-link, th button.sort-link { color: inherit; }
th a.sort-link:hover, th button.sort-link:hover { color: var(--link); text-decoration: none; }
th a.sort-link.is-sorted, th button.sort-link.is-sorted { color: var(--link); }
/* Сортировка кнопкой формы («Контрагенты», задание 48) выглядит как та же ссылка в заголовке. */
th button.sort-link { display: inline; min-height: 0; padding: 0; font-size: inherit; font-weight: inherit; }

/* Длинное название контрагента в фильтре не растягивает страницу вбок на телефоне. */
.filters label { min-width: 0; }
.filters select { max-width: 100%; }

/* Длинное название товара в списке переносится, а не уводит таблицу вбок. */
td.cell-wrap a { white-space: normal; }

/* Статус договора: «Действует» — зелёным, «Закрыт» — серым (не красным зачёркнутым, как
   отменённый документ); строка закрытого договора — приглушённым цветом. */
.badge-active { background: var(--b-green-bg); color: var(--b-green); }
.badge-closed { background: var(--b-gray-bg); color: var(--b-gray); }
tr.row-closed td { color: var(--muted); }
tr.row-closed .side { opacity: .7; }

/* Быстрые переходы под значением в шапке карточки: контрагент → его договоры, документы, долги. */
.dd-links { display: flex; flex-wrap: wrap; gap: 2px 12px; margin-top: 2px;
  font-size: 13.5px; font-weight: 400; }

/* Поле с ошибкой — красной рамкой (Django сам ставит aria-invalid), текст ошибки — под полем.
   Селектор как у общего правила полей и его :hover / :focus и ниже них: иначе красной рамки у
   поля не видно, а в фокусе она сохраняется вместе с синим кольцом. */
input:not([type=checkbox]):not([type=radio]):not([type=hidden])[aria-invalid="true"],
select[aria-invalid="true"], textarea[aria-invalid="true"] { border-color: var(--danger); }

/* Список причин внутри предупреждения («Удалить нельзя:») — без лишних отступов. */
.msg > ul { margin: 4px 0 0; padding-left: 20px; }

/* --- Журнал документов: отборы ровной сеткой (задание 26) ---------------------------------- */
/* Десять отборов — поля одной ширины рядами; длинный договор или товар не растягивает поле
   на полстроки (полный текст — в раскрытом списке). Кнопки — отдельной строкой под полями. */
.filters.filters-grid {
  display: grid; align-items: end;
  grid-template-columns: repeat(auto-fill, minmax(min(180px, 100%), 1fr));
}
.filters-grid input, .filters-grid select { width: 100%; min-width: 0; }
.filters-actions { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 8px; }
@media (max-width: 600px) {
  .filters.filters-grid { grid-template-columns: repeat(auto-fill, minmax(min(140px, 100%), 1fr)); }
  .filters-actions > * { flex: 1 1 0; }
}

/* Товар в строках документа — ссылка на карточку (задание 26): длинное название переносится,
   а не уводит таблицу вбок (общее td a — без переноса, для номеров документов). */
table[data-cols="document_lines"] td a { white-space: normal; }
/* Ссылка в новую вкладку (договор на экране заявки): стрелка ↗ — экран с правками остаётся. */
a[target="_blank"]::after { content: "\00a0\2197"; content: "\00a0\2197" / ", в новой вкладке"; font-size: .85em; }

/* --- Числа в полях ввода (задание 27а) ---------------------------------------------------- */
/* Выравнивание — по полю, а не по ячейке: на части экранов ячейки без .num. Ширина вмещает
   9 999 999 999,99 / 999 999,999 / 100,00: обрезанный край показывает другое число, ошибка в 1000
   раз. Значения в ch, поэтому сами подстраиваются под шрифт телефона. Правила ниже .lines-input
   input по файлу и потому сильнее него; table.cols-fixed и окно «Откуда брать» сильнее этих правил
   и обнуляют min-width: там ширину задаёт столбец (data-col-min, --src-cols). */
input[data-number] { text-align: right; font-variant-numeric: tabular-nums; }
input[data-number="money"] { min-width: calc(14ch + 18px); }
input[data-number="qty"] { min-width: calc(10ch + 18px); }
input[data-number="percent"] { min-width: calc(5.5ch + 18px); }
/* Серая подсказка «по правилу» — длиннее самого числа, иначе конец слова обрезан. :where — чтобы
   table.cols-fixed по-прежнему сжимал поле до столбца. */
input[data-number="percent"]:where([placeholder="по правилу"]) { min-width: calc(9ch + 18px); }
/* Формула ширины считает отступы по 8 px. Общее правило полей сильнее .lines-input input и оставляет 12 px: край числа обрезался бы. */
.lines-input input[type=text][data-number] { padding-inline: 8px; }
/* Фон — с [type=text]: общее правило полей выше (input:not(…):not(…):not(…)) сильнее короткого селектора. */
input[type=text][data-number]:is([readonly], :disabled) { background: var(--input-readonly-bg); }
/* Значение не помещается в поле (core/numbers.js; полное число — в подсказке). */
input[type=text][data-number].number-long { background: var(--m-warning-bg); }
/* td.num без переноса; длинные ошибки раньше почти не доходили до сервера. */
td.num small.neg { white-space: normal; }
/* Ошибка сервера под полем — как подпись скрипта: по правому краю поля, столбец не раздувает. */
td input[data-number] ~ small.neg { display: block; width: 0; min-width: 100%; text-align: right; line-height: 1.3; }
/* Подписи под числовым полем: внутри мелкой подписи поля small дал бы 10 px. */
input[data-number] ~ small, .src-errors small { font-size: 12px; }
/* Подпись скрипта под полем, по его правому краю. Ширина столбца от неё не зависит. */
small[data-number-msg] { display: block; white-space: normal; text-align: right; line-height: 1.3; }
td small[data-number-msg] { width: 0; min-width: 100%; }
small[data-number-msg] + br { display: none; }
/* Окно «Откуда брать» вводит те же деньги: не мелкий полужирный шрифт подписи (font: inherit), а как
   в таблице: 14 px обычным начертанием. Полужирные цифры шире, и край суммы обрезался бы. */
dialog.src-dialog .source-row label input[data-number] { font-size: 14px; font-weight: 400; }

/* Настройка «уменьшить движение»: без плавных переходов. */
@media (prefers-reduced-motion: reduce) {
  .loading-bar, .sidebar, button, .button, input, select, textarea { transition: none; }
}

/* Себестоимость в окне «Откуда брать» и карточке товара (задание 31). min-width и прокрутку не убирать:
   ниже 888 px ячейка сетки иначе раздвинула бы окно по ширине таблицы. */
.src-where-stock { min-width: 0; }
.src-stock-scroll { overflow-x: auto; }
.src-dialog .src-stock-table th.num { white-space: normal; }
/* Слово без пробелов в названии склада не выталкивает числа за край; 96 px — место под метку склада. */
.src-dialog .src-stock-table td:nth-child(2),
table[data-cols="item_stock"] td:nth-child(2):not(.num) { min-width: 96px; overflow-wrap: anywhere; }
.cost-note { margin: 6px 0 0; font-size: 13px; }
@media (max-width: 600px) {
  .src-dialog .src-stock-table th, .src-dialog .src-stock-table td { padding-left: 8px; padding-right: 8px; }
}

/* --- Таблицы позиций: единый набор колонок (задание 32) -------------------------------------- */
/* Поля ячеек уже, заголовки переносятся, товар 200 px: иначе закуп не помещается и на 1366 px. */
table.lines-input.pos-lines { --cell-x: 8px; }
table.pos-lines th.num { white-space: normal; }
table.pos-lines th.num[data-col="qty"] { white-space: nowrap; } /* иначе «Кол-во» рвётся по дефису */
table.pos-lines td.cell-item > input[type=search] { min-width: 200px; }
table.pos-lines:not(.lines-input) > tbody > tr > td[data-label="Наименование"] { min-width: 180px; }
/* Название одним длинным словом не раздвигает столбец и страницу. В окне «Откуда брать» правила свои. */
table.pos-lines td[data-label="Наименование"] { overflow-wrap: anywhere; }
table.pos-lines td[data-label="Наименование"] dialog { overflow-wrap: normal; }
/* Название текстом при полях в строке («Заказ поставщику»): столбец закреплён, поэтому
   не занимает полэкрана, но и не сжимается в полоску на 15 строк. */
table.lines-input.pos-lines td.cell-item:not(:has(> input[type=search], > select)) { width: 220px; min-width: 180px; }
/* Таблицы показа: сохранённая ширина одна на вид таблицы, а числа у документов разные. Столбец можно расширить,
   но сумма другого документа не обрежется «…». !important — tables.js ставит table-layout прямо на таблицу. */
table.pos-lines:not(.lines-input).cols-fixed { table-layout: auto !important; }
/* Tab не прячет поле под закреплённую колонку. */
.table-wrap:has(> table.request-lines) { scroll-padding-left: 216px; }
/* Остаток «доступно / всего» — одной строкой на всех экранах (задание 90, слово владельца «Да, и там»;
   прежнее правило «всегда две строчки» отменено). Узкий столбец переносит число у « / ». */
.cell-stock span + span, .cell-stock span + button { display: inline; margin-left: 0; }
/* Столбец остатка, суженный сотрудником: «всего» уходит на вторую строчку, а не прячется под «…»
   (td.num не переносит). Число не рвётся посередине («1 496,» / «25» читается как два числа):
   разряды — неразрывный пробел, перенос только у « / »; не влезает и одно число — «…». */
table.cols-fixed > tbody > tr > td.cell-stock { white-space: normal; }
table.cols-fixed > tbody > tr > td.cell-stock > span { overflow-wrap: normal; }
/* Остаток в строке заявки (задание 89) — одной строкой: «5 / 13 · не хватает 8». Правила ниже —
   только у заявки (правка и просмотр): метка нехватки и окно «Откуда брать». Каждая
   часть не переносится; столбец, суженный сотрудником (table.cols-fixed), переносит метку «не
   хватает …» целиком на вторую строчку, а не обрезает её «…»: метка — inline-block (уходит вниз
   целиком, а шире столбца — переносится внутри), числа переносятся у « / » (разряды — неразрывный
   пробел). На телефоне (карточка) части ячейки — друг под другом, поэтому точка-разделитель там не
   нужна; :not(:empty) в правиле телефона — иначе правило с точкой сильнее его. */
table:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > div { display: inline; white-space: nowrap; }
table:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock span + button { display: inline-block; margin-left: 0; }
table:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > .line-need { margin-top: 0; }
table:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > .line-need:not(:empty)::before { content: "·"; margin: 0 6px; color: var(--muted); font-weight: 400; }
table.cols-fixed:is([data-cols="request"], [data-cols="request_view"]) > tbody > tr > td.cell-stock { white-space: normal; }
table.cols-fixed:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > div { white-space: normal; }
table.cols-fixed:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > .line-need { display: inline-block; max-width: 100%; }
/* Точка — внутри самой метки: перенос внутри узкой метки не оставляет «·» одну на строчке. */
table.cols-fixed:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > .line-need:not(:empty)::before { content: none; }
@media (min-width: 601px) {
  table.cols-fixed:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > .line-need > :first-child::before { content: "·"; margin: 0 6px; color: var(--muted); font-weight: 400; }
}
@media (max-width: 600px) {
  table:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > div { white-space: normal; }
  table:is([data-cols="request"], [data-cols="request_view"]) td.cell-stock > .line-need:not(:empty)::before { content: none; }
}
/* НДС: ставка и под ней сумма. width: 0 — иначе поле ставки растягивает столбец на свою ширину по умолчанию.
   flex-wrap — чтобы подпись core/numbers.js под полем ушла на свою строку. */
.vat-pair { display: grid; gap: 4px; }
.vat-pair-rate { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.vat-pair-rate > span { color: var(--muted); font-size: 12.5px; }
.lines-input .vat-pair-rate > input[type=text][data-number] { flex: 1 1 0; width: 0; min-width: 0; }
/* Подсказка суммы НДС бывает длиннее 14ch: 6 px вместо 8 дают место 11 цифрам до запятой. */
.lines-input .vat-pair input[type=text][data-number] { padding-inline: 6px; }
td.num .vat-pair small { margin-top: 0; }
.vat-err { width: 0; min-width: 100%; }
.vat-err small.neg { display: block; white-space: normal; text-align: right; line-height: 1.3; font-size: 12px; }
/* Красная рамка — у поля со своим значением. Серая подсказка не виновата: при предупреждении про ставку сумма не краснеет.
   Предупреждение без права (.vat-warn, задание 32б) рамку не зажигает: число допустимо, итоги посчитаны. */
.vat-pair:has(.vat-err small.neg:not(.vat-warn)) > input:not(:placeholder-shown),
.vat-pair:has(.vat-err small.neg:not(.vat-warn)) > .vat-pair-rate > input:not(:placeholder-shown) { border-color: var(--danger); }
/* Заказ на покупку: что уже заказано — под количеством. */
.po-cover { display: block; margin-top: 3px; font-size: 12.5px; line-height: 1.3; color: var(--muted); white-space: nowrap; }
tr.total td small { display: block; }
/* Документы заявки: блок строк прокручивается сам. Правило пустой таблицы (colspan, только ребёнок) здесь перебито. */
td.line-items[colspan]:only-child { padding: 4px 8px 12px; text-align: left; color: inherit; }
.line-items-in { width: 0; min-width: 100%; overflow-x: auto; }
.line-items-in table > thead > tr > th:first-child,
.line-items-in table > tbody > tr > td:first-child { position: sticky; left: 0; z-index: 2; background: var(--surface); box-shadow: inset -1px 0 0 var(--border); }

@media (max-width: 600px) {
  /* Строка — карточка; подпись берётся из data-label. Сетка, а не абсолютная подпись: длинная подпись увеличивает ячейку. */
  .table-wrap:has(> table.pos-lines) { margin-left: 0; margin-right: 0; overflow: visible; background: none; border: 0; box-shadow: none; }
  table.pos-lines, table.pos-lines > tbody { display: block; width: auto !important; table-layout: auto !important; }
  table.pos-lines > thead { display: none; }
  table.pos-lines > tbody > tr { display: block; position: relative; margin-bottom: 8px; padding: 6px 0; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-sm); }
  table.pos-lines > tbody > tr:has(> td.row-tools, > td > input[name$="-delete"]) { padding-top: 50px; }
  table.pos-lines > tbody > tr > td,
  table.lines-input.request-lines.pos-lines > tbody > tr > td.num:not(:has(input, select)) { display: grid; grid-template-columns: minmax(0, 45%) minmax(0, 1fr); column-gap: 8px; position: relative; padding: 6px 12px; border: 0; text-align: right; white-space: normal; }
  table.pos-lines > tbody > tr > td > * { grid-column: 2; }
  table.pos-lines > tbody > tr > td > br { display: none; }
  table.pos-lines > tbody > tr > td::before { content: attr(data-label); grid-column: 1; grid-row: span 6; text-align: left; font-size: 12.5px; font-weight: 500; color: var(--text-2); }
  /* Наименование — во всю ширину, без подписи и без закрепления. */
  table.request-lines.pos-lines > tbody > tr > td.cell-item:not([colspan]),
  .table-wrap > table.pos-lines:not(.lines-input) > tbody > tr > td:first-child:not([colspan]),
  table.pos-lines > tbody > tr > td[data-label="Наименование"] { display: block; position: static; width: auto; min-width: 0; padding: 6px 12px; text-align: left; background: none; box-shadow: none; font-weight: 500; }
  table.pos-lines > tbody > tr > td[data-label="Наименование"]::before { content: none; }
  /* Стрелки — слева вверху рядом, «Удалить» — справа вверху. */
  table.pos-lines > tbody > tr > td.row-tools { display: block; position: absolute; left: 8px; top: 2px; width: auto; padding: 0; }
  table.pos-lines .row-move { flex-direction: row; }
  table.pos-lines > tbody > tr > td:has(> input[name$="-delete"]) { display: block; position: absolute; right: 8px; top: 2px; padding: 0; }
  table.pos-lines > tbody > tr > td.row-tools::before,
  table.pos-lines > tbody > tr > td:has(> input[name$="-delete"])::before { content: none; }
  /* Пустое расчётное значение не занимает строку. */
  table.pos-lines > tbody > tr > td:has(> span:not([hidden]):empty),
  table.pos-lines > tbody > tr > td:has(> [id^="info-"]:empty),
  table.lines-input.request-lines.pos-lines > tbody > tr > td.num:has(> span:not([hidden]):empty),
  table.lines-input.request-lines.pos-lines > tbody > tr > td.num:has(> [id^="info-"]:empty) { display: none; }
  table.pos-lines tr.total > td:empty { display: none; }
  /* «Все строки удалены…» в «Изменить» черновика (задание 87): текст на всю ширину карточки, без колонки подписи. */
  table.pos-lines > tbody > tr[data-removed-empty] > td { display: block; padding: 16px 12px; text-align: left; }
  table.pos-lines > tbody > tr[data-removed-empty] > td::before { content: none; }
  table.pos-lines td.num small.muted { white-space: normal; }
  table.pos-lines > tbody > tr.total > td[colspan] { display: block; text-align: left; }
  table.pos-lines td input:not([type=checkbox]) { width: 100%; }
  .cell-stock span + span, .cell-stock span + button { display: inline; margin-left: 0; }
  .cols-reset:has(+ .table-wrap > table.pos-lines) { display: none; }
  /* Блок строк в документах заявки держится у левого края экрана при прокрутке внешней таблицы. */
  .line-items-in { position: sticky; left: 8px; width: calc(100vw - 16px); min-width: 0; overflow: visible; }
  .line-items-in table > tbody > tr > td:first-child { box-shadow: none; }
}

/* --- Заявка только для просмотра (задание 32а) ------------------------------------------------- */
/* Название текстом: 80 символов — три строчки. Только от 601 px: на телефоне строка — карточка. */
@media (min-width: 601px) {
  table.request-lines.pos-lines:not(.lines-input) > tbody > tr > td.cell-item:not([colspan]) { width: 280px; min-width: 280px; }
}
/* Tab на число остатка не прячет его под закреплённый столбец. */
.table-wrap:has(> table.request-lines:not(.lines-input)) { scroll-padding-left: 296px; }
.request-date > span { color: var(--text); font-variant-numeric: tabular-nums; }
/* Комментарий — связный текст, поэтому обычным начертанием, а не как короткие значения шапки. */
.request-comment label > span { max-width: 640px; font-size: 14px; font-weight: 400; color: var(--text); overflow-wrap: anywhere; }
/* Окно лежит внутри строки таблицы: без .lines-input мышь над окном красила бы все строки «Где есть товар». */
dialog.src-dialog .src-stock-table tbody tr:not(.src-own) td { background: transparent; }
/* Значения без поля — вровень с заголовками: отступ 8 px нужен только рядом с полями ввода. */
dialog.src-dialog .src-view .source-row .src-value { padding-inline: 0; overflow-wrap: anywhere; }
.src-view .source-row[data-kind="own"] .src-f-group::after,
.src-view .source-row[data-kind="stock"] .src-f-supplier::after { padding-inline: 0; }
@media (max-width: 600px) {
  /* Доля — строки «подпись — значение», как карточка позиции. display ниже возвращает скрытие: сетка его перебила бы.
     Прочерки запертой доли сетка не трогает: их прячет прежнее правило .source-row[data-locked] .src-f-none. */
  dialog.src-dialog .src-view .source-row label:not(.src-f-none) { display: grid; grid-template-columns: minmax(0, 45%) minmax(0, 1fr); column-gap: 8px; align-items: baseline; }
  dialog.src-dialog .src-view .source-row[data-kind="own"] .src-f-group,
  dialog.src-dialog .src-view .source-row[data-kind="stock"] .src-f-supplier { display: none; }
  .src-view .src-cap { font-size: 12.5px; }
  dialog.src-dialog .src-view .source-row .src-value { padding-block: 0; text-align: right; }
  .src-view .source-row { gap: 6px; }
}

/* Серое число в поле: подпись «= цена» его только повторяет (задание 33). */
table.request-lines td:has(input:placeholder-shown) small[id^="calc-"] { display: none; }
/* Серая наценка бывает большой: `99 999,99` входит целиком. */
table.request-lines td[data-label="Наценка, %"] input[data-number="percent"] { min-width: calc(8ch + 18px); padding-inline: 6px; }

/* Полоса заявки по веткам (задание 35): линейки на широком экране, список на узком. */
.req-bar .steps { grid-template-columns: repeat(auto-fit, minmax(112px, 1fr)); }
.req-bar .step-body { flex: 1 1 auto; flex-direction: column; align-items: stretch; }
.req-bar .step-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 8px; }
.req-bar .step-wide { grid-column: span 2; }
.req-bar .step-body form { margin: 0; }
.step-hint { margin: 4px 0 0; font-size: 13.5px; line-height: 1.45; color: var(--text-2); max-width: 52ch; }
.step-action { margin-top: 8px; min-height: 42px; padding: 9px 22px; font-size: 15px; width: fit-content; max-width: 100%; }
.step-go { display: inline-flex; align-items: center; margin-top: 2px; font-size: 13.5px; font-weight: 500; }
.step-more { font-size: 12px; color: var(--muted); line-height: 1.35; }

/* Голова и «Свой склад»: без линии между ними — это не последовательность. */
.req-top { display: flex; flex-wrap: wrap; gap: 8px 48px; }
.req-top > .steps { display: block; }
.req-own .step, .branch-side .step { flex-direction: row; align-items: flex-start; gap: 10px; padding: 0; }
.req-own .step-body, .branch-side .step-body { padding-top: 4px; }
.branch-side { margin-top: 10px; display: block; }
/* Серые строки — не последовательность: линии между ними нет (их стало две, задание 44). */
.branch-side .step::before { display: none; }
.branch-side .step + .step { margin-top: 8px; }
.step-gray .step-no { border-style: dotted; background: transparent; }
.step-gray .step-title { color: var(--muted); }

.branch-wrap { margin-top: 14px; padding-top: 10px; border-top: 1px solid var(--border); }
.req-tail { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border); }
.branch > summary { list-style: none; cursor: pointer; display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 8px; padding: 4px 0; font-size: 14px; font-weight: 600; color: var(--text); }
.branch > summary::-webkit-details-marker { display: none; }
.branch > summary::before { content: ""; flex: none; width: 0; height: 0; margin-inline: 9px 11px; border-block: 5px solid transparent; border-inline-start: 7px solid var(--muted); align-self: center; }
.branch[open] > summary::before { transform: rotate(90deg); }
.branch-state { font-weight: 500; font-size: 13px; color: var(--muted); }
.branch-state::before { content: "\00b7\00a0"; }
.branch-partial .branch-state { color: var(--b-yellow); }
.branch-done .branch-state { color: var(--b-green); }
.branch-next { margin: 0; padding-left: 27px; font-size: 13.5px; color: var(--text-2); }
.branch-next .doc-no { white-space: nowrap; }
.branch > .steps:first-of-type { margin-top: 6px; }
details[open] + .branch-next { display: none; }
.req-bar[data-wide] .branch > summary { cursor: default; padding: 0 0 8px; }
.req-bar[data-wide] .branch > summary::before { display: none; }

/* Экран заявки: сверху следующий шаг, остальное свёрнуто (решение владельца 2026-11-05). */
.process-all { margin-top: 12px; padding-top: 8px; border-top: 1px solid var(--border); }
.process-all > summary { cursor: pointer; font-size: 13.5px; font-weight: 500; color: var(--link); padding: 4px 0; }
.process-all > .req-bar { margin-top: 10px; }
.process-title + .step-next, .process-title + .process-all { margin-top: 0; padding-top: 0; border-top: 0; }
.step-next .step-action { margin-top: 0; }

/* Уже 1200 px линейка не помещается: список сверху вниз, как на телефоне. */
@media (max-width: 1199px) {
  .req-bar .steps { grid-template-columns: 1fr; gap: 6px; }
  .req-bar .step { flex-direction: row; align-items: flex-start; gap: 10px; padding: 2px 0 8px; }
  .req-bar .step::before { top: 14px; bottom: -8px; left: 12px; right: auto; width: 2px; height: auto; }
  .req-bar .step-body { padding-top: 3px; }
  .req-bar .step-wide { grid-column: auto; }
  .req-top { display: block; }
  .req-own { margin-top: 6px; }
  .branch-wrap { margin-top: 4px; padding-top: 6px; }
  .req-tail { margin-top: 6px; padding-top: 10px; }
  .branch > summary { padding: 8px 0 6px; font-size: 14.5px; }
  .branch > .steps { margin: 2px 0 4px 8px; }
  .branch > .branch-side { margin-top: 4px; }
}
@media (max-width: 600px) {
  .process:has(.req-bar) { padding: 16px; }
  .req-bar form, .step-action { width: 100%; }
}

/* --- Мелкие правки по отчёту проверки (задание 43) ------------------------------------------- */
/* Обязательное поле — звёздочка перед подписью: по атрибуту required, который ставит сама форма.
   Подпись — колонка flex, поэтому звёздочка стоит абсолютно, слева от текста, и строк не добавляет.
   Отборы, вход, дата в шапке заявки и закупа (прилипала к заголовку) и тесная сетка окна «Откуда брать» —
   без звёздочек. Вторая запись content — чтобы программа чтения с экрана не
   произносила «звёздочка»: обязательность она берёт из required. */
label:not(.filters label, .login label, .request-date, [class*="src-f-"]):has(> input:required:not([type=hidden]):not([type=checkbox]):not([type=radio]), > select:required, > textarea:required) { position: relative; }
label:not(.filters label, .login label, .request-date, [class*="src-f-"]):has(> input:required:not([type=hidden]):not([type=checkbox]):not([type=radio]), > select:required, > textarea:required)::before {
  content: "*"; content: "*" / "";
  position: absolute; top: var(--req-top, 0); left: -.7em; translate: 0 var(--req-shift, 0);
  color: var(--danger); font-weight: 600;
}
/* Карточка из двух-трёх полей (товар): поля делят всю ширину карточки, пустого места справа нет. */
.form-grid.form-grid-fit { display: flex; flex-wrap: wrap; }
.form-grid-fit > label { flex: 1 1 220px; min-width: 0; }
.form-grid-fit > label.wide { flex-basis: 100%; }
/* «Закуп на склад»: поле товара шире, чем в заявке, — название видно целиком. Поле и так растягивается
   на свободное место столбца; минимум растёт с экраном, чтобы на ноутбуке 1366 px «Сумма с НДС» и «×»
   не уезжали далеко за правый край. Столбец сузили вручную (table.cols-fixed) или экран уже —
   действуют прежние правила (200 px). */
@media (min-width: 1280px) {
  table[data-cols="stock_purchase"] td.cell-item > input[type=search] { min-width: 240px; }
}
@media (min-width: 1600px) {
  table[data-cols="stock_purchase"] td.cell-item > input[type=search] { min-width: 280px; }
}
/* Страница входа: «Показать пароль» — флажок и подпись в строку. */
.login label:has(> input[type=checkbox]) { flex-direction: row; align-items: center; gap: 8px; font-weight: 400; cursor: pointer; }
.login input[type=checkbox] { margin: 0; flex: none; }
/* Страницы «не найдено» и «нет доступа»: карточка как у входа, без меню. */
.error-page p { margin: 0 0 20px; color: var(--text-2); }
.error-page .button { display: flex; justify-content: center; align-items: center; min-height: 42px; }
/* Отборы журналов на телефоне свёрнуты под «Фильтры» (раскрывает и считает выбранное скрипт
   core/_filters_fold.html; без скрипта отборы раскрыты). На широком экране заголовка нет. */
.filters-fold > summary { display: none; }
@media (max-width: 600px) {
  .filters-fold { margin-bottom: 16px; }
  .filters-fold > summary {
    display: flex; align-items: center; gap: 8px; min-height: 44px; padding: 0 2px;
    list-style: none; cursor: pointer; font-size: 14.5px; font-weight: 600; color: var(--link);
  }
  .filters-fold > summary::-webkit-details-marker { display: none; }
  .filters-fold > summary::before {
    content: ""; flex: none; width: 0; height: 0;
    border-block: 5px solid transparent; border-inline-start: 7px solid currentColor;
  }
  .filters-fold[open] > summary::before { transform: rotate(90deg); }
  .filters-fold > summary > small { font-weight: 400; color: var(--muted); }
  .filters-fold > .filters { margin-bottom: 0; }
}

/* Журналы с поиском (задание 46). Форма .filters.filters-stack: поле поиска (.filters-search) всегда
   на виду, остальные отборы — в .filters-fold (на телефоне свёрнуты), кнопки (.filters-actions) —
   отдельной строкой. Короткий ряд отборов («Остатки», «Долги») на ноутбуке стоит в одной строке с
   поиском; сетка «Документов» (.filters-grid) занимает всю ширину, поиск — строкой выше. */
.filters-stack .filters-fold > .filters { margin-bottom: 0; }
.filters-stack > .filters-actions { flex: 1 1 100%; }
.filters-search input { width: 100%; text-overflow: ellipsis; }
@media (min-width: 601px) {
  .filters-stack > .filters-search { flex: 0 1 320px; }
  .filters-stack > .filters-fold { flex: 0 1 auto; min-width: 0; }
  .filters-stack > .filters-fold:has(> .filters-grid) { flex: 1 1 100%; }
}
@media (max-width: 600px) {
  .filters-stack > .filters-fold { margin-bottom: 0; }
}

/* Пустое состояние журнала (задание 46): таблица из одних заголовков шире экрана, и длинное
   объяснение со ссылкой сброса уезжало за край. Текст держится в видимой части: не шире окна и
   остаётся на месте при прокрутке таблицы вбок. На широком экране ограничение не срабатывает. */
.table-wrap td > .empty-note { position: sticky; left: 16px; max-width: calc(100vw - 66px); }
@media (max-width: 600px) {
  .table-wrap td > .empty-note { max-width: calc(100vw - 32px); }
}

/* Форма контрагента (задание 45). «Кто это» — галочки одной группой в строку: галочка слева, слово
   справа; строка не ниже 44 px — в неё попадают и пальцем. Закрытый ПИНФЛ — текстом на месте поля. */
.form-grid fieldset.checks {
  display: flex; flex-wrap: wrap; align-items: center; gap: 0 20px;
  flex: 1 1 220px; min-width: 0; margin: 0; padding: 0; border: 0;
}
.form-grid fieldset.checks > legend { padding: 0; margin-bottom: 5px; font-size: 13px; font-weight: 500; color: var(--text-2); }
.form-grid fieldset.checks > label { flex-direction: row; align-items: center; gap: 8px; min-height: 44px; cursor: pointer; }
.form-grid fieldset.checks input[type=checkbox] { margin: 0; flex: none; }
.form-grid fieldset.checks > small { flex-basis: 100%; }
.form-grid .field-static {
  display: flex; flex-direction: column; gap: 5px; flex: 1 1 220px; min-width: 0;
  font-size: 13px; font-weight: 500; color: var(--text-2);
}
.form-grid .field-static > output {
  display: flex; align-items: center; min-height: 32px;
  font-size: 14px; font-weight: 400; color: var(--text); font-variant-numeric: tabular-nums;
}
.form-grid .field-static > small { font-weight: 400; }
/* Список контрагентов на телефоне: метка «организация группы» переносится по словам, иначе
   строка с ней шире экрана 360 px и таблица прокручивается вбок. */
td.cell-wrap .badge { white-space: normal; }
/* Задание 44: главные кнопки формы и карточки на телефоне — во всю ширину (страница «Получить
   поступление», карточка ожидаемого поступления). */
@media (max-width: 600px) {
  .actions-fill > *, .actions-fill > form > button { flex: 1 1 auto; }
}

/* Складские формы (перемещение, оприходование, списание): свободное место таблицы — названию
   товара, а не столбцам с короткими числами. Нижние пределы — чтобы «Остаток» и «Сумма» не
   сжимались в столбик. Не действует, когда ширину столбцов задал сам сотрудник (table.cols-fixed). */
table.lines-input:is([data-cols="transfer_lines"], [data-cols="stock_entry_lines"], [data-cols="writeoff_lines"]):not(.cols-fixed) > thead > tr > th[data-col="item"] { width: 60%; }
table.lines-input:is([data-cols="transfer_lines"], [data-cols="stock_entry_lines"], [data-cols="writeoff_lines"]):not(.cols-fixed) > thead > tr > th[data-col="unit"] { min-width: 72px; }
table.lines-input:is([data-cols="transfer_lines"], [data-cols="writeoff_lines"]):not(.cols-fixed) > thead > tr > th[data-col="stock"] { min-width: 150px; }
table.lines-input[data-cols="stock_entry_lines"]:not(.cols-fixed) > thead > tr > th[data-col="amount"] { min-width: 132px; }
/* Кнопки «создать документ» над списком («Остатки»: до четырёх): на ноутбуке 1024 px — в один ряд,
   на телефоне — плитка в два столбца, а не лесенка; уже 340 px — по одной в строке. */
@media (max-width: 1100px) {
  .actions-grid > .button { padding-inline: 12px; }
}
@media (max-width: 600px) {
  .actions-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
  .actions-grid > .button { padding-inline: 6px; font-size: 13.5px; white-space: nowrap; }
}

/* «Изменить» (deals/document_edit.html, форма с классом section-…): причина списания и
   комментарий оприходования — отдельной строкой во всю ширину (в ряду с датой и складом текст
   обрезался). Только эта страница: «Назначение» на форме оплаты заказа — тоже .deal-row и тоже
   name="purpose", его не трогаем. */
form[class^="section-"] > .deal-row > label:has(> [name="purpose"]) { flex-basis: 100%; }

/* «Остатки», блок из четырёх кнопок (задание 34ж): на телефоне уже 380 px подпись «+ Инвентаризация»
   была шире кнопки на 2 px — убавляем поля и кегль всех кнопок блока (13 px — нижняя граница). */
@media (max-width: 380px) {
  .actions-grid > .button { padding-inline: 4px; font-size: 13px; }
}
/* Полоса «Идёт инвентаризация» на «Остатках»: строка на документ, ссылка переносится вместе с текстом. */
.stocktake-pending > div + div { margin-top: 4px; }

/* Форма «Новая инвентаризация»: подсказка числа товаров и переключатели «Заполнить лист» — во всю
   ширину блока; переключатели — столбиком, подпись каждого сразу под ним. Пустая подсказка места
   не занимает. */
.form-grid p.wide, .form-grid fieldset.checks-column { grid-column: 1 / -1; margin: 0; }
.form-grid p.wide:empty { display: none; }
.form-grid fieldset.checks-column { flex-direction: column; align-items: flex-start; flex-wrap: nowrap; gap: 0; }
.form-grid fieldset.checks-column input[type=radio] { margin: 0; flex: none; }
.form-grid fieldset.checks-column > small { margin: -8px 0 4px 24px; }
/* Дата и склад текстом на «Изменить» документа по инвентаризации — как .field-static формы. */
.deal-row .field-static {
  display: flex; flex-direction: column; gap: 5px; flex: 1 1 220px; min-width: 0;
  font-size: 13px; font-weight: 500; color: var(--text-2);
}
.deal-row .field-static > output {
  display: flex; align-items: center; min-height: 32px;
  font-size: 14px; font-weight: 400; color: var(--text); font-variant-numeric: tabular-nums;
}

/* Лист подсчёта инвентаризации (задание 34ж): свободное место — названию товара; числа не
   сжимаются. Не действует, когда ширину столбцов задал сам сотрудник (table.cols-fixed). */
table.stocktake-sheet:not(.cols-fixed) > thead > tr > th[data-col="item"] { width: 50%; }
table.stocktake-sheet:not(.cols-fixed) > thead > tr > th[data-col="unit"] { min-width: 72px; }
table.stocktake-sheet:not(.cols-fixed) > thead > tr > th:is([data-col="book"], [data-col="diff"]) { min-width: 120px; }
table.stocktake-sheet .fact-input { width: 100%; min-width: 104px; text-align: right; font-variant-numeric: tabular-nums; }
/* Ноутбук 1024 px: в поле «Факт» целиком видна подсказка «не считали», а место отдано названию —
   столбец «×» без полей заголовка. */
table.stocktake-sheet td input.fact-input:not([type=checkbox]):not([type=radio]):not([type=hidden]) { padding-inline: 8px; }
@media (min-width: 601px) {
  table.stocktake-sheet > tbody > tr > td[data-label="Факт"] { padding-inline: 8px; }
}
table.stocktake-sheet:not(.cols-fixed) > thead > tr > th[data-col="delete"] { width: 40px; padding-inline: 0; }
table.stocktake-sheet td.cell-delete { padding-inline: 2px; }
/* «✓» после сохранения — в строке с разницей: строка не подпрыгивает (общее td.num small.muted — блок). */
table.stocktake-sheet td.num small.muted[title] { display: inline; margin: 0; }
table.stocktake-sheet td.cell-delete { width: 36px; text-align: center; }
/* «×» строки — квадрат «Удалить» (задание 87, общее правило у флажка строк форм ввода). */
table.stocktake-sheet .line-delete { display: inline-block; vertical-align: middle; margin: 0; }
/* Строка, которая не ушла на сервер: видна и без цвета — по тексту «не сохранено» в ячейке. */
table.stocktake-sheet tr[data-unsaved] { background: var(--m-warning-bg); }
/* Ошибку ввода факта сервер пишет в ячейке «Разница»; вторую подпись под полем (её ставит
   core/numbers.js) не показываем. Серая подсказка «Понято как…» остаётся. */
table.stocktake-sheet small.neg[data-number-msg] { display: none; }
/* Блок «Изменить дату, склад, комментарий» на листе: свёрнут, заголовок — как ссылка. */
details.stocktake-header > summary { cursor: pointer; color: var(--link); font-weight: 500; }
details.stocktake-header[open] > summary { margin-bottom: 12px; }
/* Полоса «Посчитано X из Y»: обычный блок под таблицей. */
.stocktake-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin: 8px 0; }
.stocktake-bar > .button { margin-left: auto; }
@media (max-width: 600px) {
  /* Телефон: «Факт» — главное поле карточки; полоса прилипает к низу (как кнопки заявки).
     Селектор нарочно специфичнее общего правила полей в блоке (pointer: coarse) в конце файла:
     там всем полям ставится 16 px и 44 px, а у «Факта» остаются 18 px и 48 px. */
  table.stocktake-sheet td input.fact-input:not([type=checkbox]):not([type=radio]):not([type=hidden]) { font-size: 18px; min-height: 48px; }
  /* «×» — справа вверху карточки; название его не перекрывает. */
  table.stocktake-sheet > tbody > tr > td.cell-delete { display: block; position: absolute; right: 4px; top: 2px; width: auto; padding: 0; }
  table.stocktake-sheet > tbody > tr > td.cell-delete::before { content: none; }
  /* Специфичность — выше общего правила первой ячейки карточки (.table-wrap > table.pos-lines:not(.lines-input) …). */
  .table-wrap > table.pos-lines.stocktake-sheet > tbody > tr > td.cell-wrap[data-label]:first-child { padding-right: 52px; }
  .stocktake-bar {
    position: sticky; bottom: 0; z-index: 5; margin: 8px -16px 0;
    padding: 10px 16px calc(10px + env(safe-area-inset-bottom, 0px));
    background: var(--bg); border-top: 1px solid var(--border);
  }
  /* Полоса не выше одной-двух строк: «Посчитано…» мелко и слева, кнопка — в той же строке справа;
     «Не сохранено строк…» — отдельной строкой под ними. */
  .stocktake-bar { gap: 4px 12px; font-size: 13px; line-height: 1.35; }
  .stocktake-bar > #stocktake-progress { flex: 1 1 0; min-width: 0; }
  .stocktake-bar > #stocktake-unsaved { order: 3; flex-basis: 100%; }
  .stocktake-bar > .button { margin-left: 0; padding-inline: 12px; }
  /* «×» карточки: квадрат 44 × 44 — цель нажатия пальцем (задание 87). */
  table.stocktake-sheet .line-delete { width: 44px; height: 44px; --del-x: 16px; }
}
/* Сообщение «не удалось обновить» (задание 62, core/htmx-errors.js): у верхнего края — кнопки
   «Сохранить / Закрыть» и полосу листа инвентаризации снизу не закрывает. z-index 22: выше
   .mobile-top (21) и выпадающего списка (15), ниже затемнения меню (25) и самого меню (30). */
.htmx-error {
  position: fixed; z-index: 22;
  top: calc(env(safe-area-inset-top, 0px) + 12px);
  left: calc(var(--side-w) + 24px); right: 24px;
  max-width: 640px; margin: 0 auto;
  padding-right: 52px;
  box-shadow: var(--shadow-lg);
}
.htmx-error-title { display: block; font-weight: 600; }
.htmx-error-close {
  position: absolute; top: 6px; right: 6px;
  min-height: 0; width: 32px; height: 32px; padding: 0;
  background: transparent; border: 0; border-radius: var(--radius-sm);
  color: var(--muted); font-size: 22px; line-height: 1; font-weight: 400;
}
.htmx-error-close:hover { background: var(--surface-2); color: var(--text); border: 0; }
/* В открытом окне — первым элементом, в общем потоке, без тени; relative (не static): от блока
   отсчитываются значок «!» (.htmx-error::before) и «×». У окна «Откуда брать» своих полей
   нет (padding: 0) — отступ даём сообщению. */
dialog .htmx-error { position: relative; top: auto; left: auto; right: auto; max-width: none; margin: 0 0 12px; box-shadow: none; }
dialog.src-dialog .htmx-error { margin: 12px 24px 0; }
@media (max-width: 900px) {
  .htmx-error { top: calc(env(safe-area-inset-top, 0px) + 60px); left: 8px; right: 8px; font-size: 14px; }
  dialog.src-dialog .htmx-error { margin: 8px 8px 0; }
}
@media print { .htmx-error { display: none; } }
/* ============================ новые правила — выше этой строки ================================
   Блок (pointer: coarse) должен оставаться последним в файле: правило той же специфичности ниже
   него молча перебьёт 44 px. Новые стили — только на переменных и только выше этой метки. */

/* Сенсорный экран: один блок на все цели нажатия — не ниже 44 px, поля 16 px (иначе iPhone при
   нажатии на поле увеличивает страницу). Один медиазапрос на всё: планшет с мышью получает те же
   цели. Строчные кнопки-ссылки в ячейках (остаток, «не хватает…», ошибки мест «Откуда брать») намеренно остаются
   текстом — иначе строка позиций станет слишком высокой; им цель ≥ 24 px вертикальным отступом. */
@media (pointer: coarse) {
  input:not([type=checkbox]):not([type=radio]):not([type=hidden]), select, textarea { font-size: 16px; min-height: 44px; }
  button:not(.link):not([data-move]), .button, .pages a, .menu a, .theme-switch button,
  .step-next button, .step-next .button, .lines-actions button.secondary.add-row,
  .combo-results .combo-option, .combo-results .combo-create, .brand-mini,
  .branch > summary, .process-all > summary, .step-action, .step-go { min-height: 44px; }
  .req-bar .step-docs a { display: inline-flex; align-items: center; min-height: 24px; }
  .branch-next a { display: inline-flex; align-items: center; min-height: 44px; }
  button.link { display: inline-block; min-height: 24px; padding: 2px 0; }
  .login label:has(> input[type=checkbox]) { min-height: 44px; }  /* «Показать пароль», задание 43 */
  .lines-hint summary, .new-contract summary { padding: 12px 0; }
  .logout .link { display: inline-flex; align-items: center; min-height: 44px; padding: 0; }
  .deal-row .place-choice label { min-height: 44px; }
  dialog.src-dialog .src-close { width: 44px; height: 44px; }
  .htmx-error-close { width: 44px; height: 44px; top: 2px; right: 2px; }  /* задание 62 */
  .lines-input td:last-child > input[name$="-delete"] { width: 44px; height: 44px; --del-x: 16px; margin-top: 0; }
  .lines-removed button.link:not([hidden]) { display: inline-flex; align-items: center; min-height: 44px; padding: 0 4px; }  /* «Вернуть», задание 87 */
  /* Ручка перетаскивания скрыта, кнопки ↑ ↓ столбиком 44×44 — колонка порядка остаётся узкой. */
  .row-handle { display: none; }
  .row-move button { width: 44px; height: 44px; font-size: 18px; border-color: var(--border-strong); background: var(--surface); }
  .col-resizer { width: 16px; }
  .col-resizer::after { right: 6px; }
  /* Деньги в окне «Откуда брать»: минимумы колонок посчитаны под 16 px (задание 27а). */
  dialog.src-dialog .source-row label input[data-number] { font-size: 16px; }
  .src-table {
    --src-cols: minmax(150px, 1.5fr) minmax(120px, .8fr) minmax(130px, 1.3fr)
                minmax(158px, 1.1fr) minmax(76px, .6fr) minmax(158px, 1.1fr) 28px;
  }
}
