:root {
    --bg: #f5f6f8;
    --surface: #ffffff;
    --text: #1c2128;
    --muted: #6b7280;
    --border: #e2e5ea;
    /* Цвет взят из логотипа компании (icon-192.png), а не дженерик-синий. */
    --accent: #00249f;
    --accent-hover: #001b78;
    --danger: #dc2626;
    /* R,G,B того же синего — для теней, тонированных в цвет акцента вместо
       обычной чёрной тени (rgba(var(--accent-rgb), ...)). */
    --accent-rgb: 0, 36, 159;
    /* Сильная ease-out кривая вместо стандартной "ease" — у встроенной не
       хватает "отклика", кастомная даёт то самое premium-ощущение при входе/
       выходе элементов (форма добавления, карточки, тост). */
    --ease-out: cubic-bezier(0.23, 1, 0.32, 1);
    /* Для полупрозрачного "материала" панели фильтра (backdrop-filter) —
       нужен именно rgb-триплет, не hex, чтобы подставлять в rgba(). */
    --surface-rgb: 255, 255, 255;
}

@media (prefers-color-scheme: dark) {
    :root {
        --bg: #14161a;
        --surface: #1d2025;
        --text: #e7e9ec;
        --muted: #9aa1ab;
        --border: #2b2f36;
        /* Тот же фирменный синий, осветлённый для читаемости на тёмном фоне. */
        --accent: #667cc5;
        --accent-hover: #8496d3;
        --danger: #ef5350;
        --accent-rgb: 102, 124, 197;
        --surface-rgb: 29, 32, 37;
    }
}

/* Golos Text — переменный шрифт, спроектированный под кириллицу (не просто
   расширенная латиница), а не системный дефолт браузера. Один файл на
   подмножество покрывает все начертания 400-800 через ось веса. */
@font-face {
    font-family: "Golos Text";
    src: url("/static/fonts/golos-text-cyrillic.woff2") format("woff2");
    font-weight: 400 800;
    font-style: normal;
    font-display: swap;
    unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
    font-family: "Golos Text";
    src: url("/static/fonts/golos-text-latin.woff2") format("woff2");
    font-weight: 400 800;
    font-style: normal;
    font-display: swap;
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122;
}

/* Manrope — только для названия бренда "ГИПЕРИОН" (шапка + логотип на
   странице входа), по просьбе взять именно этот шрифт с публичного сайта
   компании. Только кириллический поднабор — в самом названии нет ни одной
   латинской буквы, остальные подмножества грузить незачем. */
@font-face {
    font-family: "Manrope";
    src: url("/static/fonts/manrope-cyrillic.woff2") format("woff2");
    font-weight: 400 800;
    font-style: normal;
    font-display: swap;
    unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}

* { box-sizing: border-box; }

/* Плавный скролл только если пользователь явно не просил обратное в ОС —
   у людей с чувствительным вестибулярным аппаратом он может вызывать
   дискомфорт, reduced-motion — это прямая просьба его не делать. */
@media (prefers-reduced-motion: no-preference) {
    html { scroll-behavior: smooth; }
}

body {
    margin: 0;
    font-family: "Golos Text", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
    background: var(--bg);
    color: var(--text);
    font-variant-numeric: tabular-nums;
    /* Страховка: если где-то ещё вылезет непереносимое значение шире экрана
       (как в мобильных карточках), страница физически не сможет
       проскроллиться вбок и утащить за собой прилипающую шапку — просто
       обрежется, а не разъедет вёрстку. */
    overflow-x: hidden;
}

/* Шапка (лого/поиск/выход) и меню разделов закреплены вместе одним блоком —
   если бы sticky стоял только на .topbar, при прокрутке вниз меню разделов
   уезжало бы вместе с контентом, и для перехода в другой раздел пришлось бы
   каждый раз скроллить обратно наверх. */
.header-sticky {
    position: sticky;
    top: 0;
    z-index: 10;
}

.topbar {
    background: var(--surface);
    border-bottom: 1px solid var(--border);
}

/* Строка 1: бренд слева, кнопки действий (Выйти/гамбургер) справа —
   margin-left:auto на .topbar-actions прижимает их к правому краю без
   justify-content:space-between (тот распределял бы все 3 элемента, включая
   ФИО, по всей ширине). Строка 2 — ФИО+роль, всегда на всю ширину снизу
   (flex-basis: 100% у .user-info ниже) — не соревнуется за место с кнопками,
   поэтому не обрезается и не наезжает на бренд ни на каком экране. */
.topbar-inner {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    row-gap: 0.35rem;
    padding: 0.75rem 1rem;
}

.brand {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-family: "Manrope", "Segoe UI", Arial, sans-serif;
    font-weight: 800;
    font-size: 1.15rem;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: var(--text);
    text-decoration: none;
}

.brand-logo {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    background: #fff;
}

.topbar-actions {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-left: auto;
}

.user-info {
    flex-basis: 100%;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.btn-logout {
    padding: 0.35rem 0.7rem;
    border-radius: 6px;
    text-decoration: none;
    font-size: 0.85rem;
    white-space: nowrap;
}

.nav-toggle {
    display: none;
    background: none;
    border: 1px solid var(--border);
    border-radius: 6px;
    font-size: 1.2rem;
    padding: 0.25rem 0.6rem;
    color: var(--text);
}

.nav {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 0.4rem;
    padding: 0.6rem 1rem;
    background: var(--surface);
    border-bottom: 1px solid var(--border);
}

.nav a {
    color: var(--muted);
    text-decoration: none;
    padding: 0.4rem 0.7rem;
    border-radius: 6px;
    font-size: 0.9rem;
    white-space: nowrap;
}

.nav-search { display: flex; }
.nav-search input {
    width: 200px;
    max-width: 40vw;
    padding: 0.35rem 0.7rem;
    border-radius: 6px;
    border: 1px solid var(--border);
    background: var(--bg);
    color: var(--text);
    font-size: 0.85rem;
    line-height: 1.3;
}

.nav a.active, .nav a:hover {
    background: var(--accent);
    color: #fff;
}

.content {
    max-width: none;
    margin: 0 auto;
    padding: 1.25rem 1.5rem 3rem;
}

/* Обычные ссылки в контенте — без стандартного синего цвета/подчёркивания
   браузера, но остаются кликабельными (курсор + подчёркивание при наведении). */
.content a {
    color: inherit;
    text-decoration: none;
    cursor: pointer;
}
.content a:hover { text-decoration: underline; }

.section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 0.5rem;
}
.section-header h2 { margin: 0; }
/* margin-left:auto прижимает поиск+кнопку "Добавить" друг к другу справа,
   не трогая justify-content:space-between (нужен для остальных мест,
   где у .section-header только 2 ребёнка — например, пагинация). */
.section-search {
    display: flex;
    align-items: center;
    gap: 0.4rem;
    margin-left: auto;
}
.section-search input {
    width: 180px;
    max-width: 40vw;
    padding: 0.4rem 0.6rem;
    border-radius: 6px;
    border: 1px solid var(--border);
    background: var(--bg);
    color: var(--text);
    font-size: 0.85rem;
}
/* a.toggle-btn — та же специфичность (1 класс + 1 тег), что и у ".content a"
   (см. ниже, там color: inherit для обычных ссылок в контенте) — без явного
   тега побеждало то правило, и текст кнопки "Вперёд" (она <a>, не <button>)
   был почти не виден на синем фоне. */
.toggle-btn, a.toggle-btn {
    background: var(--accent);
    color: #fff;
    border: none;
    border-radius: 6px;
    padding: 0.4rem 0.9rem;
    font-size: 0.85rem;
    cursor: pointer;
    white-space: nowrap;
}
/* Плавное раскрытие/сворачивание без JS-измерения высоты: контейнер —
   grid с одной строкой 0fr→1fr, у неё анимируется сама высота трека.
   Внутренний div обязателен — grid-элементам нужен явный min-height:0,
   иначе они не сжимаются меньше содержимого и анимация не работает. */
.toggle-form {
    display: grid;
    grid-template-rows: 0fr;
    opacity: 0;
    transition: grid-template-rows 0.25s var(--ease-out), opacity 0.2s var(--ease-out), margin-top 0.25s var(--ease-out);
}
.toggle-form.open {
    grid-template-rows: 1fr;
    opacity: 1;
    margin-top: 0.75rem;
}
.toggle-form-inner {
    overflow: hidden;
    min-height: 0;
}

h1 { font-size: 1.85rem; font-weight: 700; letter-spacing: -0.015em; margin: 0 0 0.35rem; }
.hint { color: var(--muted); margin-top: 0; }

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 0.75rem;
    margin-top: 1rem;
}

.card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 1rem;
    text-decoration: none;
    color: var(--text);
    display: block;
    /* Тень в цвет акцента вместо чёрной по умолчанию — тот самый
       "premium" эффект вместо típical border+чёрная тень. */
    box-shadow: 0 1px 2px rgba(var(--accent-rgb), 0.05), 0 8px 20px rgba(var(--accent-rgb), 0.06);
    transition: box-shadow 0.15s ease, transform 0.15s var(--ease-out);
}
/* hover:hover — иначе на телефоне/планшете тап по карточке "залипает" в
   приподнятом состоянии до следующего тапа (инженеры на объекте часто
   заходят с телефона, см. офлайн-очередь поступлений материалов). */
@media (hover: hover) and (pointer: fine) {
    .card:hover {
        box-shadow: 0 2px 4px rgba(var(--accent-rgb), 0.08), 0 12px 28px rgba(var(--accent-rgb), 0.1);
        transform: translateY(-1px);
    }
}

/* Карточки на дашборде/бюджете появляются каскадом, а не все разом — только
   .card, никогда .card-block (там таблицы со sticky-заголовками, см. баг
   с "исчезающими" заголовками при более ранней попытке анимации разделов). */
@keyframes card-fade-in {
    from { opacity: 0; transform: translateY(8px); }
    to { opacity: 1; transform: none; }
}
@media (prefers-reduced-motion: no-preference) {
    .grid .card {
        animation: card-fade-in 300ms var(--ease-out) both;
    }
    .grid .card:nth-child(1) { animation-delay: 0ms; }
    .grid .card:nth-child(2) { animation-delay: 30ms; }
    .grid .card:nth-child(3) { animation-delay: 60ms; }
    .grid .card:nth-child(4) { animation-delay: 90ms; }
    .grid .card:nth-child(5) { animation-delay: 120ms; }
    .grid .card:nth-child(6) { animation-delay: 150ms; }
    .grid .card:nth-child(7) { animation-delay: 180ms; }
    .grid .card:nth-child(8) { animation-delay: 210ms; }
    .grid .card:nth-child(9) { animation-delay: 240ms; }
    .grid .card:nth-child(10) { animation-delay: 270ms; }
    .grid .card:nth-child(n+11) { animation-delay: 300ms; }
}

.card-count { font-size: 1.6rem; font-weight: 700; color: var(--accent); }
.card-title { color: var(--muted); font-size: 0.85rem; margin-top: 0.25rem; }
.card-icon { color: var(--accent); opacity: 0.8; margin-bottom: 0.4rem; }
.card-icon svg { width: 24px; height: 24px; display: block; }

.project-board-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    margin-top: 0.75rem;
}
/* flex-column + margin-top:auto на .project-card-actions прижимает кнопки
   к низу карточки независимо от того, сколько текста выше (адрес, клиент,
   ответственный — у разных объектов разное число строк) — иначе кнопки
   стояли на разной высоте в одном ряду карточек. */
.project-card { cursor: default; display: flex; flex-direction: column; }
.project-card-title { font-weight: 700; margin-bottom: 0.25rem; }
.project-card-title .row-link { color: var(--text); }
.project-card-title .row-link:hover { text-decoration: underline; }
.project-card-meta {
    color: var(--muted);
    font-size: 0.85rem;
    margin-top: 0.5rem;
    display: flex;
    flex-direction: column;
    gap: 0.15rem;
}
.project-card-budget { color: var(--accent); font-weight: 700; margin-top: 0.6rem; }
/* margin-top:auto (вместе с .project-card flex-column выше) прижимает
   кнопки к низу карточки независимо от того, сколько текста выше —
   иначе кнопки стояли на разной высоте у карточек с разным числом строк. */
.project-card-actions {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-top: auto;
    padding-top: 0.6rem;
    border-top: 1px solid var(--border);
    font-size: 0.85rem;
}
.project-card-actions form { margin: 0; }

.budget-cell {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.3rem;
}
.budget-cell-wide { align-items: stretch; max-width: 320px; }
.budget-bar {
    width: 100%;
    max-width: 140px;
    height: 8px;
    border-radius: 999px;
    background: var(--border);
    overflow: hidden;
}
.budget-cell-wide .budget-bar { max-width: none; }
.budget-bar-fill { height: 100%; border-radius: 999px; }
.budget-bar-fill.status-green   { background: #16a34a; }
.budget-bar-fill.status-yellow  { background: #ca8a04; }
.budget-bar-fill.status-red     { background: #dc2626; }
.budget-bar-fill.status-neutral { background: var(--muted); }
@media (prefers-color-scheme: dark) {
    .budget-bar-fill.status-green   { background: #22c55e; }
    .budget-bar-fill.status-yellow  { background: #eab308; }
    .budget-bar-fill.status-red     { background: #ef4444; }
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    padding: 2.25rem 1rem;
    color: var(--muted);
}
.empty-state svg { width: 34px; height: 34px; opacity: 0.55; }
.empty-state p { margin: 0; font-size: 0.9rem; }

.form-error {
    display: flex;
    align-items: flex-start;
    gap: 0.5rem;
    background: rgba(220, 38, 38, 0.08);
    border: 1px solid rgba(220, 38, 38, 0.25);
    color: var(--danger);
    border-radius: 8px;
    padding: 0.7rem 0.9rem;
    margin: 0 0 0.9rem;
    font-size: 0.9rem;
}
.form-error svg { width: 18px; height: 18px; flex-shrink: 0; margin-top: 1px; }
.form-error p { margin: 0; }

.login-body {
    min-height: 100vh;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg);
    font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
    color: var(--text);
}
.login-card {
    width: 100%;
    max-width: 380px;
    margin: 1rem;
    padding: 2.5rem 2rem 2rem;
    background: var(--surface);
    border: 1px solid var(--border);
    border-top: 4px solid var(--accent);
    border-radius: 14px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    text-align: center;
}
.login-logo {
    width: 72px;
    height: 72px;
    padding: 8px;
    background: #fff;
    border-radius: 16px;
    margin-bottom: 1rem;
}
.login-title {
    margin: 0;
    font-family: "Manrope", "Segoe UI", Arial, sans-serif;
    font-weight: 800;
    font-size: 1.5rem;
    letter-spacing: 0.06em;
    text-transform: uppercase;
}
.login-subtitle { margin: 0.35rem 0 1.5rem; }
.login-card .form-grid { text-align: left; }

.card-block {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 1rem;
    margin-top: 1rem;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 0.75rem;
    align-items: end;
}

.form-field { display: flex; flex-direction: column; gap: 0.3rem; }
.form-field label { font-size: 0.8rem; color: var(--muted); }

input, select, button {
    font-size: 0.95rem;
    padding: 0.5rem 0.6rem;
    border-radius: 6px;
    border: 1px solid var(--border);
    background: var(--bg);
    color: var(--text);
}

.form-submit { align-self: end; }

button {
    background: var(--accent);
    color: #fff;
    border: none;
    cursor: pointer;
    transition: background-color 0.15s ease, transform 0.1s var(--ease-out);
}
/* :active (нажатие) остаётся без media query — это тактильный отклик на тап,
   он должен работать одинаково и мышью, и пальцем. :hover же на тач-экране
   "залипает" после тапа до следующего касания — гасим его там, где нет
   настоящего курсора. */
@media (hover: hover) and (pointer: fine) {
    button:hover { background: var(--accent-hover); }
}
button:active { transform: scale(0.97); }
button.is-loading { opacity: 0.65; cursor: wait; transform: none; }

.btn-danger { background: var(--danger); color: #fff; transition: filter 0.15s ease, transform 0.1s var(--ease-out); }
@media (hover: hover) and (pointer: fine) {
    .btn-danger:hover { background: var(--danger); filter: brightness(0.88); }
}
.btn-danger:active, .toggle-btn:active { transform: scale(0.97); }

/* Видимая обводка при навигации с клавиатуры (Tab) — не только для button,
   везде, где может быть фокус: ссылки, поля форм. Без :focus-visible (только
   :focus) обводка мелькала бы и при обычном клике мышью — раздражает. */
a:focus-visible, button:focus-visible, input:focus-visible,
select:focus-visible, textarea:focus-visible {
    outline: 2px solid var(--accent);
    outline-offset: 2px;
}

.offline-banner {
    background: #ca8a0433;
    color: #92620a;
    border: 1px solid #ca8a0466;
    border-radius: 8px;
    padding: 0.6rem 0.9rem;
    margin-bottom: 1rem;
    font-size: 0.9rem;
}
@media (prefers-color-scheme: dark) {
    .offline-banner { color: #facc15; }
}

.budget-warning-banner {
    background: #dc262633;
    color: #991b1b;
    border: 1px solid #dc262666;
    border-radius: 8px;
    padding: 0.6rem 0.9rem;
    margin-bottom: 1rem;
    font-size: 0.9rem;
}
.budget-warning-banner ul {
    margin: 0.35rem 0 0;
    padding-left: 1.2rem;
}
.budget-warning-banner a { color: inherit; text-decoration: underline; }
@media (prefers-color-scheme: dark) {
    .budget-warning-banner { color: #fca5a5; }
}

.status-badge {
    display: inline-block;
    padding: 0.15rem 0.6rem;
    border-radius: 999px;
    font-size: 0.82rem;
    font-weight: 600;
    white-space: nowrap;
}
.status-green   { background: #16a34a33; color: #16a34a; }
.status-yellow  { background: #ca8a0433; color: #ca8a04; }
.status-red     { background: #dc262633; color: #dc2626; }
.status-neutral { background: #6b728033; color: #6b7280; }

@media (prefers-color-scheme: dark) {
    .status-green   { background: #22c55e33; color: #4ade80; }
    .status-yellow  { background: #eab30833; color: #facc15; }
    .status-red     { background: #ef444433; color: #f87171; }
    .status-neutral { background: #9aa1ab33; color: #9aa1ab; }
}

.table-wrap {
    overflow: auto;
    max-height: 65vh;
    margin-top: 0.75rem;
    border: 1px solid var(--border);
    border-radius: 8px;
}

/* Форма вокруг кнопки "Удалить" по умолчанию блочная и растягивается на
   всю ширину ячейки — из-за этого кнопка визуально "гуляла" внутри
   колонки. inline-block без отступов держит её ровно по центру ячейки. */
.table-wrap td form {
    display: inline-block;
    margin: 0;
}

/* Последние столбцы-действия ("Изменить", "Удалить") не должны растягиваться
   под свободное место таблицы (min-width ниже) — иначе в таблицах без
   длинных значений в остальных колонках кнопки "плавают" в широких ячейках
   вместо того, чтобы плотно прилегать друг к другу и к правому краю.
   width:1% в auto-раскладке означает "не больше, чем нужно содержимому" —
   все "лишние" пиксели уходят другим столбцам. */
th:last-child, td:last-child,
th:nth-last-child(2), td:nth-last-child(2) {
    width: 1%;
}

/* separate, а не collapse — иначе объединённые границы ячеек некорректно
   рендерятся вместе с закреплёнными (sticky) столбцами: соседняя колонка
   может на 1-2px наехать на предыдущую и обрезать первый символ текста. */
table { border-collapse: separate; border-spacing: 0; width: 100%; min-width: 600px; }
th, td {
    text-align: center;
    padding: 0.5rem 0.6rem;
    border-bottom: 1px solid var(--border);
    border-right: 1px solid var(--border);
    font-size: 0.9rem;
    white-space: nowrap;
}
th:last-child, td:last-child { border-right: none; }
th {
    position: sticky;
    top: 0;
    color: var(--muted);
    font-weight: 600;
    background: var(--surface);
    /* Должен быть выше z-index у "td .sticky-col" ниже (закреплённые слева
       ячейки данных) — иначе они равны, и при прокрутке вниз строка данных
       красится поверх заголовка (при равном z-index более поздний в HTML
       элемент побеждает, а <tbody> всегда позже <thead>). Из-за этого
       "Документ"/"№" в заголовке уезжали визуально под текст строки. */
    z-index: 3;
}

/* Первые два столбца (# и название/ФИО и т.п.) остаются на месте при
   горизонтальной прокрутке. Sticky ставим не на саму ячейку <td>/<th> —
   у sticky на table-cell в паре с auto-раскладкой таблицы разные браузеры
   по-разному считают ширину соседней колонки и обрезают её первый символ.
   Вместо этого закрепляем <div>-обёртку внутри ячейки (см. entity.html) —
   для обычного блочного элемента sticky считается предсказуемо. */
th:first-child, td:first-child,
th:nth-child(2), td:nth-child(2) {
    padding: 0;
}
.sticky-col {
    position: sticky;
    display: block;
    background: var(--surface);
    padding: 0.5rem 0.6rem;
}
.sticky-col-1 { left: 0; width: 3rem; }
.sticky-col-2 { left: 3rem; box-shadow: 1px 0 0 var(--border); }
th .sticky-col { z-index: 4; }
td .sticky-col { z-index: 2; }

/* Таблицы с одним закреплённым столбцом (напр. «Объект» в Бюджете) — в
   отличие от entity.html, тут нет отдельной узкой колонки "№" перед ним,
   поэтому фиксированная ширина 3rem от .sticky-col-1 обрезала длинные
   названия объектов. Ширина здесь по содержимому; второй по счёту
   столбец таблицы больше не первый/второй в паре "№ + название" — ему
   возвращаем обычный паддинг, снятый правилом выше. */
.sticky-col-only { left: 0; box-shadow: 1px 0 0 var(--border); }
.table-sticky-single th:nth-child(2),
.table-sticky-single td:nth-child(2) {
    padding: 0.5rem 0.6rem;
}

.row-link {
    color: inherit;
    text-decoration: none;
    cursor: pointer;
}
.row-link:hover { text-decoration: underline; }

@media (max-width: 720px) {
    .nav-toggle { display: inline-block; }
    .nav { display: none; flex-direction: column; }
    .nav.open { display: flex; }
    .btn-logout { padding: 0.35rem 0.55rem; }
    /* Бренду, поиску, кнопке "Выйти" и гамбургеру тесно в одну строку на
       телефоне — сжимаем поиск сильнее, чем на десктопе, вместо того чтобы
       дать ему выталкивать соседей за край экрана. */
    .nav-search input { width: auto; min-width: 0; max-width: 28vw; }
}

/* На узких экранах таблица не помещается — горизонтальная прокрутка
   с зафиксированными столбцами всё равно неудобна, когда полей много.
   Вместо неё превращаем каждую строку в карточку: слева — название
   поля (из data-label в шаблоне), справа — значение. Заголовок таблицы
   в этом режиме не нужен — скрываем его. */
@media (max-width: 640px) {
    .table-wrap { overflow: visible; max-height: none; border: none; }
    .table-wrap table { min-width: 0; border: none; }
    .table-wrap thead { display: none; }
    .table-wrap tr {
        display: block;
        background: var(--surface);
        border: 1px solid var(--border);
        border-radius: 8px;
        margin-bottom: 0.6rem;
    }
    .table-wrap td {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 0.75rem;
        width: auto !important;
        text-align: right;
        white-space: normal;
        border-right: none;
        /* У flex-элементов по умолчанию min-width:auto — они отказываются
           сжиматься меньше своего содержимого, даже с white-space:normal
           выше. Длинный номер документа/файла без пробелов (напр.
           "РДР0818-0024/6101") раздвигал всю карточку шире экрана, а
           .table-wrap { overflow: visible } в мобильном режиме ничего не
           обрезал — переполнение вылезало на всю страницу и утаскивало
           за собой шапку (та прилипает только по вертикали). */
        min-width: 0;
        overflow-wrap: anywhere;
    }
    .table-wrap td > * {
        min-width: 0;
        overflow-wrap: anywhere;
    }
    /* Пустое состояние — не пара "подпись/значение", а самостоятельный
       блок на всю ширину карточки, как на десктопе. */
    .table-wrap td.empty-cell {
        display: block;
        text-align: center;
    }
    .table-wrap td::before {
        content: attr(data-label);
        font-weight: 600;
        font-size: 0.8rem;
        color: var(--muted);
        text-align: left;
    }
    .table-wrap td.td-action {
        justify-content: flex-end;
    }
    .table-wrap td.td-action::before {
        content: none;
    }
    /* Номер записи — не отдельная строка "подпись / значение", а
       единый заголовок карточки ("№2"), прижатый к левому краю. */
    .table-wrap td.td-id {
        justify-content: flex-start;
    }
    .table-wrap td.td-id .sticky-col {
        font-weight: 700;
        text-align: left;
    }
    /* Закреплённые колонки теряют смысл без горизонтальной прокрутки —
       убираем позиционирование/фон и собственный padding у обёртки:
       вместо неё padding даёт сама td (переопределено ниже), иначе
       подпись поля (не она, а именно ::before — он не внутри обёртки)
       для этой строки прилипала к левому краю без отступа, съезжая
       из общего столбца подписей остальных строк. flex:1 растягивает
       обёртку на всю доступную ширину строки — без этого длинное
       значение при переносе на 2 строки "сжималось" в свою ширину и
       текст внутри выглядел смещённым от правого края карточки. */
    .sticky-col {
        position: static;
        background: none;
        box-shadow: none;
        padding: 0;
        flex: 1 1 auto;
        text-align: right;
    }
    .table-wrap td:first-child,
    .table-wrap td:nth-child(2) {
        padding: 0.5rem 0.6rem;
    }
}

/* Короткое всплывающее подтверждение после add/edit/delete (см. flash в
   сессии на бэкенде) — само исчезает через ~3 секунды (JS в base.html
   убирает элемент, эта анимация только гасит его визуально чуть раньше). */
/* transition, а не @keyframes — keyframes всегда стартуют с нуля, transition
   плавно ретаргетится, если появится ещё один тост, пока первый не исчез
   (сейчас тост один, но так безопаснее на будущее). Появление — быстрое
   и отзывчивое (ease-out), исчезновение — свой, отдельный класс от JS,
   т.к. transition сам по себе не умеет асимметричных enter/exit таймингов
   без явной смены состояния. */
.toast {
    position: fixed;
    bottom: 1.25rem;
    right: 1.25rem;
    background: var(--text);
    color: var(--bg);
    padding: 0.7rem 1.1rem;
    border-radius: 8px;
    font-size: 0.9rem;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
    z-index: 50;
    opacity: 1;
    transform: translateY(0);
    transition: opacity 250ms var(--ease-out), transform 250ms var(--ease-out);
}
@starting-style {
    .toast {
        opacity: 0;
        transform: translateY(8px);
    }
}
.toast.toast-leaving {
    opacity: 0;
    transform: translateY(8px);
    transition: opacity 200ms ease, transform 200ms ease;
}

/* Иконки у "Изменить"/"Удалить" — через mask-image, а не отдельный <svg>
   в каждом шаблоне: currentColor красится сам под тему, повторять разметку
   в каждом из трёх мест с "Изменить" и во всех "Удалить" не нужно. */
.action-edit::before,
button.btn-danger::before {
    content: "";
    display: inline-block;
    width: 13px;
    height: 13px;
    margin-right: 0.35rem;
    vertical-align: -2px;
    background-color: currentColor;
    -webkit-mask-size: contain;
    mask-size: contain;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
}
.action-edit::before {
    -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 20h9'/%3E%3Cpath d='M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z'/%3E%3C/svg%3E");
    mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 20h9'/%3E%3Cpath d='M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z'/%3E%3C/svg%3E");
}
button.btn-danger::before {
    -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='3 6 5 6 21 6'/%3E%3Cpath d='M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6'/%3E%3Cpath d='M10 11v6'/%3E%3Cpath d='M14 11v6'/%3E%3Cpath d='M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2'/%3E%3C/svg%3E");
    mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='3 6 5 6 21 6'/%3E%3Cpath d='M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6'/%3E%3Cpath d='M10 11v6'/%3E%3Cpath d='M14 11v6'/%3E%3Cpath d='M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2'/%3E%3C/svg%3E");
}

/* Кнопка "Фильтр" с бейджем количества применённых фильтров. */
.filter-trigger { position: relative; }
.filter-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 1.1rem;
    height: 1.1rem;
    padding: 0 0.3rem;
    margin-left: 0.4rem;
    border-radius: 999px;
    background: #fff;
    color: var(--accent);
    font-size: 0.7rem;
    font-weight: 700;
}

/* Панель фильтра — "лист" (sheet), выезжающий справа, поверх затемнённого
   фона. Полупрозрачный "материал" (backdrop-filter) вместо сплошной заливки —
   контент страницы едва заметен под панелью, это даёт ощущение слоя поверх
   контента, а не отдельного экрана (см. apple-design: материалы и глубина).
   Заход/выход по одному и тому же пути (справа) — открытие и закрытие
   зеркальны, а не "выезжает справа, исчезает вниз". */
.sheet-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.35);
    opacity: 0;
    pointer-events: none;
    transition: opacity 300ms var(--ease-out);
    z-index: 60;
}
.sheet-backdrop.sheet-open {
    opacity: 1;
    pointer-events: auto;
}
.sheet {
    position: fixed;
    top: 0;
    right: 0;
    height: 100%;
    width: min(380px, 90vw);
    background: rgba(var(--surface-rgb), 0.85);
    backdrop-filter: blur(20px) saturate(180%);
    -webkit-backdrop-filter: blur(20px) saturate(180%);
    box-shadow: -8px 0 32px rgba(0, 0, 0, 0.18);
    z-index: 61;
    display: flex;
    flex-direction: column;
    transform: translateX(100%);
    /* visibility скрывает панель от клавиатурной навигации/скринридеров,
       пока она за экраном — но должна смениться ПОСЛЕ анимации, иначе
       transition на transform обрубается на середине (visibility не
       интерполируется, переключается мгновенно). */
    transition: transform 320ms var(--ease-out), visibility 0s linear 320ms;
    visibility: hidden;
}
.sheet.sheet-open {
    transform: translateX(0);
    visibility: visible;
    transition: transform 320ms var(--ease-out), visibility 0s linear;
}
.sheet-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1rem 1.25rem;
    border-bottom: 1px solid var(--border);
    flex: 0 0 auto;
}
.sheet-header h3 { margin: 0; font-size: 1.1rem; }
.sheet-close {
    background: none;
    border: none;
    color: var(--muted);
    font-size: 1rem;
    line-height: 1;
    cursor: pointer;
    padding: 0.4rem 0.6rem;
    border-radius: 8px;
}
.sheet-close:active { transform: scale(0.9); }
.sheet-body {
    padding: 1.25rem;
    overflow-y: auto;
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    gap: 1.25rem;
}
.sheet-fieldset {
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 0.4rem 0.9rem 0.9rem;
    margin: 0;
}
.sheet-fieldset legend {
    padding: 0 0.4rem;
    font-size: 0.8rem;
    color: var(--muted);
    font-weight: 600;
}
.sheet-fieldset-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0.6rem;
}
.sheet-footer {
    display: flex;
    justify-content: flex-end;
    gap: 0.6rem;
    padding: 1rem 1.25rem;
    border-top: 1px solid var(--border);
    flex: 0 0 auto;
}

/* Подсказки по объекту — простой автокомплит без библиотек: полный список
   объектов уже отрисован сервером в <li>, JS только показывает/прячет
   совпадения по мере ввода (см. app.js). */
.autocomplete { position: relative; }
.autocomplete-list {
    position: absolute;
    top: calc(100% + 4px);
    left: 0;
    right: 0;
    max-height: 220px;
    overflow-y: auto;
    margin: 0;
    padding: 0.3rem;
    list-style: none;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    z-index: 5;
}
.autocomplete-list li {
    padding: 0.45rem 0.6rem;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.9rem;
}
.autocomplete-list li:hover {
    background: var(--accent);
    color: #fff;
}

@media (prefers-reduced-motion: reduce) {
    /* Плавный слайд заменяется на кросс-фейд без сдвига — резкое движение
       через весь экран может быть неприятно людям с чувствительным
       вестибулярным аппаратом (см. apple-design). */
    .sheet {
        transform: none;
        transition: opacity 200ms ease;
        opacity: 0;
        visibility: visible;
        pointer-events: none;
    }
    .sheet.sheet-open {
        opacity: 1;
        pointer-events: auto;
    }
}
@media (prefers-reduced-transparency: reduce) {
    .sheet { background: var(--surface); backdrop-filter: none; -webkit-backdrop-filter: none; }
}
@media (max-width: 480px) {
    .sheet-fieldset-row { grid-template-columns: 1fr; }
}

/* Печать: убираем всё, что не нужно на бумаге (шапка, навигация, поиск,
   кнопки действий, форма добавления) — остаются только заголовок и данные. */
@media print {
    .topbar, .nav, .toggle-btn, .toggle-form, .toast,
    .td-action, .project-card-actions, .section-search,
    .budget-warning-banner, form button, .empty-state svg,
    .sheet, .sheet-backdrop {
        display: none !important;
    }
    body { background: #fff; color: #000; }
    .content { max-width: none; padding: 0; }
    .card-block, .card, .project-card { border: 1px solid #ccc; box-shadow: none; }
    .table-wrap { overflow: visible; max-height: none; }
    a { color: #000; text-decoration: none; }
}
