/* =========================================================================
   МЕДКОНСУЛЬТАЦИЯ — АДАПТИВНЫЙ СЛОЙ (responsive.css)
   =========================================================================
   Подключается ПОСЛЕ css/style.css и только переопределяет геометрию.
   Не меняет DOM, ID, data-атрибуты и обработчики. Цвета берутся из
   существующих CSS-переменных :root / [data-theme="dark"].

   BREAKPOINTS
     xl   >= 1400px  расширенный десктоп
     lg   1200–1399  десктоп (базовый, стили из style.css)
     md   992–1199   малый ноутбук / ландшафтный планшет
     sm   768–991    планшет
     xs   480–767    смартфон (крупный)
     xxs  < 480      смартфон (компактный)
   ========================================================================= */

:root {
    --tap-target: 44px;      /* минимальная тач-цель (Apple HIG / WCAG 2.5.5) */
    --safe-bottom: env(safe-area-inset-bottom, 0px);
    --sheet-radius: 20px;
}

/* =========================================================================
   1. БАЗОВЫЕ ПРАВИЛА ДЛЯ ВСЕХ ЭКРАНОВ
   ========================================================================= */

/* Предотвращаем горизонтальный скролл всей страницы */
html, body { max-width: 100%; overflow-x: hidden; }

/* Исправление давнего бага style.css: .modal имеет width:100% + padding:15px
   без border-box, из-за чего оверлей вылезает на 30px за вьюпорт. */
.modal { box-sizing: border-box; }
.modal * { box-sizing: border-box; }

/* Тот же класс бага: .compact-input имеет width:100%, но content-box.
   Ширина = 100% + padding + border, поэтому поля вылезали за ячейку сетки
   (замерено: 340px в контейнере 314px). Критично для карточек на мобильном. */
.compact-input,
.item-cell,
.input-group input,
.list-input-group input,
textarea.main-area{
    box-sizing: border-box;
}

*, *::before, *::after { -webkit-tap-highlight-color: rgba(14, 165, 233, 0.12); }

/* Плавный скролл к секциям при переключении вкладок */
@media (prefers-reduced-motion: no-preference) {
    html { scroll-behavior: smooth; }
}

/* Уважаем системную настройку «уменьшить движение» */
@media (prefers-reduced-motion: reduce) {
    *, *::before, *::after {
        animation-duration: 0.01ms !important;
        transition-duration: 0.01ms !important;
        scroll-behavior: auto !important;
    }
}

/* -------------------------------------------------------------------------
   1.1 ТАЧ-УСТРОЙСТВА: элементы, спрятанные за :hover, недоступны пальцем.
   Ключевой UX-баг текущей вёрстки — кнопка удаления строки назначения.
   ------------------------------------------------------------------------- */
@media (hover: none), (pointer: coarse) {
    .sortable-item .delete-btn {
        opacity: 0.75 !important;
        pointer-events: auto !important;
        padding: 10px !important;
        min-width: var(--tap-target);
        min-height: var(--tap-target);
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .sortable-item .drag-handle {
        color: #94a3b8;
        min-width: 32px;
        min-height: var(--tap-target);
        font-size: 1.25em;
    }
    /* Убираем hover-трансформации, залипающие после тапа */
    .modern-card:hover,
    .export-card:hover,
    .export-card-mini:hover,
    .zoom-trigger:hover {
        transform: none !important;
    }
}

/* =========================================================================
   2. XL — ШИРОКИЙ ДЕСКТОП (>= 1400px)
   Даём рабочей области больше воздуха, ограничиваем длину строки текста.
   ========================================================================= */
@media (min-width: 1400px) {
    .main-app-container { max-width: 1720px; padding: 0 24px; }
    textarea.main-area { min-height: 360px; }
}

/* =========================================================================
   3. MD — МАЛЫЙ НОУТБУК / ЛАНДШАФТНЫЙ ПЛАНШЕТ (992–1199px)
   Сжимаем самую широкую сетку — таблицу назначений.
   ========================================================================= */
@media (max-width: 1199px) {
    .main-app-container { max-width: 100%; padding: 0 14px; }

    /* 8 колонок -> ужимаем фиксированные и второстепенные */
    .grid-mode1 {
        grid-template-columns: 1.1fr 0.9fr 0.9fr 132px 96px 0.6fr 1.2fr 1.2fr;
        gap: 4px;
    }
    .compact-input { padding: 6px; font-size: 0.85em; }
}

/* =========================================================================
   4. SM — ПЛАНШЕТ (768–991px)
   Точка, где 8-колоночная таблица перестаёт быть читаемой.
   Переводим её в 4 колонки x 2 ряда, шапку колонок скрываем.
   ========================================================================= */
@media (max-width: 991px) {

    .app-wrapper { padding: 10px 0 96px 0; min-height: auto; }
    .main-app-container { padding: 0 12px; gap: 12px; }
    .modern-card, .text-area-container { padding: 14px 16px; }

    /* --- Шапка пациента: две строки вместо одной --- */


    .input-group { min-width: calc(50% - 5px); }


    /* --- Вкладки разделов: горизонтальный скролл вместо переноса --- */
    .section-tabs {
        flex-wrap: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        scroll-snap-type: x proximity;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none;
        padding: 8px;
        gap: 6px;
    }
    .section-tabs::-webkit-scrollbar { display: none; }
    .section-button {
        flex: 0 0 auto;
        scroll-snap-align: start;
        min-height: var(--tap-target);
        padding: 10px 16px;
        white-space: nowrap;
    }

    /* --- Таблица назначений: 4 колонки в 2 ряда --- */
    .sortable-header { display: none !important; }
    .item-text.grid-mode1,
    .grid-mode1 {
        grid-template-columns: repeat(4, 1fr);
        gap: 6px;
    }
    .sortable-item {
        align-items: flex-start;
        padding: 10px 8px;
        border: 1px solid var(--border-color);
        border-radius: var(--radius-sm);
    }
    .compact-input {
        border-color: var(--border-color);
        background: var(--bg-gray);
        min-height: 38px;
        font-size: 0.9em;
    }

    /* Внутренние вкладки (диагноз/анамнез/осмотр) — тоже в скролл.
       Обёртка у них без класса (инлайн-стили), поэтому берём её через :has().
       Baseline-поддержка :has() — с конца 2023 г. во всех актуальных браузерах. */
    div:has(> .diag-tab-btn),
    .calc-tabs {
        flex-wrap: nowrap !important;
        overflow-x: auto;
        overflow-y: hidden;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none;
    }
    div:has(> .diag-tab-btn)::-webkit-scrollbar,
    .calc-tabs::-webkit-scrollbar { display: none; }
    .diag-tab-btn, .calc-tab-btn {
        flex: 0 0 auto;
        min-height: var(--tap-target);
        white-space: nowrap;
    }

    /* Калькуляторы: модалка тянется по экрану, сайдбар сужается */
    #calcModal .modal-content {
        width: 100% !important;
        height: auto !important;
        max-height: 92vh !important;
    }
    #calc-sidebar { width: 190px !important; }
}

/* =========================================================================
   5. XS — СМАРТФОН (< 768px)
   Полная перестройка: карточки вместо таблиц, bottom sheet вместо модалок,
   компактная панель действий, тач-цели 44px.
   ========================================================================= */
@media (max-width: 767px) {

    /* iOS зумит страницу при фокусе на поле с font-size < 16px.
       Поэтому все поля ввода — ровно 16px. */
    input, select, textarea,
    .input-group input,
    .list-input-group input,
    .compact-input,
    .modal-content input,
    .modal-content select,
    .modal-content textarea {
        font-size: 16px !important;
    }

    .app-wrapper { padding: 8px 0 110px 0; }
    .main-app-container { padding: 0 10px; gap: 10px; }
    .modern-card, .text-area-container { padding: 12px; border-radius: var(--radius-sm); }

    /* --- Шапка: поля пациента в одну колонку, дата+пол в ряд --- */


    .input-group,
    .input-group[style] { min-width: 100% !important; flex-grow: 1 !important; }
    .input-group input { height: var(--tap-target); }


    .lang-switch { order: 1; }
    .auth-panel { order: 2; flex-wrap: wrap; gap: 6px; }
    .auth-panel button {
        min-height: 38px;
        padding: 6px 12px;
        font-size: 0.85em;
    }
    /* Скрываем длинную подпись Dashboard, оставляем иконку */
    .auth-panel button[title="Dashboard"] { font-size: 0; padding: 6px 10px; }
    .auth-panel button[title="Dashboard"] i { font-size: 1rem; }

    /* --- ГЛАВНОЕ: таблица назначений -> карточки --- */
    .sortable-list { gap: 10px; }
    .sortable-item {
        flex-wrap: wrap;
        gap: 6px;
        padding: 12px 10px;
        background: var(--surface);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        box-shadow: 0 1px 3px rgba(0,0,0,0.04);
    }
    /* Ручка перетаскивания и корзина — по краям верхней строки карточки */
    .sortable-item .drag-handle { order: 1; flex: 0 0 auto; }
    .sortable-item .item-text   { order: 3; flex: 1 1 100%; }
    .sortable-item .delete-btn  { order: 2; margin-left: auto; }

    /* Каждое поле — на всю ширину, друг под другом */
    .item-text.grid-mode1,
    .grid-mode1 {
        grid-template-columns: 1fr !important;
        gap: 8px;
    }
    .item-text.mode4, .item-text { gap: 8px; }
    .compact-input {
        min-height: var(--tap-target);
        padding: 10px 12px;
        border: 1px solid var(--border-color);
        background: var(--bg-gray);
        white-space: normal;      /* снимаем nowrap: на узком экране нужен перенос */
        overflow: visible;
        text-overflow: clip;
    }
    .item-cell { min-height: var(--tap-target); padding: 10px 12px; }

    /* Иерархия внутри карточки: препарат — главный, остальное вторично.
       Подписи колонок скрыты, поэтому опираемся на placeholder + акцент. */
    .compact-input[data-col="1"] {
        font-weight: 700;
        font-size: 17px !important;
        color: var(--primary-blue);
        background: var(--surface);
        border-color: var(--accent-blue);
    }
    .compact-input[data-col="2"] { font-style: italic; color: var(--text-muted); }
    .compact-input::placeholder { color: var(--text-muted); opacity: 0.75; }

    /* Тайм-переключатели (утро/день/вечер) — крупнее под палец */
    .time-toggles { padding: 4px; gap: 4px; }
    .time-btn { min-height: 38px; font-size: 1.25em; }
    .time-inputs input[type="time"] { font-size: 0.9em !important; padding: 6px 0; }

    /* Поле добавления препарата: кнопка под инпутом */
    .list-input-group { flex-direction: column; gap: 8px; }
    .list-input-group input { min-height: var(--tap-target); }
    .btn-add { min-height: var(--tap-target); justify-content: center; padding: 0 16px; }

    /* Текстовые области разделов */
    textarea.main-area { min-height: 220px; padding: 12px; }

    /* Комбобокс режима «Лечения» — на всю ширину строки заголовка.
       Панель инструментов раздела (обёртка без класса) должна переноситься,
       иначе на 320px кнопки уезжают за край. Берём её через :has(). */


    /* Группа иконочных кнопок (копировать/очистить) прижимается вправо */


    /* --- МОДАЛКИ -> BOTTOM SHEET --- */
    .modal { padding: 0; align-items: flex-end; }
    .modal-content {
        width: 100%;
        max-width: 100% !important;
        max-height: 92vh;
        margin: 0;
        padding: 20px 16px calc(20px + var(--safe-bottom)) 16px;
        border-radius: var(--sheet-radius) var(--sheet-radius) 0 0;
        animation: sheetUp 0.28s cubic-bezier(0.32, 0.72, 0, 1);
        overscroll-behavior: contain;
    }
    /* Визуальный «хват» сверху листа */
    .modal-content::before {
        content: "";
        display: block;
        width: 40px;
        height: 4px;
        border-radius: 2px;
        background: var(--border-color);
        margin: -6px auto 14px auto;
    }
    .close-modal {
        top: 14px; right: 14px;
        width: var(--tap-target); height: var(--tap-target);
        display: flex; align-items: center; justify-content: center;
    }
    .modal-content button { min-height: var(--tap-target); }

    @keyframes sheetUp {
        from { transform: translateY(100%); }
        to   { transform: translateY(0); }
    }

    /* --- НИЖНЯЯ ПАНЕЛЬ ДЕЙСТВИЙ --- */
    /* В style.css два конкурирующих правила .action-buttons-footer; второе
       (стр. ~661) делает панель плавающей «таблеткой» width:fit-content.
       Перебиваем width/margin/radius явно, иначе бар не растянется. */
    .action-buttons-footer {
        position: fixed;
        left: 0 !important; right: 0 !important; bottom: 0 !important;
        width: auto !important;
        margin: 0 !important;
        border-radius: 0 !important;
        border-left: none; border-right: none;
        border-top: 1px solid var(--border-color);
        background: var(--surface) !important;
        padding: 10px 12px calc(10px + var(--safe-bottom)) 12px !important;
        justify-content: space-between;
        gap: 8px !important;
        box-shadow: 0 -4px 16px rgba(0,0,0,0.08) !important;
    }
    .action-buttons-footer button {
        min-height: var(--tap-target);
        padding: 10px 16px;
        font-size: 0.88em;
    }
    /* Выпадающие меню открываются вверх и во всю ширину */
    .archive-dropup, .export-dropup {
        left: 0; right: 0;
        width: auto;
        max-width: 100%;
        bottom: calc(100% + 10px);
    }
    .exp-mini-grid { grid-template-columns: repeat(2, 1fr) !important; gap: 10px; }
    .export-card-mini { min-height: 84px; }

    /* Сетка выбора формата экспорта */


    /* --- Калькуляторы: сайдбар уезжает наверх, контент под ним --- */
    #calcModal .modal-content {
        width: 100% !important;
        height: auto !important;
        max-height: 92vh !important;
        padding: 20px 12px calc(20px + var(--safe-bottom)) 12px !important;
    }
    /* Родитель сайдбара и контента — flex-строка с инлайн-стилем, разворачиваем */
    #calcModal div:has(> #calc-sidebar) {
        flex-direction: column !important;
        overflow: visible !important;
        gap: 12px !important;
    }
    #calc-sidebar {
        width: 100% !important;
        flex-shrink: 1 !important;
        border-right: none !important;
        border-bottom: 1px solid var(--border-color);
        padding-right: 0 !important;
        padding-bottom: 10px;
        flex-direction: row !important;
        overflow-x: auto !important;
        scrollbar-width: none;
    }
    #calc-sidebar::-webkit-scrollbar { display: none; }
    #calc-sidebar > * { flex: 0 0 auto; white-space: nowrap; }
    #calc-content { padding-left: 0 !important; padding-right: 0 !important; }
    /* Внутренние сетки калькуляторов (инлайн grid-template-columns) — в одну колонку */
    #calc-content div[style*="grid-template-columns"] {
        grid-template-columns: 1fr !important;
    }

    /* Архив/шаблоны */
    #archiveModal .modal-content { max-height: 92vh; }

    /* Скрываем декоративный прелоадер-кольцо на слабых устройствах */
    .spinner-ring.inner { display: none; }
}

/* =========================================================================
   6. XXS — КОМПАКТНЫЙ СМАРТФОН (< 480px)
   ========================================================================= */
@media (max-width: 479px) {
    .main-app-container { padding: 0 8px; }
    .modern-card, .text-area-container { padding: 10px; }

    .section-button { padding: 9px 12px; font-size: 0.9em; }

    /* Заголовки разделов компактнее */
    .text-area-container h3 { font-size: 1em; }

    .action-buttons-footer button span { font-size: 0.85em; }
    .exp-mini-grid { grid-template-columns: 1fr !important; }

    /* Языковой переключатель компактнее */
    .lang-switch a { padding: 6px 10px; font-size: 0.85em; }
}

/* =========================================================================
   7. ЛАНДШАФТНАЯ ОРИЕНТАЦИЯ НА СМАРТФОНЕ
   Высота мала — уменьшаем вертикальные отступы и высоту листов.
   ========================================================================= */
@media (max-height: 500px) and (orientation: landscape) {
    .modal { align-items: center; padding: 8px; }
    .modal-content { max-height: 96vh; border-radius: var(--radius-md); }
    .modal-content::before { display: none; }
    .action-buttons-footer { position: sticky; }
    textarea.main-area { min-height: 140px; }
}

/* =========================================================================
   8. ПЕЧАТЬ — @media print
   -------------------------------------------------------------------------
   Цель: на бумагу уходит только клинический документ. Весь UI-хром
   (вкладки, кнопки, модалки, панели) убирается; таблицы не рвутся по строкам.
   ========================================================================= */
@media print {

    /* --- 8.1 Геометрия страницы --- */


    html, body {
        background: #fff !important;
        color: #000 !important;
        font-size: 11pt;
        line-height: 1.35;
        overflow: visible !important;
    }

    /* --- 8.2 Скрываем весь интерфейс --- */
    .section-tabs,
    .action-buttons-footer,
    .lang-switch,
    .auth-panel,
    .textarea-controls,
    .control-button,
    .btn-add,
    .list-input-group,
    .sortable-header,
    .drag-handle,
    .delete-btn,
    .empty-list-msg,
    .modal,
    .lightbox-overlay,
    #modern-preloader,
    #app-skeleton,
    .cookie-banner,
    .offline-banner,
    .theme-toggle-btn,
    .archive-combo-wrapper,
    .export-combo-wrapper,
    .btn-pro-simple{
        display: none !important;
    }

    /* --- 8.3 Снимаем экранные эффекты --- */
    .app-wrapper,
    .main-app-container,
    .modern-card,
    .text-area-container,
    .content,
    .sortable-item {
        background: #fff !important;
        box-shadow: none !important;
        border: none !important;
        padding: 0 !important;
        margin: 0 !important;
        max-width: 100% !important;
        backdrop-filter: none !important;
    }

    .app-wrapper { min-height: auto !important; padding: 0 !important; }

    /* Тёмная тема не должна попадать на бумагу */
    [data-theme="dark"] {
        --surface: #ffffff;
        --bg-gray: #ffffff;
        --text-main: #000000;
        --text-muted: #333333;
        --border-color: #999999;
    }
    [data-theme="dark"] * {
        background-color: #fff !important;
        color: #000 !important;
    }

    /* --- 8.4 Поля ввода печатаются как обычный текст --- */
    input, textarea, select,
    .compact-input,
    .item-cell {
        border: none !important;
        background: transparent !important;
        color: #000 !important;
        padding: 1pt 2pt !important;
        font-size: 10.5pt !important;
        min-height: 0 !important;
        height: auto !important;
        -webkit-appearance: none;
        appearance: none;
        white-space: normal !important;
        overflow: visible !important;
    }
    textarea {
        resize: none !important;
        overflow: visible !important;
        height: auto !important;
    }

    /* --- 8.5 Назначения: печатаем сеткой, строку не рвём --- */
    .sortable-list { display: block !important; }
    .sortable-item {
        display: block !important;
        page-break-inside: avoid;
        break-inside: avoid;
        border-bottom: 0.5pt solid #ccc !important;
        padding: 2pt 0 !important;
    }
    .item-text.grid-mode1,
    .grid-mode1 {
        display: grid !important;
        grid-template-columns: 1.3fr 1fr 1fr 0.8fr 0.8fr 0.7fr 1fr 1fr !important;
        gap: 2pt !important;
    }

    /* --- 8.6 Заголовки и типографика --- */
    h1, h2, h3, h4 {
        page-break-after: avoid;
        break-after: avoid;
        color: #000 !important;
        font-size: 12pt;
        margin: 6pt 0 3pt 0;
    }
    p, li { orphans: 3; widows: 3; }

    table { border-collapse: collapse !important; width: 100% !important; }
    table, tr, td, th { page-break-inside: avoid; break-inside: avoid; }
    th, td { border: 0.5pt solid #000 !important; padding: 2pt 4pt !important; }
    thead { display: table-header-group; }  /* шапка таблицы на каждой странице */

    /* Разворачиваем скрытые вкладки: печатаем ВСЕ разделы, а не только активный */
    .content > div { display: block !important; page-break-inside: auto; }

    /* Ссылки без URL-хвостов */
    a, a:visited { text-decoration: none !important; color: #000 !important; }
    a[href]::after { content: none !important; }

    /* Водяной знак из style.css сохраняем как есть (.has-watermark::before) */
}
