/* ============================================================================
   Мобильный слой кабинета «Контроль витрин» (320–768px).

   Подключается ПОСЛЕ app.css и ничего в нём не переопределяет на десктопе:
   все правила живут внутри @media (max-width: 768px), кроме блока
   «hover только для мыши» — на тач-экранах :hover залипает после тапа.

   Принципы:
   • тач-таргет ≥ 44×44 CSS-px (WCAG 2.5.5 / HIG);
   • поля ввода 16px — иначе iOS Safari зумит страницу при фокусе;
   • анимации только transform/opacity (композитные слои, без layout-трэшинга);
   • safe-area — контент не уезжает под «чёлку» и домашний индикатор.
   ========================================================================== */

/* --- hover-эффекты только там, где есть настоящая мышь ------------------- */
@media (hover: none) {
  .side button:hover,
  .click-row:hover td,
  .stock-table .click-row:hover td:first-child { background: initial; }
  .bakery-card:hover { border-color: var(--line); }
}

/* --- состояния нажатия вместо наведения (все платформы) ------------------ */
button, .btn, .click-row, .bakery-card, .display-btn {
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation; /* убирает 300ms задержку клика */
}
button:active, .btn:active { transform: scale(.97); }
button, .btn { transition: transform .12s ease, background-color .15s ease; }
.click-row:active td { background: #f5ebe0; }
.bakery-card:active { border-color: var(--gold); transform: scale(.99); }

/* ========================================================================== */
@media (max-width: 768px) {

  :root {
    --safe-top: env(safe-area-inset-top, 0px);
    --safe-bottom: env(safe-area-inset-bottom, 0px);
    --safe-left: env(safe-area-inset-left, 0px);
    --safe-right: env(safe-area-inset-right, 0px);
    --tabbar-h: 58px;
    --topbar-h: 52px;
  }

  html { -webkit-text-size-adjust: 100%; }
  body {
    /* overscroll-behavior гасит «резинку» всей страницы, чтобы работал
       собственный pull-to-refresh и не дёргался фон под bottom sheet */
    overscroll-behavior-y: none;
  }

  /* --- каркас: одна колонка, боковое меню превращается в нижний таб-бар --- */
  .shell { grid-template-columns: 1fr; min-height: 100dvh; }
  .side { display: none; }

  /* min-width:0 обязателен: у grid-элемента по умолчанию min-width:auto,
     из-за чего широкая матрица наличия (12 000+px) растягивает всю страницу
     вместо того, чтобы скроллиться внутри своего контейнера. */
  .main { min-width: 0; overflow-x: hidden; }
  .main > * { max-width: 100%; }

  .main {
    padding: calc(var(--topbar-h) + var(--safe-top) + .5rem)
             calc(.75rem + var(--safe-right))
             calc(var(--tabbar-h) + var(--safe-bottom) + 1.25rem)
             calc(.75rem + var(--safe-left));
  }

  /* --- верхняя панель: закреплена, показывает раздел и пользователя ------ */
  .topbar {
    position: fixed; top: 0; left: 0; right: 0; z-index: 40;
    height: calc(var(--topbar-h) + var(--safe-top));
    padding: var(--safe-top) calc(.85rem + var(--safe-right)) 0 calc(.85rem + var(--safe-left));
    margin: 0; gap: .6rem;
    background: color-mix(in srgb, var(--bg) 92%, transparent);
    backdrop-filter: saturate(140%) blur(8px);
    -webkit-backdrop-filter: saturate(140%) blur(8px);
    border-bottom: 1px solid var(--line);
  }
  .topbar h2 {
    font-size: 1.05rem; white-space: nowrap;
    overflow: hidden; text-overflow: ellipsis;
  }
  #userMeta {
    font-size: .78rem !important; max-width: 42%;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right;
  }

  /* --- нижний таб-бар ---------------------------------------------------- */
  .tabbar {
    position: fixed; left: 0; right: 0; bottom: 0; z-index: 45;
    display: grid; grid-auto-flow: column; grid-auto-columns: 1fr;
    background: var(--brown);
    padding-bottom: var(--safe-bottom);
    box-shadow: 0 -2px 12px rgba(42, 26, 18, .18);
  }
  .tabbar__btn {
    all: unset;
    min-height: 44px; height: var(--tabbar-h);
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    gap: 2px; padding: 4px 2px;
    color: rgba(248, 239, 228, .72); cursor: pointer;
    -webkit-tap-highlight-color: transparent;
    transition: color .15s ease;
  }
  .tabbar__btn[aria-current="page"] { color: #fff; }
  .tabbar__btn:active { background: rgba(255, 255, 255, .1); }
  .tabbar__icon { font-size: 1.15rem; line-height: 1; }
  .tabbar__label {
    font-size: .64rem; font-weight: 600; letter-spacing: .01em;
    max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  /* индикатор активного таба */
  .tabbar__btn[aria-current="page"] .tabbar__icon {
    transform: translateY(-1px);
    transition: transform .18s cubic-bezier(.2, .8, .3, 1);
  }

  /* --- bottom sheet (меню «Ещё» и любые вспомогательные панели) ---------- */
  .sheet-bg {
    position: fixed; inset: 0; z-index: 60;
    background: rgba(42, 26, 18, .45);
    opacity: 0; transition: opacity .22s ease;
    -webkit-backdrop-filter: blur(2px); backdrop-filter: blur(2px);
  }
  .sheet-bg.is-open { opacity: 1; }
  .sheet {
    position: fixed; left: 0; right: 0; bottom: 0; z-index: 61;
    max-height: 82dvh; overflow: auto; -webkit-overflow-scrolling: touch;
    background: var(--card);
    border-radius: 18px 18px 0 0;
    border-top: 1px solid var(--line);
    padding: .5rem calc(1rem + var(--safe-right))
             calc(1rem + var(--safe-bottom)) calc(1rem + var(--safe-left));
    transform: translateY(100%);
    transition: transform .26s cubic-bezier(.2, .8, .3, 1);
    will-change: transform;
  }
  .sheet.is-open { transform: translateY(0); }
  .sheet__grip {
    width: 42px; height: 4px; border-radius: 999px; background: var(--line);
    margin: 6px auto 12px; flex: none;
  }
  .sheet__title {
    margin: 0 0 .6rem; font-size: 1rem; font-weight: 700; color: var(--brown);
  }
  .sheet__list { display: grid; gap: .3rem; }
  .sheet__item {
    all: unset; box-sizing: border-box;
    display: flex; align-items: center; gap: .65rem;
    min-height: 48px; padding: .6rem .75rem; border-radius: 10px;
    color: var(--ink); font-weight: 600; cursor: pointer;
  }
  .sheet__item:active { background: #f5ebe0; }
  .sheet__item[aria-current="page"] { background: #f0e6da; color: var(--brown); }
  .sheet__item--danger { color: var(--bad); }

  /* --- фильтры: горизонтальная лента вместо переноса в 3 ряда ------------ */
  .toolbar {
    display: grid; grid-template-columns: 1fr 1fr; gap: .5rem;
    margin-bottom: .7rem; align-items: end;
  }
  .toolbar > * { min-width: 0; width: 100%; }
  .toolbar > button { grid-column: 1 / -1; }
  .toolbar label { margin: 0; font-size: .78rem; }
  /* Поля 16px — единственный способ запретить iOS зум при фокусе */
  input, select, textarea { font-size: 16px; min-height: 44px; }
  textarea { min-height: 76px; }
  input[type="checkbox"], input[type="radio"] { min-height: 0; width: 22px; height: 22px; }
  button, .btn { min-height: 44px; }

  /* --- KPI-карточки: 2 колонки, компактнее --------------------------------*/
  .cards { grid-template-columns: 1fr 1fr; gap: .5rem; margin-bottom: .75rem; }
  .card { padding: .65rem .7rem; border-radius: 12px; }
  .card .n { font-size: 1.25rem; }
  .card .t { font-size: .74rem; line-height: 1.25; }

  /* ======================================================================
     ТАБЛИЦЫ → КАРТОЧКИ.
     data-label проставляет mobile.js по <th>, поэтому существующий рендер
     в app.js трогать не нужно. Матрица наличия (.stock-table) исключена —
     для неё ниже отдельный компактный режим с горизонтальным скроллом.
     ====================================================================== */
  .table-scroll { max-height: none; overflow: visible; }

  table:not(.stock-table) { border: none; background: transparent; font-size: .92rem; }
  table:not(.stock-table) thead { display: none; }
  table:not(.stock-table) tbody { display: grid; gap: .5rem; }
  table:not(.stock-table) tr {
    display: block; background: var(--card);
    border: 1px solid var(--line); border-radius: 12px; padding: .55rem .7rem;
  }
  table:not(.stock-table) tr.click-row { position: relative; padding-right: 1.6rem; }
  /* шеврон-подсказка «строка кликабельна» */
  table:not(.stock-table) tr.click-row::after {
    content: "›"; position: absolute; right: .7rem; top: 50%;
    transform: translateY(-50%); color: var(--muted); font-size: 1.3rem; line-height: 1;
  }
  table:not(.stock-table) td {
    display: flex; gap: .75rem; align-items: baseline;
    padding: .22rem 0; border: none; text-align: left;
  }
  table:not(.stock-table) td::before {
    content: attr(data-label);
    flex: 0 0 42%; max-width: 42%;
    color: var(--muted); font-size: .78rem; font-weight: 600;
  }
  /* Ячейка без подписи (пустой data-label) занимает всю ширину — например
     колонка с кнопкой действия или превью-фото. */
  table:not(.stock-table) td[data-label=""]::before { display: none; }
  table:not(.stock-table) td[data-label=""] { padding-top: .35rem; }
  table:not(.stock-table) td > button { width: auto; min-width: 44px; }
  table:not(.stock-table) td .thumb { width: 96px; height: 72px; }
  table:not(.stock-table) tr.totals-row { background: #f7efe4; }
  /* Первая ячейка карточки — заголовок */
  table:not(.stock-table) td:first-child {
    font-weight: 700; color: var(--brown); font-size: 1rem;
    padding-bottom: .35rem; margin-bottom: .25rem; border-bottom: 1px dashed var(--line);
  }
  table:not(.stock-table) td:first-child::before { display: none; }
  /* Заглушка «данных нет» не должна выглядеть карточкой-таблицей */
  table:not(.stock-table) td[colspan] { display: block; text-align: center; }
  table:not(.stock-table) td[colspan]::before { display: none; }

  /* --- матрица наличия: остаётся таблицей, но компактной ----------------- */
  .stock-table-hint {
    display: flex; align-items: center; gap: .4rem;
    color: var(--muted); font-size: .8rem; margin: 0 0 .4rem;
  }
  .stock-table-hint::before { content: "↔"; font-size: 1rem; }
  #stTableWrap {
    overflow: auto; -webkit-overflow-scrolling: touch;
    scroll-snap-type: x proximity; max-height: 66dvh;
  }
  .stock-table { font-size: .8rem; }
  .stock-table th { min-width: 68px; scroll-snap-align: start; }
  .stock-table th, .stock-table td { padding: .4rem .35rem; text-align: center; }
  .stock-table th:first-child, .stock-table td:first-child {
    min-width: 132px; max-width: 132px; text-align: left;
  }
  .stock-table td:first-child small { font-size: .7rem; }
  .stock-th { font-size: .64rem; }
  .stock-th img { width: 28px; height: 22px; }

  /* --- модалки → полноэкранные bottom sheet ------------------------------ */
  .modal-bg { padding: 0; align-items: flex-end; }
  .modal {
    width: 100%; max-height: 92dvh; border-radius: 18px 18px 0 0;
    padding: .5rem calc(1rem + var(--safe-right))
             calc(1.25rem + var(--safe-bottom)) calc(1rem + var(--safe-left));
    border-bottom: none;
    animation: sheet-up .26s cubic-bezier(.2, .8, .3, 1);
    -webkit-overflow-scrolling: touch;
  }
  @keyframes sheet-up { from { transform: translateY(100%); } to { transform: translateY(0); } }
  /* «ручка» для свайпа вниз — рисуем псевдоэлементом, чтобы не менять разметку */
  .modal::before {
    content: ""; display: block; width: 42px; height: 4px; border-radius: 999px;
    background: var(--line); margin: 4px auto 10px; position: sticky; top: 0;
  }
  .modal h3 { font-size: 1.05rem; }
  .modal .form-grid { grid-template-columns: 1fr; }
  /* Кнопки в модалке — в ряд, крупные, с прилипанием к низу листа */
  .modal .modal-actions,
  .modal > div[style*="display:flex"] { flex-wrap: wrap; gap: .5rem; }
  .modal button { width: auto; flex: 1 1 auto; min-width: 44%; }

  /* --- сравнение фото / галереи ------------------------------------------ */
  .compare-grid { grid-template-columns: 1fr; gap: .5rem; }
  .compare-grid img { height: 190px; }
  .prod-gallery figure { width: calc(50% - .3rem); }
  .prod-gallery img { height: 88px; }
  .bakery-grid { grid-template-columns: 1fr; }
  .checks { grid-template-columns: 1fr; max-height: 220px; }
  .checks label { min-height: 40px; }
  .prod-plan { max-height: 50dvh; }
  .prod-plan-row { min-height: 48px; }
  .form-grid { grid-template-columns: 1fr; }

  /* --- просмотрщик фото: панель под safe-area ---------------------------- */
  .pv-bar {
    padding-top: calc(.6rem + var(--safe-top));
    padding-left: calc(.9rem + var(--safe-left));
    padding-right: calc(.9rem + var(--safe-right));
  }
  .pv-actions button, .pv-actions .pv-open { min-height: 40px; padding: .45rem .8rem; }
  .photo-viewer { padding-bottom: var(--safe-bottom); }

  /* --- pull-to-refresh --------------------------------------------------- */
  .ptr {
    position: fixed; left: 0; right: 0;
    top: calc(var(--topbar-h) + var(--safe-top));
    display: flex; align-items: center; justify-content: center;
    height: 0; overflow: hidden; z-index: 30; pointer-events: none;
    color: var(--muted); font-size: .8rem; font-weight: 600;
  }
  .ptr__spinner {
    width: 20px; height: 20px; border-radius: 50%;
    border: 2px solid var(--line); border-top-color: var(--brown);
    margin-right: .45rem;
  }
  .ptr.is-armed .ptr__spinner { transform: rotate(180deg); }
  .ptr.is-loading .ptr__spinner { animation: ptr-spin .7s linear infinite; }
  @keyframes ptr-spin { to { transform: rotate(360deg); } }

  /* --- вход ---------------------------------------------------------------*/
  .login-wrap { padding: calc(1rem + var(--safe-top)) 1rem calc(1rem + var(--safe-bottom)); }
  .login-card { padding: 1.15rem; }
}

/* --- очень узкие экраны (iPhone SE, 320px) -------------------------------- */
@media (max-width: 360px) {
  .cards { grid-template-columns: 1fr; }
  .toolbar { grid-template-columns: 1fr; }
  .tabbar__label { font-size: .58rem; }
  table:not(.stock-table) td::before { flex-basis: 46%; max-width: 46%; }
}

/* --- ландшафт на телефоне: экономим вертикаль ----------------------------- */
@media (max-width: 900px) and (orientation: landscape) and (max-height: 480px) {
  :root { --topbar-h: 44px; --tabbar-h: 48px; }
  .cards { grid-template-columns: repeat(4, 1fr); }
  .modal, .sheet { max-height: 96dvh; }
  .compare-grid { grid-template-columns: 1fr 1fr; }
  .compare-grid img { height: 140px; }
}

/* --- уважаем системную настройку «меньше движения» ------------------------ */
@media (prefers-reduced-motion: reduce) {
  .sheet, .modal, button, .btn, .tabbar__btn, .ptr__spinner {
    transition: none !important; animation: none !important;
  }
}
