/* Дурак — стили. Воссоздают визуал React/Tailwind-версии на чистом CSS. */
*, *::before, *::after { box-sizing: border-box; }

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  height: 100dvh; /* fallback для мобильных браузеров с динамической адресной строкой */
  font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
  background: #0f172a;
  overflow: hidden;

  /* === Блокировка выделения и контекстного меню === */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;          /* отключает long-tap меню на iOS */
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;           /* убирает зум по double-tap */

  /* Требование Яндекс.Игр 1.10.2: не должно быть системной прокрутки
     страницы и «потянуть-обновить». overscroll-behavior обрывает цепочку
     скролла до документа (иначе свайп вниз по странице перезагружает её). */
  overscroll-behavior: none;
}

/* iOS Safari не знает overscroll-behavior, там помогает только position:
   fixed на body — без него страница всё равно уезжает и тянет refresh. */
@supports not (overscroll-behavior: none) {
  body { position: fixed; inset: 0; width: 100%; }
}

/* Разрешаем выделение только там, где это действительно нужно */
.name-input,
.name-modal-input,
.join-code-input,
.name-select,
.rules-body,
.modal-body,
.rating-scroll {
    -webkit-user-select: text;
    user-select: text;
    -webkit-touch-callout: default;
}

/* Интерактивные зоны — без задержки 300ms и без зума */
.btn, .card, .char-card {
  touch-action: manipulation;
}

/* Фон локации во весь экран: отдельный фиксированный слой в body, ПОД
   трансформируемой доской (#app). Кадр вписан по центру во всю высоту
   (auto 100%: верх/низ арта никогда не режутся), а на сверхшироких экранах
   к его краям примыкают боковые полосы back_left/back_right, закрывающие
   пустоту по бокам (полосы 320:1080 масштабируются вместе с кадром). */
.game-bg {
  position: fixed;
  inset: 0;
  z-index: 0;
  pointer-events: none;
  /* Основной арт подставляется из JS инлайн-списком слоёв (бока + кадр),
   поэтому здесь оставляем безопасный дефолт (полосы без кадра). Правый край
   левой полосы стоит в x = 50vw - (8/9)*100dvh (левый край 16:9-кадра),
   левый край правой — в x = 50vw + (8/9)*100dvh. */
  background-image:
    url('../img/screen/back_left.webp'),
    url('../img/screen/back_right.webp'),
    none;
  background-repeat: no-repeat, no-repeat, no-repeat;
  background-position:
    right calc(50vw + (8 / 9) * 100dvh) center,
    left  calc(50vw + (8 / 9) * 100dvh) center,
    center;
  background-size: auto 100%, auto 100%, auto 100%;
}

/* Контейнер приложения. Доска свёрстана в фиксированной «дизайнерской» ширине
   920px; JS масштабирует её через transform: translate()+scale(), вписывая в
   экран по ширине и высоте, чтобы игра занимала весь экран (origin top-left). */
#app {
  position: fixed;
  top: 0;
  left: 0;
  width: 920px;
  transform-origin: top left;
}

/* ---------- доска ---------- */
/* Без скругления и тени: стол — прозрачная область поверх полноэкранного
   фона локации, никакой рамки-«окна» на экране быть не должно. */
.board {
  position: relative;
  width: 920px;
  margin: 0 auto;
  border-radius: 0;
  overflow: hidden;
  box-shadow: none;
}

/* ---------- кнопки ---------- */
.btn {
  border: none;
  cursor: pointer;
  border-radius: 6px;
  font-family: inherit;
  font-size: 14px;
  padding: 7px 14px;
  color: #fff;
  transition: background 0.15s, transform 0.1s;
}
.btn:active { transform: translateY(1px); }
.btn-new { background: #059669; font-weight: 600; }
.btn-new:hover { background: #10b981; }
.btn-char { background: #374151; }
.btn-char:hover { background: #4b5563; }
.btn-rating { background: #b45309; font-weight: 600; }
.btn-rating:hover { background: #d97706; }
.btn-fs { background: #1d4ed8; font-weight: 700; font-size: 18px; line-height: 1; padding: 6px 12px; }
.btn-fs:hover { background: #2563eb; }

/* Кнопки хода — на плашках из img/new/button.
   Цвет по смыслу: «Бито» зелёная (ход завершён удачно), «Беру» красная
   (забираешь карты), «Хватит» синяя (нейтральное действие). */
.act-bito, .act-beru, .act-hvatit {
    /* Пропорции плашки 257x66. Размер — в координатах доски (920px):
       её целиком масштабирует JS через transform: scale(), поэтому vw/vh
       здесь дали бы двойное масштабирование. */
    width: 118px;
    aspect-ratio: 257 / 66;
    /* Только не в %: процентный padding считается от ШИРИНЫ и вместе с
       aspect-ratio раздувал border-box (132px превращались в ~200px).
       Текст центрируем флексом, а не отступом. */
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    border-radius: 0;
    background: center / 100% 100% no-repeat;
    color: #fff;
    font-weight: 900;
    font-size: 15px;
    text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
    transition: transform 0.1s ease, filter 0.12s ease;
}
.act-bito { background-image: url('../img/new/button/ui_button_game_beaten.webp'); }
.act-beru { background-image: url('../img/new/button/ui_button_game_took.webp'); }
.act-hvatit { background-image: url('../img/new/button/ui_button_game_pass.webp'); }
.act-bito:hover, .act-beru:hover, .act-hvatit:hover {
    filter: brightness(1.1);
    transform: translateY(-1px);
}
.act-bito:active, .act-beru:active, .act-hvatit:active {
    transform: translateY(1px) scale(0.98);
    filter: brightness(0.95);
}

/* ---------- стол ---------- */
.table {
  position: relative;
  /* Сверху отступ больше: там висят пузырь реплики и эмодзи соперника,
     а у .table-tavern overflow:hidden — без запаса их срезает край стола. */
  padding: 64px 16px 16px;
  background: radial-gradient(circle at 50% 40%, #15803d, #14532d);
}

.bot-row {
  position: relative;      /* якорь для пузыря реплики без аватара */
  display: flex;
  /* Колонка, а не строка: окно соперника стоит НАД его картами.
     В строке оно вставало бы слева от веера. */
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  margin-top: -14px;
  margin-bottom: 10px;
  min-height: 96px;
}
/* Реплика соперника без аватара — по центру, между шапкой и картами:
   нижний край сразу над верхним краем веера соперника. Селектор
   специфичнее .bot-speech, иначе базовое правило перебивает bottom. */
.bot-row .bot-speech-row {
  bottom: calc(100% + 4px);
}
.bot-avatar {
  position: relative;         /* якорь для пузыря реплики */
  width: 64px;
  height: 64px;
  border-radius: 50%;
  flex-shrink: 0;
  border: 2px solid rgba(255, 255, 255, 0.5);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
  background: rgba(0, 0, 0, 0.2);
}
/* Картинку скругляем на ней самой, т.к. у аватара overflow виден (пузырь) */
.bot-avatar img { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; }

/* Пузырь с репликой бота над аватаркой */
.bot-speech {
  position: absolute;
  bottom: calc(100% + 12px);
  left: 50%;
  transform: translateX(-50%);
  white-space: normal;
  text-align: center;
  max-width: 240px;
  padding: 8px 14px;
  border-radius: 14px;
  background: #fff;
  color: #1e293b;
  font-size: 15px;
  font-weight: 700;
  line-height: 1.2;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.45);
  z-index: 40;
  animation: botSpeechPop 0.22s ease-out;
}
/* Хвостик пузыря — вниз, к аватарке */
.bot-speech::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 8px solid transparent;
  border-top-color: #fff;
}
@keyframes botSpeechPop {
  0%   { transform: translateX(-50%) scale(0.7); opacity: 0; }
  100% { transform: translateX(-50%) scale(1);   opacity: 1; }
}

/* ---------- локация-таверна (единый стол для всех персонажей) ---------- */
.table-tavern {
  background: none; /* фон задаётся инлайн через back_tavern.webp */
  overflow: hidden;
}
/* Место соперника/игрока: окно-портрет + (для игрока) плашка с именем */
.tavern-seat {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}
/* Окно выбранного персонажа игрока — слева внизу над картой стола.
   Место для p_-арта (со своей лентой и бочками) или круглый аватар;
   отдельные плашка name_table и бочонок tavern_tr_1 убраны — они
   теперь нарисованы в артах и фоне локации. */
.tavern-seat-me {
  position: absolute;
  left: 20px;
  bottom: 6px;
  z-index: 5;
  pointer-events: none;
  display: block; /* переопределяем flex — используем абсолютные слои */
  width: 132px;
  height: 156px; /* место под круг + вынос плашки/бочонка */
}
/* Окно игрока без p_-арта: круглый аватар без рамки windown.webp —
   весь декор таверны теперь нарисован в фоне и в объединённых p_*.webp. */
.tavern-window {
  position: relative;
  width: 132px;
  height: 132px;
  flex-shrink: 0;
}
/* Плашка с именем (место без p_-арта): плашки name_table.webp больше нет,
   имя — просто текст под аватаркой. */
.tavern-name {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #f4ecd6;
  font-size: 13px;
  font-weight: 800;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.65);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* --- Слои окна игрока слева внизу --- */
/* Круг-окно с аватаркой — базовый слой, приподнят */
.tavern-seat-me .tavern-window {
  position: absolute;
  left: -20px;
  top: -80px;
  z-index: 1;
  /* Десктопные размеры зафиксированы: мобильный @media не должен их менять */
  width: 132px;
  height: 132px;
}
/* Имя под круглым аватаром (место без p_-арта). Окно-аватар в кресле:
   left -20, top -80, высота 132 → низ круга на y≈52; имя ставим под ним. */
.tavern-seat-me .tavern-name {
  position: absolute;
  left: 50%;
  top: 60px;
  transform: translateX(-50%);
  margin: 0;
  z-index: 5;
  width: max-content;
  max-width: 132px;
  padding: 0;
  background: none;
  font-size: 12px;
  line-height: 1.15;
}
/* ---------- место игрока одной картинкой (img/characters/p_*.webp) ----------
   В арте уже нарисованы персонаж, зелёная лента под имя и бочки, поэтому
   рамка windown, плашка name_table и слой бочек ::after здесь не нужны.
   Арты вытянутые (394x659 против прежних 394x381), и высота у них чуть
   разная — от 648 до 691px. Размер задаём ТОЛЬКО по ширине, высоту считает
   aspect-ratio по «типовой» пропорции: так картинка нигде не сплющивается,
   а расхождение в ±3% высоты съедает object-fit: contain. */
.tavern-seat-me.tavern-seat-art {
  /* Единая точка правки масштаба блока. Высота — из пропорции арта
     (394:659 ≈ 1.673), иначе кресло ниже картинки и та вылезает за
     нижний край стола, где её срезает overflow: hidden. */
  width: 240px;
  height: calc(240px * 659 / 394);
  /* Арт нарисован «стоящим» на столе и занимает весь свой холст (пустых
     полей по краям нет). Кресло лежит в #app (вне стола, у нижнего края
     доски), поэтому bottom: 0 — бочки стоят на краю стола, а не ниже. */
  left: 0px;
  bottom: 0;
}
.tavern-seat-me .tavern-window-art {
  position: absolute;
  background: none;
  /* Класс bot-avatar даёт овал (border-radius:50%, белую кайму и тень) —
     он был виден вокруг прямоугольного арта. Прямоугольник без рамок. */
  border-radius: 0;
  border: none;
  box-shadow: none;
  /* Ширину берём от кресла, высоту — из пропорции арта (394:659).
     Единая точка правки масштаба блока — width у .tavern-seat-art. */
  left: 0;
  width: 100%;
  height: auto;
  aspect-ratio: 394 / 659;
  /* Арт «стоит» на нижнем крае кресла: прижимаем его низом, чтобы бочки
     ложились на край стола независимо от того, какой из семи артов выбран
     (их высота отличается на десятки px). Ниже нуля не опускаем — у стола
     overflow: hidden, и низ картинки обрезался бы. */
  top: auto;
  bottom: 0;
}
.tavern-seat-me .tavern-window-art img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  /* contain, а не fill: пропорции арта сохраняются при любой высоте бокса */
  object-fit: contain;
  object-position: bottom center;
  border-radius: 0;
}
/* Имя игрока на нарисованной ленте. Замерено по всем семи артам: плоская
   часть ленты (без хвостов) занимает x 24–79%, центр по горизонтали ≈51%,
   середина надписи по вертикали ≈53.5%. Значения общие для всех артов,
   поэтому отдельных правил на персонажа не нужно. */
.tavern-seat-me .tavern-window-art .tavern-name {
  position: absolute;
  left: 45%;
  top: 52%;
  transform: translate(-50%, -50%);
  /* Ширина плоской части ленты ≈52%; берём чуть меньше, чтобы длинные имена
     («Капитан Барахта») не наезжали на загнутые хвосты по краям. */
  width: 50%;
  min-width: 0;
  max-width: none;
  height: auto;
  padding: 0;
  background: none;
  display: flex;
  align-items: center;
  justify-content: center;
  /* Имя игрока — до 20 символов (NAME_MAX_LEN), а лента узкая. Многоточие
     здесь недопустимо: «Капитан Барахта» превращалось в «Капитан Ба…».
     Поэтому длинные имена ужимает по ширине JS (fitSeatName в ui/render.js),
     меняя --seat-name-scale; базовый кегль держим крупным. */
  font-size: 18px;
  line-height: 1.15;
  color: #f7f0dc;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;   /* перекрываем ellipsis из базового .tavern-name */
}
/* Сжатие длинного имени под ширину ленты. transform, а не font-size:
   масштаб не «прыгает» по целым пикселям кегля и не задевает раскладку.
   flex-shrink: 0 обязателен — иначе flex-контейнер ужмёт span по ширине
   ленты ещё до замера, и текст обрежется вместо масштабирования. */
.tavern-seat-me .tavern-window-art .tavern-name > span {
  display: inline-block;
  flex-shrink: 0;
  transform: scale(var(--seat-name-scale, 1));
  transform-origin: center center;
}
/* ---------- ряд соперников (мультиплеер на 3-4) ---------- */
.opponents-row {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  /* Места стоят плотно, как на макете; запас справа от карт оставлен
     под кружок со счётчиком (он вынесен за край веера). */
  gap: 34px;
  margin-top: -14px;
  margin-bottom: 10px;
  min-height: 110px;
  flex-wrap: nowrap;
}
.opponent-seat {
  position: relative;   /* якорь для пузыря эмодзи этого соперника */
  display: flex;
  flex-direction: column;
  align-items: center;
  /* Без зазора: карты должны выходить прямо из-под ленты окна */
  gap: 0;
  padding: 4px 8px;
  border-radius: 12px;
  transition: background 0.15s, box-shadow 0.15s;
}
.opponent-seat .bot-avatar { width: 48px; height: 48px; }
/* Окно соперника в ряду мест — мельче, чем в игре с ботом: мест до трёх,
   и они должны поместиться в ряд. Пропорция та же (арт не растягиваем). */
.opponent-seat .opp-window { width: 132px; }
/* Окно уже (132 против 168), поэтому имя на ленте — мельче, иначе
   длинные ники не помещаются в одну строку и обрезаются многоточием. */
.opponent-seat .opp-window-name { font-size: 9px; }
/* Карты заходят на нижний край окна: на макете веер начинается прямо
   из-под ленты с именем, а не отступает от неё. */
.opponent-seat .hand-row {
  transform: scale(0.88);
  transform-origin: top center;
  margin-top: -14px;
  margin-bottom: -12px;
}
/* Подсветка активных ролей */
/* Счётчик в ряду мест: справа от веера, по центру его высоты, синий —
   как на макете (красный бейдж остаётся для игры с ботом). */
.opponent-seat .opp-count-badge {
  right: -22px;
  bottom: auto;
  top: 50%;
  transform: translateY(-50%);
}
.opponent-seat.seat-attacker { background: rgba(220, 38, 38, 0.22); box-shadow: 0 0 0 2px rgba(220,38,38,0.5); }
.opponent-seat.seat-defender { background: rgba(37, 99, 235, 0.22); box-shadow: 0 0 0 2px rgba(37,99,235,0.5); }
.opponent-seat.seat-out { opacity: 0.4; filter: grayscale(0.7); }

/* Обратный отсчёт хода: показывается только на последних 30 секундах и
   только у того, чей сейчас ход. Абсолютный бейдж не сдвигает аватар,
   карты и подписи; у .opponent-seat и .tavern-window уже есть якорь. */
.turn-timer {
  position: absolute;
  top: -8px;
  right: -8px;
  z-index: 80;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 46px;
  height: 24px;
  padding: 0 8px;
  border-radius: 12px;
  background: rgba(15, 23, 42, 0.92);
  border: 1px solid rgba(251, 191, 36, 0.85);
  color: #fde68a;
  font-size: 13px;
  font-weight: 800;
  line-height: 1;
  white-space: nowrap;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.45);
  pointer-events: none;
}
.turn-timer-hot {
  border-color: rgba(248, 113, 113, 0.95);
  color: #fecaca;
  box-shadow: 0 0 10px rgba(248, 113, 113, 0.55);
}
.opponent-label {
  font-size: 12px;
  font-weight: 700;
  color: #e2e8f0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
  white-space: nowrap;
}
.opponent-seat.seat-attacker .opponent-label { color: #fecaca; }
.opponent-seat.seat-defender .opponent-label { color: #bfdbfe; }
/* Козырный бейдж на колоде, когда лица карты нет (мультиплеер) */
.deck-trump-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 40px;
  font-weight: 800;
  background: #fff;
  border-radius: 6px;
}

.hand-row {
  display: flex;
  justify-content: center;
  gap: 4px;
  flex-wrap: wrap;
}
/* min-height ≈ высота карты (H=120) + запас на подъём при ховере/волне */
/* min-height ≈ высота карты в руке (HAND_H=144) + запас на подъём */
.player-hand { margin-top: 4px; min-height: 154px; }

/* ---------- рука «веером» ----------
   Карты наезжают друг на друга и повёрнуты по дуге. Величины поворота,
   сдвига и подъёма считает layoutFan() в assets/ui/render.js и кладёт
   в переменные --fan-rot / --fan-x / --fan-y на каждой карте.
   Здесь они лишь собираются в один transform. */
.hand-row.fan {
  flex-wrap: nowrap;   /* веер не переносится: перенос ломает дугу */
  gap: 0;
  /* Карты уезжают за границы контейнера — не даём им обрезаться */
  overflow: visible;
}
.hand-row.fan .card {
  --fan-rot: 0deg;
  --fan-y: 0px;
  /* Подъём при подсветке живёт отдельной переменной, чтобы .playable
     не затирал поворот, а добавлялся к нему */
  --fan-hover: 0px;
  /* Волна: подъём к пику (--fan-hover), масштаб (--fan-scale),
     наклон к пику (--fan-tilt). Карту при ходе НЕ перетаскиваем. */
  --fan-scale: 1;
  --fan-tilt: 0deg;
  flex-shrink: 0;
  /* Вращаем вокруг нижнего края — карты расходятся веером из одной точки,
     как в руке. Origin ниже карты (>100%) заваливал бы края вверх. */
  transform-origin: 50% 100%;
  transform:
    translate(0, calc(var(--fan-y) + var(--fan-hover)))
    rotate(calc(var(--fan-rot) + var(--fan-tilt)))
    scale(var(--fan-scale));
  will-change: transform;
  /* Волну сглаживаем: подольше и с мягкой кривой, чтобы пик
     перетекал между картами, а не дёргался */
  transition: transform 0.22s cubic-bezier(.25, .8, .25, 1);
}
/* Веер соперника — «радугой»: дуга вверх в центре, как у руки игрока
   (layoutFan без flip). Контейнер не поворачиваем, точку вращения карт
   не переопределяем — берётся базовая (50% 100%, низ карты). */
.hand-row.fan.bot-hand { transform: rotate(0deg); position: relative; margin-top: -18px; }

/* Подсветка доступной карты: поднимаем, не трогая поворот */
.hand-row.fan .card.playable {
  --fan-hover: -14px;
  z-index: 50 !important;
}
.hand-row.fan .card.playable:hover,
.hand-row.fan .card.clickable:hover {
  --fan-hover: -22px;
  z-index: 60 !important;
}

/* ---------- веер: волна под курсором/пальцем ---------- */
.hand-row.fan .card.wave-peak {
  z-index: 70 !important;
}
.hand-row.player-hand,
.hand-row.player-hand .card {
  touch-action: none;
}

.count-label {
  text-align: center;
  color: #d1fae5;
  font-size: 12px;
  margin: 4px 0 8px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
}

/* Кружок с числом карт соперника: в ряду мест мультиплеера он есть
   всегда, в игре с ботом — только когда карт больше, чем влезает в веер. */
.opp-count-badge {
  position: absolute;
  right: -6px;
  bottom: -6px;
  width: 30px;
  height: 30px;
  padding: 0 0 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('../img/characters/window_opponent/card_c_table_opponent.webp') center / 100% 100% no-repeat;
  color: #fff;
  font-size: 12px;
  font-weight: 800;
  line-height: 1;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
  z-index: 70;
}

/* ---------- карты ---------- */
.card {
  border-radius: 6px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.35);
  user-select: none;
  overflow: hidden;
  border: 1px solid #d1d5db;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 4px;
  transition: transform 0.12s;
  background: #fff;
}
.card-back { border: 1px solid rgba(255, 255, 255, 0.3); }
.card.clickable { cursor: pointer; }
.card.playable {
  cursor: pointer;
  box-shadow: 0 0 0 2px #facc15, 0 6px 12px rgba(0, 0, 0, 0.4);
}
/* Подъём подсвеченной карты — только вне веера: внутри .fan карта уже
   повёрнута, и свой transform там задаёт блок «рука веером» выше. */
.hand-row:not(.fan) .card.playable { transform: translateY(-8px); }
.card-corner { font-size: 13px; font-weight: 700; line-height: 1; }
.card-corner-b { align-self: flex-end; transform: rotate(180deg); }
.card-suit { text-align: center; font-size: 22px; }

/* ---------- центральная зона ---------- */
.center-row {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  min-height: 128px;
  margin-bottom: 4px;
}

/* Окно соперника над колодой: аватарка в рамке с зелёной лентой внизу.
   Лента уже нарисована в самом арте (o_<id>.webp), отдельной плашки нет —
   поверх ленты кладём только текст имени.
   Картинку НЕ растягиваем: ширину задаём явно, высоту выводим из
   пропорции исходника (278x158), поэтому арт рисуется один в один. */
.opp-window {
  /* Обычный поток: стоит первым в колонке .bot-row, то есть прямо
     над веером карт соперника и по центру вместе с ним. */
  position: relative;
  width: 168px;
  aspect-ratio: 278 / 158;
  flex-shrink: 0;
}
.opp-window-art {
  display: block;
  width: 100%;
  height: 100%;
  /* contain при совпадающей пропорции бокса не даёт полей и не искажает */
  object-fit: contain;
  pointer-events: none;
}
/* Имя — по центру ленты. Лента занимает нижнюю часть арта (55 из 158 по
   высоте ≈ 35%), поэтому центр текста ставим на её середину. */
.opp-window-name {
  position: absolute;
  left: 0;
  right: 0;
  /* середина ленты от низа: 55/2 / 158 ≈ 17.4% */
  bottom: 9%;
  /* Лента сужается к краям — текст держим в её ровной середине */
  padding: 0 11%;
  text-align: center;
  color: #f4ecd6;
  /* Мелко: самые длинные имена («Капитан Барахта», «Гусыня Га-Га») должны
     помещаться в одну строку, иначе nowrap обрежет их многоточием. */
  font-size: 11px;
  font-weight: 800;
  line-height: 1.1;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.65);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  pointer-events: none;
}

/* Зона колоды: стопка рубашек и торчащий слева повёрнутый козырь.
   В ряду стоит справа (order:2). Ширина — по стопке (≈64+смещения);
   козырь вынесен влево отрицательным left, запас справа ему не нужен. */
.deck-zone { position: relative; width: 104px; height: 152px; flex-shrink: 0; order: 2; margin-right: -8px; }
.deck-trump {
  position: absolute;
  left: -54px;           /* выезжает левее стопки */
  top: 18px;
  /* Размер задаём явно: внутри лежит либо карта-«лицо» (ей ширину/высоту
     проставляет JS), либо бейдж козырной масти с width/height:100% —
     без размеров на родителе абсолютный блок схлопывался по содержимому,
     и бейдж выходил узкой полоской. 80x120 — те же W/H, что у карты
     (assets/core/game-flow.js): меняя их там, поправьте и здесь. */
  width: 80px;
  height: 120px;
  transform: rotate(-90deg);
  transform-origin: center;
  z-index: 1;            /* под рубашками */
}
.deck-back {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 2;            /* поверх козыря, но козырь торчит справа */
}
.deck-count {
  position: absolute;
  /* Плашка счётчика — по центру верхней карты стопки (карта 80x120). */
  left: 40px;
  top: 60px;
  transform: translate(-50%, -50%);
  z-index: 3;
  width: 54px;
  height: 54px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  background: url('../img/cards/ui_card_nimber.webp') center / 100% 100% no-repeat;
  color: #fff;
  font-weight: 700;
  font-size: 15px;
}
.deck-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  border-radius: 6px;
  color: #d1fae5;
  font-size: 12px;
  border: 1px dashed rgba(255, 255, 255, 0.4);
}

.play-zone {
  flex: 1;
  order: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: flex-start;
  justify-content: center;
}
.table-empty {
  align-self: center;
  color: #d1fae5;
  font-size: 14px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
}
.pair { position: relative; }
.pair-attack { position: absolute; top: 0; left: 0; }
.pair-defense { position: absolute; top: 16px; left: 16px; }

/* ---------- сообщение и действия ---------- */
.msg {
  text-align: center;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  margin: 12px 0 8px;
  min-height: 20px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
}
.actions {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-bottom: 12px;
  min-height: 36px;
}

/* ---------- оверлей «ЯППИ» ---------- */
/* Fixed (а не absolute): оверлей лежит в body вне #app — так его не сносит
   render(), и анимация «ЯППИ» не перезапускается на каждом ре-рендере. */
.celebrate {
  position: fixed;
  inset: 0;
  overflow: hidden;
  z-index: 50;
  pointer-events: none;
}
.celebrate-flash {
  position: absolute;
  inset: 0;
  background: radial-gradient(circle at 70% 60%, #fde047, transparent 60%);
  animation: flashBg 2.3s ease-out forwards;
}
.celebrate-hero {
  position: absolute;
  right: 0;
  bottom: 0;
  animation: heroSlide 2.3s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
}
.celebrate-hero img {
  height: 280px;
  max-height: 85%;
  filter: drop-shadow(-8px 0 16px rgba(0, 0, 0, 0.55));
}
.celebrate-emoji { font-size: 150px; line-height: 1; }
.celebrate-text {
  position: absolute;
  left: 50%;
  top: 26%;
  animation: yapText 2.3s ease-out forwards;
}
.celebrate-yap {
  font-size: 68px;
  font-weight: 900;
  color: #fde047;
  -webkit-text-stroke: 3px #b91c1c;
  text-shadow: 0 5px 0 #7f1d1d, 0 8px 14px rgba(0, 0, 0, 0.5);
  display: inline-block;
  white-space: nowrap;
}

@keyframes heroSlide {
  0%   { transform: translateX(130%) scale(0.9); opacity: 0; }
  18%  { transform: translateX(0) scale(1); opacity: 1; }
  30%  { transform: translateX(-6%) scale(1.04); }
  42%  { transform: translateX(0) scale(1); }
  78%  { transform: translateX(0) scale(1); opacity: 1; }
  100% { transform: translateX(130%) scale(0.9); opacity: 0; }
}
@keyframes yapText {
  0%   { transform: translateX(-50%) scale(0) rotate(-12deg); opacity: 0; }
  20%  { transform: translateX(-50%) scale(1.3) rotate(6deg); opacity: 1; }
  32%  { transform: translateX(-50%) scale(1) rotate(-3deg); }
  44%  { transform: translateX(-50%) scale(1.08) rotate(2deg); }
  56%  { transform: translateX(-50%) scale(1) rotate(0); }
  80%  { opacity: 1; }
  100% { transform: translateX(-50%) scale(0.4) rotate(0); opacity: 0; }
}
@keyframes flashBg {
  0%   { opacity: 0; }
  12%  { opacity: 0.55; }
  30%  { opacity: 0.12; }
  100% { opacity: 0; }
}

/* ---------- финал ---------- */
/* Fixed, а не absolute: оверлей вешается в body (вне #app), т.к. #app
   трансформируется fitBoard() и absolute-затемнение покрыло бы только рамку
   доски, оставляя экран по краям не затемнённым. */
.over {
  position: fixed;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
  z-index: 60;
}
.over-box {
  box-sizing: border-box;
  width: min(520px, calc(100vw - 32px), calc((100dvh - 32px) * 955 / 928));
  aspect-ratio: 955 / 928;
  background: url('../img/new/wld/ui_wld-8.webp') center / 100% 100% no-repeat;
  border-radius: 14px;
  padding: 46px 20px 22px;
  text-align: center;
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
  margin: 0 16px;
  overflow-y: auto;
  scrollbar-width: none;
}
.over-box::-webkit-scrollbar {
  width: 0;
  display: none;
}
/* На десктопе плашка не должна растягиваться во всю высоту экрана.
   Сохраняет пропорцию 955/928 и ужимается по ширине. */
@media (min-width: 561px) {
    .over-box {
        max-height: 80dvh;
    }
}
.over-title {
    margin: 16px auto 4px;
    background: center / 100% 100% no-repeat;
    font-size: 0;
}
/* Надписи результата — арты wld: победа/поражение/ничья */
.over-title-win { width: 60%; aspect-ratio: 643 / 149; background-image: url('../img/new/wld/ui_wld_wi.webp'); }
.over-title-lo { width: 70%; aspect-ratio: 780 / 157; background-image: url('../img/new/wld/ui_wld_lo.webp'); }
.over-title-dr { width: 55%; aspect-ratio: 527 / 145; background-image: url('../img/new/wld/ui_wld_dr.webp'); }
/* Кнопки финального окна — на плашках из img/new/button (230x69). */
.over-again,
.over-menu,
.over-cancel {
    aspect-ratio: 230 / 69;
    width: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    border-radius: 0;
    padding: 0 8px;
    background: center / 100% 100% no-repeat;
    box-shadow: none;
    color: #fff;
    font-size: clamp(12px, 1.4vw, 15px);
    font-weight: 900;
    letter-spacing: 0.3px;
    text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
    cursor: pointer;
    transition: transform 0.1s ease, filter 0.12s ease;
}
.over-again  { background-image: url('../img/new/button/ui_button_green.webp'); }
.over-menu   { background-image: url('../img/new/button/ui_button_blue.webp'); }
.over-cancel { background-image: url('../img/new/button/ui_button_red.webp'); }
.over-again:hover,
.over-menu:hover,
.over-cancel:hover { filter: brightness(1.08); }
.over-again:active,
.over-menu:active,
.over-cancel:active { transform: translateY(1px) scale(0.98); filter: brightness(0.95); }

/* Ряд кнопок в финальной модалке — та же ширина, что и у рейтинга (92%),
   чтобы все кнопки помещались в один ряд и не были уже/шире блока рейтинга. */
.over-btn-row {
    display: flex;
    gap: 10px;
    justify-content: center;
    flex-wrap: wrap;
    margin: 0 auto 4px;
    width: 100%;
}

/* На мобильных кнопки должны оставаться в один ряд (в мультиплеере к ним
   добавляется «Отмена»), поэтому убираем перенос и растягиваем кнопки
   внутри ряда поровну. */
@media (pointer: coarse), (max-width: 560px) {
    .over-box {
        padding: 22px 6px 12px;
        width: min(560px, calc(100vw - 32px), calc((100dvh - 32px) * 955 / 928));
    }
    .over-btn-row {
        flex-wrap: nowrap;
        gap: 8px;
        width: 100%;
    }
    .over-btn-row .over-again,
    .over-btn-row .over-menu,
    .over-btn-row .over-cancel {
        flex: 1 1 0;
        width: auto;
        min-width: 0;
        max-width: 120px;
    }
}
/* Очень узкие экраны — компактнее кнопки, чтобы три в ряд влезали */
@media (max-width: 480px) {
    .over-btn-row {
        gap: 6px;
        width: 92%;
    }
    .over-again,
    .over-menu,
    .over-cancel {
        font-size: 10px;
        padding: 0 2px;
        letter-spacing: 0;
        max-width: 112px;
    }
}

/* Рейтинг под кнопкой «Сыграть ещё» — как окно рейтинга из меню:
   шапка колонок + верёвочный скролл, внутри белого окна. */
.over-rating {
  width: 92%;
  margin: 6px auto 0;
}
.over-rating-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 800;
  color: #ffdca8;
  margin-bottom: 10px;
}
/* Иконка рейтинга слева от подписи — арт ui_wld_rating (60×69) */
.over-rating-title-icon {
  flex: 0 0 auto;
  width: 1.2em;
  aspect-ratio: 60 / 69;
  background: url('../img/new/wld/ui_wld_rating.webp') center / 100% 100% no-repeat;
}
.over-rating-inner {
  border-radius: 10px;
  padding: 8px 10px;
  display: flex;
  flex-direction: column;
  /* Десктоп: область показывает ~7 строк рейтинга. На телефоне ужимаем
     до 3 строк и приподнимаем к заголовку (медиа ниже). */
  max-height: 240px;
}
/* cqw в финале не считается (нет container-type) — фиксируем размеры шапки */
.over-rating .rating-head {
  flex: 0 0 auto;
  font-size: 11px;
  padding: 0 20px 6px 0;
}
.over-rating .rating-scroll-wrap {
  flex: 1 1 auto;
  min-height: 0;
}
.over-rating-body {
  flex: 1 1 auto;
  min-width: 0;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
  /* Родная полоса скрыта — справа верёвочный скролл, как в окне из меню */
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.over-rating-body::-webkit-scrollbar {
  width: 0;
  height: 0;
  display: none;
}
.over-rating-body .rating-loading,
.over-rating-body .rating-empty,
.over-rating-body .rating-error { padding: 14px 0; }

/* На телефоне/тач-устройстве показываем компактную область (3 строки),
   приподнимаем таблицу ближе к надписи «Текущий рейтинг» и фиксируем высоту
   полосы равной 3 строкам: нижняя стрелка скролла заканчивается ровно на 3-м
   месте, а не висит ниже таблицы. Условия те же, что и у мобильного .over-box
   (pointer: coarse + ширина), иначе на тач-планшете окно мобильное, а рейтинг
   остаётся по 7 строк. */
@media (pointer: coarse), (max-width: 560px) {
  .over-rating {
    margin-top: 0;
  }
  .over-rating-title {
    margin-bottom: 8px;
  }
  .over-rating .rating-scroll-wrap {
    flex: 0 0 auto;
    height: 90px; /* 3 строки по 30px */
  }
  .over-rating-inner {
    max-height: none;
    padding: 0 10px 8px; /* без верхнего отступа — таблица под надписью */
  }
}

/* ---------- экран выбора персонажа ---------- */
/* ---------- экран выбора персонажа (карусель) ---------- */
.char-screen {
  display: none;
  position: fixed;
  inset: 0;
  height: 100dvh;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;   /* карусель по центру, плашка описания снизу */
  /* Заголовок «ВЫБОР ПЕРСОНАЖА» впечатан в фон, поэтому привязываем фон
     к ВЕРХУ: при cover режется низ (ковёр под плашкой), а заголовок сверху
     остаётся виден целиком на любом соотношении экрана. Сверху вписываем
     кадр во всю высоту, бока закрывают полосы back_left/back_right. */
  background-image:
    url('../img/screen/back_left.webp'),
    url('../img/screen/back_right.webp'),
    url('../img/menu/character_menu/back_character_menu.webp');
  background-position:
    right calc(50vw + (8 / 9) * 100dvh) center,
    left  calc(50vw + (8 / 9) * 100dvh) center,
    top center;
  background-size: auto 100%, auto 100%, auto 100%;
  background-repeat: no-repeat;
  background-color: #2a1a10;   /* подложка на случай узкого экрана */
  z-index: 100;
  padding: 0;
  overflow: hidden;
}
.char-screen.visible { display: flex; }

/* Логотип над каруселью: абсолютно вверху по центру. z-index:0 — первый
   ребёнок экрана, поэтому карточки карусели (positioned, идут позже в DOM)
   рисуются поверх него, если логотип наезжает.

   Размер — по той же логике, что у стрелок и карточек: доля от ШИРИНЫ СЦЕНЫ
   (кадр 177.78dvh) с потолком в натуральный размер картинки.
   logo_character_menu.webp = 896x257, то есть 896 / 177.78 = 5.04 от ширины
   кадра, или 83dvh от высоты: на экране 1080px и выше логотип рисуется
   полностью (896px), ниже пропорционально уменьшается вместе со сценой.
   Прежние 50dvh с потолком 560px давали лишь 60% натурального размера и
   упирались в потолок уже на высоте 1120px. */
.char-logo {
  position: absolute;
  /* top уменьшен с 2.5vh: при полном размере логотипа на 1920x1080 старая
     величина давала наезд 3px на верх карточек, здесь остаётся 13px. */
  top: 1vh;
  left: 50%;
  transform: translateX(-50%);
  z-index: 0;
  width: min(896px, 83dvh);
  height: auto;
  pointer-events: none;
}

/* Кнопка выхода — в левом верхнем углу */
.char-back-btn {
  position: absolute;
  top: 14px;
  left: 14px;
  z-index: 5;
  width: 48px;
  height: 48px;
  border: none;
  border-radius: 12px;
  background: rgba(0, 0, 0, 0.45);
  color: #fff;
  font-size: 22px;
  cursor: pointer;
  transition: background 0.15s, transform 0.1s;
}
.char-back-btn:hover { background: rgba(0, 0, 0, 0.65); }
.char-back-btn:active { transform: scale(0.94); }

/* ---------- выбор имени ---------- */
/*  .name-pick {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 0 24px;
  padding: 10px 16px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.06);
  border: 2px solid transparent;
}
.name-pick.flash {
  animation: namePulse 0.7s ease;
}
@keyframes namePulse {
  0%, 100% { border-color: transparent; background: rgba(255, 255, 255, 0.06); }
  30%      { border-color: #f87171; background: rgba(248, 113, 113, 0.18); }
}  */
.name-label { color: #cbd5e1; font-size: 16px; font-weight: 600; }
.name-input,
.name-select {
  font-family: inherit;
  font-size: 16px;
  padding: 8px 12px;
  border-radius: 8px;
  border: 1px solid #475569;
  background: #1e293b;
  color: #fff;
  cursor: pointer;
  min-width: 180px;
}
.name-input { cursor: text; }
.name-input::placeholder { color: #64748b; }
.name-input:focus,
.name-select:focus { outline: 2px solid #facc15; }

.char-sub { color: #cbd5e1; font-size: 18px; margin: 0 0 24px; }

/* Список персонажей заблокирован, пока не выбрано имя */
.char-list.locked { opacity: 0.45; filter: grayscale(0.4); }
.char-list.locked .char-card { cursor: not-allowed; }
/* Размер карточек задаётся transform: scale() (соседи 0.88, крайние 0.75),
   но при наведении масштаб НЕ меняется — только яркость. Поэтому здесь
   сбрасывать нечего, блокировку списка показываем прозрачностью и курсором. */
.char-list.locked .char-card:hover { filter: none; }

.btn-rating-link {
  background: #b45309;
  font-size: 16px;
  padding: 10px 22px;
  font-weight: 700;
}
.btn-rating-link:hover { background: #d97706; }
.btn-fs-link {
  width: clamp(150px, 17vw, 230px);
  aspect-ratio: 230 / 69;
  display: none;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 0;
  border-radius: 0;
  font-weight: 900;
  /* Кегль как у подписей кнопок главного меню (.menu-btn-label — 20px),
     в связке с .char-play-btn и .btn-back-link. Потолок clamp на 16px
     оставлен для узких экранов, где надпись иначе станет крупнее плашки. */
  font-size: clamp(13px, 1.6vw, 20px);
  border: none;
  cursor: pointer;
  background: url('../img/new/button/ui_button_red.webp') center / 100% 100% no-repeat;
  color: #fff;
  text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
  transition: transform 0.12s ease, filter 0.15s ease;
}
.btn-fs-link:hover {
  transform: translateY(-2px);
  filter: brightness(1.08);
}

/* Показываем кнопку "На весь экран" только на touch-устройствах.
   На Яндекс.Играх полноэкранный режим недоступен (там своё окно), поэтому
   правило исключает их — иначе кнопка была бы видна, но не работала бы.
   Метку ставит platform.js при загрузке скрипта. */
@media (pointer: coarse) {
    html:not([data-platform="yandex"]) .btn-fs-link {
        display: inline-block;
    }
}

/* ---------- карусель ---------- */
.char-carousel {
  /* Карусель выводим из flex-колонки (absolute по всему экрану), чтобы её
     высота не зависела от плашки описания. Симметричные верхний и нижний
     отступы делают контент-бокс концентричным экрану, поэтому flex-
     центрирование ставит карточки точно в центр экрана. */
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* Карусель (включая стрелки) не шире 16:9-кадра основного изображения:
     на сверхшироких экранах стрелки не уезжают за его края в боковые полосы. */
  margin: 0 auto;
  max-width: calc(100dvh * (16 / 9));
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5dvh;
  padding: 26vh 12px 26vh;
  min-height: 0;              /* чтобы flex не распирал по высоте */
  /* Высота карточки — общая величина для всей карусели: от неё считаются
     и ряд, и стрелки (стрелка = 0.133 * карточки). Объявлена здесь, а не в
     .char-card, чтобы .char-arrow видела то же значение.

     Кадр = 100dvh x 177.78dvh, поэтому весь ряд считаем в dvh.
     Стрелка — полного размера там, где сцена влезает (соотношение сторон
     экрана >= 16/9), и уменьшается вместе с ней дальше; см. .char-arrow.
       пять карточек   5 * 0.5813 * 48 = 139.5
       промежутки ряда 4 * 1.7           =   6.8
       промежутки карусели 2 * 0.5       =   1.0
       две стрелки     2 * 8.89           =  17.8
       ИТОГО                              165.1 из 177.78
     Свободно 6.35dvh с каждой стороны, из них 4.73dvh занимает ВЫСТУП
     СВЕЧЕНИЯ центральной карточки (120% высоты, .char-card-center::before)
     — остаётся ~1.6dvh запаса, то есть свечение гарантированно не выходит
     в боковые полосы кадра даже на сверхшироких экранах.

     Потолок 640px страхует от гигантских мониторов. Нижнего предела нет
     намеренно: 48dvh на самом низком разумном экране (360px высоты) даёт
     173px, и карточка вписывается по вертикали вместе с логотипом и
     плашкой. Жёсткий floor «раздул» бы карточки на низких экранах и опять
     вытолкнул бы стрелки за кадр. */
  --char-h: min(48dvh, 640px);
}

/* Стрелки: одна картинка, левая — отзеркалена.
   При наведении — высветление, при нажатии — затемнение (как у кнопок меню). */
.char-arrow {
  flex: 0 0 auto;
  align-self: center;
  /* Размер — доля ШИРИНЫ СЦЕНЫ (кадр 177.78dvh), а не высота карточки.
     Карусель ограничена шириной кадра (max-width: 177.78dvh), поэтому 6.5%
     от ширины СЦЕНЫ = 0.065 * 177.78 = 11.56dvh, а не 6.5vw: вvw на 16/9
     в 1.78 раза больше, и привязка к окну, а не к кадру, заставляла стрелку
     расти вместе с боковыми полосами.

     Итог: на любом экране, где сцена влезает целиком (соотношение сторон
     >= 16/9), стрелка полного размера — 96px; на более узких экранах
     она пропорционально уменьшается вместе со сценой. Это ровно то, что
     делала исходная clamp(44px, 6.5vw, 96px), только от кадра, а не от
     окна: на 16:9 значения совпадают с точностью до долей пикселя. */
  width: min(96px, 11.56dvh);
  height: min(96px, 11.56dvh);
  border: none;
  background: url('../img/menu/character_menu/c_arrow.webp') center / contain no-repeat;
  cursor: pointer;
  transition: transform 0.1s, filter 0.15s;
  filter: drop-shadow(0 3px 4px rgba(0, 0, 0, 0.4));
}
.char-arrow-left { transform: scaleX(-1); }
/* Высветление только на устройствах с мышью: на тач-экранах hover
   залипает после нажатия, и стрелка остаётся засвеченной. */
@media (hover: hover) {
  .char-arrow:hover { filter: brightness(1.18) drop-shadow(0 3px 4px rgba(0, 0, 0, 0.4)); }
  .char-arrow-right:hover { transform: scale(1.08); }
  .char-arrow-left:hover { transform: scaleX(-1) scale(1.08); }
}
.char-arrow-right:active { transform: scale(0.98); filter: brightness(0.82) drop-shadow(0 2px 3px rgba(0,0,0,0.4)); }
.char-arrow-left:active { transform: scaleX(-1) scale(0.98); filter: brightness(0.82) drop-shadow(0 2px 3px rgba(0,0,0,0.4)); }

.char-list {
  display: flex;
  align-items: center;
  justify-content: center;
  /* Промежуток между карточками (см. расчёт ряда в --char-h на
     .char-carousel): подобран так, чтобы после вычета выступа свечения
     оставался запас ~1.6dvh до края кадра. */
  gap: 1.7dvh;
  flex: 1 1 auto;
  max-width: 176dvh;
}

/* Карточка персонажа — подложка c_back.webp, картинка героя поверх.
   Размер задаём долей высоты вьюпорта (dvh) — ровно в тех же координатах,
   что и сам кадр локации: .game-bg вписан как background-size: auto 100%,
   то есть кадр всегда 100dvh в высоту и 177.78dvh в ширину (16:9).
   Благодаря этому карточки живут той же пропорцией к фону на любом экране,
   а на сверхшироких полосы по бокам добавляются снаружи — стрелки остаются
   внутри кадра. Именно dvh, а не vh: на мобильных при уходе адресной строки
   высота вьюпорта меняется, и фон по правилу auto 100% меняется вместе с
   ней — карточки обязаны ехать так же, иначе отстанут от кадра.

   Ширина выводится из aspect-ratio по РОДНОЙ пропорции c_back
   (304x523 = 0.5813), поэтому 100% 100% не искажает картинку. */
.char-card {
  position: relative;
  flex: 0 0 auto;
  /* Высота = --char-h с .char-carousel (см. там же подробный расчёт):
     49dvh с потолком 640px. Нижнего предела нет намеренно — на самом низком
     разумном экране (360px высоты) получается 176px, и карточка вписывается
     по вертикали вместе с логотипом и плашкой. Жёсткий floor раздул бы
     карточки на низких экранах и опять вытолкнул бы стрелки за кадр. */
  height: var(--char-h);
  aspect-ratio: 304 / 523;
  width: auto;
  cursor: pointer;
  background: url('../img/menu/character_menu/c_back.webp') center / 100% 100% no-repeat;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  transition: filter 0.18s ease, transform 0.18s ease;
  /* Размер: центральная карточка 100%, её соседи 88%, крайние 75%.
     Уменьшение через transform, а не height: transform не трогает раскладку,
     поэтому ширина ряда в dvh остаётся прежней (см. расчёт --char-h выше) и
     стрелки не сдвинутся. Масштаб от центра карточки — тогда карточка
     стягивается к общему центру, и ноги героев остаются на одной линии.
     Раньше размер был одинаковым у всех пяти, карточки различались только
     яркостью. */
  transform: scale(0.88);
  transform-origin: 50% 50%;
  filter: brightness(0.78) saturate(0.88);
  opacity: 0.95;
}
/* Базовое состояние всех карточек и hover по умолчанию. У слотов разные
   базы (центр 1.00, соседи 0.78, крайние 0.68), поэтому hover задаётся
   отдельно для каждого — см. правила у .char-card-edge ниже и
   .char-card-center здесь. Единое значение 0.88 подходит соседям, но для
   центра (filter: none) оно было бы затемнением. */
.char-card:hover { filter: brightness(0.88) saturate(0.94); }
.char-card-center:hover { filter: brightness(1.12) saturate(1.06); }

/* Центральная карточка. Свой background убран нарочно: рамку (c_back_cha) и
   свечение (c_back_glow) рисуем двумя псевдоэлементами, чтобы они попали в
   один контекст наложения и порядок задавался z-index'ом.

   Почему нельзя было оставить c_back_cha фоном элемента: фон родителя
   всегда рисуется ПЕРВЫМ, до всех дочерних элементов, поэтому свечение с
   z-index: -1 оказывалось НАД рамкой, а не под ней. Отрицательный z-index
   опускает элемент только под содержимое родителя, но не под его фон. */
.char-card-center {
  background: none;
  transform: scale(1);
  filter: none;
  opacity: 1;
  z-index: 2;
}

/* Рамка центральной карточки — верхний из двух слоёв. inset: 0 кладёт её
   ровно в бокс карточки; её пропорция (302x522) отличается от карточки
   (304x523) на 0.3%, поэтому 100% 100% картинку не искажает. */
.char-card-center::after {
  content: "";
  position: absolute;
  inset: 0;
  background: url('../img/menu/character_menu/c_back_cha.webp') center / 100% 100% no-repeat;
  pointer-events: none;
  z-index: 1;
}

/* Свечение центральной карточки — нижний слой из двух, под рамкой.
   Почему не через background: у фона background-clip по умолчанию
   border-box, то есть картинка обрезается по боксу элемента и за его
   пределы не выходит НИКОГДА. Попытка задать c_back_glow вторым слоем фона
   дала невидимое свечение: наружу всё срезалось, а внутри бокса картинку
   полностью закрывал c_back_cha.
   Псевдоэлемент с position: absolute обрезается только теми предками,
   у которых задан overflow — здесь его нет ни у карточки, ни у .char-list,
   ни у .char-carousel, поэтому свечение свободно выходит за края.
   z-index: 0 против z-index: 1 у рамки (::after) задаёт нужный порядок
   независимо от того, что ::before в DOM идёт раньше.
   Размер задан по ПРОПОРЦИИ самой картинки (c_back_glow 408x629):
   height 120% + aspect-ratio 408/629 даёт свечение высотой 1.2 высоты
   карточки и шириной 0.778 высоты карточки — то есть шире карточки
   (0.529 высоты) на 27% её ширины: выходит примерно на 13.5% ширины
   карточки с каждой стороны, перекрывая соседей, но не слишком сильно.
   Степень задана шириной кадра: выступ съедает свободное место, нужное для
   запаса до края (расчёт в --char-h). При 120% и карточке 49dvh остаётся
   3.25dvh запаса. Менять свободно: 115% → 4.05dvh, 125% → 2.46dvh. */
.char-card-center::before {
  content: "";
  position: absolute;
  left: 50%;
  top: 50%;
  height: 120%;
  width: auto;
  aspect-ratio: 408 / 629;
  transform: translate(-50%, -50%);
  background: url('../img/menu/character_menu/c_back_glow.webp') center / contain no-repeat;
  pointer-events: none;
  /* Под рамкой карточки (::after с z-index: 1), но всё ещё внутри её
     контекста наложения (z-index: 2) — поэтому мягко ложится поверх
     соседних карточек, не залезая под их фон. */
  z-index: 0;
}

/* Крайние карточки — самые дальние от центра, поэтому самые мелкие: 75%
   против 88% у соседей. Как и соседи, отличаются ещё и яркостью. */
.char-card.char-card-edge {
  transform: scale(0.75);
  filter: brightness(0.68) saturate(0.82);
  opacity: 0.85;
}
/* Высветление при наведении. У трёх слотов РАЗНЫЕ базы (центр 1.00,
   соседи 0.78, крайние 0.68), поэтому и hover у них разный — так, чтобы
   прирост яркости был одинаковым (+0.12 у каждого). Единое значение
   здесь давало бы соседям шаг 0.02 вместо 0.12: они почти не светлели бы,
   выглядя «мёртвыми» на фоне остальных.

   Порядок селекторов важен: у соседей два :not() — специфичность (0,4,0)
   против (0,3,0) у правила крайних, иначе :not(.char-card-center) забрал бы
   и крайние карточки, вернув им 0.90 вместо их 0.80. */
.char-card.char-card-edge:hover {
  filter: brightness(0.8) saturate(0.9);
}
.char-card:not(.char-card-center):not(.char-card-edge):hover {
  filter: brightness(0.9) saturate(0.95);
}

/* Персонаж внутри карточки. object-fit: contain держит пропорции при любом
   размере бокса, поэтому масштабирование (в т.ч. по dvh) картинку не
   искажает. Натуральные соотношения семи героев различаются (0.432 у
   зомби … 0.754 у гнома), поэтому по общей высоте бокса вписываются все,
   а самые «узкие» выглядят мельче — это цена разнородных исходников. */
.char-card-img {
  /* Бокс героя. Раньше было 85% x 85% с отступом снизу 12% — теперь
     92% x 90%, то есть примерно на 8% крупнее. Рамка c_back имеет поля
     около 3-4%, поэтому 92% по ширине — это ровно впритык к внутреннему
     краю рамки, без выхода за неё. */
  width: 92%;
  height: 90%;
  object-fit: contain;
  /* object-position: bottom — картинка «стоит» на своей нижней кромке,
     а сам бокс приподнят от низа карточки, чтобы ноги персонажа не
     вылезали за декоративную рамку c_back и не наезжали на плашку имени.
     ВАЖНО: процентный margin в CSS считается от ШИРИНЫ контейнера, а не
     от высоты, поэтому 10% здесь = 0.10 * 307px ≈ 31px, а не 53px.
     Вместе с высотой бокса 90% это даёт ~22px запаса сверху до рамки. */
  object-position: bottom center;
  margin-bottom: 10%;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.35));
  /* Поверх обоих псевдоэлементов карточки (рамки и свечения). Иначе герой,
     как обычный потоковый элемент без позиционирования, рисовался бы под
     ними. Плашке имени (.char-name) нужен z-index: 3 — см. ниже: с z-index
     всего лишь auto она рисовалась бы под героем. */
  position: relative;
  z-index: 2;
}

/* Плашка имени — картинка-подложка name_character.webp (323x145), текст
   поверх. Сидит в нижней части карточки (как в макете), текст центрирован
   по её видимому телу (лёгкий сдвиг вверх компенсирует «ушки» плашки).

   Размер — по родным пропорциям макета. Плашка ВИДНЕЕ рамки карточки:
   name_character.webp = 323x145, а c_back_cha.webp = 302x522, то есть
   плашка шире на (323-302)/2 = 10.5px с каждой стороны, или 107% ширины
   карточки. Высота из этого следует автоматически: 107% ширины карточки
   при её пропорции 304/523 даёт 27.9% высоты карточки.
   Раньше стояло 82% x 18.7% — плашка была и уже карточки, и растянута
   по ширине на 14% (соотношение 2.55 против натуральных 2.23). */
.char-name {
  position: absolute;
  /* Отступ от низа карточки. Было 3.3% -> 1% -> 0 -> -5.8% -> -8%.
     Отрицательное значение выносит нижнюю кромку плашки ЗА пределы карточки.
     Ориентир -5.8% был не случайным: ноги героя стоят на margin-bottom бокса
     .char-card-img = 10% ШИРИНЫ карточки, а проценты у bottom считаются от
     ВЫСОТЫ, поэтому 10% * (304/523) = 5.81% высоты карточки — тогда плашка
     лежала ровно на линии ног. Теперь на 2.2% ниже (ещё ~11px на 1080p):
     плашка ушла из-под ног, герой читается целиком.
     Двигать дальше вниз незачем: нижняя плашка экрана (.char-bottom) начинается
     на 76-80dvh от верха, а низ плашки имени и так на 29.8dvh — зазор
     ~46dvh, то есть до края ещё далеко.
     Минус возможен потому, что overflow у карточки открытый; если открыть
     .char-card, плашка обрежется по нижнему краю карточки. */
  bottom: -5.8%;
  left: 50%;
  transform: translateX(-50%);
  width: 107%;
  height: auto;
  aspect-ratio: 323 / 145;
  background: url('../img/menu/character_menu/name_character.webp') center / 100% 100% no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
/* Текст внутри плашки двигаем padding-bottom (сама плашка неподвижна, её
       bottom = -5.8% кладёт подложку на линию ног героя).
       Шкала: -4% — по линию ног; 0% — геометрический центр;
       4% — исходное положение с поправкой на «ушки» плашки;
       10% (сейчас) — на 6% выше исходного, около 8.7px на 1080p.
       Выше подниматься нельзя: на 375px высота плашки 50px при строке 31px,
       то есть запас до верхнего края всего 19%, и при ~16% текст уже
       вылезает в «ушки». */
    padding-bottom: 10%;
  color: #6b3410;
    /* Кегль имени привязан к ШИРИНЕ плашки, а не к ширине окна: плашка
       масштабируется вместе с карточкой (107% её ширины = 29.8dvh), значит и
       текст должен уменьшаться вместе с ней. Иначе на мобильных длинный
       ник шире плашки. Длина имени ограничена: самое длинное в characters.json
— «Сэр Хрюстон Фунтович», 20 символов.
        Потолок по ширине: 20 симв * 0.55em (кириллица в весе 800) = 11em,
        доступно 29.85dvh => кегль <= 2.71dvh. То есть 2.7dvh — это ровно
        предел, поднимать его нельзя: на любой высоте экрана длинное имя
        займёт 99.5% ширины плашки.

        Подвинуть можно только потолок в px. 20px упирался на высоте от
        741px (20 / 0.027 = 741), то есть на десктопе кегль не зависел от
        экрана и стоял на 20px. Теперь 26px — на 1080p длинное имя занимает
        88.7% плашки, на 960px 99.8% (впритык), ниже 960px работает 2.7dvh.
        Высоты плашки хватает с большим запасом: при кегле 26px строка
        31px против 145px высоты плашки на 1080p. */
    font-size: min(26px, 2.7dvh);
  font-weight: 800;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.35);
  white-space: nowrap;
  /* ПОВЕРХ героя. Без этого плашка оказывалась под картинкой персонажа:
     у .char-card-img стоит z-index: 2, а позиционированный элемент с
     z-index: auto рисуется в порядке отрисовки ДАЛЕЕ положительных
     z-index — то есть под ним. */
  z-index: 3;
}
/* Имя показываем только у центральной карточки (как в макете) */
.char-card:not(.char-card-center) .char-name { display: none; }

/* ---------- нижняя плашка: описание + кнопка «Играть» ---------- */
.char-bottom {
  /* Прижимаем к нижнему краю экрана (а не к низу карусели): карусель
     absolute и не занимает места в потоке, поэтому в flex-колонке её
     центрирование уводит плашку в центр экрана. */
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 3;   /* поверх absolute-карусели, иначе перекрывает кнопки */
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1dvh;
  /* Нижний отступ поднимает кнопки над краем экрана */
  padding: 6px 12px 4.5dvh;
}
.char-stats {
  position: relative;
  width: min(92vw, 1100px);
  /* Высота окна описания — доля dvh (8.5dvh ≈ 92px при 1080), чтобы нижняя
     плашка занимала одну и ту же долю кадра на любом экране. Раньше стоял
     фиксированный min-height, и на низких экранах плашка съедала место,
     которого карточкам уже не хватало. */
  min-height: 8.5dvh;
  background: url('../img/menu/character_menu/statistics_window.webp') center / 100% 100% no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1.3dvh 5.5dvh;
}
.char-stats-desc {
  color: #3a2410;
  /* Шрифт описания — доля dvh, чтобы держал масштаб вместе с плашкой. */
  font-size: clamp(11px, 1.4dvh, 15px);
  font-weight: 600;
  line-height: 1.3;
  text-align: center;
  max-width: 92%;
  /* Вертикальный зазор до рамки плашки, не сжимается при малой высоте */
  padding: 4px 0;
}
.char-actions {
  display: flex;
  gap: 1.2dvh;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

/* Кнопки экрана выбора персонажа — на плашках из img/new/button.
   Пропорции плашки 230x69 — как у кнопки «На весь экран» (.btn-fs-link),
   поэтому и размер задаём ТОТ ЖЕ: clamp(150px, 17vw, 230px). Раньше здесь
   стояло 21dvh без нижнего предела, и на мобильных кнопки схлопывались
   вдвое (79px против 150px у «На весь экран») — dvh уменьшается с высотой
   окна, а нижний предел у .btn-fs-link этого не позволял. */
.char-play-btn,
.btn-back-link {
  width: clamp(150px, 17vw, 230px);
  aspect-ratio: 230 / 69;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none !important;
  border-radius: 0 !important;
  padding: 0 !important;
  background: center / 100% 100% no-repeat !important;
  box-shadow: none !important;
  color: #fff !important;
  font-family: inherit;
  /* Кегль как у подписей кнопок главного меню (.menu-btn-label — 20px).
     Потолок clamp остаётся на 16px и срабатывает на узких экранах, где
     надпись иначе станет крупнее плашки. Кнопку «Как играть с друзьями»
     сюда намеренно НЕ включаем — её текст в 230px не влезает. */
  font-size: clamp(13px, 1.6vw, 20px) !important;
  font-weight: 900 !important;
  letter-spacing: 0.5px;
  text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
  cursor: pointer;
  transition: transform 0.1s ease, filter 0.12s ease;
}
.char-play-btn {
  background-image: url('../img/new/button/ui_button_green.webp') !important;
}
.btn-back-link {
  background-image: url('../img/new/button/ui_button_blue.webp') !important;
}
.char-play-btn:hover,
.btn-back-link:hover {
  transform: translateY(-2px);
  filter: brightness(1.08);
  background-image: url('../img/new/button/ui_button_green.webp') !important;
}
.btn-back-link:hover {
  background-image: url('../img/new/button/ui_button_blue.webp') !important;
}
.char-play-btn:active,
.btn-back-link:active {
  transform: translateY(1px) scale(0.98);
  filter: brightness(0.95);
}

/* ---------- десктоп (широкий И высокий экран) ----------
   Размер карточек больше НЕ трогаем: он задаётся в базе через 53dvh и держит
   одну пропорцию с кадром локации на любом экране. Здесь только вложения
   (картинка героя, плашка описания, шрифты) и вертикальные отступы.
   Медиазапрос оставлен по той же причине, по которой существует блок
   max-height:480px: на низких широких окнах вертикального бюджета не хватает,
   и крупные вложения наезжают на плашку. */
@media (min-width: 1200px) and (min-height: 800px) {
  /* Бокс героя на десктопе — те же 92% x 90%, что и в базе: переопределять
     нечего, размер идёт от высоты карточки (dvh) и одинаков на всех
     экранах. Раньше здесь стояло 90% x 76%, из-за чего на больших мониторах
     герой был мельче, чем на мобильных. */
  .char-card-img { width: 92%; height: 90%; }
  /* Отступ сверху под впечатанный в фон заголовок «ВЫБОР ПЕРСОНАЖА»,
     иначе карточки на него налезают. Нижний отступ сделан равным
     верхнему, чтобы карусель оставалась строго по центру экрана. */
  .char-carousel { padding-top: 30vh; padding-bottom: 30vh; align-items: center; }

  /* Кнопки «В меню»/«Играть» поднимаем над нижним краем */
  .char-bottom { padding-bottom: 6vh; }
  .char-stats {
    width: min(90vw, 1300px);
    min-height: 12dvh;
    padding: 1.7dvh 7.4dvh;
  }
  .char-stats-desc { font-size: clamp(12px, 1.7dvh, 18px); line-height: 1.32; }
  /* Кегль кнопок «Играть»/«В меню» здесь переопределять не нужно: он задан
     в базе через !important и потому всё равно перебивает обычное
     объявление из медиазапроса. */
}

/* ---------- модальное окно рейтинга ---------- */
.modal-overlay {
  display: none;
  position: fixed;
  inset: 0;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.65);
  z-index: 200;
  padding: 24px;
}
.modal-overlay.visible { display: flex; }
.modal {
  width: 100%;
  max-width: 480px;
  background: #1e293b;
  border: 1px solid #334155;
  border-radius: 16px;
  box-shadow: 0 24px 60px rgba(0, 0, 0, 0.6);
  overflow: hidden;
}
.modal-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #0f172a;
  border-bottom: 1px solid #334155;
}
.modal-title { color: #fde047; font-size: 20px; font-weight: 800; }
.modal-close {
  border: none;
  background: transparent;
  color: #94a3b8;
  font-size: 20px;
  cursor: pointer;
  line-height: 1;
  padding: 4px 8px;
  border-radius: 6px;
}
.modal-close:hover { background: #334155; color: #fff; }
.modal-body { padding: 16px 20px 20px; max-height: 70vh; overflow-y: auto; }

.rating-loading, .rating-empty, .rating-error {
  text-align: center;
  color: #94a3b8;
  padding: 24px 0;
  font-size: 15px;
}
.rating-error { color: #f87171; }


@media (max-width: 560px) {
  /* Карточка/имя/стрелка масштабируются через clamp() и % в базе. */
  .char-stats { min-height: 68px; padding: 10px 40px; }
  .char-stats-desc { font-size: 13px; line-height: 1.25; }
  /* Кегль кнопок «Играть»/«В меню» не переопределяем: в базе он объявлен
     с !important и перебивает обычное объявление из медиазапроса. */
}

/* ---------- просьба повернуть телефон (портрет на тач-устройствах) ---------- */
.rotate-notice {
  display: none;
  position: fixed;
  inset: 0;
  z-index: 1000;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 18px;
  padding: 24px;
  text-align: center;
  background-image:
    radial-gradient(circle at 50% 35%, rgba(30, 41, 59, 0.55), rgba(15, 23, 42, 0.75)),
    url('../img/screen/back_left.webp'),
    url('../img/screen/back_right.webp'),
    url('../img/menu/back_menu.webp');
  background-position:
    center,
    right calc(50vw + (8 / 9) * 100dvh) center,
    left  calc(50vw + (8 / 9) * 100dvh) center,
    center;
  background-size: auto, auto 100%, auto 100%, auto 100%;
  background-repeat: no-repeat;
}
.rotate-icon {
  font-size: 84px;
  line-height: 1;
  animation: rotateHint 2s ease-in-out infinite;
}
@keyframes rotateHint {
  0%, 60%, 100% { transform: rotate(0deg); }
  75%, 90%      { transform: rotate(-90deg); }
}
.rotate-text { color: #fde047; font-size: 24px; font-weight: 800; line-height: 1.3; }
.rotate-sub { color: #94a3b8; font-size: 15px; }

/* Показываем просьбу только на тач-устройствах в портретной ориентации.
   На таком экране прячем игру и экран выбора, чтобы не мешали. */
@media (orientation: portrait) and (pointer: coarse) {
    .rotate-notice { display: flex; }
    #app, #main-menu.visible, #mode-screen.visible, #char-screen.visible, .modal-overlay.visible { display: none !important; }
}

/* ---------- мобильные правки экрана выбора (ландшафт / низкий экран) ----------
   Телефон в игре всегда горизонтальный. Высоты мало — ужимаем карточки,
   стрелки и плашку описания, чтобы карусель, описание и кнопка «Играть»
   помещались без прокрутки. */
@media (max-height: 480px) {
    .char-screen { justify-content: center; }
    .char-carousel { gap: 0.4dvh; padding: 4vh 6px 4vh; align-content: center; }
    /* Размер карточки — из min(53dvh, 640px) в базе, поэтому на низком
       экране карточка сама пропорционально меньше. Никаких scale(): все
       пять карточек одного размера, как и кадр локации. Мобильный размер —
       следствие общей dvh-пропорции, а не отдельного коэффициента.

       Длинные имена (Капитан Барахта) не влезают в плашку при крупном кегле —
       уменьшаем шрифт и расширяем плашку, чтобы имя помещалось в одну строку. */
    /* Кегль имени в @media max-height:480px больше не переопределяем: он
       считается от ширины плашки (min(16px, 2.8dvh) в базе) и сам
       уменьшается вместе с ней. */
    /* Логотип и плашка описания — тоже в долях dvh: на низком экране места
       по вертикали мало, и фиксированные px съедали бы его целиком. */
    /* Размер логотипа в @media max-height:480px НЕ переопределяем: он считается
       в базе как min(896px, 83dvh) — полный натуральный размер там, где
       помещается, и пропорциональное уменьшение ниже. Прежнее здесь стояло
       min(30dvh, 220px), из-за чего мобильный логотип был втрое меньше
       десктопного, а не пропорцией того же ряда. */
    .char-bottom { padding: 2px 8px 3dvh; }
    .char-stats { min-height: 5.5dvh; width: min(88vw, 640px); padding: 0.6dvh 3dvh; }
    .char-stats-desc { font-size: 10px; line-height: 1.18; max-width: 96%; }
    /* Размер кнопок «Играть»/«В меню» отдельного правила не требует: он
       задан тем же clamp(150px, 17vw, 230px), что у «На весь экран», и
       потому одинаков на всех экранах. Прежние font-size/padding/
       border-radius/box-shadow здесь ничего не меняли — в базе у них
       !important с padding: 0, border-radius: 0 и box-shadow: none. */
    .char-back-btn { width: 36px; height: 36px; font-size: 16px; top: 8px; left: 8px; }
}



/* ---------- кнопка Mute ---------- */
.btn-mute {
    background: #6b7280;
    font-size: 18px;
    line-height: 1;
    padding: 6px 12px;
}
.btn-mute:hover { background: #9ca3af; }

/* ---------- кнопка Pause ---------- */
.btn-pause {
    background: #7c3aed;
    font-weight: 700;
    font-size: 18px;
    line-height: 1;
    padding: 6px 12px;
}
.btn-pause:hover { background: #8b5cf6; }

/* ---------- оверлей паузы ---------- */
.pause-overlay {
    position: fixed;
    inset: 0;
    display: none;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.75);
    z-index: 1000;
}
.pause-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    /* Высотная привязка: композиция (табличка + кнопка) примерно квадратная,
       поэтому на невысоких экранах ограничиваем шириной от dvh. */
    width: min(420px, 90vw, 80dvh);
    max-width: none;
    /* cqw-единицы: кнопка и текст масштабируются вместе с окном */
    container-type: inline-size;
}
/* Табличка «ПАУЗА» с цепями */
.pause-sign {
    width: 100%;
    aspect-ratio: 380 / 310;
    background: url('../img/new/pause/ui_pau_pause.webp') center / contain no-repeat;
}
/* Кнопка «Продолжить» — тень и фон */
.pause-btn-wrap {
    position: relative;
    width: 60%;
    margin-top: -34%;
    z-index: 1;
}
.pause-btn-shadow {
    position: absolute;
    top: 1.4cqw;
    left: 0;
    right: 0;
    height: 100%;
    background: url('../img/new/pause/ui_pau_button_sh.webp') center / 100% 100% no-repeat;
    z-index: 1;
    pointer-events: none;
}
.pause-resume {
    position: relative;
    z-index: 2;
    width: 100%;
    padding: 4.8cqw 0 5.7cqw;
    border: none;
    border-radius: 3.8cqw;
    background: url('../img/new/pause/ui_pau_button.webp') center / 100% 100% no-repeat;
    color: #5c3a1e;
    font-family: inherit;
    font-size: 5.2cqw;
    font-weight: 800;
    cursor: pointer;
    text-shadow: 0 1px 0 rgba(255,255,255,0.4);
    transition: transform 0.1s;
}
.pause-resume:hover { transform: scale(1.02); filter: brightness(1.18); }
.pause-resume:active { transform: scale(0.98); filter: brightness(0.82); }

/* ---------- кастомный confirm/alert: плашка ui_animated ---------- */
.confirm-overlay {
    position: fixed;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.7);
    z-index: 300;
}
.confirm-box {
    /* Плашка ui_exit.webp (715×436) — широкая баннерная рамка (≈1.64:1).
       aspect-ratio задаём на border-box, чтобы рамка (включая паддинг)
       совпадала с артом 1:1, без сплющивания. */
    box-sizing: border-box;
    width: min(360px, calc(100vw - 48px));
    aspect-ratio: 715 / 436;
    background: url('../img/new/exit/ui_exit.webp') center / 100% 100% no-repeat;
    border-radius: 14px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 34px 44px 18px;
    text-align: center;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.6);
    max-width: 360px;
    margin: 0 24px;
}
.confirm-text {
    color: #ffdca8;
    font-size: 16px;
    font-weight: 700;
    line-height: 1.4;
    margin-bottom: 18px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.65);
}
.confirm-row {
    display: flex;
    gap: 16px;
    justify-content: center;
    flex-wrap: wrap;
}
.confirm-yes,
.confirm-no,
.confirm-ok {
    width: 128px;
    aspect-ratio: 230 / 69;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    border-radius: 0;
    padding: 0 8px;
    background: center / 100% 100% no-repeat;
    color: #fff;
    font-family: inherit;
    font-size: 15px;
    font-weight: 900;
    text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
    cursor: pointer;
    transition: transform 0.1s ease, filter 0.12s ease;
}
.confirm-yes {
    background-image: url('../img/new/button/ui_button_green.webp');
}
.confirm-no {
    background-image: url('../img/new/button/ui_button_red.webp');
}
.confirm-ok {
    background-image: url('../img/new/button/ui_button_white.webp');
    color: #3a2410;
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.35);
}
.confirm-yes:hover,
.confirm-no:hover,
.confirm-ok:hover {
    filter: brightness(1.08);
}
.confirm-yes:active,
.confirm-no:active,
.confirm-ok:active {
    transform: translateY(1px) scale(0.98);
    filter: brightness(0.95);
}

/* ---------- кнопка Rules ---------- */
.btn-rules-link {
    background: #0891b2;
    font-size: 16px;
    padding: 10px 22px;
    font-weight: 700;
}
.btn-rules-link:hover { background: #06b6d4; }

.btn-rules {
    background: #0891b2;
    font-size: 18px;
    line-height: 1;
    padding: 6px 12px;
}
.btn-rules:hover { background: #06b6d4; }

/* ---------- модальное окно правил ---------- */
.rules-body {
    color: #e2e8f0;
    font-size: 15px;
    line-height: 1.6;
}
.rules-body h3 {
    color: #fde047;
    font-size: 18px;
    font-weight: 700;
    margin: 20px 0 10px;
}
.rules-body h3:first-child {
    margin-top: 0;
}
.rules-body p {
    margin: 8px 0;
}
.rules-body strong {
    color: #93c5fd;
    font-weight: 600;
}

/* ---------- главное меню ---------- */
.main-menu {
  display: none;
  position: fixed;
  inset: 0;
  min-height: 100dvh;
  flex-direction: column;
  align-items: center;
  /* Кадр меню по центру во всю высоту + боковые полосы поверх пустых боков */
  background-image:
    url('../img/screen/back_left.webp'),
    url('../img/screen/back_right.webp'),
    url('../img/menu/back_menu.webp');
  background-position:
    right calc(50vw + (8 / 9) * 100dvh) center,
    left  calc(50vw + (8 / 9) * 100dvh) center,
    center;
  background-size: auto 100%, auto 100%, auto 100%;
  background-repeat: no-repeat;
  z-index: 100;
  padding: 24px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain;
}
/* Экран выбора режима оставляем на прежнем фоне — меняем только главное меню */
.mode-screen {
  background-image:
    url('../img/screen/back_left.webp'),
    url('../img/screen/back_right.webp'),
    url('../img/menu/back_menu.webp');
  background-position:
    right calc(50vw + (8 / 9) * 100dvh) center,
    left  calc(50vw + (8 / 9) * 100dvh) center,
    center;
  background-size: auto 100%, auto 100%, auto 100%;
  background-repeat: no-repeat;
}
.main-menu.visible {
  display: flex;
}

.main-menu-inner {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  margin: auto 0;
}

.menu-logo {
  width: 100%;
  max-width: 640px;
  height: auto;
  margin-bottom: 20px;
  display: block;
}

.menu-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
  max-width: 840px;
}

.menu-row {
  display: flex;
  gap: 20px;
  justify-content: center;
  align-items: center;
}

.menu-row-center {
  justify-content: center;
}

.menu-btn-wrapper {
  position: relative;
  width: 400px;
  height: 80px;
  flex-shrink: 0;
}

.menu-btn-shadow {
  position: absolute;
  top: 6px;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('../img/menu/m_button_shadow.webp') center/contain no-repeat;
  z-index: 1;
  pointer-events: none;
}

.menu-btn-img {
  position: relative;
  width: 100%;
  height: 100%;
  border: none;
  cursor: pointer;
  background: transparent center/contain no-repeat;
  z-index: 2;
  transition: transform 0.1s;
  padding: 0;
  display: block;
}

/* Состояния: размер (scale) + яркость фильтром вместо отдельных картинок
   _g (высветление) / _c (затемнение). */
.menu-btn-img:hover:not(:disabled) {
  transform: scale(1.02);
  filter: brightness(1.18);
}

.menu-btn-img:active:not(:disabled) {
  transform: scale(0.98);
  filter: brightness(0.82);
}

/* Заблокированная кнопка (Турнир) */
.menu-btn-disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(0.6);
}

.menu-btn-disabled:hover {
  transform: none;
}

/* Состояния кнопок */
.menu-btn-img[data-btn="resume"] {
  background-image: url('../img/menu/m_button_new_game.webp'); /* Если нужна отдельная картинка, замените на m_button_resume.webp */
}

.menu-btn-img[data-btn="newgame"] {
  background-image: url('../img/menu/m_button_new_game.webp');
}

.menu-btn-img[data-btn="online"] {
  background-image: url('../img/menu/m_button_only.webp');
}

.menu-btn-img[data-btn="friend"] {
  background-image: url('../img/menu/m_button_frend.webp');
}

.menu-btn-img[data-btn="characters"] {
  background-image: url('../img/menu/m_button_characters.webp');
}

.menu-btn-img[data-btn="cards"] {
  background-image: url('../img/menu/m_button_cards.webp');
}

.menu-btn-img[data-btn="rating"] {
  background-image: url('../img/menu/m_button_rating.webp');
}

.menu-btn-img[data-btn="rules"] {
  background-image: url('../img/menu/m_button_rules.webp');
}

.menu-btn-img[data-btn="settings"] {
  background-image: url('../img/menu/m_button_settings.webp');
}

.menu-btn-img[data-btn="tournament"] {
  background-image: url('../img/menu/m_button_tournament.webp');
}

/* Кнопка «Назад» на экране выбора режима. Отдельной картинки в наборе нет.
   Берём рамку «Правил»: на этом экране такой кнопки нет, поэтому иконка не
   дублируется (шестерёнка читалась бы как «Настройки», а кубок — как
   соседний «Турнир»). Смысл несёт подпись «← Назад». */
.menu-btn-img[data-btn="back"] {
  background-image: url('../img/menu/m_button_rules.webp');
}

/* ---------- экран выбора режима партии ----------
   Наследует всю раскладку от .main-menu (тот же фон, сетка, кнопки),
   отдельным классом отличается только видимость: показ/скрытие делает
   showModeScreen()/hideModeScreen() в assets/ui/menu.js. */
.mode-screen { display: none; }
.mode-screen.visible { display: flex; }

/* Кнопка "На весь экран" — на красной плашке ui_button_red.
   Высоту ведём ПО брейкпоинтам от соседних кнопок (0.5 модальных .menu-btn-wrapper):
   80 → 68 (≤860) → 60 (≤720) → 56 (≤560) → 50 (ландшафт). */
.menu-btn-fs {
  /* Арт ui_button_red.webp = 230x69 (R = 3.333). Высоту задаём через
     aspect-ratio, а не числом: раньше в @media ширину держали 217px, а высоту
     урезали до 50-56px, и кнопка растягивалась (R = 4.34 и 3.88). На экране
     выбора персонажа та же кнопка сделана правильно — .btn-fs-link с
     aspect-ratio: 230 / 69. */
  width: 267px;
  aspect-ratio: 230 / 69;
  display: none;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: clamp(13px, 1.6vw, 16px);
  padding: 0;
  border-radius: 0;
  font-weight: 900;
  border: none;
  cursor: pointer;
  background: url('../img/new/button/ui_button_red.webp') center / 100% 100% no-repeat;
  color: #fff;
  transition: transform 0.12s ease, filter 0.15s ease;
}
.menu-btn-fs:hover {
  transform: translateY(-2px);
  filter: brightness(1.08);
}
.menu-btn-fs:active {
  transform: translateY(1px) scale(0.98);
  filter: brightness(0.95);
}

/* Показываем кнопку "На весь экран" на экране режимов только на touch.
   Без !important: JS сам выставляет display через style.display, и !important
   перебивал бы его проверку !Platform.isYandex (кнопка была видна, но
   не работала). На Яндекс.Играх кнопку не показываем — см. выше. */
@media (pointer: coarse) {
    html:not([data-platform="yandex"]) #btn-mode-fs {
        display: flex;
    }
}

/* Адаптив: планшеты */
@media (max-width: 860px) {
  .menu-btn-wrapper {
    width: 340px;
    height: 68px;
  }
  .menu-btn-fs { width: 227px; }
  .menu-row { gap: 12px; }
  .menu-logo { max-width: 520px; }
}

/* Адаптив: мобильные — одна колонка.
   На телефоне уменьшаем и логотип, и кнопки: строк меню стало больше
   (экран режима — 4 ряда), и в полный рост они не помещаются без прокрутки. */
@media (max-width: 720px) {
  .menu-buttons { max-width: 320px; gap: 10px; }
  .menu-row {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  .menu-btn-wrapper {
    width: 100%;
    max-width: 320px;
    height: 60px;   /* было 80px из базового правила */
  }
  .menu-btn-fs { width: 200px; }
  .menu-logo { max-width: 300px; margin-bottom: 12px; }
}

/* Низкие экраны (мобильный ландшафт) — правила ниже, в конце секции меню,
   чтобы перебивать одноимённые из блоков ≤720px/≤560px по порядку каскада.
   См. блок «@media (max-height: 480px)» после .menu-btn-label. */

/* ---------- экран лобби ---------- */
.lobby-screen {
    display: none;
    position: fixed;
    inset: 0;
    height: 100dvh;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-image:
        radial-gradient(circle at 50% 30%, rgba(30, 41, 59, 0.55), rgba(15, 23, 42, 0.75)),
        url('../img/screen/back_left.webp'),
        url('../img/screen/back_right.webp'),
        url('../img/menu/back_menu.webp');
    background-position:
        center,
        right calc(50vw + (8 / 9) * 100dvh) center,
        left  calc(50vw + (8 / 9) * 100dvh) center,
        center;
    background-size: auto, auto 100%, auto 100%, auto 100%;
    background-repeat: no-repeat;
    z-index: 100;
    padding: 24px;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
}
.lobby-screen.visible { display: flex; }

/* Панель-окно лобби: арт ui_animated (img задаёт размер), внутри — подпись и кнопки */
.lobby-panel {
    position: relative;
    flex: 0 0 auto;
    width: min(560px, 92vw, 78dvh);
    container-type: inline-size;
}
.lobby-panel-art {
    display: block;
    width: 100%;
    height: auto;
}
.lobby-panel-inner {
    position: absolute;
    inset: 0;
    box-sizing: border-box;
    padding: 18% 7% 6%;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* Заголовок лежит на верхней планке арта (как .rating-title в меню) */
.lobby-title {
    position: absolute;
    top: 8.6%;
    left: 12%;
    right: 12%;
    transform: translateY(-50%);
    text-align: center;
    color: #5b2c10;
    font-size: clamp(18px, 6cqw, 48px);
    font-weight: 900;
    letter-spacing: 0.5px;
    line-height: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    pointer-events: none;
}
.lobby-subtitle {
    color: #f3e2c0;
    font-size: clamp(12px, 2.6cqw, 18px);
    font-weight: 700;
    text-align: center;
    letter-spacing: 0.5px;
    margin: 0 0 2.5cqw;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
}

.lobby-buttons {
    display: flex;
    flex-direction: column;
    gap: 12px;
    width: 90%;
    margin-top: 4cqw;
}

/* Кнопки — арт ui_am_button (463×84), под каждой слоем тень ui_am_button_sh */
.lobby-btn {
    position: relative;
    width: 100%;
    aspect-ratio: 463 / 84;
    padding: 0;
    border: none;
    border-radius: 0;
    background: none;
    box-shadow: none;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: clamp(12px, 3.1cqw, 20px);
    font-weight: 800;
    color: #fff;
    text-shadow: 0 2px 0 rgba(60, 24, 10, 0.55);
    cursor: pointer;
    isolation: isolate;
    transition: transform 0.12s ease, filter 0.12s ease;
}
/* Тень-подложка (z-index:-2) ниже арта кнопки (z-index:-1), текст — выше */
.lobby-btn::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    aspect-ratio: 464 / 92;
    background: url('../img/new/animated_menu/ui_am_button_sh.webp') center / 100% 100% no-repeat;
    transform: translateY(8%);
    z-index: -2;
    pointer-events: none;
}
.lobby-btn::after {
    content: '';
    position: absolute;
    inset: 0;
    background: url('../img/new/animated_menu/ui_am_button.webp') center / 100% 100% no-repeat;
    z-index: -1;
    pointer-events: none;
}
.lobby-btn > .lobby-btn-label {
    position: relative;
    z-index: 1;
    color: #4A3B32;
    font-size: 20px;
    font-weight: 800;
    letter-spacing: 0.5px;
    line-height: 1.2;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.35);
}
.lobby-btn:hover { filter: brightness(1.08); }
.lobby-btn:active { transform: translateY(2px); box-shadow: none; }

/* ---------- модалка кода комнаты ---------- */
.room-code-modal,
.join-code-modal {
    position: fixed;
    inset: 0;
    display: none;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.75);
    z-index: 150;
    padding: 24px;
}
.room-code-modal.visible,
.join-code-modal.visible { display: flex; }

/* Панель «Комната создана!» — арт ui_animated, как в других окнах */
.room-code-panel { width: min(520px, 92vw, 78dvh); }
.room-code-panel .lobby-panel-inner { padding: 16% 7% 4%; }
.room-code-panel .room-code-title { font-size: clamp(16px, 4.6cqw, 34px); }

.room-code-label {
    color: #f6e7d2;
    font-size: clamp(12px, 2.8cqw, 17px);
    font-weight: 700;
    letter-spacing: 0.5px;
    margin: 0 0 1cqw;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
}
.room-code-display {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    aspect-ratio: 453 / 92;
    background: url('../img/new/mpfr/ui_roo_code.webp') center / 100% 100% no-repeat;
    text-align: center;
    font-family: 'Courier New', monospace;
    font-size: clamp(26px, 9cqw, 44px);
    font-weight: 900;
    letter-spacing: 6px;
    color: #fde047;
    padding: 0 1.4cqw;
    min-width: 0;
    margin: 0 0 1.5cqw;
}
/* Строка «код + кнопка копирования» — кнопка правее кода */
.room-code-row {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 2cqw;
    margin: 0 0 1.5cqw;
}
.room-code-row .room-code-display {
    flex: 0 1 auto;
    width: min(240px, 100%);
    min-width: 0;
    margin: 0;
}
/* Кнопка копирования: иконочный арт ui_roo_copy (86×91),
   тень ui_roo_copy_sh (86×93) лежит под ним */
.room-code-copy {
    position: relative;
    z-index: 0;
    flex: 0 0 auto;
    width: clamp(44px, 12cqw, 58px);
    aspect-ratio: 86 / 91;
    border: none;
    border-radius: 0;
    padding: 0;
    background: none;
    cursor: pointer;
    transition: transform 0.1s ease, filter 0.12s ease;
}
.room-code-copy::before {
    content: "";
    position: absolute;
    inset: 0;
    background: url('../img/new/mpfr/ui_roo_copy.webp') center / 100% 100% no-repeat;
}
.room-code-copy::after {
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    top: 3%;
    bottom: -4%;
    background: url('../img/new/mpfr/ui_roo_copy_sh.webp') center / 100% 100% no-repeat;
    z-index: -1;
    pointer-events: none;
}
.room-code-copy:hover { filter: brightness(1.12); }
.room-code-copy:active { transform: translateY(1px) scale(0.97); }
.room-code-copy.copied { filter: brightness(1.3); }
.room-code-hint {
    color: #cbb489;
    font-size: clamp(11px, 2.6cqw, 15px);
    line-height: 1.35;
    margin: 1.2cqw 0 0;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
}
.room-wait-count {
    color: #f3e2c0;
    font-size: clamp(13px, 3cqw, 18px);
    font-weight: 700;
    margin-top: 2.4cqw;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
}

/* Кнопка «Отмена» — плашка ui_button_red (230×69) */
.room-code-cancel {
    width: 150px;
    aspect-ratio: 230 / 69;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 2.6cqw;
    border: none;
    border-radius: 0;
    padding: 0 8px;
    background: url('../img/new/button/ui_button_red.webp') center / 100% 100% no-repeat;
    color: #fff;
    font-family: inherit;
    font-size: clamp(12px, 3cqw, 16px);
    font-weight: 900;
    text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
    cursor: pointer;
    transition: transform 0.1s ease, filter 0.12s ease;
}
.room-code-cancel:hover { filter: brightness(1.08); }
.room-code-cancel:active { transform: translateY(1px) scale(0.98); filter: brightness(0.95); }

/* ---------- модалка ввода кода: панель ui_animated, без крестика ---------- */
.join-code-panel { width: min(520px, 92vw, 78dvh); }
.join-code-panel .lobby-panel-inner { padding: 17% 7% 5%; }
.join-code-panel .lobby-title { font-size: clamp(16px, 4.6cqw, 34px); }
.join-code-panel .lobby-buttons { margin-top: 2cqw; }

.join-code-label {
    color: #f3e2c0;
    font-size: clamp(12px, 2.6cqw, 18px);
    font-weight: 700;
    text-align: center;
    letter-spacing: 0.5px;
    margin: 2cqw 0 1cqw;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
}

.join-wait-count {
    display: none;
    margin-top: 1cqw;
    color: #f3e2c0;
    font-size: clamp(14px, 3cqw, 20px);
    font-weight: 700;
    text-align: center;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
}
.join-code-modal.join-waiting .join-code-title { margin-bottom: 8px; }
.join-code-modal.join-waiting .join-code-label,
.join-code-modal.join-waiting .join-code-input,
.join-code-modal.join-waiting .join-code-paste,
.join-code-modal.join-waiting .join-code-confirm { display: none; }
.join-code-modal.join-waiting .join-wait-count { display: block; }

.join-code-input {
    width: 76%;
    box-sizing: border-box;
    font-size: clamp(18px, 5cqw, 34px);
    font-weight: 800;
    text-align: center;
    text-transform: uppercase;
    padding: 1.4cqw 2cqw;
    border-radius: 10px;
    border: 2px solid #8a5a2b;
    background: rgba(255, 248, 230, 0.94);
    color: #4a2c12;
    margin: 0.5cqw 0;
    font-family: 'Courier New', monospace;
    letter-spacing: 4px;
}
.join-code-input:focus {
    outline: none;
    border-color: #d9a441;
    box-shadow: 0 0 0 2px rgba(217, 164, 65, 0.45);
}
.join-code-input::placeholder {
    color: #b08a5e;
    letter-spacing: 2px;
}

/* Кнопки — общий арт .lobby-btn, поэтому фон не задаём */
.join-code-paste:disabled {
    cursor: not-allowed;
    opacity: 0.5;
}
.join-code-paste:disabled:hover { filter: none; }

/* Адаптив для модалки входа в комнату: кнопки не влезали в окно-картинку.
   Высоту кнопок задаём в cqw — она масштабируется вместе с панелью на любом
   экране и заметно ниже исходной пропорции 463/84 (≈18% ширины панели). */
.join-code-panel .lobby-btn { aspect-ratio: auto; height: 11cqw; }
.join-code-panel .lobby-btn::before { aspect-ratio: auto; height: 11.6cqw; }
.join-code-panel .lobby-buttons { gap: 1.4cqw; }

@media (max-width: 560px) {
    .join-code-panel { width: min(460px, 92vw, 80dvh); }
    .join-code-panel .lobby-panel-inner { padding: 17% 7% 4%; }
    .join-code-panel .lobby-title { font-size: clamp(13px, 4.2cqw, 26px); }
    .join-code-label { margin: 1cqw 0 0.6cqw; }
    .join-code-input { font-size: 18px; padding: 1.2cqw 2cqw; margin: 0.4cqw 0; }
}
@media (pointer: coarse) and (max-height: 480px) {
    .join-code-panel { width: min(440px, 90vw, 82dvh); }
    .join-code-panel .lobby-panel-inner { padding: 15% 7% 3%; }
    .join-code-label { margin: 0.8cqw 0 0.4cqw; }
    .join-code-input { font-size: 16px; padding: 0.8cqw 2cqw; }
    .join-wait-count { margin-top: 0.6cqw; }
}

/* Адаптив для лобби */
@media (pointer: coarse) and (max-height: 480px) {
    .lobby-panel { width: min(480px, 90vw, 82dvh); }
    .lobby-panel-inner { padding: 17% 7% 5%; }
    .lobby-buttons { gap: 8px; }
    .room-code-display { font-size: 36px; padding: 12px; }
    .join-code-input { font-size: 24px; padding: 12px; }
}

@media (max-width: 560px) {
    .lobby-panel { width: min(520px, 96vw, 80dvh); }
    .room-code-display { font-size: 40px; }
}

/* ---------- адаптив «Комната создана» ----------
   Элементы вылезали за нижнюю рамку окна — ужимаем код-блок, подписи
   и «Отмена». Идёт после адаптивов лобби, чтобы перекрыть
   .room-code-display { font-size: 40px }. */

@media (max-width: 560px) {
    .room-code-panel { width: min(520px, 96vw, 92dvh); }
    .room-code-panel .lobby-panel-inner { padding: 12% 7% 3%; }
    .room-code-row .room-code-display { width: min(150px, 100%); }
    .room-code-panel .room-code-title { font-size: clamp(14px, 4.2cqw, 28px); }
    .room-code-display { font-size: 28px; letter-spacing: 4px; padding: 1cqw 2cqw; margin: 0 0 1cqw; }
    .room-code-label { margin: 0 0 0.6cqw; }
    .room-code-hint { margin-top: 0.8cqw; font-size: 12px; }
    .room-wait-count { margin-top: 0.6cqw; }
    .room-code-cancel { width: 120px; margin-top: 0.3cqw; }
}
@media (pointer: coarse) and (max-height: 480px) {
    .room-code-panel { width: min(500px, 94vw, 88dvh); }
    .room-code-panel .lobby-panel-inner { padding: 12% 7% 2%; }
    .room-code-row .room-code-display { width: min(150px, 100%); }
    .room-code-display { font-size: 26px; letter-spacing: 3px; padding: 0.8cqw 2cqw; }
    .room-code-hint { font-size: 11px; }
    .room-wait-count { margin-top: 0.6cqw; }
    .room-code-cancel { width: 110px; margin-top: 0.3cqw; }
}

.btn-menu { background: #7c3aed; font-weight: 600; }
.btn-menu:hover { background: #8b5cf6; }

/* ---------- кнопка справки мультиплеера на экране выбора ---------- */
.btn-mp-help {
    width: clamp(150px, 17vw, 230px);
    aspect-ratio: 230 / 69;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none !important;
    border-radius: 0 !important;
    padding: 0 !important;
    background: url('../img/new/button/ui_button_white.webp') center / 100% 100% no-repeat !important;
    box-shadow: none !important;
    color: #3a2410 !important;
    font-size: clamp(13px, 1.6vw, 16px) !important;
    font-weight: 800 !important;
    line-height: 1.2 !important;
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.35);
    order: -1; /* размещаем ПЕРЕД "Выход в меню" (слева) */
    transition: transform 0.1s ease, filter 0.12s ease;
}
.btn-mp-help:hover {
    transform: translateY(-2px);
    filter: brightness(1.06);
}

/* Подсказка "ИГРА С ДРУГОМ" над списком персонажей */
.lobby-title-hint {
    color: #facc15;
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 3px;
    text-transform: uppercase;
    margin-top: 18px;
    padding: 6px 14px;
    border: 1px dashed rgba(250, 204, 21, 0.4);
    border-radius: 8px;
    background: rgba(250, 204, 21, 0.06);
}

/* ---------- ожидание реванша в финальном оверлее ---------- */
.over-rematch-status {
    margin: 12px 0 16px;
    padding: 12px 16px;
    border-radius: 10px;
    background: #f1f5f9;
    border: 1px dashed #94a3b8;
}
.rematch-text {
    color: #334155;
    font-size: 15px;
    font-weight: 600;
    text-align: center;
    animation: rematchPulse 1.6s ease-in-out infinite;
}
.rematch-text.rematch-both {
    color: #059669;
    animation: none;
    font-weight: 800;
}
.rematch-text.rematch-opp {
    color: #b45309;
}
@keyframes rematchPulse {
    0%, 100% { opacity: 1; }
    50%      { opacity: 0.55; }
}

/* Disabled-кнопка «Сыграть ещё» после нажатия */
.over-again.disabled,
.over-again:disabled {
    background: #9ca3af;
    cursor: not-allowed;
    opacity: 0.85;
}
.over-again.disabled:hover,
.over-again:disabled:hover {
    background: #9ca3af;
}

/* ---------- модалка выбора стиля карт ---------- */
/* ==========================================================================
   Окно «Стиль карт» на арте (img/new/style_card). Слоты-плитки с парой карт,
   выбранный подсвечен золотом, незанятые слоты — силуэт «???????».
   Сетка сама растёт при добавлении новых стилей в manifest.json.
   ========================================================================== */

.cards-box {
    position: relative;
    /* Пропорции арта окна 958x972 сохраняем при любом размере экрана */
    height: min(760px, calc((100dvh - 24px) * 0.92), calc((100vw - 24px) * 972 / 958));
    width: auto;
    aspect-ratio: 958 / 972;
    background: url('../img/new/style_card/ui_sc_style_card.webp') center / 100% 100% no-repeat;
    display: flex;
    flex-direction: column;
    /* cqw-единицы считаются от ширины окна — подписи масштабируются с ним */
    container-type: inline-size;
}

/* --- шапка: заголовок на планке + крестик --- */
.cards-titlebar {
    position: relative;
    flex: 0 0 auto;
    height: 12.2%;
    display: flex;
    align-items: center;
    justify-content: center;
    /* Слева на арте закладка с картами, справа крестик */
    padding: 0 12% 0 11%;
}

.cards-title {
    color: #5b2c10;
    font-size: clamp(15px, 4cqw, 40px);
    font-weight: 900;
    letter-spacing: 0.5px;
    line-height: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.cards-close {
    position: absolute;
    top: 55%;
    right: 4%;
    transform: translateY(-50%);
    width: 6.6%;
    aspect-ratio: 1;
    padding: 0;
    background: none;
    isolation: isolate;
    border: none;
    border-radius: 50%;
    font-size: 0;
    color: transparent;
    cursor: pointer;
    transition: transform 0.12s ease, filter 0.12s ease;
}

/* Подложка ui_x_back выходит за края кнопки (она крупнее ui_x на ~27%):
   обычный background-size >100% обрезался бы боксом кнопки, поэтому
   подложка — отдельный ::before с отрицательным inset (z-index 0).
   isolation на кнопке держит оба слоя поверх модалки. */
.cards-close::before,
.settings-close::before,
.char-detail-close::before,
.rating-close::before,
.rules-close::before,
.player-count-close::before {
    content: '';
    position: absolute;
    inset: -13.5%;
    background: url('../img/new/x/ui_x_back.webp') center / contain no-repeat;
    z-index: 0;
    pointer-events: none;
}

/* Сам крестик — ::after (z-index 1) поверх подложки: в собственном
   стекинг-контексте кнопки отрицательный z-index относительно её фона
   не работает, поэтому крестик отдельным слоем. */
.cards-close::after,
.settings-close::after,
.char-detail-close::after,
.rating-close::after,
.rules-close::after,
.player-count-close::after {
    content: '';
    position: absolute;
    inset: 0;
    background: url('../img/new/x/ui_x.webp') center / contain no-repeat;
    z-index: 1;
    pointer-events: none;
}

/* При наведении подсвечиваем ТОЛЬКО крестик (::after), подложка
   ui_x_back остаётся в исходной яркости. */
.cards-close:hover::after,
.settings-close:hover::after,
.char-detail-close:hover::after,
.rating-close:hover::after,
.rules-close:hover::after,
.player-count-close:hover::after {
    filter: brightness(1.1);
}

.cards-close:hover {
    transform: translateY(-50%) scale(1.06);
}

.cards-close:active {
    transform: translateY(-50%) scale(0.95);
}

/* --- тело окна: сетка слотов + верёвочная полоса --- */
.cards-inner {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    gap: 2%;
    /* Сетка стоит по центру окна: левый отступ компенсирует верёвочную
       полосу справа (3.6% + gap 2%), чтобы центр сетки совпадал с
       центром окна, а не уезжал влево. */
    padding: 2.4% 7.6% 5% 13.2%;
}

.cards-box .card-sets-grid {
    flex: 1 1 auto;
    min-width: 0;
    display: grid;
    /* Ровно 2 колонки — совпадает с CARDS_GRID_COLS в screens.js */
    grid-template-columns: repeat(2, 1fr);
    align-content: start;
    gap: 2.5%;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 4px;
    /* Родная полоса скрыта — рисуем свою справа (.cards-sb) */
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.cards-box .card-sets-grid::-webkit-scrollbar {
    width: 0;
    height: 0;
    display: none;
}

/* --- слот стиля --- */
.cards-box .card-set-card {
    position: relative;
    /* Подложка слота; у выбранного её заменяет золотая версия */
    background: url('../img/new/style_card/ui_sc_back_card.webp') center / 100% 100% no-repeat;
    border: none;
    border-radius: 0;
    padding: 7% 5% 6%;
    margin: 0;
    cursor: pointer;
    text-align: center;
    transition: transform 0.12s ease, filter 0.12s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 6%;
    /* Слот тянется по содержимому: иначе подпись упиралась в нижний край */
    aspect-ratio: 356 / 324;
}

.cards-box .card-set-card:hover {
    transform: translateY(-2px);
    filter: brightness(1.06);
    background: url('../img/new/style_card/ui_sc_back_card.webp') center / 100% 100% no-repeat;
    border: none;
}

/* Выбранный стиль: золотая подложка + свечение под картами */
.cards-box .card-set-card.active {
    background: url('../img/new/style_card/ui_sc_glow_back_card.webp') center / 100% 100% no-repeat;
    border: none;
    box-shadow: none;
}

.cards-box .card-set-card:active {
    transform: scale(0.985);
}

/* Пара карт стиля — одна готовая картинка (styleArt) или силуэт */
.card-set-art {
    position: relative;
    z-index: 1;
    width: 74%;
    aspect-ratio: 335 / 275;
    background-position: center;
    background-repeat: no-repeat;
    background-size: contain;
}

/* Свечение под картами выбранного стиля (ui_sc_glow_card).
   Рисуем отдельным слоем на самом слоте: ::before у .card-set-art
   с z-index:-1 оказался бы ПОВЕРХ его же фоновой картинки. */
.cards-box .card-set-card.active::before {
    content: '';
    position: absolute;
    top: 6%;
    left: 50%;
    width: 92%;
    aspect-ratio: 456 / 385;
    transform: translateX(-50%);
    background: url('../img/new/style_card/ui_sc_glow_card.webp') center / contain no-repeat;
    z-index: 0;
    pointer-events: none;
}

.cards-box .card-set-label {
    position: relative;
    z-index: 2;
    color: #fff;
    font-size: clamp(11px, 2.8cqw, 26px);
    font-weight: 900;
    line-height: 1.1;
    text-shadow: 0 2px 0 rgba(50, 20, 8, 0.55);
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    max-width: 100%;
}

/* Выбранный — жёлтая подпись, как на макете */
.cards-box .card-set-card.active .card-set-label {
    color: #ffd23f;
}

/* Слот-заглушка: не кликается, силуэт слегка приглушён */
.cards-box .card-set-card.is-locked {
    cursor: default;
    pointer-events: none;
}

.cards-box .card-set-card.is-locked:hover {
    transform: none;
    filter: none;
}

/* --- верёвочный скроллбар окна стилей --- */
/* Насколько слой каната выходит за ложе под стрелки. Вырез в основании
   стрелки глубиной ~3 px (от 37 px арта это 7–19 %), а срез каната уходит
   на 6 px — он оказывается под непрозрачной частью стрелки, поэтому
   виден только сам заход каната в вырез, без разрыва и без «обрезка». */
.cards-sb,
.char-detail-sb,
.rating-sb,
.rules-sb {
    --sb-join: 6px;
}

.cards-sb {
    flex: 0 0 auto;
    width: 3.6%;
    min-width: 14px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.cards-sb.is-hidden {
    visibility: hidden;
}

.cards-sb-up,
.cards-sb-down {
    flex: 0 0 auto;
    width: 100%;
    aspect-ratio: 43 / 37;
    padding: 0;
    border: none;
    background: center / contain no-repeat;
    cursor: pointer;
    transition: filter 0.12s ease, transform 0.12s ease;
    /* Выше слоя каната (см. .rules-sb-track::before). */
    position: relative;
    z-index: 2;
}

.cards-sb-up {
    background-image: url('../img/new/scroll/ui_arrow_up.webp');
}

.cards-sb-down {
    background-image: url('../img/new/scroll/ui_arrow_down.webp');
}

.cards-sb-up:hover,
.cards-sb-down:hover {
    filter: brightness(1.12);
}

.cards-sb-up:active,
.cards-sb-down:active {
    transform: scale(0.92);
}

.cards-sb-track {
    position: relative;
    z-index: 0;
    flex: 1 1 auto;
    width: 100%;
    min-height: 0;
    /* Без вертикального margin: он укорачивал ход бегунка
       относительно видимой верёвки — на краях оставался зазор. */
    cursor: pointer;
    touch-action: none;
}

/* Канат — отдельный слой, который заходит под стрелки (см. .rules-sb-track). */
.cards-sb-track::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: calc(-1 * var(--sb-join));
    bottom: calc(-1 * var(--sb-join));
    z-index: 0;
    pointer-events: none;
    /* Бесшовный тайл, общий для всех лож: один период узора, поэтому
       repeat-y без разрыва и без растяжения витков. */
    background-image: url('../img/new/scroll/ui_arrow_scroll_b_seamless.webp'), url('../img/new/scroll/ui_arrow_scroll_b_sh_seamless.webp');
    background-repeat: repeat-y, repeat-y;
    background-position: center top, center top;
    background-size: 50% auto, 50% auto;
}

.cards-sb-thumb {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    /* Выше слоя каната: бегунок — узел, он должен лежать поверх верёвки. */
    z-index: 1;
    /* Ползунок — общий узел ui_arrow_scroll_a (47x72) в натуральной пропорции.
       aspect-ratio держит ту же пропорцию у бокса: иначе contain центрировал
       картинку в блоке произвольной высоты и на краях оставались зазоры.
       Высоту JS не навязывает — только измеряет, transform сдвигает. */
    aspect-ratio: 47 / 72;
    background: url('../img/new/scroll/ui_arrow_scroll_a.webp') center / contain no-repeat;
    cursor: grab;
}

.cards-sb-thumb:active {
    cursor: grabbing;
    filter: brightness(0.95);
}

/* ---------- модалка поиска соперника ---------- */
/* Затемнённый back_menu как фон всего оверлея */
.matchmaking-modal {
    background-image:
        radial-gradient(circle at 50% 40%, rgba(15, 23, 42, 0.68), rgba(8, 12, 20, 0.9)),
        url('../img/screen/back_left.webp'),
        url('../img/screen/back_right.webp'),
        url('../img/menu/back_menu.webp');
    background-position:
        center,
        right calc(50vw + (8 / 9) * 100dvh) center,
        left  calc(50vw + (8 / 9) * 100dvh) center,
        center;
    background-size: auto, auto 100%, auto 100%, auto 100%;
    background-repeat: no-repeat;
}

.matchmaking-panel {
    display: flex;
    flex-direction: column;
    align-items: center;
    /* Ширина — ровно как у панелей лобби (.lobby-panel), чтобы кнопка
       «Отмена» вышла того же размера. Раньше стоял потолок 520px против 560px
       у эталона, и кнопка была на 31px уже. Высоту панели задаёт содержимое:
       арта .lobby-panel-art здесь нет, так что ширину можно брать свободно. */
    width: min(560px, 92vw, 78dvh);
    container-type: inline-size;
    text-align: center;
}

.matchmaking-title {
    color: #f3e2c0;
    font-size: clamp(24px, 4.6vw, 42px);
    font-weight: 900;
    letter-spacing: 0.5px;
    line-height: 1.05;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.7);
}

.matchmaking-subtitle {
    margin-top: 6px;
    color: #cbb489;
    font-size: clamp(14px, 2.4vw, 20px);
    font-weight: 700;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7);
}

.matchmaking-status {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    margin: 22px 0 10px;
}

.matchmaking-spinner {
    width: 48px;
    height: 48px;
    border: 4px solid rgba(250, 204, 21, 0.2);
    border-top-color: #facc15;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.matchmaking-text {
    color: #cbb489;
    font-size: 16px;
    font-weight: 600;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7);
}

.matchmaking-text span {
    color: #fde047;
    font-weight: 800;
}

.matchmaking-hint {
    color: #9aa7b8;
    font-size: 13px;
    margin: 0 0 22px;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7);
}
/* Кнопка «Отмена» здесь — .lobby-btn, а та тянется на 100% ширины. Задаём ей
   ровно ту же долю, что и у кнопок в окне «Игра с друзьями», на десктопе и
   на мобильных.

   Путь до кнопки в эталоне: панель -> .lobby-panel-inner с боковым
   padding 7% (остаётся 86%) -> .lobby-buttons 90% -> кнопка 100%.
   Итого 0.86 * 0.9 = 77.4% панели.

   У .matchmaking-panel нет .lobby-panel-inner — это flex-колонка напрямую,
   поэтому процент задаём от самой панели. Панель поиска уже, чем панель
   лобби на телефонах (92vw против 96vw), поэтому в @media ниже доля
   поднята до 80.8% — иначе кнопка вышла бы на 12-13px уже эталона.
   Дальше 80.8% не поднимаем: панель поиска узкая, и кнопка «Отмена»
   вторична, её размах должен оставаться в пределах панели.

   align-items: center у .matchmaking-panel уже есть, кнопка центрируется
   сама. */
/* Кнопка «Отмена» здесь — .lobby-btn, а та тянется на 100% ширины. Задаём ей
   ровно ту же долю, что и у кнопок в окне «Игра с друзьями», — на всех
   экранах сразу, без breakpoint'ов.

   Путь до кнопки в лобби: панель -> .lobby-panel-inner с боковым padding 7%
   (остаётся 86%) -> .lobby-buttons 90% -> кнопка 100%.
   Итого 0.86 * 0.9 = 77.4% панели.

   У .matchmaking-panel нет .lobby-panel-inner — это flex-колонка напрямую,
   поэтому процент задаём от самой панели. Панели одинаковой ширины
   (min(560px, 92vw, 78dvh) у обеих), так что доли совпадают всюду: и на
   десктопе (433px), и на телефоне в ландшафте (217-235px).

   Потолок 463px — натуральная ширина картинки ui_am_button. При панели в
   560px он не срабатывает (77.4% даёт 433px) и оставлен как страховка на
   случай, если панель когда-нибудь станет шире.

   Раньше здесь стояло min(463px, 43dvh) — привязка к натуральному размеру
   арта. На десктопе кнопка «дышала»: 463px на 1080p и 310px на 720p, то
   есть на низких ноутбуках была на 100+px уже кнопок лобби. Привязка к dvh
   вообще не доходила до телефонов: игра живёт только в ландшафте
   (в портрете .rotate-notice, см. @media orientation: portrait), и на
   844x390 панель узкая (304px), поэтому 43dvh = 168px против 235px у лобби. */
.matchmaking-panel .lobby-btn {
    width: min(463px, 77.4%);
    flex: 0 0 auto;
}

/* На низких экранах уменьшаем размер кнопки справки до размера
   соседних кнопок «В меню»/«Играть» (150px) */
@media (pointer: coarse) and (max-height: 480px) {
    .btn-mp-help {
        width: clamp(110px, 40vw, 150px);
        font-size: 14px;
    }
}

/* ==========================================================================
   Окно «Настройки» на арте (img/new/settings). Профиль на свитке с
   карандашом, звук и музыка — иконка + ползунок + выключатель.
   ========================================================================== */

.settings-box {
    position: relative;
    /* Пропорции арта окна 716x630 сохраняем при любом размере экрана */
    height: min(500px, calc((100dvh - 24px) * 0.78), calc((100vw - 24px) * 630 / 716));
    width: auto;
    aspect-ratio: 716 / 630;
    background: url('../img/new/settings/ui_set_settings.webp') center / 100% 100% no-repeat;
    display: flex;
    flex-direction: column;
    /* cqw-единицы считаются от ширины окна — подписи масштабируются с ним */
    container-type: inline-size;
}

/* --- шапка: заголовок на планке + крестик --- */
.settings-titlebar {
    position: relative;
    flex: 0 0 auto;
    height: 16.5%;
    display: flex;
    align-items: center;
    justify-content: center;
    /* Слева на арте закладка с шестерёнкой, справа крестик */
    padding: 0 12% 0 13%;
}

.settings-title {
    color: #5b2c10;
    font-size: clamp(15px, 4.6cqw, 42px);
    font-weight: 900;
    letter-spacing: 0.5px;
    line-height: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.settings-close {
    position: absolute;
    top: 60%;
    right: 4%;
    transform: translateY(-50%);
    width: 8.4%;
    aspect-ratio: 1;
    padding: 0;
    background: none;
    isolation: isolate;
    border: none;
    border-radius: 50%;
    font-size: 0;
    color: transparent;
    cursor: pointer;
    transition: transform 0.12s ease, filter 0.12s ease;
}

.settings-close:hover {
    transform: translateY(-50%) scale(1.06);
}

.settings-close:active {
    transform: translateY(-50%) scale(0.95);
}

/* --- тело окна --- */
.settings-inner {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    flex-direction: column;
    gap: 3.5cqw;
    padding: 2% 10% 7% 10.5%;
    overflow-y: auto;
    /* Родная полоса не нужна: содержимое влезает целиком */
    scrollbar-width: none;
}

.settings-inner::-webkit-scrollbar {
    width: 0;
    display: none;
}

.settings-section-title {
    color: #fff;
    font-size: clamp(13px, 3.8cqw, 34px);
    font-weight: 900;
    line-height: 1;
    text-shadow: 0 2px 0 rgba(60, 24, 10, 0.55);
}

/* Заголовки «ЗВУК»/«МУЗЫКА» — отступ слева как у иконок (у «ПРОФИЛЬ»
   собственный отступ в .settings-head-content ниже). */
.settings-section > .settings-section-title {
    margin-left: 1.5cqw;
}

/* --- профиль --- */
.settings-section-head {
    display: flex;
    align-items: center;
    gap: 2.4cqw;
    margin-bottom: 2cqw;
}

/* Аватар-заглушка впечатан в арт окна — своей картинки не рисуем,
   просто резервируем под него место слева от подписи. */
.settings-profile-icon {
    width: 15%;
    aspect-ratio: 106 / 78;
    flex: 0 0 auto;
}

/* Надпись «ПРОФИЛЬ» — правее и чуть ниже относительно строки заголовка */
.settings-profile .settings-section-title {
    margin-left: 4cqw;
    transform: translateY(2.8cqw);
}

.settings-profile-row {
    display: flex;
    align-items: center;
    gap: 2.6cqw;
    margin-top: 5cqw;
}

/* Свиток с именем. Отступ 100px задан в координатах макета (окно 716px).
   .settings-inner уже даёт слева 10.5%, поэтому добавляем только разницу:
   100/716 = 13.97% минус 10.5% ≈ 3.5% ширины окна.
   flex:1 — свиток растягивается вправо до карандаша; карандаш тогда
   заканчивается ровно там же, где правые края выключателей вкл/выкл. */
.settings-name-plate {
    flex: 1 1 auto;
    min-width: 0;
    margin-left: 0;   /* пластина прижата к левому краю строки */
    position: relative;
    z-index: 0;   /* контекст для тени ::before (z-index:-1) */
    aspect-ratio: 463 / 84;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* Тень пластины ui_set_profile_sh — рисуется до арта (z-index:-1), выступ вниз */
.settings-name-plate::before {
    content: '';
    position: absolute;
    inset: 0;
    background: url('../img/new/settings/ui_set_profile_sh.webp') center / 100% 100% no-repeat;
    transform: translateY(7%);
    z-index: -1;
    pointer-events: none;
}

/* Арт пластины ui_set_profile — поверх тени */
.settings-name-plate::after {
    content: '';
    position: absolute;
    inset: 0;
    background: url('../img/new/settings/ui_set_profile.webp') center / 100% 100% no-repeat;
    z-index: 0;
    pointer-events: none;
}

.settings-name-input {
    position: relative;
    z-index: 1;   /* поверх арта-псевдо ::after пластины */
    width: 84%;
    border: none;
    background: transparent;
    text-align: center;
    color: #5b2c10;
    font-family: inherit;
    font-size: clamp(15px, 4.8cqw, 46px);
    font-weight: 900;
    letter-spacing: 0.5px;
    padding: 0;
    /* Поле «заблокировано» до нажатия карандаша — но должно читаться
       как обычный текст, а не как выключенный инпут. */
    opacity: 1;
    -webkit-text-fill-color: #5b2c10;
}

.settings-name-input:focus {
    outline: none;
}

.settings-name-input:disabled {
    cursor: default;
}

/* Карандаш «изменить». В режиме правки подсвечивается. */
.settings-edit-btn {
    flex: 0 0 auto;
    width: 11%;
    aspect-ratio: 1;
    padding: 0;
    border: none;
    position: relative;
    z-index: 0;   /* контекст для тени ::before */
    background: none;
    cursor: pointer;
    font-size: 0;
    color: transparent;
    transition: transform 0.12s ease, filter 0.12s ease;
}

/* Тень карандаша ui_set_edit_sh — до арта ::after (z-index:-1) */
.settings-edit-btn::before {
    content: '';
    position: absolute;
    inset: 0;
    opacity: 0.65;
    background: url('../img/new/settings/ui_set_edit_sh.webp') center / contain no-repeat;
    transform: translateY(9%);
    z-index: -1;
    pointer-events: none;
}

/* Арт карандаша ui_set_edit — поверх тени */
.settings-edit-btn::after {
    content: '';
    position: absolute;
    inset: 0;
    background: url('../img/new/settings/ui_set_edit.webp') center / contain no-repeat;
    z-index: 0;
    pointer-events: none;
}

.settings-edit-btn:hover {
    transform: scale(1.08);
    filter: brightness(1.1);
}

.settings-edit-btn:active {
    transform: scale(0.94);
}

.settings-edit-btn.editing {
    filter: drop-shadow(0 0 6px rgba(255, 210, 63, 0.9)) brightness(1.12);
}

.settings-edit-btn.saved {
    filter: drop-shadow(0 0 7px rgba(74, 222, 128, 0.95)) brightness(1.15);
}

/* --- строка «иконка + ползунок + выключатель» --- */
.settings-row {
    display: flex;
    align-items: center;
    gap: 2.6cqw;
    margin-top: 1.6cqw;
}

.settings-icon {
    flex: 0 0 auto;
    position: relative;
    z-index: 0;   /* контекст для тени ::before */
    margin-left: 1.5cqw;   /* отступ от левого края строки */
}

/* Обе иконки в одном размере бокса (11% ширины строки, соотношение 72/58):
   арт ui_set_sound (72x58) заполняет бокс точно, ui_set_music (57x62) —
   по высоте; тени и сдвиг при этом совпадают. */
.settings-icon-sound,
.settings-icon-music {
    width: 11%;
    aspect-ratio: 72 / 58;
}

/* Арт иконок ui_set_sound/ui_set_music — поверх тени ::before */
.settings-icon::after {
    content: '';
    position: absolute;
    inset: 0;
    background-position: center;
    background-repeat: no-repeat;
    background-size: contain;
    z-index: 0;
    pointer-events: none;
}

.settings-icon-sound::after {
    background-image: url('../img/new/settings/ui_set_sound.webp');
}

.settings-icon-music::after {
    background-image: url('../img/new/settings/ui_set_music.webp');
}

/* Тени иконок — до арта (z-index:-1). Боксы иконок теперь одного размера,
   поэтому общий translateY(12%) даёт одинаковый сдвиг у обеих. */
.settings-icon-sound::before {
    content: '';
    position: absolute;
    inset: 0;
    opacity: 0.65;
    background: url('../img/new/settings/ui_set_sound_sh.webp') center / contain no-repeat;
    transform: translateY(12%);
    z-index: -1;
    pointer-events: none;
}

.settings-icon-music::before {
    content: '';
    position: absolute;
    inset: 0;
    opacity: 0.65;
    background: url('../img/new/settings/ui_set_music_sh.webp') center / contain no-repeat;
    transform: translateY(12%);
    z-index: -1;
    pointer-events: none;
}

/* --- ползунок громкости --- */
.settings-slider-wrap {
    position: relative;
    flex: 1 1 auto;
    min-width: 0;
    max-width: 64%;   /* слайдер чуть короче */
    display: flex;
    align-items: center;
}

/* Зелёная заливка слева — прогрессбар громкости. Правый край заливки
   рисуется ровно по центру ромба (width ставит paintSlider() в px — --fill-px),
   поэтому заливка всегда остаётся под ромбом, не вылезая ни левее, ни правее. */
.settings-slider-wrap::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    width: var(--fill-px, 0px);
    height: 3.4cqw;
    transform: translateY(-50%);
    background: url('../img/new/settings/ui_set_slider_a.webp') left center / auto 100% repeat-x;
    border-radius: 2px;
    pointer-events: none;
    z-index: 2;
}

.settings-slider {
    -webkit-appearance: none;
    appearance: none;
    position: relative;
    z-index: 1;   /* ложе выше тени-подложки (.settings-slider-shadow z-index:0) */
    width: 100%;
    height: 4.6cqw;
    margin: 0;
    background: transparent;
    cursor: pointer;
}

/* Дорожка: тёмное ложе ui_set_slider_back слегка короче рамки
   ui_set_slider_back_tr (::after выше) — отступает от краёв по бокам.
   Заливка — сине-зелёный маркер ui_set_slider_a в ::before обёртки. */
.settings-slider::-webkit-slider-runnable-track {
    height: 100%;
    background: url('../img/new/settings/ui_set_slider_back.webp') center / calc(100% - 1cqw) 100% no-repeat;
    box-sizing: border-box;
}

.settings-slider::-moz-range-track {
    height: 100%;
    background: url('../img/new/settings/ui_set_slider_back.webp') center / calc(100% - 1cqw) 100% no-repeat;
    box-sizing: border-box;
}

/* Ложе-тень ui_set_slider_back_sh — ОТДЕЛЬНЫЙ элемент под дорожкой.
   Сдвиг вниз 15% (нижний край у арта затухает — alpha~72, поэтому показываем
   под ложем плотную часть силуэта, а не только полупрозрачный кант).
   Область под дорожкой видна, сверху ничего не выпирает (top:0).
   Тень под ложем: z-index:0 < input 1. Ширина чуть уже ложа
   (100% - 1.2cqw) — без боковых выступов. */
.settings-slider-shadow {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    height: 100%;
    width: calc(100% - 1.2cqw);
    margin: 0 auto;
    transform: translateY(15%);
    opacity: 0.65;   /* затемнить/осветлить: 0 — скрыть, 1 — сплошная */
    background: url('../img/new/settings/ui_set_slider_back_sh.webp') center / 100% 100% no-repeat;
    pointer-events: none;
    z-index: 0;
}

/* Рамка дорожки (только верхняя/нижняя рейки tr) — над заливкой и ложем,
   но под ромбом. */
.settings-slider-wrap::after {
    content: '';
    position: absolute;
    inset: 0;
    background: url('../img/new/settings/ui_set_slider_back_tr.webp') center / 100% 100% no-repeat;
    pointer-events: none;
    z-index: 3;
}

/* Ромб — ОТДЕЛЬНЫЙ слой (не псевдо-элемент input): нативный thumb Firefox
   не гарантирует z-index поверх заливки/рамки, а обычный позиционированный
   элемент в обёртке — гарантирует (z-index:2 > 0). Позицию и размеры
   ставит paintSlider() в px (--thumb-w/--thumb-h). Сам клик/драг обрабатывает
   прозрачный нативный thumb. */
.settings-slider-knob {
    position: absolute;
    top: 50%;
    left: 0;
    width: var(--thumb-w, 0px);
    height: var(--thumb-h, 0px);
    transform: translateY(-50%);
    background: url('../img/new/settings/ui_set_slider.webp') center / contain no-repeat;
    pointer-events: none;
    z-index: 4;
}

.settings-slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 5.6cqw;
    height: 7.8cqw;
    /* Центрируем ромб по дорожке: (высота дорожки - высота бегунка) / 2 */
    margin-top: calc((4.6cqw - 7.8cqw) / 2);
    background: transparent;
    border: none;
    cursor: grab;
}

.settings-slider::-moz-range-thumb {
    width: 5.6cqw;
    height: 7.8cqw;
    background: transparent;
    border: none;
    cursor: grab;
}

.settings-slider:active::-webkit-slider-thumb { cursor: grabbing; }
.settings-slider:active::-moz-range-thumb { cursor: grabbing; }

/* Выключенное состояние. opacity НЕ вешаем на сам <input> — со стекинг-
   контекстом ромб (z-index:1) запирается внутри и прячется под заливкой
   и рамкой. Вместо этого приглушаем каждый слой отдельно: рамку и заливку
   через :has() у обёртки (они ниже ромба), ложе и сам ромб — через
   псевдо-элементы <input> (внутри него, ромб всё равно сверху). */
.settings-slider:disabled {
    cursor: not-allowed;
}

.settings-slider-wrap:has(.settings-slider:disabled)::before,
.settings-slider-wrap:has(.settings-slider:disabled)::after {
    opacity: 0.45;
}

.settings-slider-wrap:has(.settings-slider:disabled) .settings-slider-knob {
    opacity: 0.45;
}

.settings-slider:disabled::-webkit-slider-runnable-track,
.settings-slider:disabled::-moz-range-track {
    opacity: 0.45;
}

.settings-slider:disabled::-webkit-slider-thumb {
    opacity: 0.45;
    cursor: not-allowed;
}

.settings-slider:disabled::-moz-range-thumb {
    opacity: 0.45;
    cursor: not-allowed;
}

/* --- выключатель (полное отключение звука/музыки) --- */
.settings-switch {
    flex: 0 0 auto;
    width: 14%;
    aspect-ratio: 102 / 74;
    padding: 0;
    border: none;
    background: transparent;
    cursor: pointer;
    font-size: 0;
    color: transparent;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: filter 0.12s ease, transform 0.12s ease;
}

.settings-switch:hover {
    filter: brightness(1.1);
}

.settings-switch:active {
    transform: scale(0.95);
}

/* «Таблетка»-заливка: нижний слой, видна во включённом состоянии */
.settings-switch::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 88%;
    aspect-ratio: 80 / 46;
    transform: translate(-50%, -50%);
    background: url('../img/new/settings/ui_set_on_off.webp') center / contain no-repeat;
    opacity: 0;
    transition: opacity 0.14s ease;
    pointer-events: none;
}

.settings-switch.is-on::before {
    opacity: 1;
}

/* Жёлтая рамка ui_set_on_off_back: верхний слой, поверх заливки.
   Центр прозрачный — заливка видна сквозь отверстие. */
.settings-switch::after {
    content: '';
    position: absolute;
    inset: 0;
    background: url('../img/new/settings/ui_set_on_off_back.webp') center / 100% 100% no-repeat;
    pointer-events: none;
}

/* Выключенное состояние — рамка приглушена */
.settings-switch:not(.is-on) {
    filter: saturate(0.45) brightness(0.85);
}

.settings-switch:not(.is-on):hover {
    filter: saturate(0.6) brightness(0.95);
}

/* Обёртка выключателя (ширина та же, что у самого выключателя — 14% окна) */
.settings-toggle {
    flex: 0 0 auto;
    width: 14%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.settings-toggle .settings-switch {
    width: 100%;
}

/* Текст «Вкл»/«Выкл» — ВНУТРИ выключателя, в отверстии рамки
   ui_set_on_off_back (рисуется поверх «таблетки» ::before). */
.settings-switch-text {
    display: block;
    position: relative;
    font-size: clamp(7px, 1.9cqw, 10px);   /* плавно по окну, но мельче */
    font-weight: 900;
    color: #fff;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    line-height: 1;
    white-space: nowrap;
    text-shadow: 0 1px 1px rgba(60, 24, 10, 0.55);
}

/* Центрированная кнопка обычной ширины (как в колонках) */
.menu-center-row {
    grid-column: 1 / -1;
    display: flex;
    justify-content: center;
    margin-top: 4px;
}

/* Кнопка внутри — такая же ширина, как у кнопок в колонках */
.menu-center-row .menu-btn {
    width: calc((600px - 12px) / 2); /* ширина колонки = (max-width - gap) / 2 */
    max-width: 100%;
}

/* Адаптив для мобильных */
@media (max-width: 560px) {
    .menu-center-row .menu-btn {
        width: 100%;
        max-width: 320px;
    }
}

/* ---------- мобильные правки главного меню (ландшафт / низкие экраны) ---------- */
@media (pointer: coarse) and (max-height: 480px) {
    .main-menu {
        padding: 12px;
        justify-content: flex-start;   /* на низких экранах — прижать к верху */
    }
    .main-menu-inner {
        margin: 0;                     /* отменяем центрирование */
    }
    .menu-title {
        font-size: 40px;
        margin-bottom: 2px;
    }
    .menu-subtitle {
        font-size: 13px;
        margin-bottom: 16px;
    }
    .menu-buttons {
        gap: 8px;
        max-width: 480px;
    }
    .menu-btn {
        font-size: 15px;
        padding: 10px 16px;
    }
    .menu-btn-full {
        max-width: 300px;
    }
}

/* Совсем маленькие экраны (iPhone SE в ландшафте, ~320px высоты) */
@media (pointer: coarse) and (max-height: 360px) {
    .menu-title { font-size: 32px; }
    .menu-subtitle { font-size: 12px; margin-bottom: 10px; }
    .menu-buttons { gap: 6px; }
    .menu-btn { font-size: 14px; padding: 8px 14px; }
}

/* ---------- Splash-экран (стартовая заставка) ---------- */
.splash-screen {
    position: fixed;
    inset: 0;
    display: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-image:
        radial-gradient(circle at 50% 40%, rgba(30, 41, 59, 0.6), rgba(15, 23, 42, 0.9)),
        url('../img/screen/back_left.webp'),
        url('../img/screen/back_right.webp'),
        url('../img/menu/back_menu.webp');
    background-position:
        center,
        right calc(50vw + (8 / 9) * 100dvh) center,
        left  calc(50vw + (8 / 9) * 100dvh) center,
        center;
    background-size: auto, auto 100%, auto 100%, auto 100%;
    background-repeat: no-repeat;
    z-index: 500; /* ВЫШЕ главного меню (у него 100) */
    cursor: pointer;
    user-select: none;
    overflow: hidden;
}
.splash-screen.visible {
    display: flex;
    animation: splashFadeIn 0.8s ease-out;
}
@keyframes splashFadeIn {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Исчезновение splash */
.splash-screen.fade-out {
    animation: splashFadeOut 0.6s ease-in forwards;
}
@keyframes splashFadeOut {
    from { opacity: 1; transform: scale(1); }
    to   { opacity: 0; transform: scale(1.05); }
}

.splash-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 48px;
}

/* Логотип с картами */
.splash-logo {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    position: relative;
    top: -24px;
    animation: logoAppear 1.2s cubic-bezier(0.2, 0.8, 0.2, 1);
}
@keyframes logoAppear {
    0%   { transform: translateY(-40px) scale(0.8); opacity: 0; }
    60%  { transform: translateY(8px) scale(1.05); opacity: 1; }
    100% { transform: translateY(0) scale(1); opacity: 1; }
}

/* Четыре карты в веере */
.splash-cards {
    position: relative;
    width: 260px;
    height: 150px;
    margin-bottom: 8px;
}
.splash-card {
    position: absolute;
    width: 80px;
    height: 120px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 56px;
    font-weight: 900;
    top: 15px;
    left: 90px;
    transform-origin: bottom center;
    animation-fill-mode: forwards;
}
/* ♠ — крайняя левая */
.splash-card-1 {
    color: #111827;
    z-index: 1;
    animation: cardFan1 1s cubic-bezier(0.2, 0.8, 0.2, 1) 0.15s backwards;
}
/* ♥ — левая центральная */
.splash-card-2 {
    color: #dc2626;
    z-index: 2;
    animation: cardFan2 1s cubic-bezier(0.2, 0.8, 0.2, 1) 0.3s backwards;
}
/* ♦ — правая центральная */
.splash-card-3 {
    color: #dc2626;
    z-index: 2;
    animation: cardFan3 1s cubic-bezier(0.2, 0.8, 0.2, 1) 0.45s backwards;
}
/* ♣ — крайняя правая */
.splash-card-4 {
    color: #111827;
    z-index: 1;
    animation: cardFan4 1s cubic-bezier(0.2, 0.8, 0.2, 1) 0.6s backwards;
}

@keyframes cardFan1 {
    0%   { transform: rotate(0deg) translateY(60px) scale(0.5); opacity: 0; }
    100% { transform: rotate(-25deg) translateX(-40px); opacity: 1; }
}
@keyframes cardFan2 {
    0%   { transform: rotate(0deg) translateY(60px) scale(0.5); opacity: 0; }
    100% { transform: rotate(-8deg) translateX(-14px) translateY(-6px); opacity: 1; }
}
@keyframes cardFan3 {
    0%   { transform: rotate(0deg) translateY(60px) scale(0.5); opacity: 0; }
    100% { transform: rotate(8deg) translateX(14px) translateY(-6px); opacity: 1; }
}
@keyframes cardFan4 {
    0%   { transform: rotate(0deg) translateY(60px) scale(0.5); opacity: 0; }
    100% { transform: rotate(25deg) translateX(40px); opacity: 1; }
}

/* Разлёт карт при исчезновении */
.splash-screen.fade-out .splash-card-1 { animation: cardFlyFarLeft 0.6s ease-in forwards; }
.splash-screen.fade-out .splash-card-2 { animation: cardFlyLeft 0.6s ease-in forwards; }
.splash-screen.fade-out .splash-card-3 { animation: cardFlyRight 0.6s ease-in forwards; }
.splash-screen.fade-out .splash-card-4 { animation: cardFlyFarRight 0.6s ease-in forwards; }
@keyframes cardFlyFarLeft {
    to { transform: rotate(-70deg) translateX(-260px) translateY(-40px); opacity: 0; }
}
@keyframes cardFlyLeft {
    to { transform: rotate(-40deg) translateX(-140px) translateY(-20px); opacity: 0; }
}
@keyframes cardFlyRight {
    to { transform: rotate(40deg) translateX(140px) translateY(-20px); opacity: 0; }
}
@keyframes cardFlyFarRight {
    to { transform: rotate(70deg) translateX(260px) translateY(-40px); opacity: 0; }
}

.splash-title {
    font-size: 96px;
    font-weight: 900;
    color: #fde047;
    letter-spacing: 8px;
    margin: 0;
    text-shadow:
        0 4px 0 #b45309,
        0 8px 24px rgba(0, 0, 0, 0.6);
    animation: titlePulse 3s ease-in-out infinite;
}
@keyframes titlePulse {
    0%, 100% { text-shadow: 0 4px 0 #b45309, 0 8px 24px rgba(0, 0, 0, 0.6); }
    50%      { text-shadow: 0 4px 0 #b45309, 0 8px 32px rgba(253, 224, 71, 0.4); }
}

.splash-subtitle {
    font-size: 18px;
    color: #94a3b8;
    letter-spacing: 4px;
    text-transform: uppercase;
    margin: 0;
}

/* Пульсирующая подсказка */
.splash-hint {
    animation: hintAppear 0.8s ease-out 1.2s backwards;
}
@keyframes hintAppear {
    from { opacity: 0; transform: translateY(20px); }
    to   { opacity: 1; transform: translateY(0); }
}
.splash-tap {
    font-size: 20px;
    font-weight: 700;
    color: #fde047;
    letter-spacing: 2px;
    text-transform: uppercase;
    padding: 12px 32px;
    border: 2px solid rgba(253, 224, 71, 0.4);
    border-radius: 12px;
    background: rgba(253, 224, 71, 0.08);
    animation: tapPulse 2s ease-in-out infinite;
}
@keyframes tapPulse {
    0%, 100% {
        transform: scale(1);
        border-color: rgba(253, 224, 71, 0.4);
        box-shadow: 0 0 0 0 rgba(253, 224, 71, 0.4);
    }
    50% {
        transform: scale(1.05);
        border-color: rgba(253, 224, 71, 0.8);
        box-shadow: 0 0 24px 4px rgba(253, 224, 71, 0.2);
    }
}

.splash-footer {
    position: absolute;
    bottom: 24px;
    color: #64748b;
    font-size: 12px;
    letter-spacing: 2px;
}

/* Адаптив splash */
@media (max-width: 560px) {
    .splash-title { font-size: 64px; letter-spacing: 4px; }
    .splash-subtitle { font-size: 14px; }
    .splash-tap { font-size: 16px; padding: 10px 24px; }
    .splash-cards { transform: scale(0.85); }
    /* Масштабирование всего сплэша на маленьких экранах — иначе контент
       не помещается по высоте (карты + лого + подсказка). */
    .splash-content { transform: scale(0.78); }
    /* Лого выше, подсказка остаётся снизу */
    .splash-logo { position: relative; top: -60px; }
}
@media (max-width: 400px) {
    .splash-content { transform: scale(0.7); }
    .splash-logo { position: relative; top: -52px; }
}
/* Порядок важен: этот блок идёт последним, чтобы на узких ландшафтных
   экранах применялся наименьший масштаб (0.6). */
@media (pointer: coarse) and (max-height: 480px) {
    .splash-content { gap: 24px; transform: scale(0.6); }
    .splash-title { font-size: 48px; }
    .splash-cards { transform: scale(0.65); margin-bottom: 0; }
    /* Лого выше на ландшафтных экранах */
    .splash-logo { position: relative; top: -40px; }
}

.splash-logo-img {
  width: 100%;
  max-width: 520px;
  height: auto;
  display: block;
  filter: drop-shadow(0 8px 24px rgba(0, 0, 0, 0.6));
}

.menu-btn-label {
  position: absolute;
  left: 140px;
  top: 50%;
  transform: translateY(-50%);
  color: #4A3B32;  //  #1e293b;
  font-size: 20px;
  font-weight: 800;
  pointer-events: none;
  white-space: nowrap;
  letter-spacing: 0.5px;
  z-index: 3;
  line-height: 1.2;
}

.menu-btn-disabled .menu-btn-label {
  color: #64748b;
}

/* Адаптив: планшеты */
@media (max-width: 860px) {
  .menu-btn-label {
    left: 130px;
    font-size: 18px;
  }
}

/* Адаптив: мобильные. Кнопка уменьшилась до 320×60, поэтому подпись
   сдвигаем ближе к левому краю (за квадрат иконки ≈60px). */
@media (max-width: 720px) {
  .menu-btn-label {
    left: 78px;
    font-size: 15px;
  }
}

/* Низкие экраны (мобильный ландшафт). Стоит ниже блоков ≤720px/≤560px,
   поэтому его значения побеждают в каскаде при малой высоте. Держим две
   колонки и сжимаем всё, чтобы 4 ряда экрана режима влезали без прокрутки. */
@media (max-height: 480px) {
  .main-menu {
    padding: 8px;
    justify-content: flex-start;
  }
  .main-menu-inner { margin: auto 0; }
  .menu-logo {
    max-width: 200px;
    margin-bottom: 6px;
  }
  .menu-buttons { max-width: 600px; gap: 6px; }
  .menu-row {
    flex-direction: row;   /* возвращаем две колонки поверх «одной» из ≤720px */
    gap: 10px;
  }
  /* Картинка кнопки — 585×136 (соотношение 4.3:1), вписывается contain.
     Ширину держим = высота×4.3 (≈215 при h=50), иначе по бокам появляются
     поля и подпись наезжает на иконочный квадрат. Квадрат иконки ≈ высоте
     кнопки, поэтому подпись начинаем чуть правее неё. */
  .menu-btn-wrapper {
    width: 215px;
    max-width: 215px;
    height: 50px;
  }
  /* У .menu-btn-fs другой арт, чем у .menu-btn-wrapper: это ui_button_red
     230×69 (R = 3.333), а не 585×136 (R = 4.3) из комментария выше.
     Поэтому ширину считаем от высоты по СВОЕМУ арту: 50 × 3.333 = 167px.
     Раньше тут стояло 217×50 — кнопка растягивалась в 1.3 раза по горизонтали. */
  .menu-btn-fs { width: 167px; }
  .menu-btn-label {
    left: 58px;
    font-size: 13px;
  }
}

/* Совсем маленькие экраны */
@media (max-width: 560px) {
  .menu-btn-wrapper { height: 56px; }
  /* Тот же арт 230×69: 56 × 3.333 = 187px (было 217×56 — растянуто). */
  .menu-btn-fs { width: 187px; }
  .menu-buttons { max-width: 300px; }
  .menu-btn-wrapper { max-width: 300px; }
  .menu-logo { max-width: 260px; }
  .menu-btn-label {
    left: 72px;
    font-size: 14px;
  }
}

/* ---------- режим галереи на экране выбора ---------- */
.char-screen.gallery-mode .name-pick,
.char-screen.gallery-mode .lobby-title-hint,
.char-screen.gallery-mode .btn-mp-help,
.char-screen.gallery-mode #btn-char-fs {
    display: none !important;
}

/* ---------- модалка с деталями персонажа (окно на арте) ---------- */
.char-detail-box {
    position: relative;
    /* Пропорции арта окна 717x960 сохраняем всегда, иначе рамка
       растягивается. Размер ведём от высоты экрана, ширину ограничиваем
       отдельно — так окно вписывается и в низкий ландшафт, и в портрет. */
    height: min(960px, calc(100dvh - 24px), calc((100vw - 24px) * 960 / 717));
    width: auto;
    aspect-ratio: 717 / 960;
    background: url('../img/new/character_menu/ui_cm_character_menu.webp') center / 100% 100% no-repeat;
    padding: 0;
    border: none;
    border-radius: 0;
    box-shadow: none;
    overflow: visible;
    display: flex;
    flex-direction: column;
    /* Контейнер для cqw-единиц: шрифты масштабируются от ширины окна */
    container-type: inline-size;
    /* Внутренние отступы задаём в % от ширины окна, чтобы текст всегда
       ложился внутрь нарисованной рамки при любом масштабе. */
    --cd-pad-x: 7.5%;
}

/* --- шапка окна: имя героя на деревянной планке + крестик --- */
.char-detail-titlebar {
    position: relative;
    flex: 0 0 auto;
    height: 10.4%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 14% 0 8%;
}

.char-detail-name {
    color: #5b2c10;
    font-size: clamp(18px, 4.2cqw, 40px);
    font-weight: 900;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    line-height: 1;
    margin: 0;
    text-shadow: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}

.char-detail-close {
    position: absolute;
    top: 50%;
    right: 4%;
    transform: translateY(-52%);
    width: 8%;
    aspect-ratio: 1;
    padding: 0;
    background: none;
    isolation: isolate;
    border: none;
    border-radius: 50%;
    color: transparent;
    font-size: 0;
    cursor: pointer;
    transition: transform 0.12s ease, filter 0.12s ease;
}

.char-detail-close:hover {
    color: transparent;
    transform: translateY(-52%) scale(1.06);
}

.char-detail-close:active {
    transform: translateY(-52%) scale(0.95);
}

/* --- тело окна: контент + верёвочный скроллбар --- */
.char-detail-body {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    gap: 2.5%;
    /* Отступы подобраны так, чтобы и текст, и верёвка встали внутрь
       нарисованной деревянной рамки окна. */
    padding: 3.2% 8.5% 6% 12%;
}

.char-detail-scroll {
    flex: 1 1 auto;
    min-width: 0;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 6px;
    text-align: left;
    /* Родная полоса скрыта — рисуем свою справа (.char-detail-sb) */
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.char-detail-scroll::-webkit-scrollbar {
    width: 0;
    height: 0;
    display: none;
}

/* Верхний блок: портрет + характеристики */
.char-detail-top {
    display: flex;
    gap: 4%;
    align-items: flex-start;
    margin-bottom: 4%;
}

.char-detail-img {
    flex: 0 0 34%;
    width: 34%;
    height: auto;
    aspect-ratio: 216 / 254;
    object-fit: contain;
    border-radius: 0;
    background: none;
    margin: 0;
    display: block;
}

.char-detail-stats {
    flex: 1 1 auto;
    min-width: 0;
    margin: 0;
    color: #f6e7d2;
    font-size: clamp(11px, 2.5cqw, 21px);
    line-height: 1.32;
    font-weight: 700;
}

.char-detail-stats div {
    margin-bottom: 2px;
    overflow-wrap: break-word;
}

.char-detail-stats dt {
    display: inline;
    color: #f0a94a;
    font-weight: 800;
    margin: 0;
}

.char-detail-stats dd {
    display: inline;
    margin: 0 0 0 4px;
    color: #f6e7d2;
}

/* Описание — абзацы лора */
.char-detail-desc {
    color: #f6e7d2;
    font-size: clamp(11px, 2.5cqw, 21px);
    line-height: 1.38;
    font-weight: 700;
    margin: 0;
    min-height: 0;
    text-align: left;
}

.char-detail-desc p {
    margin: 0 0 0.75em;
}

.char-detail-desc p:last-child {
    margin-bottom: 0;
}

/* --- собственный верёвочный скроллбар окна --- */
.char-detail-sb {
    flex: 0 0 auto;
    width: 4.4%;
    min-width: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    /* Скрыт, пока контент помещается целиком (ставится из JS) */
}

.char-detail-sb.is-hidden {
    visibility: hidden;
}

.char-detail-sb-up,
.char-detail-sb-down {
    flex: 0 0 auto;
    width: 100%;
    aspect-ratio: 43 / 37;
    padding: 0;
    border: none;
    background: center / contain no-repeat;
    cursor: pointer;
    transition: filter 0.12s ease, transform 0.12s ease;
    /* Выше слоя каната (см. .rules-sb-track::before). */
    position: relative;
    z-index: 2;
}

.char-detail-sb-up {
    background-image: url('../img/new/scroll/ui_arrow_up.webp');
}

.char-detail-sb-down {
    background-image: url('../img/new/scroll/ui_arrow_down.webp');
}

.char-detail-sb-up:hover,
.char-detail-sb-down:hover {
    filter: brightness(1.12);
}

.char-detail-sb-up:active,
.char-detail-sb-down:active {
    transform: scale(0.92);
}

/* Ложе — тень верёвки, тянется на всю высоту между стрелками */
.char-detail-sb-track {
    position: relative;
    z-index: 0;
    flex: 1 1 auto;
    width: 100%;
    min-height: 0;
    /* Без вертикального margin: он укорачивал ход бегунка
       относительно видимой верёвки — на краях оставался зазор. */
    cursor: pointer;
    touch-action: none;
}

/* Канат — отдельный слой, который заходит под стрелки (см. .rules-sb-track). */
.char-detail-sb-track::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: calc(-1 * var(--sb-join));
    bottom: calc(-1 * var(--sb-join));
    z-index: 0;
    pointer-events: none;
    /* Бесшовный тайл, общий для всех лож: один период узора, поэтому
       repeat-y без разрыва и без растяжения витков. */
    background-image: url('../img/new/scroll/ui_arrow_scroll_b_seamless.webp'), url('../img/new/scroll/ui_arrow_scroll_b_sh_seamless.webp');
    background-repeat: repeat-y, repeat-y;
    background-position: center top, center top;
    background-size: 50% auto, 50% auto;
}

/* Ползунок — узел, движется только он */
.char-detail-sb-thumb {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    /* Выше слоя каната: бегунок — узел, он должен лежать поверх верёвки. */
    z-index: 1;
    /* Ползунок — общий узел ui_arrow_scroll_a (47x72) в натуральной пропорции.
       aspect-ratio держит ту же пропорцию у бокса: иначе contain центрировал
       картинку в блоке произвольной высоты и на краях оставались зазоры. */
    aspect-ratio: 47 / 72;
    background: url('../img/new/scroll/ui_arrow_scroll_a.webp') center / contain no-repeat;
    cursor: grab;
}

.char-detail-sb-thumb:active {
    cursor: grabbing;
    filter: brightness(0.95);
}


/* ---------- модалка ввода имени (первый запуск) ---------- */
.name-modal-overlay {
    display: none;
    position: fixed;
    inset: 0;
    align-items: center;
    justify-content: center;
    z-index: 500;
    padding: 24px;
    background-image:
        radial-gradient(circle at 50% 40%, rgba(30, 41, 59, 0.6), rgba(15, 23, 42, 0.9)),
        url('../img/screen/back_left.webp'),
        url('../img/screen/back_right.webp'),
        url('../img/menu/back_menu.webp');
    background-position:
        center,
        right calc(50vw + (8 / 9) * 100dvh) center,
        left  calc(50vw + (8 / 9) * 100dvh) center,
        center;
    background-size: auto, auto 100%, auto 100%, auto 100%;
    background-repeat: no-repeat;
    animation: splashFadeIn 0.8s ease-out;
}
.name-modal-overlay.visible {
    display: flex;
}
/* Панель модалки — тот же арт ui_animated, что и у остальных меню */
.name-modal-panel { width: min(520px, 92vw, 78dvh); }
/* Высота панели задана артом ui_name_back (715x616), а вертикальные отступы
   заданы в % и cqw — то есть линейны от ШИРИНЫ. Из-за этого отношение
   «контент / высота панели» постоянно и равно 1.09 ЛЮБОЙ ширины: сузить
   или расширить панель бесполезно, переполнение масштабируется вместе с ней.
   При 18% сверху логотип, подзаголовок, поле ввода, текст согласия и кнопка
   занимали 488px против 448px панели — минус 40px уходило за нижний край.

   Поэтому ужали вертикальные отступы, а не сами элементы:
     padding 18%/5% -> 12%/4%  (экономия 36.6px)
     margin-top кнопок 4cqw -> 2cqw, поля ввода 1cqw -> 0.6cqw,
     согласия 1.6cqw -> 1.2cqw (ещё 18.4px)
   Итог: 434.7px против 448px, запас 13.3px.

   Логотип при этом УХОДИТ НИЖЕ, как и требовалось: заголовок «Как вас
   зовут?» — absolute top:8.6% и занимает 27-51px, а логотип начинается
   теперь на 62px, то есть зазор 11px. Ниже 11% padding-top ставить нельзя:
   логотип налезет на заголовок. */
.name-modal-panel .lobby-panel-inner { padding: 12% 7% 4%; justify-content: center; }
.name-modal-panel .lobby-title { font-size: clamp(16px, 4.6cqw, 34px); }
/* Подзаголовок «Представьтесь, чтобы играть в рейтинге» — 36 символов, самый
   длинный текст модалки после согласия. Общий кегль clamp(12px, 2.6cqw, 18px)
   на панели 520px даёт 13.5px, но на десктопе упирается в 18px. Здесь потолок
   15px: строка остаётся в одну линию (36 симв * 0.5em = 18em => 270px против
   376px доступных) и даёт панели ещё 3.6px запаса по высоте. */
/* Десктоп оставляем на общем кегле .lobby-subtitle — clamp(12px, 2.6cqw, 18px).
   Уменьшенный вариант живёт в @media ниже. */
.name-modal-panel .lobby-buttons { margin-top: 2cqw; }
.name-modal-panel .name-modal-input { margin: 0.6cqw 0; }
.name-modal-panel .name-consent { margin-top: 1.2cqw; }

/* Заблокированная «Начать игру» (пока не проставлена галка согласия).
   Плашка бледнеет и не реагирует на наведение — иначе игрок не понимает,
   почему нажатие ничего не делает. */
.name-modal-panel .lobby-btn:disabled {
    filter: grayscale(0.75) brightness(0.7);
    cursor: not-allowed;
}
.name-modal-panel .lobby-btn:disabled:hover {
    transform: none;
    filter: grayscale(0.75) brightness(0.7);
}

/* Кнопка «Начать игру» уже .lobby-btn, а та растягивается на 100% ширины
   контент-бокса: при панели 520px это 447x81px, и содержимое перестаёт
   помещаться в арт ui_name_back (715x616 -> панель 448px) — логотип, поле
   ввода и текст согласия выталкивали кнопку за нижний край на ~16px.
   Сузили до 76%: 340x62px, запас 3.8px. Меньше 72% не идём — кнопка
   должна остаться заметной, а не теряться между полем ввода и краем. */
/* width вместо 100% уводит кнопку влево: .lobby-buttons — flex-колонка без
   align-items, поэтому кросс-ось выравнивается по flex-start, а не по центру.
   align-items: center возвращает кнопку в середину. */
.name-modal-panel .lobby-buttons { align-items: center; }
.name-modal-panel .lobby-btn { width: 76%; }

/* У .lobby-btn арт рисуется дважды: ::after на inset:0 повторяет контур
   кнопки, а ::before (aspect-ratio 464/92, transform: translateY(8%)) —
   вылезающую вниз «тень» плашки. Уже сжатой по width кнопке вторая
   подложка не нужна: без неё арт не вылезет за нижний край панели. */
.name-modal-panel .lobby-btn::before { display: none; }

.name-modal-logo {
    width: 55%;
    height: auto;
    margin-bottom: 2cqw;
    filter: drop-shadow(0 6px 16px rgba(0, 0, 0, 0.55));
}

.name-modal-input {
    width: 76%;
    box-sizing: border-box;
    aspect-ratio: 453 / 91;
    background: url('../img/new/ng/ui_name.webp') center / 100% 100% no-repeat;
    font-family: inherit;
    font-size: clamp(16px, 4cqw, 28px);
    font-weight: 700;
    text-align: center;
    color: #ffe9c8;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
    padding: 0 1.4cqw;
    border: none;
    border-radius: 0;
    margin: 1cqw 0;
    letter-spacing: 0.5px;
    transition: box-shadow 0.15s;
}
.name-modal-input::placeholder {
    color: #e5c896;
    font-weight: 400;
}
.name-modal-input:focus {
    outline: none;
}
/* Адаптив для модалки имени */
@media (max-width: 560px) {
    .name-modal-panel { width: min(460px, 92vw, 80dvh); }
    .name-modal-input { font-size: 18px; }
    /* На маленьких экранах те же 12%/4%, что и в базе: переполнение не
       зависит от ширины, поэтому «подстраивать» отступы здесь нечего —
       достаточно сохранить пропорцию с базой. */
    .name-modal-panel .lobby-panel-inner { padding: 12% 7% 4%; }
    .name-modal-panel .lobby-title { font-size: clamp(13px, 4.2cqw, 26px); }
    /* Подзаголовок на мобильных мельче: общий clamp(12px, 2.6cqw, 18px) упирается
       в нижний предел 12px, потому что 2.6cqw на панели 330-440px даёт лишь
       8.6-11.5px. Строка в 36 символов («Представьтесь, чтобы играть в рейтинге»)
       занимала треть панели, поэтому снижаем нижний предел до 10px. */
    .name-modal-panel .lobby-subtitle { font-size: clamp(10px, 2.4cqw, 15px); }
    .name-modal-panel .lobby-subtitle { margin-bottom: 2.5cqw; }
    .name-modal-panel .lobby-buttons { margin-top: 2cqw; }
    .name-modal-panel .name-modal-input { padding: 0 1.4cqw; margin: 0.6cqw 0; }
}
@media (pointer: coarse) and (max-height: 480px) {
    .name-modal-panel { width: min(440px, 90vw, 82dvh); }
    .name-modal-input { font-size: 16px; }
    /* Невысокие экраны (ландшафтные телефоны): те же 12%/4% и 2cqw, что и в
       базе. Логика та же — переполнение не зависит от ширины панели, а
       ужимать отступы сильнее нельзя: логотип налезет на заголовок
       «Как вас зовут?», который занимает верхние ~11% высоты панели. */
    .name-modal-panel .lobby-panel-inner { padding: 12% 7% 4%; }
    /* Тот же уменьшенный подзаголовок, что и в max-width:560px: ландшафтные
       телефоны по вертикали ещё теснее, а текст тот же — 36 символов. */
    .name-modal-panel .lobby-subtitle { font-size: clamp(10px, 2.4cqw, 15px); }
    .name-modal-panel .lobby-subtitle { margin-bottom: 2cqw; }
    .name-modal-panel .lobby-buttons { margin-top: 2cqw; }
    .name-modal-panel .name-modal-input { padding: 0 1.4cqw; margin: 0.6cqw 0; }
}

/* ---------- модалка выбора количества игроков ---------- */
/* Панель — тот же арт ui_animated и та же структура, что у лобби */
.player-count-panel {
    width: min(520px, 92vw, 78dvh);
}
.player-count-panel .lobby-title {
    font-size: clamp(16px, 4.6cqw, 34px);
}

/* Крестик в правом верхнем углу рамки (арт ui_x_back + ui_x, как в настройках) */
.player-count-close {
    position: absolute;
    top: 5%;
    right: 3.5%;
    width: 8.5%;
    aspect-ratio: 1;
    padding: 0;
    background: none;
    isolation: isolate;
    border: none;
    border-radius: 50%;
    font-size: 0;
    color: transparent;
    cursor: pointer;
    z-index: 3;
    transition: transform 0.12s ease, filter 0.12s ease;
}
.player-count-close:hover { transform: scale(1.06); }
.player-count-close:active { transform: scale(0.95); }

@media (max-width: 560px) {
    .player-count-panel { width: min(460px, 92vw, 80dvh); }
}

/* Адаптив для паузы */
@media (max-width: 480px) {
    .pause-box { width: 320px; }
    .pause-resume { font-size: 18px; padding: 16px 0 20px; }
}

/* ==========================================================================
   Кастомный скролл в стиле игры (верёвка + деревянные стрелки).
   Применяется глобально ко всем прокручиваемым областям сайта.
   ========================================================================== */

/* --- Firefox (стрелки не поддерживаются, красим полосу) --- */
* {
    scrollbar-width: thin;
    scrollbar-color: #e8a33d rgba(60, 35, 25, 0.45);
}

/* --- WebKit/Blink: полноценная верёвочная полоса со стрелками --- */
::-webkit-scrollbar {
    width: 21px;
    height: 21px;
}

/* Ложе полосы — тёмная «тень верёвки» */
::-webkit-scrollbar-track {
    background: url('../img/new/character_menu/ui_cm_arrow_scroll_b_sh.webp') center top / 21px auto repeat-y,
                rgba(40, 22, 16, 0.35);
    border-radius: 11px;
}

/* Бегунок — сама верёвка */
::-webkit-scrollbar-thumb {
    background: url('../img/new/character_menu/ui_cm_arrow_scroll_b.webp') center top / 21px auto repeat-y;
    border-radius: 11px;
    min-height: 48px;
}

::-webkit-scrollbar-thumb:hover {
    filter: brightness(1.08);
}

::-webkit-scrollbar-thumb:active {
    filter: brightness(0.94);
}

/* Кнопки-стрелки на концах полосы */
::-webkit-scrollbar-button:single-button {
    display: block;
    width: 21px;
    height: 19px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: contain;
}

::-webkit-scrollbar-button:single-button:vertical:decrement {
    background-image: url('../img/new/scroll/ui_arrow_up.webp');
}

::-webkit-scrollbar-button:single-button:vertical:increment {
    background-image: url('../img/new/scroll/ui_arrow_down.webp');
}

::-webkit-scrollbar-button:single-button:hover {
    filter: brightness(1.12);
}

::-webkit-scrollbar-button:single-button:active {
    filter: brightness(0.9);
}

/* Горизонтальные стрелки — те же спрайты, повёрнутые */
::-webkit-scrollbar-button:single-button:horizontal:decrement {
    background-image: url('../img/new/scroll/ui_arrow_up.webp');
    transform: rotate(-90deg);
}

::-webkit-scrollbar-button:single-button:horizontal:increment {
    background-image: url('../img/new/scroll/ui_arrow_down.webp');
    transform: rotate(-90deg);
}

::-webkit-scrollbar-corner {
    background: transparent;
}

/* ==========================================================================
   Окно «Рейтинг игроков» на арте (img/new/rating).
   Строки — полоски-картинки, первые три места с медалями, своя строка
   подсвечена золотом. Верёвочный скролл — как в окне персонажа.
   ========================================================================== */

.rating-box {
    position: relative;
    /* Пропорции арта окна 958x983 сохраняем при любом размере экрана.
       Окно намеренно меньше экрана — вокруг видно стол таверны. */
    height: min(760px, calc((100dvh - 24px) * 0.86), calc((100vw - 24px) * 983 / 958));
    width: auto;
    aspect-ratio: 958 / 983;
    background: url('../img/new/rating/ui_rat_rating.webp') center / 100% 100% no-repeat;
    display: flex;
    flex-direction: column;
    /* cqw-единицы считаются от ширины окна — шрифты масштабируются с ним */
    container-type: inline-size;
}

/* --- шапка: заголовок на планке + крестик --- */
.rating-titlebar {
    position: relative;
    flex: 0 0 auto;
    height: 12.5%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 12% 0 9%;
}

.rating-title {
    color: #5b2c10;
    font-size: clamp(15px, 4cqw, 42px);
    font-weight: 900;
    letter-spacing: 0.5px;
    line-height: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.rating-close {
    position: absolute;
    top: 52%;
    right: 4%;
    transform: translateY(-50%);
    width: 6.4%;
    aspect-ratio: 1;
    padding: 0;
    background: none;
    isolation: isolate;
    border: none;
    border-radius: 50%;
    font-size: 0;
    color: transparent;
    cursor: pointer;
    transition: transform 0.12s ease, filter 0.12s ease;
}

.rating-close:hover {
    transform: translateY(-50%) scale(1.06);
}

.rating-close:active {
    transform: translateY(-50%) scale(0.95);
}

/* --- внутренняя область окна (внутри нарисованной рамки) --- */
.rating-inner {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    flex-direction: column;
    padding: 1.2% 3.4% 4.6% 7.6%;
}

/* Сетка строки: #, имя, и пять числовых колонок */
.rating-head,
.rating-row {
    display: grid;
    grid-template-columns: 8.5% 1fr 13% 11% 11% 11% 11%;
    align-items: center;
    column-gap: 0;
}

/* --- шапка таблицы --- */
.rating-head {
    flex: 0 0 auto;
    padding: 0 4.4% 0.7% 0;
    color: #ffdca8;
    font-size: clamp(11px, 2.9cqw, 30px);
    font-weight: 900;
    /* Тень падает чуть вниз, как у игровых надписей */
    text-shadow: 0 2px 0 rgba(60, 24, 10, 0.65), 0 3px 4px rgba(0, 0, 0, 0.55);
}

.rating-head .rating-col-name {
    text-align: left;
    padding-left: 4%;
}

.rating-head .rating-col-rank,
.rating-head .rating-col-stat {
    text-align: center;
}

/* --- прокручиваемая область + верёвочная полоса --- */
.rating-scroll-wrap {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    gap: 1.4%;
}

.rating-scroll {
    flex: 1 1 auto;
    min-width: 0;
    overflow-y: auto;
    overflow-x: hidden;
    /* Родная полоса скрыта — справа рисуем свою (.rating-sb) */
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.rating-scroll::-webkit-scrollbar {
    width: 0;
    height: 0;
    display: none;
}

/* --- строка рейтинга --- */
.rating-list {
    display: flex;
    flex-direction: column;
}

.rating-row {
    position: relative;
    min-height: 6.2cqw;
    padding: 0.9cqw 0;
    /* Полоска-подложка строки (обычная) */
    background: url('../img/new/rating/ui_rat_classic.webp') center / 100% 100% no-repeat;
    color: #fff;
    font-size: clamp(10px, 2.7cqw, 27px);
    font-weight: 800;
    text-shadow: 0 2px 0 rgba(50, 20, 8, 0.5);
}

/* Своя строка: снизу тень-плашка ui_rat_you_b, поверх неё —
   золотое выделение ui_rat_you_a (::after). Текст всегда выше. */
.rating-row.is-me {
    background-image: url('../img/new/rating/ui_rat_you_b.webp');
    color: #fff;
}

.rating-row.is-me::after {
    content: '';
    position: absolute;
    inset: 3% 0 12%;
    background: url('../img/new/rating/ui_rat_you_a.webp') center / 100% 100% no-repeat;
    z-index: 0;
    pointer-events: none;
}

.rating-row.is-me > * {
    position: relative;
    z-index: 1;
}

.rating-cell {
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 0 2%;
}

.rating-col-name {
    text-align: left;
    padding-left: 5%;
}

.rating-col-rank {
    position: relative;
    text-align: center;
}

/* Медали за первые три места — картинки поверх ячейки места */
.rating-col-rank.has-medal {
    background-position: center;
    background-repeat: no-repeat;
    background-size: auto 100%;
    min-height: 5.2cqw;
}

.rating-col-rank.medal-1 { background-image: url('../img/new/rating/ui_rat_1.webp'); }
.rating-col-rank.medal-2 { background-image: url('../img/new/rating/ui_rat_2.webp'); }
.rating-col-rank.medal-3 { background-image: url('../img/new/rating/ui_rat_3.webp'); }

/* Очки — выделены жёлтым, как на макете */
.rating-cell.is-score {
    color: #ffd23f;
    font-weight: 900;
}

.rating-row.is-me .rating-cell.is-score {
    color: #fff;
}

/* Разрыв нумерации между топом и своей строкой */
.rating-gap {
    text-align: center;
    color: #ffdca8;
    font-weight: 900;
    letter-spacing: 2px;
    padding: 0.4cqw 0;
    opacity: 0.75;
}

/* --- верёвочный скроллбар окна рейтинга --- */
.rating-sb {
    flex: 0 0 auto;
    width: 3.4%;
    min-width: 14px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.rating-sb.is-hidden {
    visibility: hidden;
}

.rating-sb-up,
.rating-sb-down {
    flex: 0 0 auto;
    width: 100%;
    aspect-ratio: 43 / 37;
    padding: 0;
    border: none;
    background: center / contain no-repeat;
    cursor: pointer;
    transition: filter 0.12s ease, transform 0.12s ease;
    /* Выше слоя каната (см. .rules-sb-track::before). */
    position: relative;
    z-index: 2;
}

.rating-sb-up {
    background-image: url('../img/new/scroll/ui_arrow_up.webp');
}

.rating-sb-down {
    background-image: url('../img/new/scroll/ui_arrow_down.webp');
}

.rating-sb-up:hover,
.rating-sb-down:hover {
    filter: brightness(1.12);
}

.rating-sb-up:active,
.rating-sb-down:active {
    transform: scale(0.92);
}

.rating-sb-track {
    position: relative;
    z-index: 0;
    flex: 1 1 auto;
    width: 100%;
    min-height: 0;
    /* Без вертикального margin: он укорачивал ход бегунка
       относительно видимой верёвки — на краях оставался зазор. */
    cursor: pointer;
    touch-action: none;
}

/* Канат — отдельный слой, который заходит под стрелки (см. .rules-sb-track). */
.rating-sb-track::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: calc(-1 * var(--sb-join));
    bottom: calc(-1 * var(--sb-join));
    z-index: 0;
    pointer-events: none;
    /* Бесшовный тайл, общий для всех лож: один период узора, поэтому
       repeat-y без разрыва и без растяжения витков. */
    background-image: url('../img/new/scroll/ui_arrow_scroll_b_seamless.webp'), url('../img/new/scroll/ui_arrow_scroll_b_sh_seamless.webp');
    background-repeat: repeat-y, repeat-y;
    background-position: center top, center top;
    background-size: 50% auto, 50% auto;
}

.rating-sb-thumb {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    /* Выше слоя каната: бегунок — узел, он должен лежать поверх верёвки. */
    z-index: 1;
    /* Ползунок — общий узел ui_arrow_scroll_a (47x72) в натуральной пропорции.
       aspect-ratio держит ту же пропорцию у бокса: иначе contain центрировал
       картинку в блоке произвольной высоты и на краях оставались зазоры.
       Высоту JS не навязывает — только измеряет, transform сдвигает. */
    aspect-ratio: 47 / 72;
    background: url('../img/new/scroll/ui_arrow_scroll_a.webp') center / contain no-repeat;
    cursor: grab;
}

.rating-sb-thumb:active {
    cursor: grabbing;
    filter: brightness(0.95);
}

/* Служебные состояния внутри окна */
.rating-scroll .rating-loading,
.rating-scroll .rating-empty,
.rating-scroll .rating-error {
    text-align: center;
    padding: 8% 4%;
    color: #ffdca8;
    font-weight: 800;
    font-size: clamp(11px, 2.6cqw, 26px);
}

.rating-scroll .rating-error {
    color: #ffb4a2;
}

/* --- строки рейтинга в финальном оверлее партии --- */
/* Там нет окна-арта и container-type, поэтому cqw не работает:
   задаём фиксированные размеры. */
.over-rating-body .rating-row {
    min-height: 30px;
    padding: 4px 0;
    font-size: 13px;
    background-size: 100% 100%;
}

.over-rating-body .rating-col-rank.has-medal {
    min-height: 22px;
    background-size: auto 20px;
}

.over-rating-body .rating-gap {
    padding: 2px 0;
    font-size: 13px;
}

/* ==========================================================================
   Эмодзи-реакции во время партии: кнопка в шапке, выпадающая панель
   и пузыри над игроком/соперниками.
   ========================================================================== */

/* Пикер живёт внутри .tavern-seat-me (у него pointer-events:none),
   поэтому клики возвращаем точечно на сам пикер. */
/* Пока пикер открыт, кресло игрока поднимается выше карт руки:
   у самого кресла z-index:5 — оно образует свой стек-контекст, и поднять
   панель внутри него недостаточно (карты-соседи на z 50–70). */
.tavern-seat-me:has(.emoji-wrap.open) { z-index: 100; }
.emoji-wrap {
    position: absolute;
    /* Кнопка эмодзи — справа от круглого аватара, на уровне его низа. */
    left: 70%;
    bottom: 99px;
    margin-left: 0;
    transform: translateX(-50%);
    /* Выше карт руки (карты при ховере поднимаются до z-index 70),
       чтобы рука не перекрывала выбор эмодзи. */
    z-index: 90;
    display: inline-flex;
    pointer-events: auto;
}

.btn-emoji {
    background: #b45309;
    font-size: 20px;
    line-height: 1;
    /* Отступы нужны только текстовому запасному варианту (когда арта для
       персонажа нет и в кнопке стоит символ). */
    padding: 6px 10px;
    border-radius: 10px;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.45);
}

.btn-emoji:hover {
    background: #d97706;
}

/* С картинкой отступы убираем: кнопка целиком отдаётся иконке, пустого
   поля вокруг неё больше нет (специфика :has выше, чем у .btn-emoji). */
.btn-emoji:has(img) {
    padding: 0;
}

/* Арт эмодзи (256x256) вместо юникод-символа. Размер равен прежнему
   ВНЕШНЕМУ габариту кнопки (46x38 с отступами), только теперь это
   сплошная иконка; у кнопки её ширина выводится из содержимого, поэтому
   размер задан явно, а не через 100%. */
.btn-emoji img {
    display: block;
    width: 44px;
    height: 44px;
    object-fit: contain;
}

/* Пузырь и элемент панели имеют фиксированный размер — картинка занимает
   их целиком и вписывается по центру. */
.emoji-item img,
.emoji-bubble img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: contain;
}

/* У арта свой круглый фон — белую подложку пузыря убираем, иначе за
   прозрачными углами картинки проглядывал бы белый круг. */
.emoji-bubble:has(img) {
    background: transparent;
}

.emoji-wrap.open .btn-emoji {
    background: #d97706;
    box-shadow: inset 0 2px 6px rgba(0, 0, 0, 0.35);
}

/* --- выпадающая панель с эмодзи --- */
/* Пикер стоит внизу экрана, поэтому панель раскрывается ВВЕРХ */
.emoji-panel {
    display: none;
    position: absolute;
    bottom: calc(100% + 8px);
    left: 0;
    z-index: 90;
    /* 4 в ряд: панель остаётся компактной и не уезжает за край экрана.
       Размер иконок — 56px (было 40): арт эмоций 256x256, на сорока
       пикселях лица читались плохо, а выбирать приходилось «на глаз». */
    grid-template-columns: repeat(4, 1fr);
    gap: 6px;
    padding: 10px;
    border-radius: 14px;
    background: linear-gradient(180deg, #8b4a12, #6b3410);
    border: 2px solid #e8a33d;
    box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
}

.emoji-wrap.open .emoji-panel {
    display: grid;
    animation: emojiPanelPop 0.16s ease-out;
}

@keyframes emojiPanelPop {
    from { opacity: 0; transform: translateY(6px) scale(0.96); }
    to   { opacity: 1; transform: translateY(0) scale(1); }
}

.emoji-item {
    width: 56px;
    height: 56px;
    padding: 0;
    border: none;
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.1);
    /* Запасной юникод-вариант (у героя нет арта эмоций) — в размер иконки */
    font-size: 32px;
    line-height: 1;
    cursor: pointer;
    transition: transform 0.1s ease, background 0.12s ease;
}

.emoji-item:hover {
    background: rgba(255, 255, 255, 0.22);
    transform: scale(1.12);
}

.emoji-item:active {
    transform: scale(0.94);
}

/* --- пузырь с реакцией --- */
.emoji-bubble {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    z-index: 45;
    width: 52px;
    height: 52px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #fff;
    font-size: 30px;
    line-height: 1;
    box-shadow: 0 4px 14px rgba(0, 0, 0, 0.45);
    pointer-events: none;
    animation: emojiPop 0.28s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes emojiPop {
    0%   { opacity: 0; transform: translateX(-50%) scale(0.3); }
    70%  { transform: translateX(-50%) scale(1.15); }
    100% { opacity: 1; transform: translateX(-50%) scale(1); }
}

/* То же появление, но без горизонтального центрирования */
@keyframes emojiPopPlain {
    0%   { opacity: 0; transform: scale(0.3); }
    70%  { transform: scale(1.15); }
    100% { opacity: 1; transform: scale(1); }
}

/* Реакция соперника — справа и чуть выше окна соперника (игра с ботом).
   Якорь — .opp-window (position:relative); если арта нет — .bot-hand. */
.emoji-bubble-opp {
    top: -10px;
    left: calc(100% - 10px);
    right: auto;
    bottom: auto;
    transform: none;
    animation-name: emojiPopPlain;
}

/* Реакция конкретного соперника в мультиплеере — рядом с его местом.
   Якорь — сам .opponent-seat (position:relative), поэтому пузырь
   привязан к конкретному игроку. Ставим справа от его карт, по центру
   места: места стоят в ряд, и сбоку сразу видно, чья это реакция. */
.emoji-bubble-seat {
    /* Слева от места, на уровне карт: справа теперь кружок со счётчиком,
       а верх занят окном с аватаркой. Наружу (left:-100%) не выносим —
       у крайнего места пузырь срезал бы край стола (overflow:hidden). */
    top: auto;
    bottom: 4px;
    left: -14px;
    right: auto;
    transform: none;
    animation-name: emojiPopPlain;
}

/* Своя реакция — над окном персонажа слева внизу */
.emoji-bubble-me {
    bottom: calc(100% + 34px);
    /* Чуть правее центра: не наезжает на портрет, стоит у правого края окна */
    margin-left: 36px;
}

/* Новый арт места шире и выше прежнего окна, поэтому кнопку эмодзи и свой
   пузырь сдвигаем: кнопка — под правый край ленты с именем, пузырь — над
   головой персонажа, а не над серединой картинки. */
.tavern-seat-art .emoji-wrap {
    left: auto;
    right: -8px;
    bottom: 150px;
    transform: none;
}
.tavern-seat-art .emoji-bubble-me {
    bottom: calc(100% + 6px);
    margin-left: 72px;
}

/* Персонаж не выбран — окна нет, место схлопываем до кнопки эмодзи.
   Сдвигаем его от края, т.к. слева больше нет портрета. */
.tavern-seat-nochar {
    width: 0;
    height: 40px;
}
.tavern-seat-nochar .emoji-wrap {
    left: 0;
    margin-left: 0;
    bottom: 0;
    transform: none;
}
.tavern-seat-nochar .emoji-bubble-me {
    left: 26px;
}
/* Бейдж таймера у игрока без персонажа: место нулевой ширины, поэтому
   стандартные top/right увели бы его за левый край экрана. Ставим над
   кнопкой эмодзи. */
.tavern-seat-nochar .turn-timer {
    top: -26px;
    right: auto;
    left: 0;
}

/* Низкие/узкие экраны: панель и пузыри компактнее, чтобы не заслоняли стол.
   Иконки меньше десктопа, но крупнее прежних 34px: доска масштабируется
   целиком, и на телефоне 34px превращались в совсем нечитаемые значки. */
@media (max-width: 720px), (max-height: 520px) {
    .emoji-item {
        width: 46px;
        height: 46px;
        font-size: 26px;
    }
    .emoji-panel {
        gap: 4px;
        padding: 8px;
    }
    .emoji-bubble {
        width: 40px;
        height: 40px;
        font-size: 23px;
    }
    .btn-emoji {
        font-size: 17px;
        padding: 5px 8px;
    }
    .btn-emoji img {
        width: 38px;
        height: 38px;
    }
    /* Позицию .emoji-wrap не переопределяем: иконка должна стоять как
       на десктопе (у правого низа кресла), а не ниже. */
}

/* ==========================================================================
   Окно «Правила игры» на арте (img/new/rules). Заголовок на планке,
   крестик-картинка, текст с верёвочным скроллом внутри рамки.
   ========================================================================== */

.rules-box {
    position: relative;
    /* Пропорции арта окна 717x972 сохраняем при любом размере экрана */
    height: min(760px, calc((100dvh - 24px) * 0.92), calc((100vw - 24px) * 972 / 717));
    width: auto;
    aspect-ratio: 717 / 972;
    background: url('../img/new/rules/ui_rul_rules.webp') center / 100% 100% no-repeat;
    display: flex;
    flex-direction: column;
    /* cqw-единицы считаются от ширины окна — текст масштабируется с ним */
    container-type: inline-size;
}

/* --- шапка: заголовок на планке + крестик --- */
.rules-titlebar {
    position: relative;
    flex: 0 0 auto;
    height: 12.6%;
    display: flex;
    align-items: center;
    justify-content: center;
    /* Слева на арте закладка-книга, справа крестик — поджимаем текст */
    padding: 0 13% 0 11%;
}

.rules-title {
    color: #5b2c10;
    font-size: clamp(15px, 4.4cqw, 42px);
    font-weight: 900;
    letter-spacing: 0.5px;
    line-height: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* В окне «Как играть с друзьями» заголовок длиннее — чуть уменьшаем */
.mp-rules-title {
    font-size: clamp(12px, 3.4cqw, 30px);
}

.rules-close {
    position: absolute;
    top: 50%;
    right: 4%;
    transform: translateY(-50%);
    width: 8%;
    aspect-ratio: 1;
    padding: 0;
    background: none;
    isolation: isolate;
    border: none;
    border-radius: 50%;
    font-size: 0;
    color: transparent;
    cursor: pointer;
    transition: transform 0.12s ease, filter 0.12s ease;
}

.rules-close:hover {
    transform: translateY(-50%) scale(1.06);
}

.rules-close:active {
    transform: translateY(-50%) scale(0.95);
}

/* --- тело окна: текст + верёвочная полоса --- */
.rules-inner {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    gap: 2%;
    padding: 3% 7.5% 5.5% 10%;
}

/* Переопределяем старые .modal-body-правила: теперь это блок внутри арта */
.rules-box .rules-body {
    flex: 1 1 auto;
    min-width: 0;
    max-height: none;
    padding: 0 6px 0 0;
    overflow-y: auto;
    overflow-x: hidden;
    text-align: left;
    color: #f6e7d2;
    font-size: clamp(10px, 2.4cqw, 20px);
    line-height: 1.4;
    font-weight: 700;
    /* Родная полоса скрыта — рисуем свою справа (.rules-sb) */
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.rules-box .rules-body::-webkit-scrollbar {
    width: 0;
    height: 0;
    display: none;
}

.rules-box .rules-body h3 {
    margin: 0.9em 0 0.35em;
    color: #f0a94a;
    font-size: clamp(12px, 2.9cqw, 24px);
    font-weight: 900;
}

.rules-box .rules-body h3:first-child {
    margin-top: 0;
}

.rules-box .rules-body p {
    margin: 0 0 0.6em;
    color: #f6e7d2;
}

.rules-box .rules-body strong {
    color: #ffd23f;
    font-weight: 900;
}

/* --- верёвочный скроллбар окна правил --- */
.rules-sb {
    flex: 0 0 auto;
    width: 4.4%;
    min-width: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.rules-sb.is-hidden {
    visibility: hidden;
}

.rules-sb-up,
.rules-sb-down {
    flex: 0 0 auto;
    width: 100%;
    aspect-ratio: 43 / 37;
    padding: 0;
    border: none;
    background: center / contain no-repeat;
    cursor: pointer;
    transition: filter 0.12s ease, transform 0.12s ease;
    /* Выше слоя каната: конец каната заходит под стрелку, и она его
       перекрывает — стык читается как продолжение каната. */
    position: relative;
    z-index: 2;
}

.rules-sb-up {
    background-image: url('../img/new/scroll/ui_arrow_up.webp');
}

.rules-sb-down {
    background-image: url('../img/new/scroll/ui_arrow_down.webp');
}

.rules-sb-up:hover,
.rules-sb-down:hover {
    filter: brightness(1.12);
}

.rules-sb-up:active,
.rules-sb-down:active {
    transform: scale(0.92);
}

.rules-sb-track {
    position: relative;
    z-index: 0;
    flex: 1 1 auto;
    width: 100%;
    min-height: 0;
    /* Без вертикального margin: он укорачивал ход бегунка относительно
       видимой верёвки, и на краях оставался зазор. */
    cursor: pointer;
    touch-action: none;
}

/* Канат вынесен в отдельный слой на ::before, а не в фон самого ложа:
   слой выходит за верхнюю и нижнюю границы ложа на --sb-join и уходит
   под стрелки. У стрелок в основании вырез, канат заходит в него и
   обрывается уже под непрозрачной частью стрелки — стыка не видно. */
.rules-sb-track::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: calc(-1 * var(--sb-join));
    bottom: calc(-1 * var(--sb-join));
    z-index: 0;
    pointer-events: none;
    /* Канат — бесшовный тайл: из исходного арта вырезан ровно один период
       узора (206 px), поэтому repeat-y стыкуется без «перетяжки».
       Растягивать картинку на всю высоту не нужно — витки остаются
       натурального размера при любом размере окна.

       Тайл общий для всех четырёх лож (см. .cards-sb-track): во всех
       исходных артах нарисован один и тот же канат, отличались только
       палитра фона и длина. Поэтому лежит он в img/new/scroll, а не
       копией в папке каждого окна. */
    background-image: url('../img/new/scroll/ui_arrow_scroll_b_seamless.webp'), url('../img/new/scroll/ui_arrow_scroll_b_sh_seamless.webp');
    background-repeat: repeat-y, repeat-y;
    background-position: center top, center top;
    background-size: 50% auto, 50% auto;
}

.rules-sb-thumb {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    /* Выше слоя каната: бегунок — узел, он должен лежать поверх верёвки. */
    z-index: 1;
    /* Бегунок — общий узел 47x72 с фиксированными пропорциями: не тянем его,
       а задаём боксу ту же пропорцию (высоту считать в JS не нужно).
       contain при совпадающей пропорции зазоров уже не даёт.
       Тот же файл используется во всех окнах — см. .cards-sb-thumb. */
    aspect-ratio: 47 / 72;
    background: url('../img/new/scroll/ui_arrow_scroll_a.webp') center / contain no-repeat;
    cursor: grab;
}

.rules-sb-thumb:active {
    cursor: grabbing;
    filter: brightness(0.95);
}

/* ==========================================================================
   Навигация во время партии: кнопки-иконки поверх игрового поля справа.
   Порядок: Назад, Правила игры, меню (выпадающий список), Выход.
   Всё прочее убрано в список, чтобы на столе было минимум кнопок.
   ========================================================================== */

.game-nav {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 30;
    display: flex;
    align-items: center;
    gap: 6px;
}

.game-nav-btn {
    /* Нижнюю границу ниже ~29px не опускаем: на тач-экранах в кнопку
       перестаёт попадать палец. */
    width: clamp(29px, 3.9vw, 44px);
    aspect-ratio: 1;
    padding: 0;
    border: none;
    border-radius: 0;
    background: center / contain no-repeat;
    cursor: pointer;
    font-size: 0;
    color: transparent;
    filter: drop-shadow(0 3px 5px rgba(0, 0, 0, 0.45));
    transition: transform 0.12s ease, filter 0.12s ease;
}

.game-nav-btn:hover {
    transform: translateY(-2px);
    filter: drop-shadow(0 4px 7px rgba(0, 0, 0, 0.5)) brightness(1.08);
}

.game-nav-btn:active {
    transform: translateY(1px) scale(0.95);
}

.nav-back  { background-image: url('../img/new/button/ui_button_back.webp'); }
.nav-rules { background-image: url('../img/new/button/ui_button_who.webp'); }
.nav-multi { background-image: url('../img/new/button/ui_button_multi.webp'); }
/* Домик нарисован чуть шире прочих (87x79) — компенсируем, чтобы
   визуальный размер совпадал с соседями */
.nav-home  {
    background-image: url('../img/new/button/ui_button_home.webp');
    /* ~+9% к базовой кнопке — пропорция сохранена при уменьшении панели */
    width: clamp(32px, 4.3vw, 48px);
}

/* --- выпадающий список остальной навигации --- */
.game-nav-menu {
    position: relative;
    display: inline-flex;
}

.game-nav-list {
    display: none;
    position: absolute;
    top: calc(100% + 6px);
    right: 0;
    z-index: 60;
    min-width: 178px;
    flex-direction: column;
    gap: 3px;
    padding: 7px;
    border-radius: 12px;
    background: linear-gradient(180deg, #8b4a12, #6b3410);
    border: 2px solid #e8a33d;
    box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
}

.game-nav-menu.open .game-nav-list {
    display: flex;
    animation: gameNavPop 0.16s ease-out;
}

@keyframes gameNavPop {
    from { opacity: 0; transform: translateY(-6px) scale(0.97); }
    to   { opacity: 1; transform: translateY(0) scale(1); }
}

.game-nav-item {
    padding: 9px 12px;
    border: none;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.1);
    color: #f6e7d2;
    font-family: inherit;
    font-size: 14px;
    font-weight: 800;
    text-align: left;
    white-space: nowrap;
    cursor: pointer;
    transition: background 0.12s ease, color 0.12s ease;
}

.game-nav-item:hover {
    background: rgba(255, 255, 255, 0.22);
    color: #fff;
}

.game-nav-item:active {
    background: rgba(0, 0, 0, 0.2);
}

/* --- адаптив --- */
/* Узкие и низкие экраны: кнопки мельче, список компактнее. */
@media (max-width: 720px), (max-height: 520px) {
    .game-nav {
        top: 6px;
        right: 6px;
        gap: 4px;
    }
    .game-nav-item {
        padding: 8px 10px;
        font-size: 13px;
    }
    .game-nav-list {
        min-width: 156px;
    }
}

/* Совсем узкие экраны — список не должен уезжать за край поля */
@media (max-width: 420px) {
    .game-nav-list {
        min-width: 142px;
        padding: 6px;
    }
    .game-nav-item {
        font-size: 12px;
        padding: 7px 9px;
    }
}

/* ==========================================================================
   Уведомление об обработке персональных данных (первое посещение).
   Плашка у нижнего края экрана: не закрывает заставку и меню целиком,
   но лежит поверх них. Показом управляет assets/consent.js.
   ========================================================================== */
.consent-notice {
    position: fixed;
    left: 50%;
    bottom: max(12px, env(safe-area-inset-bottom));
    /* Ниже .rotate-notice (1000): в портрете просьба повернуть телефон
       важнее и должна перекрывать всё. */
    z-index: 950;
    width: min(880px, calc(100vw - 24px));
    display: flex;
    align-items: center;
    gap: clamp(10px, 2vw, 22px);
    padding: clamp(10px, 1.6vw, 18px) clamp(12px, 2vw, 24px);
    border-radius: 14px;
    /* Та же «деревянная» панель с золотой каймой, что у меню в партии */
    background: linear-gradient(180deg, #8b4a12, #6b3410);
    border: 2px solid #e8a33d;
    box-shadow: 0 0 0 3px rgba(43, 20, 6, 0.85), 0 14px 34px rgba(0, 0, 0, 0.65);
    color: #f6e7d2;
    opacity: 0;
    transform: translate(-50%, 24px);
    transition: opacity 0.28s ease, transform 0.28s ease;
}
.consent-notice[hidden] { display: none; }
.consent-notice.visible {
    opacity: 1;
    transform: translate(-50%, 0);
}
.consent-text { flex: 1 1 auto; min-width: 0; }
.consent-title {
    margin-bottom: 4px;
    font-size: clamp(14px, 1.7vw, 19px);
    font-weight: 900;
    color: #ffd98a;
    text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
}
.consent-desc {
    font-size: clamp(11px, 1.25vw, 14px);
    line-height: 1.4;
    font-weight: 600;
}
.consent-desc a {
    color: #ffd98a;
    font-weight: 800;
    text-decoration: underline;
    text-underline-offset: 2px;
    white-space: nowrap;
}
.consent-desc a:hover { color: #fff; }
.consent-buttons {
    flex: 0 0 auto;
    display: flex;
    flex-direction: column;
    gap: 6px;
}
/* Кнопки — те же плашки 230x69, что «Играть» / «В меню» */
.consent-btn {
    width: clamp(118px, 15vw, 170px);
    aspect-ratio: 230 / 69;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    border: none;
    border-radius: 0;
    background: center / 100% 100% no-repeat;
    color: #fff;
    font-family: inherit;
    font-size: clamp(13px, 1.6vw, 18px);
    font-weight: 900;
    letter-spacing: 0.3px;
    text-shadow: 0 2px 0 rgba(30, 12, 6, 0.55);
    cursor: pointer;
    transition: transform 0.1s ease, filter 0.12s ease;
}
.consent-accept { background-image: url('../img/new/button/ui_button_green.webp'); }
.consent-close  { background-image: url('../img/new/button/ui_button_blue.webp'); }
@media (hover: hover) {
    .consent-btn:hover { transform: translateY(-2px); filter: brightness(1.08); }
}
.consent-btn:active { transform: translateY(1px) scale(0.98); filter: brightness(0.9); }
.consent-btn:focus-visible { outline: 2px solid #ffd98a; outline-offset: 2px; }

/* Узкий экран (телефон в портрете до просьбы повернуть, узкое окно):
   текст сверху, кнопки в ряд под ним. */
@media (max-width: 560px) {
    .consent-notice { flex-direction: column; align-items: stretch; }
    .consent-buttons { flex-direction: row; justify-content: center; }
    .consent-desc a { white-space: normal; }
}
/* Низкий экран (телефон в ландшафте): плашка компактнее, чтобы не
   закрывать кнопку заставки и меню. */
@media (max-height: 480px) {
    .consent-notice { bottom: 6px; padding: 8px 12px; }
    .consent-title { margin-bottom: 2px; }
}
/* Широкий экран: кнопки в ряд — плашка ниже и не закрывает подсказку
   «Нажмите, чтобы начать» на заставке. */
@media (min-width: 900px) {
    .consent-notice { width: min(1080px, calc(100vw - 24px)); }
    .consent-buttons { flex-direction: row; gap: 10px; }
}

/* ---------- согласие с политикой в модалке ввода имени ----------
   Чекбокс рисуем сами (золотая рамка под стиль панели): нативный выглядит
   чужеродно и слишком мелкий для пальца. Сам input остаётся в разметке —
   работает с клавиатуры и читается скринридером. */
.name-consent {
    position: relative;
    display: flex;
    align-items: center;
    gap: 1.6cqw;
    width: 86%;
    margin: 1.6cqw 0 0;
    padding: 0.8cqw 1.2cqw;
    border-radius: 8px;
    color: #f3e2c0;
    font-size: clamp(10px, 2.5cqw, 15px);
    font-weight: 700;
    line-height: 1.25;
    text-align: left;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
    cursor: pointer;
}
.name-consent-input {
    position: absolute;
    opacity: 0;
    width: 1px;
    height: 1px;
    pointer-events: none;
}
.name-consent-box {
    flex: 0 0 auto;
    width: clamp(18px, 4.6cqw, 26px);
    aspect-ratio: 1;
    border-radius: 5px;
    border: 2px solid #e8a33d;
    background: rgba(43, 20, 6, 0.75);
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.6);
    position: relative;
    transition: background 0.12s ease, border-color 0.12s ease;
}
/* Галочка — повёрнутый уголок */
.name-consent-box::after {
    content: "";
    position: absolute;
    left: 32%;
    top: 10%;
    width: 30%;
    height: 58%;
    border: solid #fff;
    border-width: 0 3px 3px 0;
    transform: rotate(45deg) scale(0);
    transition: transform 0.12s ease;
}
.name-consent-input:checked + .name-consent-box {
    background: linear-gradient(180deg, #3fbf5a, #1f8a3a);
    border-color: #ffd98a;
}
.name-consent-input:checked + .name-consent-box::after { transform: rotate(45deg) scale(1); }
.name-consent-input:focus-visible + .name-consent-box { outline: 2px solid #ffd98a; outline-offset: 2px; }
.name-consent-text a {
    color: #ffd98a;
    font-weight: 800;
    text-decoration: underline;
    text-underline-offset: 2px;
}
.name-consent-text a:hover { color: #fff; }
/* Попытка начать игру без отметки: строка краснеет и вздрагивает */
.name-consent-error {
    background: rgba(220, 38, 38, 0.28);
    box-shadow: 0 0 0 2px #f87171;
    animation: nameConsentShake 0.35s ease;
}
.name-consent-error .name-consent-box { border-color: #f87171; }
@keyframes nameConsentShake {
    0%, 100% { transform: translateX(0); }
    20%, 60% { transform: translateX(-5px); }
    40%, 80% { transform: translateX(5px); }
}
/* Отступ перед кнопками уже задан выше как 2cqw — здесь стояло 2.2cqw и
   правило перебивало базу (правило ниже по файлу выигрывает при равной
   специфичности). Оставлено 2cqw, как в базе. */
