/* ==================================================================
   Телефон: программа должна выглядеть и вестись как приложение.

   Правила отсюда работают только на узком экране (до 860 px). На
   мониторе остаётся фирменное оформление с Times New Roman — здесь
   же берём системный шрифт Apple: на телефоне он читается мельче и
   плотнее, а привычные размеры и отступы iOS убирают «скученность».

   Размеры взяты из Human Interface Guidelines: body 17, subhead 15,
   footnote 13, caption 12; минимальная цель нажатия 44 × 44.
   ================================================================== */
@media (max-width: 860px) {

  /* ---------- 1. Шрифт и размеры ---------- */
  :root {
    --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI",
            system-ui, "Helvetica Neue", Arial, sans-serif;
    --serif: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI",
             system-ui, "Helvetica Neue", Arial, sans-serif;
    /*  Скругления из макета: карточка списка 14, кнопка 12, сегмент 9  */
    --r: 14px;
    --rs: 12px;
  }
  body, main, h1, h2, h3, .subnav a, .cal-title, .page-tabs a,
  button, input, select, textarea {
    font-family: var(--sans);
    -webkit-font-smoothing: antialiased;
  }
  /*  Кегли из макета: заголовок экрана 20/600, строка списка 16/600,
      пояснение 13,5, подпись группы 13/600 заглавными  */
  body { font-size: 16px; line-height: 1.41; letter-spacing: -0.01em; }
  h1 { font-size: 20px; font-weight: 600; letter-spacing: -0.02em; }
  h2 { font-size: 17px; font-weight: 600; }
  h3 { font-size: 15px; font-weight: 600; }
  .small, .muted, .box-sum, .page-sub { font-size: 13.5px; }
  .tag, .fchip .n { font-size: 12px; }
  .what, .case-row .nm, .more-list a, .dash-docs .what { font-size: 16px; font-weight: 600; }

  /* ---------- 2. Вкладки раздела: как сегменты в iOS ---------- */
  .subnav {
    gap: 6px; border-bottom: 0; margin: 2px -14px 10px; padding: 2px 14px 6px;
    align-items: center;
  }
  .subnav a {
    font-size: 15px; font-weight: 500; color: var(--graphite);
    padding: 7px 13px; min-height: 36px; border: 0; border-radius: 999px;
    background: var(--bg); letter-spacing: -0.01em;
  }
  .subnav a.on {
    background: var(--ink); color: #fff; font-weight: 600; border-color: transparent;
  }

  /* ---------- 3. Карточки: сгруппированный список iOS ---------- */
  .panel, .box, table.zebra {
    border-radius: var(--r);
    box-shadow: 0 1px 2px rgba(20, 22, 26, .06);
  }
  /*  Отступы из макета: боковое поле 16, между группами 14  */
  .panel { padding: 14px 16px; margin-bottom: 14px; }
  main { padding-left: 16px; padding-right: 16px; }

  /* ---------- 4. Кнопки ---------- */
  /*  Главное действие — заливка, остальное тихо. Кнопка во всю ширину
      только там, где она и есть главное действие карточки  */
  button, .btn-main, .btn-plain, .ghost {
    font-size: 15px; font-weight: 600; letter-spacing: -0.01em;
    border-radius: var(--rs); min-height: 44px;
  }
  /*  Второстепенная кнопка в iOS — заливка светлым, а не голый текст:
      без неё «Обновить все данные» читалась как подпись  */
  .ghost, .btn-plain {
    background: var(--accent-s); border: 0; color: var(--accent-ink);
    padding: 11px 16px;
  }
  .btn-main { background: var(--ink); color: #fff; border: 0; padding: 12px 18px; }
  .mini, .link-btn, .tag, .fchip {
    min-height: 34px; font-weight: 500;
  }
  /*  Мелкая кнопка-призрак на телефоне читалась как подпись: даём ей
      светлую заливку, чтобы было видно, что по ней нажимают  */
  .ghost.mini, button.ghost.mini {
    background: var(--accent-s); color: var(--accent-ink);
    padding: 9px 14px; border: 0;
  }
  /*  Мелкие значки в строке остаются значками: 44 px им ни к чему,
      палец попадает по невидимой подложке  */
  .del, .tickbox, .row-tools button, .corner-tools button {
    min-height: 32px; min-width: 32px;
  }

  /* ---------- 5. Действия строки не висят поверх текста ---------- */
  /*  Кнопки, приклеенные к правому верхнему углу, на узком экране
      налезали на заголовок и казались «съехавшими». Ставим их в поток  */
  .feed li .trow-acts, tr.has-tools td.tools-cell .corner-tools,
  .case-row .corner-tools, .feed .item .row-tools {
    position: static; opacity: 1;
    display: flex; gap: 8px; justify-content: flex-end;
    margin-top: 6px;
  }
  /*  Кнопки лежат в разметке первыми, и без порядка они всплывали над
      записью пустой строкой со значками. Ставим их последними  */
  .feed > li:has(> .corner-tools) {
    display: flex; flex-direction: column;
  }
  .feed > li > .corner-tools { order: 9; }

  /* ---------- 6. Поля ввода ---------- */
  input, select, textarea {
    font-size: 16px;               /* ниже 16 Safari увеличивает страницу */
    border-radius: var(--rs); min-height: 44px;
    background: var(--card);
  }

  /* ---------- 7. Шапка и безопасные поля ---------- */
  .appbar {
    padding-top: env(safe-area-inset-top);
    background: rgba(255, 255, 255, .92);
    -webkit-backdrop-filter: saturate(180%) blur(12px);
    backdrop-filter: saturate(180%) blur(12px);
  }
  main { padding-left: 14px; padding-right: 14px; }
}

/* ==================================================================
   Нижняя панель вкладок — то, чем приложение отличается от сайта:
   главные разделы всегда под большим пальцем.
   ================================================================== */
@media (max-width: 860px) {
  .tabbar {
    position: fixed; left: 0; right: 0; bottom: 0; z-index: 60;
    display: flex; justify-content: space-around; align-items: stretch;
    background: rgba(255, 255, 255, .94);
    -webkit-backdrop-filter: saturate(180%) blur(14px);
    backdrop-filter: saturate(180%) blur(14px);
    border-top: 1px solid var(--line);
    padding-bottom: env(safe-area-inset-bottom);
  }
  /*  Нижняя панель: высота 78 с учётом домашней полосы, значок 20,
      подпись 10,5 — значения из макета  */
  .tabbar a {
    flex: 1 1 0; display: flex; flex-direction: column; align-items: center;
    justify-content: center; gap: 3px; padding: 9px 2px 6px;
    min-height: 54px;
    font-size: 10.5px; font-weight: 500; letter-spacing: 0;
    color: var(--muted); text-decoration: none;
  }
  .tabbar a.on { color: var(--accent-ink); }
  .tabbar svg { width: 20px; height: 20px; display: block; }
  .tabbar .t { line-height: 1.1; }
  /*  Содержимое не прячется под панелью и под кнопкой чата  */
  main { padding-bottom: calc(92px + env(safe-area-inset-bottom)); }
  /*  Кнопка чата закреплена по id, поэтому и здесь по id: иначе она
      садится поверх нижней панели  */
  #chat-panel:not(.open) {
    bottom: calc(60px + env(safe-area-inset-bottom));
  }
}
@media (min-width: 861px) { .tabbar { display: none; } }

/* ==================================================================
   Сводка на телефоне: порядок блоков и ничего лишнего сверху.

   Первый экран отвечает на вопрос «что у меня сегодня», а не показывает
   заголовок, кнопку обновления и отбор исполнителей. Порядок такой:
   мероприятия с календарём → задачи → договоры → деньги.
   ================================================================== */
@media (max-width: 860px) {
  /*  Шапка, обновление и отбор — в боковое меню, тут им не место  */
  .dash-head { display: none; }
  .dash-pretrial { display: none; }       /* претензии смотрят с компьютера */

  /*  Порядок блоков задаём явно  */
  main.with-side { display: flex; flex-direction: column; }
  .split3 { display: contents; }          /* колонки раскрываются в общий поток */
  #events { order: 1; }
  .cal-wide { order: 2; }
  #tasks { order: 3; }
  .dash-contracts { order: 4; }
  .dash-money { order: 5; }
  .dash-pretrial { order: 6; }

  /*  Договоры: строка читается сверху вниз, ссылка — крупной меткой  */
  .dash-contracts { background: var(--card); border-radius: var(--r);
    padding: 14px; margin-bottom: 10px; box-shadow: 0 1px 2px rgba(20,22,26,.06); }
  .dash-docs .what { font-size: 16px; font-weight: 600; }
  .dash-docs .meta { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
  .dash-docs .meta .tag { min-height: 30px; display: inline-flex; align-items: center; }

  /*  Деньги: плитки в две колонки, а не в одну длинную ленту  */
  .dash-money { background: var(--card); border-radius: var(--r);
    padding: 14px; margin-bottom: 10px; box-shadow: 0 1px 2px rgba(20,22,26,.06); }
  .dash-money h2 { margin: 0 0 8px; }
  .dash-money .cards { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
  .dash-money .card { margin: 0; }
}

/* ==================================================================
   На экране списка — только данные.

   Горизонтальные вкладки над содержимым, поиск в шапке и плавающая
   кнопка чата съедали первый экран и давали боковую прокрутку. Всё
   это уходит: вкладки — в нижнюю панель, поиск и чат — в «Ещё».
   ================================================================== */
@media (max-width: 860px) {
  .subnav { display: none; }
  .appbar .search, .appbar form[role="search"], .appbar .topsearch { display: none; }
  #chat-panel { display: none; }

  /*  Экран «Ещё»: список разделов строками, как в настройках iOS  */
  .more-block { padding: 0; overflow: hidden; }
  .more-block h2 {
    font-size: 13px; font-weight: 600; text-transform: uppercase;
    letter-spacing: .04em; color: var(--muted);
    margin: 0; padding: 14px 14px 6px;
  }
  .more-list { list-style: none; margin: 0; padding: 0; }
  .more-list li + li { border-top: 1px solid var(--line); }
  .more-list a {
    display: flex; align-items: center; justify-content: space-between;
    min-height: 48px; padding: 0 14px; font-size: 16px;
    color: var(--ink); text-decoration: none;
  }
  .more-list .chev { color: var(--muted); font-size: 20px; }
  .more-search { display: flex; flex-direction: column; gap: 8px; }

  /*  Потяните вниз, чтобы обновить  */
  .pull-hint {
    position: fixed; left: 0; right: 0; top: 0; z-index: 70;
    display: flex; align-items: center; justify-content: center;
    height: 0; overflow: hidden; font-size: 13px; color: var(--muted);
    background: var(--bg); transition: height .15s ease;
  }
  .pull-hint.on { height: 42px; }
}

/*  Кнопки внутри строки на телефоне не нужны: то же делает свайп  */
@media (max-width: 860px) {
  .feed.tasks li .trow-acts, .feed li .corner-tools { display: none; }
  .feed.tasks li, .feed li[data-task] { touch-action: pan-y; }
  /*  Счётчик «показано N из M» заменяем короткой ссылкой  */
  .list-count .of { display: none; }
}

/*  Деньги на телефоне: две крупные цифры, как в банковском приложении  */
@media (max-width: 860px) {
  .dash-now { order: 5; background: var(--card); border-radius: var(--r);
    padding: 14px; margin-bottom: 10px; box-shadow: 0 1px 2px rgba(20,22,26,.06); }
  /*  Разбор «где висит» четырьмя плитками — для монитора: на телефоне
      его заменяют две крупные цифры выше  */
  .dash-money { display: none; }
  .now-pair { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 4px 0 8px; }
  .now-cell { display: flex; flex-direction: column; gap: 2px; }
  .now-num { font-size: 26px; font-weight: 700; letter-spacing: -0.02em;
    font-variant-numeric: tabular-nums; }
  .now-cell.alert .now-num { color: var(--alert, #8f4a52); }
  .now-lbl { font-size: 13px; color: var(--muted); }
  .now-list .what { font-size: 15px; font-weight: 600; }
}
@media (min-width: 861px) { .dash-now { display: none; } }

/*  Список внутри блока листается сам — так семь ближайших записей видно
    сразу, а страница не растягивается на двенадцать тысяч пикселей  */
@media (max-width: 860px) {
  /*  Список внутри блока больше не ловит прокрутку: палец двигал
      внутренний список вместо страницы, и до нижних блоков было не
      добраться. Страница листается целиком  */
  #events .scroll, #tasks .scroll, .panel .scroll, .scroll,
  .scroll-7, .feed.scroll-7 {
    max-height: none; height: auto; overflow: visible;
  }
  /*  Подпись «показаны 7 из 26 — листайте внутри списка» заменяет ссылка
      в заголовке блока  */
  #events > .small.muted:first-of-type, #tasks > .small.muted:first-of-type {
    display: none;
  }
}

/*  Число рядом с «Задачи» и число в ссылке расходились: первое — всего
    задач, второе — сколько в этом списке. На телефоне оставляем ссылку  */
@media (max-width: 860px) {
  #tasks .sec-head > .small.muted { display: none; }
}

/* ==================================================================
   Лист «Фильтры»: выезжает снизу поверх затемнения.

   Шесть полей отбора в потоке страницы отодвигали первую строку данных
   на два экрана вниз. Теперь на экране их нет вовсе — только кнопка.
   ================================================================== */
@media (max-width: 860px) {
  .sheet-open {
    display: block !important; width: 100%; margin: 0 0 10px;
    background: var(--bg); border: 0; border-radius: var(--rs);
    min-height: 44px; font-size: 15px; font-weight: 600; color: var(--ink);
    text-align: left; padding: 0 14px;
  }
  .filters-form {
    position: fixed; left: 0; right: 0; bottom: 0; z-index: 80;
    max-height: 82vh; overflow-y: auto;
    background: var(--card); border-radius: 16px 16px 0 0;
    padding: 6px 16px calc(74px + env(safe-area-inset-bottom));
    box-shadow: 0 -8px 28px rgba(20, 22, 26, .18);
    transform: translateY(102%); transition: transform .22s ease;
    display: flex; flex-direction: column; gap: 10px; margin: 0;
  }
  .filters-form.open { transform: translateY(0); }
  .filters-form > div { width: 100%; }
  .filters-form select, .filters-form input { width: 100%; }
  .sheet-head {
    display: flex; align-items: center; gap: 12px;
    padding: 10px 0 6px; position: sticky; top: 0; background: var(--card);
  }
  .sheet-head strong { font-size: 17px; flex: 1 1 auto; white-space: nowrap; }
  .sheet-head .link-btn { white-space: nowrap; flex: 0 0 auto; }
  .sheet-close { min-width: 44px; background: none; border: 0; font-size: 20px;
    color: var(--muted); }
  /*  Главная кнопка листа закреплена внизу, над клавиатурой: в конце
      длинной формы её не было видно  */
  .sheet-apply {
    position: absolute; left: 16px; right: 16px;
    bottom: calc(14px + env(safe-area-inset-bottom));
    width: auto; min-height: 50px; font-size: 16px;
    background: var(--accent-ink); color: #fff; border: 0; border-radius: 12px;
  }
  .sheet-back {
    position: fixed; inset: 0; z-index: 79; background: rgba(20, 22, 26, .38);
    -webkit-backdrop-filter: blur(2px); backdrop-filter: blur(2px);
  }
}
@media (min-width: 861px) {
  .sheet-head, .sheet-back, .sheet-open { display: none !important; }
}

/*  Строка фактов вместо заголовка: «чт, 24 сентября · 2 мероприятия · 5 задач»  */
.mob-context { display: none; }
@media (max-width: 860px) {
  .mob-context {
    display: block; margin: 2px 0 12px;
    font-size: 13.5px; color: var(--muted);
  }
}

/* ==================================================================
   Шапка: ровно два значка — поиск и добавить.
   ================================================================== */
.mob-only { display: none; }
@media (max-width: 860px) {
  .appbar { display: flex; align-items: center; gap: 4px; padding-left: 4px; padding-right: 8px; }
  .appbar__title { flex: 1 1 auto; font-size: 17px; font-weight: 600;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .appbar-search { display: none; }
  .mob-only { display: inline-flex; }
  .appbar-icon {
    width: 44px; height: 44px; flex: 0 0 auto;
    display: inline-flex; align-items: center; justify-content: center;
    background: none; border: 0; color: var(--ink); text-decoration: none;
  }
  .appbar-icon svg { width: 22px; height: 22px; }
  .appbar-icon:active { opacity: .5; }

  /*  Лист добавления: тот же приём, что и у фильтров  */
  .add-sheet {
    position: fixed; left: 0; right: 0; bottom: 0; z-index: 80;
    max-height: 84vh; overflow-y: auto; background: var(--card);
    border-radius: 16px 16px 0 0;
    padding: 6px 16px calc(74px + env(safe-area-inset-bottom));
    box-shadow: 0 -8px 28px rgba(20, 22, 26, .18);
    transform: translateY(102%); transition: transform .22s ease;
  }
  .add-sheet.open { transform: translateY(0); }
  .add-sheet .add-any { box-shadow: none; padding: 0; background: none; }
  .add-sheet .add-any > summary { display: none; }
  .add-sheet form { display: flex; flex-direction: column; gap: 10px; }
  .add-sheet form > div { width: 100%; }
  .add-sheet select, .add-sheet input { width: 100%; }
  .add-sheet form > button {
    position: absolute; left: 16px; right: 16px;
    bottom: calc(14px + env(safe-area-inset-bottom));
    min-height: 50px; font-size: 16px; width: auto;
    background: var(--accent-ink); color: #fff; border: 0; border-radius: 12px;
  }
}

/*  Экран «Деньги» на телефоне: три крупные цифры вместо таблицы  */
.money-mob { display: none; }
@media (max-width: 860px) {
  .money-mob { display: block; }
  /*  Всё, что не цифры и не договоры, — выгрузки, архивы, таблицы — в «⋯»  */
  .money-mob ~ *:not(.tabbar):not(script) { display: none; }
  .money-nums { display: flex; flex-direction: column; gap: 14px;
    background: var(--card); border-radius: var(--r); padding: 16px; margin-bottom: 14px;
    box-shadow: 0 1px 2px rgba(20,22,26,.06); }
  .money-cell { display: flex; flex-direction: column; gap: 2px; }
  .money-num { font-size: 30px; font-weight: 700; letter-spacing: -0.02em;
    font-variant-numeric: tabular-nums; line-height: 1.1; }
  .money-cell.alert .money-num { color: var(--alert, #8f4a52); }
  .money-cell.ok .money-num { color: var(--ok, #2f7a5f); }
  .money-lbl { font-size: 13.5px; color: var(--muted); }
  .money-mob .dash-docs { background: var(--card); border-radius: var(--r);
    padding: 6px 16px 10px; box-shadow: 0 1px 2px rgba(20,22,26,.06); }
  .money-mob .sec-head { margin-top: 4px; }
}

/*  Одна строка — один объект: название, строка подробностей, шеврон справа  */
@media (max-width: 860px) {
  .case-row { position: relative; padding-right: 26px; }
  .case-row::after {
    content: "›"; position: absolute; right: 10px; top: 50%;
    transform: translateY(-50%); color: var(--muted); font-size: 22px;
    line-height: 1; pointer-events: none;
  }
  /*  Служебные кнопки строки прячем: действия — по нажатию и свайпом  */
  .case-row .corner-tools, .case-row .row-tools { display: none; }
}

/*  Поиск отдельным экраном: поле сверху, «Отмена» рядом, результаты списком  */
@media (max-width: 860px) {
  /*  form.inline задаёт свои flex-wrap и кнопки, поэтому и здесь пишем
      с тем же весом: иначе «Отмена» остаётся заливкой во всю ширину  */
  /*  На телефоне формы выстраиваются в столбец — поиску нужна строка:
      поле и «Отмена» рядом, как в iOS  */
  form.search-form { display: flex; flex-direction: row; align-items: center;
    gap: 8px; flex-wrap: nowrap; }
  form.search-form label { display: none; }
  form.search-form .f.end { display: none; }
  form.search-form input { border-radius: 10px; background: var(--bg); border: 0; }
  form.search-form > div { flex: 1 1 auto; min-width: 0; }
  form.search-form .search-field { flex: 1 1 auto; min-width: 0; }
  form.search-form .search-cancel {
    flex: 0 0 auto; width: auto; padding: 0 4px; text-decoration: none;
    display: inline-flex; align-items: center;
    color: var(--accent-ink); font-size: 16px; font-weight: 500; min-height: 44px;
  }
  /*  Найденное — строками с разделителем, без рамок таблицы  */
  .search-hits table.zebra, .panel table.zebra { box-shadow: none; }
}

/*  Проблемные дела и вкладка «Дела из ленты» — в «Ещё → Проверить данные»  */
@media (max-width: 860px) {
  .check-line, .page-tabs { display: none; }
}

/*  Никакой блок не ловит прокрутку и не обрезает содержимое: на телефоне
    всё листается одним движением по странице  */
@media (max-width: 860px) {
  main, main > *, .panel { overflow: visible; }
  /*  Исключение — то, что шире экрана: таблицы и календарь листаются вбок  */
  .tbl-wrap, .ios-card, table.zebra { overflow-x: auto; -webkit-overflow-scrolling: touch; }
  /*  Плавная прокрутка страницы, как в приложениях  */
  html, body { -webkit-overflow-scrolling: touch; overscroll-behavior-y: contain; }
}

/*  Колонки доски задач на телефоне не ловят прокрутку: палец двигал
    содержимое колонки, а страница под ней стояла на месте — это и
    выглядело как «не прокручивается»  */
@media (max-width: 860px) {
  .board-col { max-height: none; overflow: visible; }
  .board { display: flex; flex-direction: column; gap: 12px; }
}
