/* ==========================================================================
   Морские караваны / Caravans of the Sea — стили
   Собрано из двух <style>-блоков исходного файла.
   Первый блок был побайтово идентичен началу второго (дубликат) и удалён.
   ========================================================================== */

/* --- 1. База: типографика, таблицы, кнопки, формы, модальные окна --- */
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
      background: #14130fde;
      color: #d0d0d0;
      padding: 12px;
      max-width: 1400px;
      margin: 0 auto;
    }
    h2 { 
      color: #ececec; 
      margin: 15px 0 8px 0;
      font-size: 15px;
      font-weight: 500;
      border-bottom: 1px solid #333333;
      padding-bottom: 6px;
    }
    .stats { 
      display: grid; 
      grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
      gap: 8px;
      margin-bottom: 15px;
    }
    .stat {
      background: #201f1a;
      padding: 8px;
      border-radius: 8px;
      border-left: 2px solid #4a4a4a;
      font-size: 13px;
      text-align: center;
    }
    .stat-label { 
      font-size: 11px; 
      color: #999999; 
      text-transform: uppercase; 
      letter-spacing: 0.3px;
    }
    .stat-value { 
      font-size: 17px; 
      color: #ececec; 
      font-weight: 600; 
      margin-top: 3px; 
    }
    .stat-detail {
      font-size: 12px;
      color: #999999;
      margin-top: 2px;
    }
    
    table {
      width: 100%;
      border-collapse: collapse;
      background: #161616;
      margin-bottom: 15px;
      font-size: 14px;
      border: 1px solid #2a2a2a;
      border-radius: 8px;
      overflow: hidden;
    }
    th {
      background: #201f1a;
      color: #ececec;
      padding: 8px;
      text-align: left;
      font-weight: 600;
      border-bottom: 1px solid #333333;
      font-size: 13px;
      cursor: pointer;
    }
    th:hover { background: #202020; }
    td {
      padding: 7px 8px;
      border-bottom: 1px solid #252525;
      line-height: 1.6;
    }
    tr:last-child td { border-bottom: none; }
    tr:hover { background: #1f1f1f; }
    
    .table-wrapper {
      max-height: 330px;
      overflow-y: auto;
      border-radius: 8px;
      display: block;
    }
    
    .table-wrapper table {
      width: 100%;
      /* separate, а не collapse: при схлопнутых границах прилипшая шапка
         теряет свои рамки — они принадлежат таблице, а не ячейкам. */
      border-collapse: separate;
      border-spacing: 0;
    }
    
    /* Прилипает не thead, а сами ячейки: у thead position:sticky в таблицах
       не работает, и шапка уезжала вместе с содержимым. */
    .table-wrapper thead th {
      position: sticky;
      top: 0;
      background: #201f1a;
      z-index: 10;
    }
    
    input { 
      width: 60px; 
      padding: 4px 6px;
      background: #201f1a;
      color: #d0d0d0;
      border: 1px solid #333333;
      border-radius: 3px;
      font-family: inherit;
      font-size: 13px;
    }
    input:focus {
      outline: none;
      border-color: #666666;
      background: #242424;
    }
    
    button {
      background: #2a2a2a;
      color: #d0d0d0;
      border: 1px solid #444444;
      padding: 6px 12px;
      border-radius: 3px;
      cursor: pointer;
      font-weight: 500;
      transition: 0.15s;
      font-size: 13px;
    }
    button:hover { 
      background: #333333;
      border-color: #555555;
      color: #ececec;
    }
    button:active { 
      background: #404040;
    }
    
    select {
      padding: 6px;
      background: #201f1a;
      color: #d0d0d0;
      border: 1px solid #333333;
      border-radius: 3px;
      font-family: inherit;
      cursor: pointer;
      font-size: 13px;
    }
    
    .section { margin-bottom: 20px; }
    .controls { display: flex; gap: 8px; margin-bottom: 10px; flex-wrap: wrap; align-items: center; }
    .message { 
      margin: 8px 0; 
      padding: 8px;
      border-radius: 3px;
      font-size: 13px;
    }
    .error { 
      background: #2a1a1a;
      color: #ff7d7d;
      border-left: 2px solid #cc3333;
    }
    .success { 
      background: #1a2a1a;
      color: #7dff7d;
      border-left: 2px solid #33cc33;
    }

    .port-info {
      background: #201f1a;
      padding: 8px;
      border-radius: 3px;
      margin-bottom: 10px;
      font-size: 13px;
      border-left: 2px solid #444444;
    }
    .port-info-title {
      font-weight: 600;
      color: #ececec;
      margin-bottom: 2px;
    }
    .port-info-text {
      color: #888888;
    }

    .profit-positive { color: #7dff7d; }
    .profit-negative { color: #ff7d7d; }
    .profit-neutral { color: #999999; }
    
    /* Random Events Modal */
    .modal {
      position: fixed;
      top: 0; left: 0;
      width: 100%; height: 100%;
      background: rgba(0, 0, 0, 0.7);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
      visibility: hidden;
      opacity: 0;
      transition: opacity 0.3s;
    }
    .modal.show {
      visibility: visible;
      opacity: 1;
    }
    .modal-content {
      background: #201f1a;
      border: 2px solid #444444;
      border-radius: 8px;
      max-width: 450px;
      padding: 24px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.6);
    }
    .modal-header {
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid #333333;
    }
    .modal-header h3 {
      margin: 0;
      font-size: 18px;
      color: #ececec;
      font-weight: 600;
    }
    .modal-header.danger h3 { color: #ff6b6b; }
    .modal-header.success h3 { color: #51cf66; }
    .modal-header.warning h3 { color: #ffd43b; }
    .modal-header.info h3 { color: #74c0fc; }
    .modal-body {
      margin-bottom: 20px;
      min-height: 50px;
    }
    .modal-body p {
      margin: 0;
      color: #d0d0d0;
      line-height: 1.6;
    }
    .modal-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }
    .modal-footer button {
      padding: 10px 18px;
      border: 1px solid #444444;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
      font-weight: 500;
      background: #2a2a2a;
      color: #ececec;
      transition: all 0.2s;
    }
    .modal-footer button:hover {
      background: #333333;
      border-color: #555555;
    }
    
    /* Rules modal */
    /* Правила переехали из модального окна в собственную вкладку.
       Колонка ограничена по ширине: длинные строки на широком мониторе
       читать невозможно. */
    .rules-page {
      max-width: 820px;
      padding: 18px 16px 40px;
      color: #d0d0d0;
      font-size: 15px;
      line-height: 1.5;
    }
    .rules-page .rules-title {
      font-size: 21px;
      color: #ececec;
      font-weight: 600;
      margin: 0 0 20px;
    }
    .rules-page h3 {
      color: #74c0fc;
      font-size: 16px;
      font-weight: 600;
      letter-spacing: 0.3px;
      margin: 28px 0 10px;
    }
    .rules-page h4 {
      color: #cbbd8e;
      font-size: 15px;
      font-weight: 600;
      margin: 18px 0 8px;
    }
    .rules-page p { margin: 0 0 10px; }
    .rules-page ul,
    .rules-page ol { margin: 8px 0 12px 22px; padding: 0; }
    .rules-page li { margin-bottom: 6px; }
    .rules-page strong { color: #ececec; font-weight: 600; }
    /* Разделитель между подразделами — вместо ряда дефисов из документа. */
    .rules-page .rules-sep {
      border-top: 1px solid #33322b;
      margin: 22px 0;
    }
    

/* --- 2. Каркас страницы: шапка, сайдбар, вкладки --- */
/* ===== НОВЫЙ LAYOUT ===== */
    body {
      height: 100vh;
      overflow: hidden;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
    }
    
    .main-container {
      display: flex;
      flex-direction: column;
      height: 100vh;
    }
    
    .port-photo-header {
      position: relative;
      width: 100%;
      height: 270px;
      background: #1a1a1a;
      overflow: hidden;
      border-bottom: 1px solid #333333;
    }
    
    .port-photo-header img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      object-position: center;
    }
    
    /* Подпись поверх фото: где мы сейчас или куда идём. */
    .port-photo-caption {
      position: absolute;
      left: 12px;
      bottom: 10px;
      padding: 4px 10px;
      border-radius: 4px;
      background: rgba(0, 0, 0, 0.55);
      color: #e8e8e8;
      font-size: 13px;
      font-weight: 600;
      letter-spacing: 0.3px;
      pointer-events: none;
    }

    /* Фото ещё нет — вместо битой картинки ровный тёмный фон. */
    .port-photo-header.is-empty {
      background: repeating-linear-gradient(
        135deg, #1a1a1a, #1a1a1a 12px, #1f1f1f 12px, #1f1f1f 24px);
    }


    /* Блок аннотаций под вкладками. Раньше цвета стояли инлайном в разметке
       и были яркими (#7dff7d на #1a2a1a). Приглушены. */
    .message-box {
      margin: 0 0 12px 0;
      padding: 8px;
      background: #1c241d;
      color: #a9c7ae;
      border-left: 3px solid #4f7d59;
      border-radius: 4px;
      font-size: 13px;
      line-height: 1.5;
      font-weight: 500;
    }

    /* --- Экран плавания --- */
    .voyage-panel {
      max-height: 255px;          /* та же высота, что у скрытой таблицы порта */
      overflow-y: auto;
      padding: 12px 14px;
      background: #161616;
      border: 1px solid #333333;
      border-radius: 8px;
      font-size: 13px;
      line-height: 1.9;
      color: #c2c2c2;
    }
    .voyage-line--date {
      color: #e0e0e0;
      font-weight: 600;
      margin-bottom: 4px;
    }
    .voyage-line--dim { color: #8f8f8f; }

    /* Подпись под замороженной таблицей цен назначения. */
    .frozen-note {
      margin-top: 6px;
      font-size: 12px;
      color: #8f8f8f;
      font-style: italic;
    }

    /* --- Сводка за партию --- */
    .run-summary { margin-top: 18px; }
    .run-summary h2 { margin-bottom: 10px; }
    .summary-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
      gap: 10px;
    }
    .summary-cell {
      display: flex;
      flex-direction: column;
      gap: 2px;
      padding: 10px 12px;
      background: #201f1a;
      border: 1px solid #333333;
      border-radius: 6px;
    }
    .summary-label {
      font-size: 10px;
      text-transform: uppercase;
      letter-spacing: 0.3px;
      color: #999999;
      font-weight: 600;
    }
    .summary-value {
      font-size: 15px;
      color: #ececec;
      font-weight: 600;
    }
    .summary-dim { font-size: 11px; color: #808080; }
    .summary-empty { color: #808080; font-size: 13px; }
    .summary-none { color: #808080; }

    /* Кривая капитала — отдельным блоком во всю ширину под сеткой. */
    .capital-block {
      margin-top: 12px;
      padding: 12px 14px;
      background: #201f1a;
      border: 1px solid #333333;
      border-radius: 6px;
    }
    .capital-scale {
      display: flex;
      justify-content: space-between;
      gap: 10px;
      margin: 6px 0 8px 0;
      font-size: 11px;
      color: #808080;
    }
    .capital-bars {
      display: flex;
      align-items: flex-end;
      gap: 1px;
      height: 104px;
      overflow-x: auto;
      position: relative;
      z-index: 1;
    }
    /* График = колонка подписей оси Y слева и поле со столбиками справа. */
    .chart { display: flex; gap: 8px; align-items: stretch; }
    .chart-axis {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 104px;
      min-width: 52px;
      text-align: right;
      font-size: 10px;
      line-height: 1;
      color: #808080;
    }
    .chart-plot { position: relative; flex: 1; min-width: 0; }
    /* Горизонтальные линии от делений оси — чтобы высота столбика читалась
       без наведения мышью. */
    .chart-grid {
      position: absolute;
      left: 0; right: 0; top: 0; height: 104px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      pointer-events: none;
    }
    .chart-grid i { display: block; border-top: 1px solid #3a3a3a; }
    /* Нулевая отметка, когда график уходит в минус. */
    .chart-zero {
      position: absolute;
      left: 0; right: 0;
      border-top: 1px dashed #6b6b6b;
      pointer-events: none;
    }
    .capital-bar {
      flex: 1 1 3px;
      min-width: 3px;
      background: #4f7d59;
      border-radius: 1px 1px 0 0;
    }
    /* Месяц без сделок — тон приглушён, значение перенесено с прошлого. */
    .capital-bar.is-gap { background: #33473a; }
    /* Прибыль и маржинальность — свои оттенки, чтобы графики не путались. */
    .capital-bar.is-profit { background: #7d6b4f; }
    .capital-bar.is-profit.is-gap { background: #473f33; }
    .capital-bar.is-margin { background: #4f6a7d; }
    .capital-bar.is-margin.is-gap { background: #333f47; }

    .content-wrapper {
      display: flex;
      flex: 1;
      overflow: hidden;
    }
    
    .left-sidebar {
      width: 200px;
      background: #0a0a0a;
      padding: 12px;
      overflow-y: auto;
      border-right: 1px solid #333333;
      display: flex;
      flex-direction: column;
      gap: 16px;
    }
    
    .sidebar-stats {
      background: #1a1a1a;
      border: 1px solid #333333;
      border-radius: 4px;
      padding: 12px;
    }
    
    .sidebar-stat {
      margin-bottom: 12px;
    }
    
    .sidebar-stat:last-child {
      margin-bottom: 0;
    }
    
    .sidebar-stat-label {
      font-size: 10px;
      color: #999999;
      text-transform: uppercase;
      letter-spacing: 0.3px;
      margin-bottom: 1px;
      font-weight: 600;
    }
    
    .sidebar-stat-value {
      font-size: 15px;
      color: #ececec;
      font-weight: 600;
    }
    
    .sidebar-stat-detail {
      font-size: 10px;
      color: #888888;
      margin-top: 2px;
    }
    
    .sidebar-buttons {
      display: flex;
      flex-direction: column;
      gap: 6px;
      margin-top: 12px;
    }
    
    .sidebar-button {
      width: 100%;
      padding: 8px 12px;
      background: #2a2a2a;
      color: #d0d0d0;
      border: 1px solid #444444;
      border-radius: 3px;
      cursor: pointer;
      font-weight: 500;
      font-size: 12px;
      transition: 0.15s;
    }
    
    .sidebar-button:hover {
      background: #333333;
      border-color: #555555;
      color: #ececec;
    }
    
    .sidebar-button:active {
      background: #404040;
    }

    /* Кнопка «Следующая неделя» — основное действие, поэтому выделена
       зелёной заливкой с прозрачностью 50%. Тон приглушённый: интерфейс
       тёмный, резкий контраст на нём режет глаз. */
    .sidebar-button--next {
      background: rgba(58, 122, 74, 0.5);
      border-color: rgba(88, 150, 104, 0.55);
      color: #cfe3d3;
    }
    .sidebar-button--next:hover {
      background: rgba(70, 140, 88, 0.6);
      border-color: rgba(108, 170, 124, 0.7);
      color: #e2f0e6;
    }
    .sidebar-button--next:active {
      background: rgba(84, 158, 102, 0.7);
    }
    .sidebar-button--next:disabled {
      background: rgba(58, 122, 74, 0.22);
      color: #8fa494;
    }

    /* Кнопка, которая ждёт решения прямо сейчас: «Закончить погрузку» и
       «Отплыть». Подсветка бледная — это подсказка, а не тревога. Гаснет
       сама, как только действие сделано. */
    .sidebar-button--hint {
      background: rgba(150, 130, 60, 0.28);
      border-color: rgba(190, 170, 90, 0.5);
      color: #ece2c2;
    }
    .sidebar-button--hint:hover {
      background: rgba(170, 148, 70, 0.38);
      border-color: rgba(210, 190, 110, 0.65);
      color: #f6efd8;
    }

    /* Служебные действия — сохранить, загрузить, начать заново — стоят
       в один ряд иконками: подписи им не нужны, а вертикали в панели мало. */
    .sidebar-icons {
      display: flex;
      gap: 6px;
    }
    .sidebar-button--icon {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 7px 0;
    }
    .sidebar-button--icon svg {
      width: 17px;
      height: 17px;
      display: block;
    }
    
    .right-content {
      flex: 1;
      overflow-y: auto;
      padding: 12px;
    }
    
    .tabs-container {
      display: flex;
      gap: 0;
      margin: 0 0 12px 0;
      border: 1px solid #444444;
    }
    
    .tab-button {
      padding: 10px 16px;
      background: transparent;
      color: #999999;
      border: none;
      border-right: 1px solid #444444;
      border-bottom: 2px solid transparent;
      cursor: pointer;
      font-weight: 500;
      font-size: 13px;
      transition: 0.2s;
    }
    
    .tab-button:last-child {
      border-right: none;
    }
    
    .tab-button:hover {
      color: #d0d0d0;
    }
    
    .tab-button.active {
      color: #ececec;
      border-bottom-color: #ececec;
    }
    
    .tab-content {
      display: none;
    }
    
    .tab-content.active {
      display: block;
    }


/* --- 3. Высоты таблиц (перенесено из инлайновых style= в разметке) --- */
    .table-wrapper--port { max-height: 255px; }
    .table-wrapper--dest { max-height: 225px; }
    .table-wrapper--history { max-height: 528px; }   /* было 660px, уменьшено на 20% */


/* ==========================================================================
   5. ВКЛАДКА «КАРТА МИРА»: инструменты и заметки штурмана
   ========================================================================== */

    .map-pane { padding: 12px; }

    /* Область просмотра карты: скроллится в обе стороны при увеличении */
    .map-scroll {
      overflow: auto;
      -webkit-overflow-scrolling: touch;
      /* 48vh, а не 60 — иначе панель инструментов под картой оказывается
         ровно на линии сгиба и до неё приходится скроллить */
      max-height: 48vh;
      border: 1px solid #333333;
      border-radius: 6px;
      background: #101010;
    }

    /* Сцена = картинка + холст поверх неё, размеры задаёт JS */
    .map-stage { position: relative; line-height: 0; }
    .map-stage img {
      display: block;
      user-select: none;
      -webkit-user-drag: none;
    }
    .map-stage canvas {
      position: absolute;
      top: 0;
      left: 0;
      pointer-events: none;   /* включается только в режиме рисования */
    }

    .map-toolbar {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 10px;
      flex-wrap: wrap;
    }

    .map-tool {
      display: inline-flex;
      align-items: center;
      gap: 7px;
      padding: 8px 12px;
    }
    .map-tool svg {
      width: 17px;
      height: 17px;
      flex: 0 0 auto;
    }
    .map-tool.active {
      background: #4a2020;
      border-color: #e03131;
      color: #ffb3b3;
    }

    .map-zoom-label {
      margin-left: auto;
      font-size: 12px;
      color: #999999;
      font-variant-numeric: tabular-nums;
    }

    /* --- Заметки штурмана --- */

    .notes-block {
      margin-top: 20px;
      padding-top: 16px;
      border-top: 1px solid #333333;
    }

    .notes-label {
      display: block;
      font-size: 10px;
      color: #999999;
      text-transform: uppercase;
      letter-spacing: 0.3px;
      font-weight: 600;
      margin: 12px 0 4px 0;
    }

    .notes-name {
      width: 100%;      /* перебиваем базовое input { width: 60px } */
      max-width: 480px;
    }

    .notes-text {
      width: 100%;
      height: 200px;
      resize: vertical;
      padding: 10px;
      background: #201f1a;
      color: #d0d0d0;
      border: 1px solid #333333;
      border-radius: 3px;
      font-family: inherit;
      font-size: 13px;
      line-height: 1.6;
    }
    .notes-text:focus {
      outline: none;
      border-color: #666666;
      background: #242424;
    }

    .notes-buttons {
      display: flex;
      gap: 8px;
      margin-top: 10px;
    }

    .notes-message {
      min-height: 18px;
      margin-top: 8px;
      font-size: 12px;
    }
    .notes-message.is-ok   { color: #7dff7d; }
    .notes-message.is-warn { color: #ff9d9d; }

    .notes-table { margin-top: 12px; }
    .notes-table td button { padding: 5px 10px; font-size: 12px; }

    /* Плашка режима отладки. Видна всегда, пока режим включён,
       чтобы случайно не принять отладочную партию за настоящую. */
    .debug-badge {
      position: fixed;
      right: 10px;
      bottom: 10px;
      z-index: 2000;
      padding: 5px 10px;
      border-radius: 4px;
      background: #4a2020;
      border: 1px solid #e03131;
      color: #ffb3b3;
      font-size: 11px;
      font-weight: 700;
      letter-spacing: 1px;
      pointer-events: none;
    }

/* ==========================================================================
   4. МОБИЛЬНАЯ И ПЛАНШЕТНАЯ ВЁРСТКА
   Всё ниже живёт внутри @media — десктоп (шире 900px) не затрагивается.
   ========================================================================== */

/* --- Планшеты и телефоны: до 900px --- */
@media (max-width: 900px) {

  /* Снимаем «оболочку приложения» на 100vh: на телефоне она даёт обрезанный
     контент (адресная строка съедает часть 100vh) и двойную прокрутку.
     Страница начинает скроллиться как обычная. */
  body {
    height: auto;
    overflow: visible;
  }
  .main-container {
    height: auto;
    min-height: 100vh;
  }
  .content-wrapper {
    flex-direction: column;
    overflow: visible;
  }
  .right-content {
    overflow: visible;
    padding: 10px;
  }

  /* Шапка: 300px — это треть экрана телефона */
  .port-photo-header { height: 150px; }

  /* Сайдбар превращается в горизонтальную панель над контентом */
  .left-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #333333;
    overflow: visible;
    gap: 10px;
    padding: 10px;
  }
  .sidebar-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    padding: 10px;
  }
  .sidebar-stat { margin-bottom: 0; }
  /* «Содержание судна» с длинной расшифровкой — на всю ширину */
  .sidebar-stat:nth-child(3) {
    grid-column: 1 / -1;
    min-height: 0 !important;
  }
  .sidebar-buttons {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    margin-top: 0;
  }
  .sidebar-button {
    padding: 12px 8px;   /* палец, а не курсор */
    font-size: 13px;
  }
  /* Ряд иконок — во всю ширину сетки, иначе три кнопки жмутся в одну ячейку. */
  .sidebar-icons {
    grid-column: 1 / -1;
    gap: 8px;
  }
  .sidebar-button--icon svg { width: 19px; height: 19px; }

  /* Таблицы: 8 колонок в 390px не влезут никогда — даём горизонтальную
     прокрутку и фиксируем минимальную ширину, чтобы колонки не схлопывались */
  /* max-height НЕ трогаем — 255px / 225px из раздела 3 подобраны так,
     чтобы было видно ровно 5 строк + шапку. Добавляем только скролл вбок. */
  .table-wrapper,
  .table-wrapper--port,
  .table-wrapper--dest {
    overflow: auto;
    -webkit-overflow-scrolling: touch;
  }
  /* у <table> в базовых стилях стоит overflow:hidden (ради border-radius) —
     он перехватывает sticky у ячеек, на мобильных снимаем */
  .table-wrapper table {
    min-width: 700px;
    overflow: visible;
  }
  .table-wrapper th,
  .table-wrapper td { white-space: nowrap; }

  /* Первая колонка (название товара) примерзает слева,
     чтобы при горизонтальном скролле было видно, где какая строка */
  .table-wrapper th:first-child,
  .table-wrapper td:first-child {
    position: sticky;
    left: 0;
    z-index: 5;
    background: #161616;
  }
  .table-wrapper thead th:first-child {
    z-index: 15;
    background: #201f1a;
  }
  .table-wrapper tr:hover td:first-child { background: #1f1f1f; }

  /* Вкладки: не переносить, а скроллить */
  .tabs-container {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }
  .tab-button {
    white-space: nowrap;
    flex: 0 0 auto;
    padding: 12px 14px;
  }

  .voyage-panel { max-height: 272px; line-height: 1.8; }
  .summary-grid { grid-template-columns: 1fr 1fr; }

  /* Карта: масштабом управляет js/map-notes.js, здесь только панель */
  .map-scroll { max-height: 55vh; }   /* на мобильных страница и так скроллится */
  .map-toolbar { gap: 6px; }
  .map-tool { flex: 1 1 auto; justify-content: center; padding: 10px 8px; }
  .map-tool span { display: none; }        /* на телефоне остаются только иконки */
  .map-tool svg { width: 20px; height: 20px; }
  .notes-table th:nth-child(3),
  .notes-table td:nth-child(3) { display: none; }   /* превью текста прячем */
  /* .notes-table td button специфичнее общего td button выше, поэтому
     тап-таргет в таблице заметок задаём отдельно */
  .notes-table td button { padding: 8px 10px; }

  /* Модалки не должны упираться в края экрана */
  .modal { padding: 16px; }
  .modal-content {
    width: 100%;
    max-height: 85vh;
    overflow-y: auto;
  }
}

/* --- Телефоны: до 560px --- */
@media (max-width: 560px) {

  .port-photo-header { height: 110px; }

  .sidebar-stats  { grid-template-columns: repeat(2, 1fr); }
  .sidebar-buttons { grid-template-columns: repeat(2, 1fr); }
  /* «Правила игры» — последняя, седьмая кнопка, растягиваем на всю ширину */
  .sidebar-button:last-child { grid-column: 1 / -1; }

  /* Ниже 16px iOS Safari при фокусе принудительно зумит страницу */
  input, select { font-size: 16px; }
  input { width: 64px; }

  /* Кнопки «Купить»/«Продать» внутри таблицы: тап пальцем, а не курсором.
     Из-за этого строка верхней таблицы растёт с 44px до 48px, поэтому
     ниже пересчитана и её max-height. */
  td button { padding: 8px 10px; }

  /* Держим те же 5 видимых строк: шапка 32px + 5 строк по 48px = 272px.
     Нижнюю таблицу не трогаем — там нет кнопок, строка так и осталась
     37.4px, и исходных 225px хватает ровно на 5 строк. */
  .table-wrapper--port { max-height: 272px; }

  h2 { font-size: 17px; }
}

/* Вкладка «Авторы игры». Раньше эта подпись жила в самом низу боковой
   панели восьмым кеглем — там её не читали, а место она занимала. */
.credits {
  padding: 18px 4px;
  line-height: 1.7;
  user-select: text;
}
.credits-title {
  font-size: 16px;
  color: #ececec;
  margin-bottom: 10px;
}
.credits-line {
  font-size: 13px;
  color: #b9b9b9;
}
.credits-line a { color: #cbbd8e; }
.credits-line a:hover { color: #e6d9ab; }
.credits-seed {
  margin-top: 16px;
  font-size: 12px;
  color: #8a8a8a;
}

/* Портовая молва — приглушённая строка под списком экспорта.
   Намеренно неяркая: это слух, а не данные. */
/* Портовая молва — приглушённая строка под списком экспорта.
   Намеренно неяркая и курсивом: это слух, а не данные. */
.port-rumor {
  margin-top: 5px;
  font-size: 12px;
  font-style: italic;
  line-height: 1.4;
  color: #8b9a8e;
  font-weight: 400;
}
/* Текст справок о портах и хроники года. */
.lore-body { font-size: 14px; line-height: 1.6; color: #d8d8d8; }
/* Текст диалогов со страховщиком и информатором содержит абзацы,
   разделённые переносами строк. Без pre-line они схлопываются в сплошную
   простыню — реплики сливаются и читать невозможно. */
#insuranceText { white-space: pre-line; line-height: 1.6; }
.lore-body p { margin: 0 0 10px; }
.lore-body p:last-child { margin-bottom: 0; }
/* Прозвище капитана — заголовок над сводкой за партию. */
/* Итог партии одной строкой — то, что копируют и показывают. */
.run-line {
  margin: 0 0 8px;
  padding: 7px 10px;
  background: #16211a;
  border-left: 3px solid #4f7d59;
  border-radius: 4px;
  font-size: 13px;
  color: #cfe0d3;
  user-select: all;
}

/* Имя капитана и судна — то, что игрок задал сам, поэтому крупнее и
   заметнее прозвища, которое игра присвоила за него. */
.run-names {
  margin: 0 0 4px;
  font-size: 17px;
  color: #e8d8a8;
  letter-spacing: 0.3px;
}
.run-name {
  cursor: pointer;
  border-bottom: 1px dotted #6b5f3d;
}
.run-name:hover { color: #f4e6bb; border-bottom-color: #a08f5c; }
.run-names-sep { color: #6b6b6b; margin: 0 6px; }

/* Прозвище присвоено игрой, а не выбрано игроком — оно тише имени. */
.captain-title {
  margin: 0 0 14px;
  font-size: 13px;
  font-weight: 400;
  letter-spacing: 0;
  color: #9aa89d;
}
.captain-title small {
  display: block;
  margin-top: 2px;
  font-size: 11px;
  font-style: italic;
  color: #7d8a80;
}

/* Реплика помощника: в отличие от молвы это не слух, а замечание по делу,
   поэтому цвет теплее и шрифт прямой. */
/* Реплика штурмана и портовая молва живут внутри message-box под строкой
   действия. Оформление у них одинаковое: это не данные, а голоса вокруг. */
.first-mate {
  margin-top: 5px;
  font-size: 12px;
  font-style: italic;
  line-height: 1.4;
  color: #8b9a8e;
  font-weight: 400;
}

/* Чекбоксы фильтрации списка портов — под самим списком, мелко. */
.port-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 7px;
  font-size: 12px;
  color: #9a9a9a;
  white-space: nowrap;
}
.port-filters label {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  cursor: pointer;
  user-select: none;
}
.port-filters input { cursor: pointer; }

/* Отчёт о прибылях и убытках — вид бухгалтерской книги. */
.ledger { font-size: 13px; line-height: 1.7; max-width: 560px; }
.ledger-row { display: flex; justify-content: space-between; gap: 16px; }
.ledger-row span:first-child { color: #b9c7bc; }
.ledger-row span:last-child { font-variant-numeric: tabular-nums; white-space: nowrap; }
.ledger-rule { border-top: 1px solid #3a4a3d; margin: 6px 0; }
.ledger-total { font-weight: 600; color: #e8e8e8; }
.ledger-total span:first-child { color: #e8e8e8; }
.ledger-note { margin-top: 10px; font-size: 12px; font-style: italic; color: #8b9a8e; }
.ledger-pos { color: #7dff7d; }
.ledger-neg { color: #ff7d7d; }

/* Список вех. */
.milestones { font-size: 13px; line-height: 1.7; }
.milestone { color: #cbbd94; }
.milestone-when { color: #8b9a8e; font-size: 12px; }
.milestones-empty { color: #8b9a8e; font-style: italic; }

/* Строка игрока в рейтинге. */
tr.rival-you td { color: #e8d8a8; font-weight: 600; }

/* Кнопка «взять максимум» рядом с полем количества. */
.qty-max {
  width: 22px;
  height: 22px;
  margin-left: 2px;
  padding: 0;
  line-height: 1;
  font-size: 11px;
  vertical-align: middle;
}

/* Кликабельный слух с информатором намеренно не отличается цветом от
   обычной молвы: остаётся только пунктир. Кто читает слухи — заметит,
   кто пролистывает — пройдёт мимо, и это честная плата за невнимание. */
.informant {
  color: inherit;
  cursor: pointer;
  border-bottom: 1px dotted #6f7d72;
}
.informant:hover { color: inherit; }
.informant em { font-style: italic; opacity: 0.75; }

/* ==========================================================================
   ОКНО «КОНТРАКТЫ»
   Две вкладки: подряды и паи. Карточка подряда читается сверху вниз —
   тип, заказчик, его слова, суть дела, деньги, действие.
   ========================================================================== */
#contractsModal .modal-content {
  max-width: 720px;
  width: 92vw;
  max-height: 86vh;
  display: flex;
  flex-direction: column;
}
#contractsModal .modal-body {
  overflow-y: auto;
  min-height: 120px;
}
.c-tabs {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}
.c-tab {
  padding: 6px 14px;
  border: 1px solid #444444;
  border-radius: 8px;
  background: #262521;
  color: #b8b8b8;
  cursor: pointer;
  font-size: 13px;
}
.c-tab:hover { background: #2f2e29; }
.c-tab.active {
  background: #34332c;
  color: #ececec;
  border-color: #6b6752;
}
.c-tier {
  font-size: 13px;
  color: #c8c4b4;
  padding: 10px 12px;
  margin-bottom: 12px;
  background: #1b1a16;
  border: 1px solid #33322b;
  border-radius: 8px;
  line-height: 1.5;
}
.c-card {
  border: 1px solid #3a382f;
  border-radius: 8px;
  padding: 14px;
  margin-bottom: 12px;
  background: #232219;
}
.c-card--active {
  border-color: #6b6752;
  background: #29281e;
}
.c-head {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}
.c-type {
  font-size: 15px;
  color: #ececec;
  font-weight: 600;
}
.c-tag {
  font-size: 11px;
  color: #9a9686;
  border: 1px solid #43413a;
  border-radius: 10px;
  padding: 1px 8px;
}
.c-tag--big { color: #e0c07a; border-color: #6d5c33; }
.c-client { font-size: 13px; color: #a9a493; margin-bottom: 6px; }
.c-motive {
  font-size: 13px;
  color: #c9c3ae;
  font-style: italic;
  margin-bottom: 8px;
  line-height: 1.5;
}
.c-body { font-size: 13px; color: #d0d0d0; line-height: 1.6; }
.c-progress { font-size: 13px; color: #b7b2a1; margin-top: 6px; line-height: 1.6; }
.c-money { font-size: 13px; color: #d8d2bd; margin-top: 8px; }
.c-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 12px;
}
.c-actions button {
  padding: 8px 16px;
  border: 1px solid #444444;
  border-radius: 8px;
  background: #2a2a2a;
  color: #ececec;
  cursor: pointer;
  font-size: 13px;
}
.c-actions button:hover:not(:disabled) { background: #343434; border-color: #555555; }
.c-actions button:disabled { opacity: 0.45; cursor: default; }
.c-actions button.c-danger { color: #e39a9a; }
.c-actions input {
  width: 140px;
  padding: 7px 10px;
  border: 1px solid #444444;
  border-radius: 8px;
  background: #1b1a16;
  color: #ececec;
  font-size: 13px;
}
.c-hint { font-size: 12px; color: #8b8677; margin-top: 8px; }
.c-empty {
  font-size: 13px;
  color: #8b9a8e;
  padding: 14px 2px;
}
.c-note { font-size: 13px; color: #9ad7a0; min-height: 18px; margin-top: 4px; }

@media (max-width: 640px) {
  #contractsModal .modal-content { width: 96vw; padding: 16px; }
  .c-actions { flex-wrap: wrap; }
  .c-actions input { width: 100%; }
}


/* ==========================================================================
   ОТСТУПЫ ВОКРУГ ТАБЛИЦ НА ВКЛАДКАХ
   Боковые поля в 14 пикселей были нужны прежней раскладке, где страница
   прокручивалась целиком и над таблицей требовалась полоса, за которую
   можно зацепиться колесом. Теперь прокручивается только содержимое
   вкладки, и таблицы должны стоять вровень со всем остальным — как на
   вкладке «Торговля».
   ========================================================================== */

/* Долг в кассе. Красная цифра и строка под ней: сколько осталось до
   предела, за которым груз идёт с молотка, а потом разорение. */
.gold-debt { color: #ff7d7d; }
.sidebar-stat-hint {
  margin-top: 3px;
  font-size: 10px;
  line-height: 1.3;
  color: #c08a8a;
}

/* Строка выбора порта назначения должна умещаться в одну на 1024 px.
   Три поля подряд — порт, регион, сортировка — плюс чекбокс, поэтому
   селектам задан предел ширины, а сама строка не переносится. */
.port-filters select { max-width: 170px; }
#destPortSelect { max-width: 210px; }
#portRegion { max-width: 165px; }
#portSortMode { max-width: 145px; }

/* Подпись должна липнуть к своему полю, а не висеть в отдалении:
   у label общий зазор был рассчитан на текст без вложенных элементов. */
.port-filters label { gap: 4px; }

@media (max-width: 900px) {
  /* На узком экране пусть переносится: читаемость важнее одной строки. */
  .port-filters { white-space: normal; }
}


/* ==========================================================================
   ОФОРМЛЕНИЕ ПО МАКЕТУ
   Величины взяты из макета game_newdesign.html и наложены на классы игры.
   Слой идёт последним и перекрывает всё, что выше: править полторы тысячи
   строк точечно — значит каждый раз что-нибудь пропустить.

   Оболочка (прибитые шапка, сайдбар и вкладки, прокрутка только внутри
   вкладки) включается от 901 пикселя. Ниже работает прежняя мобильная
   раскладка — она только перекрашивается.
   ========================================================================== */
:root {
  --bg:        #14150f;
  --panel-hi:  #1f2219;   /* верх сайдбара и полоса вкладок */
  --panel-lo:  #0e0f0e;   /* низ сайдбара */
  --line:      #383930;
  --line-soft: #2f3028;
  --line-tab:  #34362f;

  --ink:       #e3e0d3;
  --ink-dim:   #94948a;
  --ink-faint: #7e7e75;

  --gold:      #c8bd7e;
  --gold-soft: #d5c27d;

  --up:        #7acb8e;
  --down:      #dc7d76;

  --btn:       linear-gradient(#2d2e26, #25261f);
  --btn-line:  #4d4e45;
  --radius:    6px;
}

html, body { margin: 0; width: 100%; min-height: 100%; }

body {
  background: var(--bg);
  color: var(--ink);
  font-family: "Palatino Linotype", "Book Antiqua", Palatino, "Times New Roman", serif;
  font-size: 14px;
}

/* --- Кнопки, поля и списки: общие для всех ширин ----------------------- */
button, .sidebar-button {
  border: 1px solid var(--btn-line);
  border-radius: var(--radius);
  min-height: 35px;
  padding: 7px 10px;
  color: #dedbcf;
  background: var(--btn);
  font-family: inherit;
  font-size: 14px;
  cursor: pointer;
}
button:hover, .sidebar-button:hover { filter: brightness(1.15); background: var(--btn); }
.sidebar-button--next { background: linear-gradient(#355841, #2d4b37); border-color: #4d6954; }
.sidebar-button--hint { background: linear-gradient(#4a452b, #3d3924); border-color: #776b3d; }
.sidebar-icons { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-top: 10px; }
.sidebar-button--icon { min-height: 38px; padding: 7px 0; }
.sidebar-button--icon svg { width: 18px; height: 18px; }

/* Своя стрелка вместо системной: иначе браузер рисует собственную,
   и в тёмном интерфейсе она выглядит чужеродной. */
select, input[type="number"], input[type="text"] {
  height: 34px;
  padding: 7px 10px;
  border: 1px solid var(--btn-line);
  border-radius: var(--radius);
  color: #dedbcf;
  background: linear-gradient(#2c2e26, #25261f);
  font-family: inherit;
  font-size: 13px;
}
select {
  appearance: none;
  -webkit-appearance: none;
  padding-right: 26px;
  background-image:
    linear-gradient(45deg, transparent 50%, #89887e 50%),
    linear-gradient(135deg, #89887e 50%, transparent 50%),
    linear-gradient(#2c2e26, #25261f);
  background-position: calc(100% - 14px) 15px, calc(100% - 9px) 15px, 0 0;
  background-size: 5px 5px, 5px 5px, 100% 100%;
  background-repeat: no-repeat;
}
/* Раскрытому списку фон задаётся отдельно — иначе пункты будут белыми. */
select option, select optgroup { background: #1d1e16; color: #dedbcf; }
select:focus, input:focus { outline: none; border-color: #776b3d; }
input[type="checkbox"] { accent-color: var(--gold); width: 14px; height: 14px; }

/* --- Уведомления -------------------------------------------------------- */
.notices { display: grid; gap: 4px; }
.notice {
  min-height: 24px;
  line-height: 1.55;
  border-left: 2px solid var(--gold-soft);
  padding: 3px 10px;
  border-radius: 4px;
  color: #dad6c8;
  background: linear-gradient(90deg, #27281f, #1d1e18);
  font-family: "Segoe UI", Tahoma, sans-serif;
  font-size: 0.782rem;
  font-style: normal;
  box-shadow: 0 2px 4px rgba(0,0,0,.22);
}
/* Экран плавания — тот же вид, но текст переносится свободно. */
.voyage-panel {
  border-left: 2px solid var(--gold-soft);
  border-top: none; border-right: none; border-bottom: none;
  padding: 6px 10px;
  border-radius: 4px;
  color: #dad6c8;
  background: linear-gradient(90deg, #27281f, #1d1e18);
  font-family: "Segoe UI", Tahoma, sans-serif;
  font-size: 0.782rem;
  line-height: 1.6;
  box-shadow: 0 2px 4px rgba(0,0,0,.22);
  white-space: normal;
}

/* --- Справки о портах ---------------------------------------------------- */
.port-info {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  color: #dad6c8;
  background: #718c9c24;
  font-size: 14px;
  line-height: 17px;
  box-shadow: 0 2px 5px rgba(0,0,0,.26);
}
.port-info-title, .port-info-text { display: block; margin: 1px 0 3px; }
.port-info-title span:first-child, .port-info-text .label { color: #95988e; }
.port-name { color: #ededed; text-transform: uppercase; font-weight: normal; }

/* --- Таблицы ------------------------------------------------------------- */
.table-wrapper { border: none; border-radius: 4px; overflow: auto; }
table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  font-size: 14px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0,0,0,.24);
}
thead th {
  height: 34px;
  text-align: left;
  color: #dad6c7;
  font-weight: bold;
  background: rgb(24 25 20 / 72%);
  border-top: 1px solid #38392f;
  border-bottom: 1px solid #404136;
  padding: 7px 10px;
}
tbody td {
  height: 30px;
  padding: 6px 10px;
  border-bottom: 1px solid var(--line-soft);
  color: #dad7ca;
  background: rgb(24 25 20 / 53%);
  font-variant-numeric: tabular-nums;
}
tbody tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: rgb(32 33 26 / 62%); }
th:not(:first-child), td:not(:first-child) { text-align: right; }
.profit-positive { color: var(--up) !important; }
.profit-negative { color: var(--down) !important; }
.profit-neutral  { color: var(--ink-faint) !important; }
.data-note, .table-note, .ledger-note {
  margin-top: 8px;
  color: var(--ink-faint);
  font-size: 12px;
  font-style: italic;
}

/* --- Показатели в сайдбаре ---------------------------------------------- */
.sidebar-logo { display: block; width: 90px; height: auto; margin: 6px auto 13px; }
.sidebar-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  column-gap: 12px;
  row-gap: 7px;
  margin: 4px;
  padding: 0;
  background: none;
  border: none;
}
.sidebar-stat { margin: 5px 0; }
.sidebar-stat-label { color: var(--ink-dim); font-size: 12px; letter-spacing: .2px; margin-bottom: 2px; text-transform: uppercase; }
.sidebar-stat-value { color: #e3dfd0; font-size: 16px; font-variant-numeric: tabular-nums; }
.sidebar-stat-detail { display: none; }

/* --- Вкладки ------------------------------------------------------------- */
.tabs-container {
  height: 42px;
  display: flex;
  align-items: stretch;
  text-transform: uppercase;
  background: var(--panel-hi);
  border: none;
  border-bottom: 1px solid #3a3b31;
  border-radius: 0;
  margin: 0;
  box-shadow: 0 2px 5px rgba(0,0,0,.28);
}
.tab-button {
  min-width: 86px;
  padding: 11px 18px 9px;
  color: var(--ink-dim);
  font-family: inherit;
  font-size: 14px;
  font-weight: normal;
  background: transparent;
  border: none;
  border-right: 1px solid var(--line-tab);
  border-bottom: 2px solid transparent;
  white-space: nowrap;
}
.tab-button:hover { color: var(--ink); background: transparent; }
.tab-button.active {
  color: #e6e2d4;
  font-weight: bold;
  background: transparent;
  border-bottom: 2px solid var(--gold);
}

/* --- Строка фильтров ------------------------------------------------------ */
.dest-row { display: flex; align-items: center; gap: 7px; flex-wrap: nowrap; }
.dest-title { white-space: nowrap; margin: 0 !important; font-size: 14px; font-weight: normal; }
#destPortSelect { min-width: 147px; width: 168px; flex: none; }
#portRegion { min-width: 97px; width: 118px; }
#portSortMode { min-width: 106px; width: 122px; }
.port-filters { display: flex; align-items: center; gap: 7px; flex-wrap: nowrap; color: var(--ink-dim); font-size: 13px; }
.port-filters label { display: inline-flex; align-items: center; gap: 6px; margin: 0; white-space: nowrap; }

/* --- Правила ------------------------------------------------------------- */
.rules-page { font-family: "Segoe UI", Tahoma, sans-serif; }
.rules-page .rules-title,
.rules-page h3,
.rules-page h4 { font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif; }
.rules-page h3 { color: var(--gold); }
.rules-page h4 { color: #cbbd8e; }
.rules-page .rules-sep { border-top: 1px solid var(--line); }
.credits { font-family: "Segoe UI", Tahoma, sans-serif; }
.credits-title { font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif; }

/* --- Полосы прокрутки ----------------------------------------------------- */
* { scrollbar-width: thin; scrollbar-color: #3f4034 #1b1c16; }
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-track { background: #1b1c16; }
::-webkit-scrollbar-thumb { background: #3f4034; border: 2px solid #1b1c16; border-radius: 6px; }
::-webkit-scrollbar-thumb:hover { background: #4e4f41; }
::-webkit-scrollbar-corner { background: #1b1c16; }

/* ==========================================================================
   ОБОЛОЧКА — только для широких экранов
   Шапка, сайдбар и вкладки прибиты к окну, прокручивается одно лишь
   содержимое вкладки. Ниже 901 пикселя работает прежняя раскладка.
   ========================================================================== */
@media (min-width: 901px) {
  body { overflow: hidden; }

  .main-container {
    width: 100vw;
    height: 100vh;
    min-width: 760px;
    min-height: 500px;
    position: relative;
    background:
      radial-gradient(ellipse at 72% 20%, rgba(91,91,65,.10), transparent 34%),
      linear-gradient(180deg, #2c2d24 0%, #1d1e17 20%, #181912 100%);
    box-shadow: inset 0 1px 0 rgba(255,255,255,.04);
  }

  .port-photo-header {
    position: absolute;
    left: 0; top: 0;
    width: 100%;
    height: 272px;
    border: none;
  }
  .port-photo-header img { width: 100%; height: 100%; object-fit: cover; object-position: center; }

  /* Название порта — в правом верхнем углу снимка. */
  .port-photo-caption {
    position: absolute;
    right: 15px;
    left: auto;
    top: 235px;
    bottom: auto;
    font-size: 17px;
    padding: 4px 10px;
    border: none;
    border-radius: 4px;
    background: rgba(0,0,0,.4);
    color: #ededed;
    font-family: inherit;
  }

  .content-wrapper { display: block; }

  .left-sidebar {
    position: absolute;
    left: 0; top: 275px; bottom: 0;
    width: 211px;
    padding: 11px 8px;
    border-right: 1px solid var(--line);
    background: linear-gradient(to bottom, #1f2219 0%, #1d201b 50%, #0e0f0e 100%);
    box-shadow: 2px 0 5px rgba(0,0,0,.28), 0 1px 2px rgba(255,255,255,.025);
    overflow-y: auto;
  }
  .sidebar-buttons { display: grid; gap: 10px; margin-top: 30px; }

  .right-content {
    position: absolute;
    left: 211px; top: 275px; right: 0; bottom: 0;
    display: flex;
    flex-direction: column;
    min-width: 0;
    padding: 0;
    /* Градиент живёт на контейнере, а не на прокручиваемом блоке: иначе
       он уезжал бы вместе с текстом. */
    background: linear-gradient(to bottom, #30342e 0%, #292c28 50%, #1c1e1c 100%);
  }
  .tabs-container { flex: none; }

  /* Прокручивается только содержимое вкладки. */
  .tab-content { padding: 20px; }
  .tab-content.active {
    flex: 1 1 auto;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
  }

  /* Внутренние блоки вкладок: один зазор, без наслоений отступов. */
  .tab-content > *, .tab-content .section > * { margin: 0 0 10px 0; }
  .tab-content .section { margin: 0 0 10px 0; }
  .tab-content > *:last-child, .tab-content .section > *:last-child { margin-bottom: 0; }
  .tab-content h2 { margin: 0 0 8px 0; padding: 0; border: none; font-size: 15px; color: #ddd5c0; }

  .filters, .dest-row { margin-top: 20px; }
  .table-wrapper { max-height: none; }
}

@media (max-width: 900px) {
  /* Прежняя раскладка остаётся, меняются только цвета. */
  .left-sidebar {
    background: linear-gradient(to bottom, #1f2219 0%, #0e0f0e 100%);
    border-bottom: 1px solid var(--line);
  }
  .sidebar-logo { width: 76px; }
  .sidebar-stats { grid-template-columns: repeat(3, 1fr); }
  .tabs-container { height: auto; }
}

/* ==========================================================================
   ПРАВКИ ПО ЗАМЕЧАНИЯМ
   ========================================================================== */
@media (min-width: 901px) {
  .left-sidebar { width: 220px; padding: 0; }
  .right-content { left: 220px; }
  .sidebar-buttons { display: grid; gap: 10px; margin: 5px; }
  .sidebar-icons { margin: 5px; }
  .sidebar-stats { margin: 10px 5px; }
  .tab-content .section { margin: 20px 0 10px 0; }
}

/* Начертание подписей в панели: в макете обычное, не полужирное. */
.sidebar-stat-label { font-weight: normal; letter-spacing: .2px; font-size: 12px; color: #94948a; }
.sidebar-stat-value { font-weight: normal; }

/* Уведомления: плотнее по вертикали. */
.notice { padding: 1px 10px; }

/* Справка о порте — обычным начертанием. */
.port-info, .port-info-title, .port-info-text { font-weight: normal; }
.port-info-title span:first-child { font-weight: normal; }

/* --- Таблицы -------------------------------------------------------------
   В макете шапка темнее строк: 72% чёрного против 53%. Фон обёртки должен
   просвечивать, иначе прозрачность не работает и шапка кажется светлее. */
.table-wrapper {
  background: transparent;
  border: none;
  border-radius: 4px;
  overflow: auto;
  max-height: 212px;
}
.table-wrapper table { border-radius: 4px; overflow: hidden; }
.table-wrapper--port, .table-wrapper--dest { max-height: 212px; }

thead th {
  background: rgb(24 25 20 / 72%) !important;
  border-top: 1px solid #38392f;
  border-bottom: 1px solid #404136;
  height: 34px;
  padding: 7px 10px;
}
tbody td {
  background: rgb(24 25 20 / 53%);
  border-bottom: 1px solid #2f3028;
  height: 30px;
  padding: 6px 10px;
}
tbody tr:last-child td { border-bottom: none; }

/* Высота строк в верхней таблице равна нижней: поля ввода и кнопки внутри
   ячеек ужимаются, иначе строка растёт под них. */
.table-wrapper td input[type="number"] {
  height: 24px;
  padding: 2px 6px;
  min-height: 0;
  font-size: 13px;
}
.table-wrapper td button {
  min-height: 24px;
  height: 24px;
  padding: 0 10px;
  font-size: 13px;
  line-height: 22px;
}

/* Вкладки: верхний регистр задаётся самой кнопке — на элементе button
   наследование от контейнера в части браузеров не срабатывает. */
.tab-button { text-transform: uppercase; }

/* ==========================================================================
   ТАБЛИЦЫ — ПЕРЕСБОРКА ПО ШАБЛОНУ
   Прошлая попытка не сработала: в базовых стилях правила заданы через
   «.table-wrapper table thead th», это выше по весу, чем просто «thead th»,
   и мои значения проигрывали. Здесь тот же вес и те же селекторы.
   ========================================================================== */
.table-wrapper {
  background: transparent;
  border: none;
  border-radius: 4px;
  overflow: auto;
}
.table-wrapper table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  table-layout: auto;
  font-size: 14px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0,0,0,.24);
}
.table-wrapper table thead th {
  height: 34px;
  text-align: left;
  color: #dad6c7;
  font-weight: bold;
  background: rgb(24 25 20 / 72%);
  border-top: 1px solid #38392f;
  border-bottom: 1px solid #404136;
  padding: 7px 10px;
  position: sticky;
  top: 0;
  z-index: 10;
}
.table-wrapper table tbody td {
  height: 30px;
  padding: 6px 10px;
  border-bottom: 1px solid #2f3028;
  color: #dad7ca;
  background: rgb(24 25 20 / 53%);
  font-variant-numeric: tabular-nums;
}
.table-wrapper table tbody tr:last-child td { border-bottom: none; }
.table-wrapper table tbody tr:hover td { background: rgb(32 33 26 / 62%); }
.table-wrapper table th:not(:first-child),
.table-wrapper table td:not(:first-child) { text-align: right; }

/* Поля и кнопки внутри ячеек не должны растягивать строку. */
/* Ширина была прибита в разметке атрибутом style, из-за чего ни одна
   строка таблицы стилей до неё не доставала. Атрибут убран, величина
   перенесена сюда — на большом экране поле осталось прежним. */
.table-wrapper table td input[type="number"] {
  width: 50px;
  height: 24px;
  min-height: 0;
  padding: 2px 6px;
  font-size: 13px;
  vertical-align: middle;
}
.table-wrapper table td button {
  min-height: 24px;
  height: 24px;
  padding: 0 10px;
  font-size: 13px;
  line-height: 1;
  vertical-align: middle;
}
/* Стрелки «подставить максимум» — строго по центру квадратной кнопки. */
.table-wrapper table td button.qty-max {
  width: 24px;
  height: 24px;
  min-height: 24px;
  padding: 0;
  font-size: 11px;
  line-height: 1;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* --- Сайдбар: логотип, зазоры, заливка --------------------------------- */
.sidebar-logo { margin: 15px auto 0; }

@media (min-width: 901px) {
  .left-sidebar {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 0;
    width: 220px;
    background:
      linear-gradient(to bottom, #1f2219 0%, #1d201b 50%, #0e0f0e 100%) !important;
  }
  .sidebar-stats { margin: 10px; }
  .sidebar-buttons { margin: 10px; gap: 10px; }
  .sidebar-icons { margin: 0 10px 10px; }
}

/* --- Строка выбора порта: аккуратные зазоры ---------------------------- */
.dest-row { gap: 6px; }
.port-filters { gap: 6px; }
.port-filters label { gap: 5px; }

/* ==========================================================================
   ПРАВКИ ПО ЗАМЕЧАНИЯМ, ВТОРАЯ ПАЧКА
   ========================================================================== */
.sidebar-logo { width: 85px; }

@media (min-width: 901px) {
  .left-sidebar { width: 210px; }
  .right-content { left: 210px; }

  .sidebar-stats { margin: 10px 10px 10px 15px; column-gap: 5px; }
  .sidebar-icons { margin-left: 0; margin-right: 0; column-gap: 10px; }

  /* Градиент содержимого — на контейнере, чтобы не уезжал при прокрутке. */
  .right-content {
    background: linear-gradient(to bottom, #31362a 0%, #292c28 50%, #1c1e1c 100%);
  }
}

.sidebar-button { font-size: 14.5px; }
.sidebar-button--icon { min-height: 35px; }

/* Верхняя и нижняя таблицы живут по своим правилам. */
.table-wrapper--port { max-height: 224px; }
.table-wrapper--dest { max-height: 212px; }

.notice { padding: 2px 10px; }
#message { background: #2b2b25; }

.port-info { background: #5250435c; }

/* --- Строка выбора порта ------------------------------------------------ */
.port-filters { gap: 15px; margin-left: 20px; }
#destPortSelect { min-width: 220px; width: 220px; }
#portRegion { min-width: 130px; width: 130px; }
#portSortMode { min-width: 150px; width: 150px; }

/* --- Счётчик количества -------------------------------------------------
   Системные стрелки браузер рисует своей серой парой, и в тёмной таблице
   они выглядят чужеродной вставкой. Убираем их и ставим свои: две
   половинки кнопки справа от поля, светлеющие при наведении. */
.table-wrapper table td input[type="number"] {
  -moz-appearance: textfield;
  appearance: textfield;
}
.table-wrapper table td input[type="number"]::-webkit-outer-spin-button,
.table-wrapper table td input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
  width: 14px;
  height: 24px;
  cursor: pointer;
  opacity: 1;
  background:
    linear-gradient(45deg, transparent 46%, #8f8e83 46%, #8f8e83 54%, transparent 54%) no-repeat 3px 6px / 8px 4px,
    linear-gradient(-45deg, transparent 46%, #8f8e83 46%, #8f8e83 54%, transparent 54%) no-repeat 3px 14px / 8px 4px,
    linear-gradient(#2c2e26, #25261f);
  border-left: 1px solid #4d4e45;
  border-radius: 0 5px 5px 0;
}
.table-wrapper table td input[type="number"]:hover::-webkit-inner-spin-button { filter: brightness(1.3); }
/* Firefox своих стрелок не рисует — оставляем поле шире на их ширину. */
@supports (-moz-appearance: none) {
  .table-wrapper table td input[type="number"] { padding-right: 6px; }
}

/* --- Полосы прокрутки в раскрытых списках ------------------------------- */
select { scrollbar-width: thin; scrollbar-color: #3f4034 #1b1c16; }
select::-webkit-scrollbar { width: 8px; }
select::-webkit-scrollbar-track { background: #1b1c16; }
select::-webkit-scrollbar-thumb { background: #3f4034; border: 2px solid #1b1c16; border-radius: 6px; }

/* ==========================================================================
   ПРАВКИ ПО ЗАМЕЧАНИЯМ, ТРЕТЬЯ ПАЧКА
   ========================================================================== */
@media (min-width: 901px) {
  .left-sidebar { border-right: none; }
  .right-content { left: 210px; }
  .sidebar-stats { column-gap: 8px; }
}
.sidebar-button { padding: 7px; }

/* Вкладки без скруглений. */
.tabs-container { border-radius: 0; }
.tab-button { border-radius: 0; }

/* Справка о порте. */
.port-info {
  background: #201f1a;
  border: 1px solid #333333;
  border-radius: 6px;
}

/* Отступ текста от флажка: пробел в разметке схлопывается. */
.port-filters label input[type="checkbox"] { margin-right: 6px; }

/* --- Счётчик количества: плюс сверху, минус снизу ----------------------- */
.table-wrapper table td input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
  width: 15px;
  height: 24px;
  cursor: pointer;
  opacity: 1;
  background:
    /* плюс */
    linear-gradient(#9a998d, #9a998d) no-repeat 5px 5px / 5px 1px,
    linear-gradient(#9a998d, #9a998d) no-repeat 7px 3px / 1px 5px,
    /* едва заметный разделитель */
    linear-gradient(#3f4038, #3f4038) no-repeat 3px 11.5px / 9px 1px,
    /* минус */
    linear-gradient(#9a998d, #9a998d) no-repeat 5px 17px / 5px 1px,
    linear-gradient(#2c2e26, #25261f);
  border-left: 1px solid #4d4e45;
  border-radius: 0 5px 5px 0;
}

/* --- Раскрытые списки: подсветка строки под общий стиль ------------------ */
select option:hover,
select option:focus,
select option:checked {
  background: #2f3128 linear-gradient(#2f3128, #2f3128);
  color: #ece7d8;
}

/* --- Заметки на карте ---------------------------------------------------- */
.notes-actions { white-space: nowrap; text-align: right; }
.note-icon {
  min-height: 24px;
  height: 24px;
  width: 26px;
  padding: 0;
  margin-left: 4px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: #b9b6a8;
}
.note-icon:hover { color: #ece7d8; }

/* --- Правила: основной текст мельче, заголовки прежние ------------------- */
.rules-page { font-size: 14px; }
.rules-page p, .rules-page li { font-size: 14px; }

/* ==========================================================================
   ПРАВКИ ПО ЗАМЕЧАНИЯМ, ЧЕТВЁРТАЯ ПАЧКА
   ========================================================================== */
@media (min-width: 901px) {
  .sidebar-icons { margin-left: 10px; margin-right: 10px; }
}

/* Все три полосы уведомлений одного фона. */
.notice, #message, .notice.first-mate, .notice.port-rumor, .notice.port-lore { background: #2b2b25; }

/* --- Раскрытые списки -----------------------------------------------------
   Подсветку строки в родном списке страница красить не может: Edge и Chrome
   рисуют её средствами системы. Единственный рычаг — сказать браузеру, что
   интерфейс тёмный: тогда и список, и подсветка в нём становятся тёмными. */
select { color-scheme: dark; }

/* --- Заголовки модальных окон --------------------------------------------
   Ядовитая зелень и алый остались от ранних версий: приводим к общему
   золотистому, оттенком показывая нрав события. */
.modal-header h3 { color: #e6e2d4; }
.modal-header.success h3 { color: #c8bd7e; }
.modal-header.warning h3 { color: #d5c27d; }
.modal-header.danger h3 { color: #dc7d76; }
.success { border-left-color: #c8bd7e !important; }

/* Подписи перед именами в сводке партии. */
.run-names-label { color: #94948a; margin-right: 4px; font-weight: normal; }
.captain-title .run-names-label { display: inline-block; font-size: 13px; }

/* ==========================================================================
   ТАБЛИЦЫ — ОКОНЧАТЕЛЬНО
   Собрано в одном месте: прежние правки спорили друг с другом. Ключевое —
   полупрозрачный фон строк работает только если под ним светлая подложка.
   Раньше просвечивал тёмный низ градиента, и строки выглядели чёрными,
   поэтому подложку задаём самой обёртке.
   ========================================================================== */
.table-wrapper,
.table-wrapper--port,
.table-wrapper--dest,
.table-wrapper--history {
  background: #30342e;
  border: none;
  border-radius: 4px;
  overflow: auto;
  box-shadow: 0 2px 5px rgba(0,0,0,.24);
  /* Убирает щель под таблицей при прокрутке до конца: таблица — блочный
     элемент, а строка текста в обёртке оставляла зазор по базовой линии. */
  line-height: 0;
}
.table-wrapper table {
  width: 100%;
  margin: 0;
  border-collapse: separate;
  border-spacing: 0;
  border-radius: 0;
  box-shadow: none;
  line-height: 1.45;
}
.table-wrapper table thead th {
  background: rgb(24 25 20 / 82%);
  color: #dad6c7;
  font-weight: bold;
  height: 34px;
  padding: 7px 10px;
  border-top: 1px solid #38392f;
  border-bottom: 1px solid #404136;
  position: sticky;
  top: 0;
  z-index: 10;
}
.table-wrapper table tbody td,
.table-wrapper table tbody tr td,
.table-wrapper table tbody tr:nth-child(odd) td,
.table-wrapper table tbody tr:nth-child(even) td {
  background: rgb(24 25 20 / 53%);
  color: #dad7ca;
  height: 30px;
  padding: 6px 10px;
  border-bottom: 1px solid #2f3028;
}
.table-wrapper table tbody tr:hover td { background: rgb(32 33 26 / 62%); }
.table-wrapper table tbody tr:last-child td { border-bottom: none; }
.table-wrapper table thead th:first-child { border-top-left-radius: 4px; }
.table-wrapper table thead th:last-child { border-top-right-radius: 4px; }
.table-wrapper table tbody tr:last-child td:first-child { border-bottom-left-radius: 4px; }
.table-wrapper table tbody tr:last-child td:last-child { border-bottom-right-radius: 4px; }
.table-wrapper table th:not(:first-child),
.table-wrapper table td:not(:first-child) { text-align: right; }

.table-wrapper--port { max-height: 224px; }
.table-wrapper--dest { max-height: 212px; }
.table-wrapper--history { max-height: 440px; }
#reports .table-wrapper { max-height: 212px; }

/* --- Контракты: текст крупнее, строки плотнее --------------------------- */
.c-client { font-size: 14px; }
.c-motive { font-size: 14px; line-height: 1.1; }
.c-body   { font-size: 14px; line-height: 1.25; }
.c-money  { font-size: 14px; }

/* Таблицы во всех вкладках стоят вровень с прочими блоками. */
#history .table-wrapper,
#reports .table-wrapper,
#history table,
#reports table { margin-left: 0; margin-right: 0; }

/* ==========================================================================
   ОТЧЁТЫ: КЕГЛЬ НА ПУНКТ КРУПНЕЕ
   Вкладка почти целиком состоит из цифр и подписей, и на тринадцати
   пикселях они читались хуже остальных экранов.
   ========================================================================== */
#reports h2,
#reports h3,
#history h2,
#history h3 { font-size: 16px; }

.ledger { font-size: 14px; }
.ledger-note { font-size: 13px; }

/* «Купленные наводки» и «Вехи плавания» делят один класс. */
.milestones { font-size: 14px; }
.milestone-when { font-size: 13px; }
.milestones-empty { font-size: 14px; }

/* Сводка за партию не должна прилипать к журналу маршрутов. */
.run-summary { margin-top: 24px; }
.run-summary h2 { margin-top: 0; margin-bottom: 10px; }

/* ==========================================================================
   ИТОГ СДЕЛКИ И СОСЕДНИЕ ПОЛОСЫ
   Уведомления, слухи, слово штурмана и панель плавания — на пункт крупнее:
   это единственный текст на вкладке, который читают целиком.
   ========================================================================== */
.notice, .voyage-panel { font-size: 0.845rem; }

.deal-what { color: #dad6c8; }
.deal-net { margin-top: 1px; }
.deal-net b { font-weight: bold; }
.deal-calc {
  margin-top: 1px;
  color: #96938a;
  font-size: 0.79rem;
}

/* Сводка за партию отстоит от журнала маршрутов. */
.run-summary { margin-top: 30px; }

/* Строки экрана плавания — на той же подложке, что уведомления. */
.voyage-line { background: #2b2b25; }

/* Карта мира: кегль на пункт крупнее. */
#map h2, #map h3 { font-size: 16px; }
.notes-label { font-size: 13px; }
.notes-name, #noteName { font-size: 14px; }
.notes-text, #noteText { font-size: 14px; }
.notes-table { font-size: 14px; }

/* --- Заметки: поля имени и текста в одном стиле -------------------------- */
.notes-name,
.notes-text {
  border: 1px solid #4d4e45;
  border-radius: 6px;
  background: linear-gradient(#2c2e26, #25261f);
  color: #dedbcf;
  font-family: inherit;
  font-size: 14px;
}
/* Золотистая рамка при работе с полем — одинаково для имени и текста. */
.notes-name:focus,
.notes-text:focus {
  outline: none;
  border-color: #c8bd7e;
  background: linear-gradient(#31332a, #292a22);
  color: #ece7d8;
}

/* Прозвище капитана: подпись под ним на пункт крупнее. */
.captain-title small { font-size: 12px; }

/* --- Карта: курсоры и подсветка инструментов ---------------------------- */
#mapScroll { cursor: grab; }
#mapScroll.is-grabbing { cursor: grabbing; }
#mapScroll.tool-draw { cursor: crosshair; }
#mapScroll.tool-erase { cursor: cell; }

/* Инструменты подсвечиваются по смыслу: рисование синим — под цвет
   карандаша, стирание приглушённым красным. Прежний ярко-алый у обоих
   выбивался из палитры и не различал их между собой. */
#mapPencil.active {
  background: linear-gradient(#26356b, #1f2b56) !important;
  border-color: #3d55a8 !important;
  color: #cdd6f2 !important;
}
#mapEraser.active {
  background: linear-gradient(#4a2f2b, #3c2724) !important;
  border-color: #7d4d46 !important;
  color: #e9c7c0 !important;
}
.map-tool:hover { filter: brightness(1.12); }

/* Метка «в заметке есть разметка карты». */
.note-has-map { color: #6f86d6; margin-left: 4px; font-size: 12px; }

/* Строка с датой в экране плавания стоит вплотную к следующей. */
.voyage-line--date { margin-bottom: 0; }

/* ==========================================================================
   ОТБОР В ЖУРНАЛЕ МАРШРУТОВ
   Фильтр рождается из клика по ячейке, поэтому в интерфейсе нет ни одного
   постоянного элемента: полоса появляется, только когда отбор включён.
   ========================================================================== */
.journal-pick {
  cursor: pointer;
  text-decoration: underline dotted #4a4a3e;
  text-underline-offset: 3px;
}
.journal-pick:hover { color: #efe4c0; text-decoration-color: #c8bd7e; }

.journal-filter {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  background: #2b2b25;
  border-left: 2px solid #d5c27d;
  border-radius: 4px;
  padding: 5px 10px;
  margin-bottom: 8px;
  font-family: "Segoe UI", Tahoma, sans-serif;
  font-size: 13px;
  box-shadow: 0 2px 4px rgba(0,0,0,.22);
}
.journal-chip {
  background: #3a3520;
  border: 1px solid #6b5e34;
  border-radius: 10px;
  padding: 1px 9px;
  color: #efe4c0;
  cursor: pointer;
  white-space: nowrap;
}
.journal-chip:hover { background: #453f26; }
.journal-chip-x { color: #a2966c; margin-left: 2px; }
.journal-stat { color: #96938a; }
.journal-reset {
  margin-left: auto;
  color: #8f8e83;
  text-decoration: underline dotted;
  cursor: pointer;
  white-space: nowrap;
}
.journal-reset:hover { color: #dad6c8; }

/* Полоса отбора прилипает к верху вкладки: клик по строке в середине
   длинного журнала прежде уводил её за верхний край экрана. */
.journal-filter {
  position: sticky;
  top: 0;
  z-index: 15;
}
/* Подсказка про отбор стоит над таблицей — там её увидят до того,
   как она понадобится, а не после. */
.data-note--hint { margin: 0 0 8px 0; }

/* Экран плавания: одна плашка вместо плашки в плашке.
   Строки внутри имеют фон #2b2b25, а сама панель оставалась темнее —
   её поля просвечивали по краям тонкой рамкой. Уравниваем: фон держит
   панель, строки внутри прозрачны. */
.voyage-panel { background: #2b2b25; }
.voyage-line { background: transparent; }

/* Разделитель вне вкладки правил: раньше линия была объявлена только
   селектором «.rules-page .rules-sep», поэтому в журнале маршрутов
   пустой блок стоял без границы и без отступов. */
.rules-sep {
  border-top: 1px solid #383930;
  margin: 22px 0;
  height: 0;
}

/* Строка игрока в рейтинге капитанов — золотом, чтобы находилась
   взглядом среди десяти соперников. */
tr.rival-you td {
  color: #d5c27d !important;
  font-weight: bold;
  background: rgb(40 36 22 / 45%) !important;
}
tr.rival-you:hover td { background: rgb(48 43 26 / 55%) !important; }

/* ==========================================================================
   АДАПТАЦИЯ ПОД МОБИЛЬНЫЕ УСТРОЙСТВА
   Слой идёт последним и перебивает «оформление по макету»: тот слой писался
   без оглядки на ширину и задавал полям жёсткие пиксели (список портов —
   220px, фильтры в одну нераз­рывную строку), из-за чего на телефоне
   страница уезжала вбок, а кнопки в таблицах были 24 пикселя высотой.

   Что здесь решается, по порядку важности:
   1. Переполнение по горизонтали. Строка выбора порта переносится,
      селекты тянутся на всю ширину, жёсткие min-width снимаются.
   2. Палец вместо курсора. Кнопки, флажки и поля — не ниже 44 пикселей,
      кнопки внутри таблиц — 34.
   3. Автозум iOS. Safari увеличивает страницу при фокусе на поле с кеглем
      меньше 16px и обратно уже не возвращает. Поэтому все поля ввода и
      списки на узких экранах — ровно 16px.
   4. Полоса вкладок прилипает к верху. Панель показателей на телефоне
      занимает почти экран, и без этого каждое переключение вкладки стоило
      бы прокрутки наверх. Активная вкладка подводится в видимую часть
      полосы скриптом (js/ui.js).
   5. Таблицы остаются таблицами: горизонтальная прокрутка внутри обёртки,
      первая колонка примерзает слева.

   Раскладка не меняется — она остаётся той же, что была: шапка, панель
   показателей, вкладки, содержимое. Меняются размеры и поведение.
   ========================================================================== */

/* --- Планшеты и телефоны: до 900px ------------------------------------- */
@media (max-width: 900px) {

  /* Страница во всю ширину: 12 пикселей полей по бокам на телефоне —
     это 7% экрана, отданных пустоте. Внутренние отступы остаются у
     содержимого вкладок и у панели показателей. */
  body { padding: 0; max-width: none; }
  html { -webkit-text-size-adjust: 100%; }

  /* --- Шапка со снимком порта ------------------------------------------ */
  .port-photo-header { height: 160px; }
  .port-photo-caption { left: 10px; bottom: 8px; font-size: 13px; }

  /* --- Панель показателей ---------------------------------------------- */
  .left-sidebar { gap: 8px; padding: 8px 10px 12px; }
  .sidebar-logo { width: 52px; margin: 4px auto 0; }

  .sidebar-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    column-gap: 10px;
    row-gap: 8px;
    margin: 0;
    padding: 0;
    background: none;
    border: none;
  }
  .sidebar-stat { margin: 0; }
  /* Третьим показателем стоит «Трюм» — короткий. Прежнее правило растягивало
     его на всю строку: оно писалось, когда там было «Содержание судна». */
  .sidebar-stat:nth-child(3) { grid-column: auto; }
  .sidebar-stat-label { font-size: 11px; margin-bottom: 1px; }
  .sidebar-stat-value { font-size: 17px; }

  .sidebar-buttons {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
    margin: 4px 0 0;
  }
  .sidebar-button {
    min-height: 44px;
    padding: 8px 10px;
    font-size: 14px;
    line-height: 1.25;
  }
  /* «Апгрейд судна за N» — самая длинная подпись, ей отдельная строка. */
  .sidebar-buttons .sidebar-button:last-child { grid-column: 1 / -1; }

  .sidebar-icons {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    margin: 0;
  }
  /* Правило «.sidebar-button:last-child — во всю ширину» писалось для ряда
     кнопок и цепляло заодно последнюю иконку: она растягивалась отдельной
     строкой, а две соседние оставались половинками. */
  .sidebar-icons .sidebar-button:last-child { grid-column: auto; }
  .sidebar-button--icon { min-height: 44px; padding: 0; }
  .sidebar-button--icon svg { width: 20px; height: 20px; }

  /* --- Вкладки: одна прилипшая строка --------------------------------- */
  /* Полосе вкладок надо дать доехать до верха экрана, иначе прилипание
     бессмысленно: на короткой вкладке страница кончается раньше, чем
     вкладки упрутся в край. Вытягиваем область содержимого на экран. */
  .right-content {
    /* Сверху поля нет намеренно: полоса вкладок должна стоять первой строкой
       в своей области, иначе при прокрутке она застывает не у края экрана,
       а на высоте этого отступа. Воздух над содержимым даёт сама вкладка. */
    padding: 0 10px 12px;
    overflow: visible;
    min-height: 100vh;
  }
  @supports (height: 100dvh) {
    .right-content { min-height: 100dvh; }
  }

  .tabs-container {
    position: sticky;
    top: 0;
    z-index: 30;
    height: 44px;
    flex-wrap: nowrap;
    overflow-x: auto;
    overflow-y: hidden;
    background: var(--panel-hi);
    /* Полоса прокрутки под вкладками съедала бы их высоту — убираем её,
       но саму прокрутку оставляем: пальцем и скриптом. */
    scrollbar-width: none;
    -ms-overflow-style: none;
    /* Полоса идёт от края до края — боковые поля области содержимого
       она перекрывает отрицательными полями. */
    margin: 0 -10px;
    padding: 0 10px;
    box-shadow: 0 2px 6px rgba(0,0,0,.4);
  }
  .tabs-container::-webkit-scrollbar { height: 0; width: 0; }
  .tab-button {
    flex: 0 0 auto;
    min-width: 0;
    padding: 0 13px;
    font-size: 12.5px;
    letter-spacing: .2px;
    white-space: nowrap;
  }

  /* Полоса отбора в журнале встаёт под вкладками, а не под ними же. */
  .journal-filter { top: 44px; }

  /* --- Содержимое вкладок --------------------------------------------- */
  .tab-content { padding: 12px 0 0; }
  .tab-content > * { margin-bottom: 12px; }
  .tab-content > *:last-child { margin-bottom: 0; }
  .section { margin-bottom: 14px; }

  /* --- Строка выбора порта: главный источник уезжания вбок ------------- */
  .dest-row {
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;
    gap: 8px;
    margin-top: 0;
  }
  #destPortSelect,
  #portRegion,
  #portSortMode {
    flex: 1 1 100%;
    width: 100%;
    min-width: 0;
    max-width: none;
  }
  .port-filters {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    width: 100%;
    margin: 0;
    white-space: normal;
  }
  .port-filters select { max-width: none; }
  .port-filters label {
    flex: 1 1 calc(50% - 4px);
    min-width: 0;
    gap: 6px;
    white-space: normal;
  }
  /* Флажок «где есть спрос» — отдельной строкой: подпись длинная. */
  .port-filters label:last-child { flex: 1 1 100%; }
  .port-filters label input[type="checkbox"] { width: 18px; height: 18px; flex: 0 0 auto; }

  /* --- Поля ввода и списки -------------------------------------------- */
  /* 16px — порог, ниже которого Safari на iOS увеличивает страницу при
     фокусе и обратно не отъезжает. Высота поднята под этот кегль. */
  select,
  input,
  input[type="text"],
  input[type="number"],
  textarea {
    font-size: 16px;
    min-height: 44px;
    height: auto;
    padding: 10px 12px;
  }
  select { padding-right: 30px; background-position: calc(100% - 15px) 20px, calc(100% - 10px) 20px, 0 0; }
  input[type="checkbox"] { min-height: 0; height: 18px; width: 18px; padding: 0; }
  textarea { min-height: 0; }

  /* --- Таблицы -------------------------------------------------------- */
  .table-wrapper,
  .table-wrapper--port,
  .table-wrapper--dest,
  .table-wrapper--history {
    overflow: auto;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior-x: contain;
  }
  .table-wrapper table { min-width: 680px; overflow: visible; }
  .table-wrapper table th,
  .table-wrapper table td { white-space: nowrap; }

  /* Первая колонка примерзает слева: иначе при прокрутке вбок непонятно,
     к какому товару относится цифра. Фон здесь сплошной — полупрозрачный
     пропускал бы сквозь себя проезжающие колонки. */
  .table-wrapper table th:first-child,
  .table-wrapper table td:first-child {
    position: sticky;
    left: 0;
    z-index: 5;
    background: #232620;
  }
  .table-wrapper table thead th:first-child { z-index: 15; background: #1c1e19; }
  .table-wrapper table tbody tr:hover td:first-child { background: #262822; }

  /* Кнопки и поля в ячейках — под палец. Строка от этого растёт,
     поэтому ниже пересчитаны и высоты обёрток. */
  .table-wrapper table td button {
    min-height: 34px;
    height: 34px;
    padding: 0 12px;
    font-size: 14px;
  }
  .table-wrapper table td button.qty-max {
    width: 34px;
    height: 34px;
    min-height: 34px;
    font-size: 13px;
  }
  .table-wrapper table td input[type="number"] {
    width: 68px;
    height: 34px;
    min-height: 34px;
    padding: 4px 8px;
    font-size: 16px;
  }
  /* Нарисованные стрелки счётчика рассчитаны на поле высотой 24px и на
     мышь. На телефоне они бесполезны и ломают вид — убираем, количество
     набирается цифровой клавиатурой или кнопкой со стрелкой. */
  .table-wrapper table td input[type="number"]::-webkit-inner-spin-button,
  .table-wrapper table td input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    appearance: none;
    display: none;
    width: 0;
  }

  /* Видно те же пять строк, что и на большом экране: шапка 34 + 5×46. */
  .table-wrapper--port { max-height: 264px; }
  .table-wrapper--dest { max-height: 212px; }
  .table-wrapper--history { max-height: 340px; }
  #reports .table-wrapper { max-height: 240px; }

  /* Шапка «Отчёт о прибылях и убытках» с выбором года — в две строки. */
  #reports h2 { flex-wrap: wrap; }
  #ledgerYear { min-height: 40px; }

  /* --- Экран плавания и сводки ---------------------------------------- */
  .voyage-panel { max-height: 260px; line-height: 1.7; }
  .summary-grid { grid-template-columns: repeat(2, 1fr); gap: 8px; }
  .run-summary { margin-top: 22px; }

  /* --- Правила и авторы ----------------------------------------------- */
  .rules-page { padding: 2px 0 28px; max-width: none; line-height: 1.6; }
  .rules-page .rules-title { font-size: 19px; margin-bottom: 14px; }
  .rules-page h3 { margin: 22px 0 8px; }
  .rules-page ul,
  .rules-page ol { margin-left: 18px; }
  .credits { padding: 2px 0 20px; }

  /* --- Карта мира ------------------------------------------------------ */
  .map-pane { padding: 0; }
  .map-scroll {
    max-height: 52vh;
    touch-action: pan-x pan-y;
  }
  .map-toolbar { gap: 6px; margin-top: 8px; }
  .map-tool {
    flex: 1 1 0;
    min-width: 0;
    min-height: 44px;
    justify-content: center;
    padding: 0;
  }
  .map-tool span { display: none; }
  .map-tool svg { width: 20px; height: 20px; }
  /* Масштаб — отдельной строкой по центру: в ряду он отжимал инструменты. */
  .map-zoom-label { flex: 1 1 100%; margin: 2px 0 0; text-align: center; }

  /* Кегль этим двум полям задан через #noteName / #noteText — селектор по
     идентификатору, его не перебить ни классом, ни типом поля. */
  .notes-name, #noteName { max-width: none; font-size: 16px; }
  .notes-text, #noteText {
    height: 150px;
    min-height: 150px;
    padding: 10px 12px;
    font-size: 16px;
  }
  .notes-buttons { gap: 8px; }
  .notes-buttons button { flex: 1 1 auto; min-height: 44px; }
  .notes-table th:nth-child(3),
  .notes-table td:nth-child(3) { display: none; }
  .notes-table td button,
  .notes-table .note-icon {
    min-height: 34px;
    height: 34px;
    width: 36px;
  }

  /* --- Модальные окна -------------------------------------------------- */
  .modal { padding: 12px; align-items: flex-end; }
  .modal-content {
    width: 100%;
    max-width: none;
    max-height: 88vh;
    overflow-y: auto;
    padding: 18px 16px;
  }
  .modal-footer { flex-wrap: wrap; gap: 8px; }
  .modal-footer button { flex: 1 1 auto; min-height: 44px; }

  #contractsModal .modal-content { width: 100%; max-width: none; padding: 18px 14px; }
  .c-tabs { flex-wrap: wrap; }
  .c-tab { min-height: 40px; padding: 8px 14px; }
  .c-head { flex-wrap: wrap; gap: 6px; }
  /* Ярлык «крупный подряд» стоит в строке с деньгами и на узком экране
     разрывался посередине: половина пилюли уезжала на следующую строку
     вместе с куском рамки. */
  .c-tag { display: inline-block; white-space: nowrap; }
  .c-actions { flex-wrap: wrap; gap: 8px; }
  .c-actions button { flex: 1 1 auto; min-height: 44px; }
  .c-actions input { flex: 1 1 100%; width: 100%; }
}

/* --- Телефоны: до 560px ------------------------------------------------ */
@media (max-width: 560px) {

  .port-photo-header { height: 128px; }

  /* Три колонки держатся и на 360 пикселях: самая длинная подпись,
     «ГРУЗООБОРОТ», занимает 82 пикселя при колонке в 107. Две колонки —
     только на совсем узких экранах. */
  .sidebar-stat-value { font-size: 17px; }

  /* Подпись встаёт над полем: при подписи сбоку каждое поле получало
     свою ширину — «Регион» шире, «Сортировка» уже, — и строка выглядела
     рваной. Сверху подпись короткая, поле во всю ширину. */
  .port-filters label {
    flex: 1 1 100%;
    flex-direction: column;
    align-items: stretch;
    gap: 3px;
  }
  .port-filters label:last-child {
    flex-direction: row;
    align-items: center;
    gap: 8px;
    min-height: 32px;
  }

  .table-wrapper table { min-width: 620px; }
  .table-wrapper--history { max-height: 300px; }

  .summary-grid { grid-template-columns: 1fr; }
  .map-scroll { max-height: 46vh; }

  h2 { font-size: 16px; }
  .tab-button { padding: 0 11px; font-size: 12px; }
}

/* --- Очень узкие экраны: до 380px -------------------------------------- */
@media (max-width: 380px) {
  .sidebar-button { font-size: 13.5px; padding: 8px 6px; }
  .port-photo-header { height: 112px; }
}

/* --- Совсем узкие экраны: до 340px ------------------------------------- */
@media (max-width: 340px) {
  .sidebar-stats { grid-template-columns: repeat(2, 1fr); }
  .tab-button { padding: 0 9px; }
}

/* --- Телефон, положенный набок ----------------------------------------
   Высоты в 400 пикселей не хватает ни на снимок порта, ни на пять строк
   таблицы. Снимок сжимается, таблицы отдают часть высоты. */
@media (max-width: 900px) and (max-height: 480px) {
  .port-photo-header { height: 86px; }
  .sidebar-logo { display: none; }
  /* Экран широкий, но низкий: показатели выстраиваются в одну строку,
     кнопки — в три колонки. Панель сжимается вдвое, и до вкладок уже
     не надо прокручивать пол-экрана. */
  .sidebar-stats { grid-template-columns: repeat(6, 1fr); }
  .sidebar-buttons { grid-template-columns: repeat(3, 1fr); }
  .sidebar-stat-value { font-size: 16px; }
  .table-wrapper--port { max-height: 180px; }
  .table-wrapper--dest,
  .table-wrapper--history { max-height: 180px; }
  .map-scroll { max-height: 60vh; }
  .modal-content { max-height: 92vh; }
}

/* Историческая справка о порте — строка следом за сообщением о приходе.
   Прежде всплывала отдельным окном при первом заходе. Оформление общее с
   прочими полосами: своего цвета ей не нужно. Отбивка сверху такая же, как
   у портовой молвы, — справка отдельная мысль, а не продолжение отчёта
   о расходах. */
.notice.port-lore {
  background: #2b2b25;
  margin-top: 5px;
}

/* Подпись говорящего в полосах аннотаций — «Штурман:», «Боцман:», «Слухи:».
   Приглушена на тон: кто сказал, важно меньше, чем что сказано, а в ряду
   из трёх строк подряд одинаково яркие подписи перетягивают взгляд на
   себя. Оттенок взят из палитры макета — тот же, что у подписей
   показателей в сайдбаре. */
.notice .voice { color: var(--ink-dim); }

/* ==========================================================================
   ПАНЕЛЬ ДЕЙСТВИЙ ВНИЗУ ЭКРАНА — только для узких экранов
   На телефоне кнопки занимали почти двести пикселей над вкладками, и до
   самой игры приходилось прокручивать полэкрана. Оба ряда — обычные кнопки
   и иконки — уезжают вниз одной полосой высотой в одну кнопку. Что не
   поместилось, достаётся прокруткой вбок; иконки сохранения стоят в конце,
   потому что нужны реже всех.
   ========================================================================== */

/* На широких экранах обёртки как будто нет: её дети остаются прямыми
   элементами боковой панели, и раскладка не меняется ни на пиксель. */
.sidebar-actions { display: contents; }

@media (max-width: 900px) {
  /* 1. Логотип на телефоне — украшение ценой в полсотни пикселей. */
  .sidebar-logo { display: none; }

  /* 2–3. Обе группы кнопок — одной прокручиваемой полосой внизу. */
  .sidebar-actions {
    display: flex;
    position: fixed;
    left: 0; right: 0; bottom: 0;
    z-index: 40;
    align-items: stretch;
    gap: 8px;
    padding: 7px 10px;
    /* Нижняя безопасная зона айфонов: без неё полоса лезет под домашний
       индикатор, и нижний край кнопок не нажимается. */
    padding-bottom: calc(7px + env(safe-area-inset-bottom, 0px));
    background: var(--panel-hi);
    border-top: 1px solid var(--line);
    box-shadow: 0 -2px 8px rgba(0,0,0,.45);
    overflow-x: auto;
    overflow-y: hidden;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior-x: contain;
    /* Полоса прокрутки съела бы высоту кнопки — убираем, прокрутка пальцем
       остаётся. */
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
  .sidebar-actions::-webkit-scrollbar { height: 0; width: 0; }

  /* Оба ряда внутри полосы — просто горизонтальные группы, без сеток. */
  .sidebar-actions .sidebar-buttons,
  .sidebar-actions .sidebar-icons {
    display: flex;
    /* В базовых стилях у ряда кнопок стоит flex-direction: column — он
       достался от вертикальной панели и здесь выстраивал кнопки столбиком
       на двести пикселей вверх. */
    flex-direction: row;
    flex: 0 0 auto;
    align-items: center;
    gap: 8px;
    margin: 0;
    padding: 0;
  }
  /* Иконки идут последними: при прокрутке вбок их достают в самом конце. */
  .sidebar-actions .sidebar-icons { order: 2; }
  .sidebar-actions .sidebar-buttons { order: 1; }

  .sidebar-actions .sidebar-button {
    flex: 0 0 auto;
    /* Прежние правила раскладывали кнопки сеткой на всю ширину — здесь
       ширину задаёт подпись, а строка не переносится. */
    grid-column: auto;
    width: auto;
    min-height: 44px;
    height: 44px;
    padding: 0 15px;
    font-size: 14px;
    line-height: 1;
    white-space: nowrap;
  }
  .sidebar-actions .sidebar-button--icon { width: 50px; padding: 0; }

  /* Боковая панель осталась без кнопок — только показатели. */
  .left-sidebar { padding: 6px 10px 10px; gap: 6px; }

  /* Содержимое не должно уезжать под полосу действий. */
  .right-content {
    padding-bottom: calc(70px + env(safe-area-inset-bottom, 0px));
  }
  /* Модальные окна тоже приподняты над полосой. */
  .modal { padding-bottom: calc(70px + env(safe-area-inset-bottom, 0px)); }
}

/* Телефон набок: высоты мало, полоса действий ужимается. */
@media (max-width: 900px) and (max-height: 480px) {
  .sidebar-actions { padding: 5px 10px; padding-bottom: calc(5px + env(safe-area-inset-bottom, 0px)); }
  .sidebar-actions .sidebar-button { min-height: 38px; height: 38px; font-size: 13.5px; }
  .sidebar-actions .sidebar-button--icon { width: 46px; }
  .right-content { padding-bottom: calc(60px + env(safe-area-inset-bottom, 0px)); }
}
