/* =========================================================
   ADDITIONS.CSS
   =========================================================
   Стили, которые раньше жили прямо в <style> внутри index.html —
   исторически (на старте проекта) style.css не был доступен для
   правки, поэтому новые точечные стили (приход/должники/остатки/
   офлайн/мобильные фиксы, бейджи, карточки поставщиков и т.п.)
   добавлялись туда. Сейчас style.css полностью доступен для правки, но
   эти правила вынесены сюда КАК ЕСТЬ, одним куском, в исходном порядке,
   а не растащены по тематическим файлам выше — специально, чтобы
   гарантированно не изменить порядок каскада (правила с одинаковой
   специфичностью выигрывают по порядку подключения, и здесь порядок
   сохранён 1-в-1). Подключается последним в index.html — так же, как
   раньше этот блок шёл в HTML после <link rel="stylesheet"
   href="style.css">. При следующей уборке можно аккуратно разнести
   правила по тематическим файлам выше, сверяя вёрстку вживую.
   ========================================================= */

/* Мелкие стили для новых элементов (приход/должники/остатки/офлайн/
   мобильная версия), не выносил в style.css, т.к. файл не был
   предоставлен для правки. */
.order-subtabs { display:flex; gap:8px; margin:10px 0; flex-wrap:wrap; }
    .order-subtab-btn {
      min-height: 34px;
      padding: 7px 12px;
      border: 1px solid var(--border);
      background: var(--surface);
      border-radius: 9px;
      cursor: pointer;
      font-size: 12.8px;
      color: var(--text-muted);
      transition: all 0.15s ease;
    }
    .order-subtab-btn:hover { border-color: var(--border-strong); background: var(--surface-hover); color: var(--text); }
    .order-subtab-btn.active {
      background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
      color: #fff;
      border-color: rgba(37, 99, 235, 0.45);
      box-shadow: 0 8px 18px rgba(37,99,235,0.16);
    }
    .paid-badge { font-size:10.5px; padding:2px 7px; border-radius:20px; margin-left:6px; }
    .paid-badge.paid { background:rgba(34,197,94,0.15); color:var(--success,#16a34a); }
    .paid-badge.unpaid { background:rgba(239,68,68,0.12); color:var(--danger,#dc2626); }
    .paid-badge.partial { background:rgba(217,119,6,0.14); color:var(--warning,#d97706); }
    .paid-badge.given { background:rgba(37,99,235,0.12); color:var(--primary,#2563eb); }
    .paid-badge.given-partial { background:rgba(37,99,235,0.07); color:var(--primary,#2563eb); }
    .paid-badge.arrived { background:rgba(13,148,136,0.14); color:#0d9488; }
    .paid-badge.arrived-partial { background:rgba(13,148,136,0.08); color:#0d9488; }
    .paid-badge.waiting { background:rgba(107,114,128,0.10); color:#6b7280; }
    .paid-badge.cancelled { background:rgba(107,114,128,0.15); color:#6b7280; }
    .role-restricted .order-price-col, .role-restricted .order-paid-col { display:none; }
    .payment-box { display:flex; align-items:center; flex-wrap:wrap; gap:6px; }
    .order-dates-row label { display:flex; flex-direction:column; gap:3px; font-size:11.5px; color:var(--text-muted); }
    .order-dates-row input[type="date"] { font-size:13px; padding:4px 6px; border:1px solid var(--border); border-radius:6px; }
    @media (max-width: 560px) {
      .order-dates-row {
        display:none;
        flex-wrap:wrap;
        gap:14px;
        margin:2px 0 12px;
        padding:10px 12px;
        background:rgba(37,99,235,0.05);
        border:1px solid var(--border);
        border-radius:10px;
      }
      .order-dates-row.expanded {
        display:flex;
      }
      .mobile-inline-toggle {
        width: fit-content;
        max-width: 140px;
        align-self: flex-start;
      }
      .orders-sidebar-header .btn-new-order {
        min-height: 32px;
        padding: 6px 10px;
        font-size: 12px;
      }
    }

    /* База покупателей */
    .customer-dir-card { border:1px solid var(--border); border-radius:10px; margin-bottom:10px; overflow:hidden; }
    .customer-dir-head { display:flex; justify-content:space-between; align-items:center; gap:10px; padding:12px 14px; cursor:pointer; flex-wrap:wrap; }
    .customer-dir-head:hover { background:rgba(0,0,0,0.02); }
    .customer-dir-name { font-weight:600; font-size:14px; margin-right:8px; }
    .customer-dir-meta { font-size:11.5px; color:var(--text-muted); }
    .customer-dir-caret { font-size:11px; color:var(--text-muted); }
    .customer-dir-body { padding:0 14px 14px; border-top:1px solid var(--border); }
    .customer-dir-section-title { font-size:12px; font-weight:600; color:var(--text-muted); margin:10px 0 6px; }
    .customer-dir-favorites { display:flex; flex-wrap:wrap; gap:6px; }
    .customer-dir-fav-chip { background:rgba(37,99,235,0.08); color:var(--primary,#2563eb); font-size:11.5px; padding:4px 9px; border-radius:20px; }

    /* Динамика в Сводке — список периодов с полосками (см. renderSummaryTrend в summary.js) */
    .trend-list { display:flex; flex-direction:column; gap:14px; }
    .trend-row { border:1px solid var(--border); border-radius:10px; padding:10px 12px; background: rgba(255,255,255,0.02); transition: border-color 0.15s ease, box-shadow 0.15s ease; }
    .trend-row:hover { border-color: var(--border-strong); box-shadow: 0 4px 12px rgba(15, 23, 42, 0.04); }
    .trend-row-head { display:flex; justify-content:space-between; align-items:baseline; margin-bottom:8px; gap:8px; flex-wrap:wrap; }
    .trend-period-label { font-weight:600; font-size:13.5px; }
    .trend-summary-text { font-size:12px; color:var(--text-muted); white-space:nowrap; }
    .trend-margin { font-weight:700; font-size:14px; white-space:nowrap; }
    .trend-margin.positive { color:var(--success,#16a34a); }
    .trend-margin.negative { color:var(--danger,#dc2626); }
    .trend-bar-line { display:flex; align-items:center; gap:8px; margin-top:5px; }
    .trend-bar-tag { width:56px; flex-shrink:0; font-size:11px; color:var(--text-muted); }
    .trend-bar-track { flex:1; height:14px; background:rgba(0,0,0,0.05); border-radius:7px; overflow:hidden; }
    .trend-bar-fill { height:100%; border-radius:7px; }
    .trend-bar-fill.revenue { background:var(--primary,#2563eb); }
    .trend-bar-fill.cost { background:#f59e0b; }
    .trend-bar-value { width:92px; flex-shrink:0; text-align:right; font-size:12px; font-variant-numeric:tabular-nums; }
    @media (max-width: 640px) {
      .trend-bar-tag { width:46px; font-size:10px; }
      .trend-bar-value { width:78px; font-size:11px; }
    }
    .price-match-badge { font-size:11.5px; color:var(--success,#16a34a); margin-left:6px; white-space:nowrap; }
    .comment-cell { display:flex; align-items:center; gap:6px; max-width:260px; }
    .comment-preview { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; flex:1; font-size:13px; }
    .btn-expand-comment { border:1px solid var(--border); background:var(--surface); border-radius:6px; width:26px; height:26px; line-height:1; cursor:pointer; flex-shrink:0; font-size:13px; }
    .due-banner { background:rgba(239,68,68,0.1); border:1px solid var(--danger,#dc2626); color:var(--danger,#dc2626); padding:10px 14px; border-radius:8px; margin-bottom:14px; font-size:13.5px; }
    .row-overdue { background:rgba(239,68,68,0.06); }
    .mobile-actions-toggle { display:none; border:1px solid var(--border); background:var(--surface); border-radius:8px; width:36px; height:36px; font-size:18px; cursor:pointer; }

    /* Товары: отдельная карточная раскладка для мобильных экранов,
       вместо горизонтально обрезающейся таблицы. */
    .product-cards-mobile { display:none; flex-direction:column; gap:10px; }
    .product-card { border:1px solid var(--border); border-radius:10px; padding:12px; background:var(--surface); }
    .product-card-top { display:flex; align-items:center; gap:8px; margin-bottom:8px; }
    .product-card-name { font-weight:600; flex:1; }
    .product-card-row { display:flex; justify-content:space-between; font-size:13.5px; padding:3px 0; border-bottom:1px dashed var(--border); }
    .product-card-row:last-of-type { border-bottom:none; }
    .product-card-row .label { color:var(--text-muted); }
    .product-card-actions { display:flex; gap:8px; margin-top:10px; }
    .product-card-actions button { flex:1; }

    @media (max-width: 640px) {
      #productTableWrapper .table-container { display:none; }
      .product-cards-mobile { display:flex; }
      .mobile-actions-toggle { display:inline-flex; align-items:center; justify-content:center; }
      /* БАГ (найден и исправлен): toolbar по умолчанию не переносится на
         мобильных, из-за чего .toolbar-right (а вместе с ним кнопка "⋮")
         уезжает за правый край экрана и становится недоступной без
         горизонтальной прокрутки всей страницы. Заставляем toolbar
         переноситься и класть правый блок на отдельную полноширинную
         строку — тогда кнопка всегда в зоне видимости. */
      .toolbar { flex-wrap: wrap; row-gap: 8px; }
      .toolbar-left { flex-wrap: wrap; row-gap: 8px; width: 100%; }
      /* БАГ (предыдущая попытка через relative/absolute внутри .toolbar-right
         не помогла — судя по всему, где-то в общем style.css сам .toolbar
         или родительский контейнер на мобильных не переносится/не
         ужимается, и весь toolbar-right сдвигается за пределы экрана
         целиком вместе с кнопкой). Другое решение: кнопка и панель
         действий больше не зависят от положения .toolbar-right в потоке —
         они через position:fixed прибиты прямо к экрану (viewport), как
         уже работающие плашки офлайн/сохранения ниже. Это гарантированно
         помещает их в пределы экрана независимо от того, что происходит
         с версткой toolbar. */
      .toolbar-right { position: static; }
      .mobile-actions-toggle {
        display: flex; align-items:center; justify-content:center;
        position: fixed; right: 14px; bottom: 176px; z-index: 60;
        width: 48px; height: 48px; border-radius: 50%;
        background: var(--primary, #2563eb); color:#fff; border:none;
        box-shadow: 0 4px 14px rgba(0,0,0,0.3); font-size: 22px; line-height:1;
      }
      .toolbar-actions-list { display: none; }
      .toolbar-right.mobile-open .toolbar-actions-list {
        display: flex; flex-direction: column; gap: 10px;
        position: fixed; left: 12px; right: 12px; bottom: 236px;
        max-height: 45vh; overflow-y: auto;
        background: var(--surface); border: 1px solid var(--border); border-radius: 14px;
        padding: 14px; box-shadow: 0 12px 32px rgba(0,0,0,0.3); z-index: 61;
      }
      .toolbar-actions-list button, .toolbar-actions-list label { width: 100%; box-sizing: border-box; }
      .comment-cell { max-width:150px; }
      /* Такая же проблема "уезжает за экран" была потенциально и в других
         местах, где ряд кнопок/полей не переносится: подвкладки заказа,
         блок оплаты покупателя, действия в таблице пользователей —
         принудительно разрешаем перенос везде. */
      .order-header { flex-wrap: wrap; }
      .order-subtabs { width: 100%; }
      .payment-box { width: 100%; }
      #usersList td:last-child { display:flex; flex-wrap:wrap; gap:6px; }
      .modal-content { width: 92vw !important; max-width: 92vw !important; box-sizing: border-box; }
      .orders-layout { flex-direction: column; }
      .orders-sidebar { width: 100% !important; max-height: 220px; overflow-y: auto; }
      /* БАГ (найден и исправлен, v2): таблица товаров покупателя на
         узких экранах сжимала колонки настолько, что название товара
         внутри <select> обрезалось браузером до одной буквы. Предыдущий
         фикс (min-width: 720px на таблице) не работал надёжно на iOS
         WebKit — браузер игнорировал это ограничение при наличии 7
         колонок с процентными ширинами, и <select> всё равно схлопывался.
         Окончательное решение: колонки заголовка таблицы переведены с
         процентных на абсолютные min-width (см. index.html), а контейнер
         принудительно прокручивается горизонтально. <select> с товаром
         получает min-width: 180px напрямую — браузер не может сжать его
         ниже этого значения ни при каком размере экрана. */
      .items-section .table-container,
      #orderSubtab-receiving .table-container {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
      }
      /* Минимальная ширина таблицы = сумма min-width всех колонок */
      .items-section .order-table,
      #orderSubtab-receiving .order-table {
        width: 100% !important;
        max-width: 100% !important;
        min-width: 0 !important;
        table-layout: fixed;
      }
      /* Гарантируем, что <select> с товаром никогда не сожмётся */
      .items-section .order-select:first-child,
      .items-section td:first-child .order-select {
        min-width: 180px;
        width: 100%;
      }
      .modal .table-container {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
      }
      .modal .order-table {
        min-width: 480px;
      }
      /* Карточки покупателей (customers-list) на узких экранах: имя +
         бейджи оплаты/доставки + кнопка удаления в одну строку без
         переноса не влезали и вылезали за пределы сайдбара. Разрешаем
         содержимому одной "таблетки" переноситься на несколько строк
         (row-gap уже задан в style.css), а форму меняем с "таблетки" на
         обычную карточку — со скруглением 999px многострочный контент
         выглядит сломанным. */
      .customers-list .customer-item {
        border-radius: var(--radius-sm);
      }
      /* Таблица "Должники" — 6 колонок, включая date-picker и кнопки с
         текстом, на узких экранах не помещались и обрезались. Тот же
         подход, что и для таблицы заказа: гарантированная минимальная
         ширина + прокрутка контейнера по горизонтали вместо сжатия. */
      #tab-debtors .table-container {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
      }
      #tab-debtors .summary-detail-table {
        min-width: 640px;
      }
    }

@media (max-width: 900px) {
  html,
  body {
    width: 100%;
    max-width: 100%;
    overflow-x: clip;
  }

  .app-container,
  .main-content {
    width: 100%;
    max-width: 100%;
  }

  .main-content {
    padding-left: max(var(--mobile-page-pad, 14px), env(safe-area-inset-left, 0px));
    padding-right: max(var(--mobile-page-pad, 14px), env(safe-area-inset-right, 0px));
  }

  .mobile-global-topbar {
    left: 0;
    right: 0;
    width: auto;
    max-width: 100%;
  }

  .mobile-nav-toggle {
    right: max(12px, env(safe-area-inset-right, 0px)) !important;
  }

  .mobile-nav-back {
    left: max(12px, env(safe-area-inset-left, 0px)) !important;
  }

  input:not([type="checkbox"]):not([type="radio"]),
  select,
  textarea {
    font-size: 16px !important;
  }

  button,
  a[href],
  [role="button"],
  label.checkbox-field {
    touch-action: manipulation;
  }

  .order-meta-row {
    grid-template-columns: max-content max-content;
    justify-content: start;
    align-items: stretch;
  }

  .order-meta-field:not(.checkbox-field) {
    display: grid;
    grid-template-columns: max-content 68px;
    align-items: center;
    justify-content: start;
    gap: 6px;
    width: max-content;
    min-height: 44px;
    padding: 4px 8px;
  }

  .order-meta-field:not(.checkbox-field) > span {
    white-space: nowrap;
  }

  .order-meta-field input[type="text"] {
    width: 68px;
    max-width: 68px;
    min-height: 32px;
    padding: 4px 6px;
  }

  .order-meta-field.checkbox-field {
    justify-content: flex-start;
    width: max-content;
    min-height: 44px;
    padding: 4px 8px;
    gap: 7px;
    white-space: nowrap;
  }

  .order-meta-field.checkbox-field input[type="checkbox"] {
    width: 18px;
    height: 18px;
    min-height: 0;
    flex: 0 0 18px;
    margin: 0;
  }

  .order-meta-field.checkbox-field span {
    font-size: 14px;
    white-space: nowrap;
  }
}

@media (max-width: 360px) {
  .order-meta-row {
    grid-template-columns: minmax(0, 1fr) max-content;
  }

  .order-meta-field:not(.checkbox-field) {
    grid-template-columns: max-content minmax(48px, 1fr);
    width: 100%;
  }
}
