/* ============================================================
   base.css — механика колоды: сцена, навигация, обзор, печать.
   Никакой эстетики. Всё оформление живёт в теме варианта.
   Размеры внутри слайда задаются в cqw/cqh, поэтому слайд
   масштабируется сам: и на весь экран, и плиткой в обзоре.
   ============================================================ */

*, *::before, *::after { box-sizing: border-box; }
.svg-defs { position: absolute; width: 0; height: 0; overflow: hidden; }

html, body {
  height: 100%;
  margin: 0;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

body {
  background: var(--surface-sunken);
  color: var(--text);
  overflow: hidden;
}

/* var() внутри ::selection читается с элемента, которому принадлежит
   выделение, поэтому акцентным плоскостям достаточно переопределить
   --selection у себя — см. тему. */
::selection { background: var(--selection); }

/* ---------- сцена ---------- */

.deck {
  height: 100dvh;
  padding: var(--stage-pad, 0);
}

.slides {
  width: 100%;
  height: 100%;
  display: grid;
  place-items: center;
}

.slide {
  position: relative;
  /* Всё внутри слайда, включая метки с большим z-index, остаётся в его
     собственном слое. Панель управления всегда рисуется поверх. */
  isolation: isolate;
  width: min(100%, calc((100dvh - var(--stage-pad, 0px) * 2) * 16 / 9));
  aspect-ratio: 16 / 9;
  container-type: size;
  overflow: hidden;
  display: none;
  background: var(--bg);
  color: var(--text);
}

.slide[data-active] { display: block; }

/* внутренняя сетка слайда: поля одинаковые, содержимое — грид */
.pad {
  position: absolute;
  inset: 0;
  padding: var(--pad-y) var(--pad-x);
  display: flex;
  flex-direction: column;
}

/* ---------- обзор сеткой (G) и лентой (L) ----------
   Плитка пересобирает слайд в своём размере, а не уменьшает картинку:
   так текст остаётся чётким. Размеры внутри слайда заданы в cqw/cqh и
   потому масштабируются сами; отдельного внимания требует только
   разлиновка — см. --rule в теме. */

.deck[data-mode="grid"] {
  display: block;
  height: 100dvh;
  overflow-y: auto;
  padding: 2.5vw;
}

.deck[data-mode="grid"] .slides {
  height: auto;
  place-items: stretch;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 1.6vw;
}

.deck[data-mode="strip"] {
  --strip-slide-width: round(down, min(
    calc((100dvh - 7.5vw) * 8 / 9),
    calc((100dvw - 7.5vw) / 2)
  ), 16px);
  --strip-gap: round(down, 2.5vw, 1px);
  display: block;
  height: 100dvh;
  overflow: auto;
  padding: 2.5vw;
}

.deck[data-mode="strip"] .slides {
  display: flex;
  align-items: center;
  /* Целый зазор — половина условия для целого шага ленты, см. .slide ниже. */
  gap: var(--strip-gap);
}

.deck[data-mode="strip"][data-strip-direction="vertical"] .slides {
  height: auto;
  flex-direction: column;
}

/* Пустое место по краям позволяет поставить в центр даже первый и
   последний слайд. Из размера вычитается gap: flex добавляет его между
   распоркой и крайней плиткой. */
.deck[data-mode="strip"][data-strip-direction="vertical"] .slides::before,
.deck[data-mode="strip"][data-strip-direction="vertical"] .slides::after {
  content: "";
  flex: 0 0 max(0px, calc(50dvh - 2.5vw - var(--strip-slide-width) * 9 / 32 - var(--strip-gap)));
}

.deck[data-mode="strip"] .slide {
  /* Ширина кратна 16, поэтому высота при 16:9 выходит целым числом
     пикселей. Вместе с целым зазором это даёт целый шаг прокрутки:
     иначе плитка на каждом слайде садится на долю пикселя, текст
     пересэмплируется заново, и переключение стрелками рябит. */
  width: var(--strip-slide-width);
}

.deck[data-mode="strip"][data-strip-direction="horizontal"] {
  overflow-y: hidden;
}

.deck[data-mode="strip"][data-strip-direction="horizontal"] .slides {
  width: max-content;
  height: 100%;
  flex-direction: row;
}

.deck[data-mode="strip"][data-strip-direction="horizontal"] .slides::before,
.deck[data-mode="strip"][data-strip-direction="horizontal"] .slides::after {
  content: "";
  flex: 0 0 max(0px, calc(50dvw - 2.5vw - var(--strip-slide-width) / 2 - var(--strip-gap)));
}

.deck[data-mode="strip"][data-strip-direction="horizontal"] .slide {
  flex: 0 0 auto;
}

.deck[data-mode="grid"] .slide,
.deck[data-mode="strip"] .slide {
  display: block;
  cursor: pointer;
  outline: 1px solid var(--line, oklch(20% .02 60 / .18));
  outline-offset: 3px;
}
.deck[data-mode="grid"] .slide { width: 100%; }
/* Наведение отключено, пока идёт навигация с клавиатуры: обзор
   прокручивается под неподвижным курсором, и наведение иначе вспыхивает
   на попавших под него плитках — со стороны похоже, что выделение
   перескакивает на чужой слайд и только потом встаёт на нужный. */
.deck:not([data-input="keyboard"])[data-mode="grid"] .slide:hover,
.deck:not([data-input="keyboard"])[data-mode="strip"] .slide:hover {
  outline: 2px solid var(--accent-mark);
  outline-offset: 3px;
}
.deck[data-mode="grid"] .slide[data-active],
.deck[data-mode="strip"] .slide[data-active] {
  outline: 3px solid var(--accent-mark);
  outline-offset: 4px;
}
/* Наведение всегда добавляет вес, а не убавляет: иначе на текущем
   слайде — самом толстом — оно читалось бы как ослабление или не
   читалось вовсе. */
.deck:not([data-input="keyboard"])[data-mode="grid"] .slide[data-active]:hover,
.deck:not([data-input="keyboard"])[data-mode="strip"] .slide[data-active]:hover {
  outline-width: 5px;
  outline-offset: 4px;
}

/* ---------- справка по управлению ---------- */

.help-panel {
  --control-size: 2.5rem;
  --control-icon-size: 1rem;
  position: fixed;
  left: .75rem;
  right: .75rem;
  bottom: .75rem;
  z-index: 20;
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
  gap: .5rem;
  color: var(--text);
  font: 500 .8rem/1.2 var(--font-text);
}
.help-actions { display: flex; justify-self: start; gap: .2rem; }
.help-strip[data-direction="horizontal"] svg { transform: rotate(90deg); }
.help-theme .theme-icon-moon { display: none; }
:root[data-theme="light"] .help-theme .theme-icon-sun { display: none; }
:root[data-theme="light"] .help-theme .theme-icon-moon { display: block; }
.help-nav {
  display: grid;
  grid-template-columns: var(--control-size) auto var(--control-size);
  align-items: center;
  justify-self: center;
  gap: .2rem;
}
.help-panel button {
  position: relative;
  width: var(--control-size); height: var(--control-size);
  padding: 0;
  display: grid; place-items: center;
  border: 1px solid var(--line);
  background: var(--bg);
  color: var(--text);
  cursor: pointer;
}
.help-panel button svg {
  width: var(--control-icon-size); height: var(--control-icon-size);
  display: block;
  fill: none;
  stroke: currentColor;
  stroke-width: 1.9;
  stroke-linecap: round;
  stroke-linejoin: round;
}
.help-nav button svg { stroke-width: 2.25; }
.help-panel button:hover:not(:disabled),
.help-panel button:focus-visible {
  border-color: var(--accent-mark);
  color: var(--accent);
  outline: none;
}
.help-panel button:disabled {
  color: var(--muted, currentColor);
  opacity: .28;
  cursor: default;
}
.help-page {
  width: 5.5rem; height: var(--control-size);
  display: flex; align-items: center; justify-content: center; gap: .3rem;
  padding: 0 .45rem;
  color: var(--text);
  background: var(--bg);
  border: 1px solid var(--line);
  font: 700 .9rem/1 var(--font-display);
  font-variant-numeric: tabular-nums;
  cursor: text;
}
.help-page:focus-within { border-color: var(--accent-mark); }
.help-page-input {
  width: 2ch;
  min-width: 0;
  padding: 0;
  border: 0;
  outline: 0;
  color: inherit;
  background: transparent;
  font: inherit;
  text-align: right;
  font-variant-numeric: inherit;
}
.help-page-total { color: var(--muted); }
.help-close { justify-self: end; }
/* Одна строка панели занимает около 26rem. Уже неё панель собирается
   в две колонки по краям: слева обзор и полный экран столбиком, справа
   тема над закрытием, которое стоит на месте кнопки открытия панели.
   Навигация остаётся внизу по центру. Размер касания не меняется. */
@media (max-width: 30rem) {
  .help-panel {
    grid-template-columns: auto 1fr auto;
    grid-template-rows: auto auto;
    align-items: end;
    column-gap: .5rem;
    row-gap: .2rem;
  }
  .help-actions { display: contents; }
  .help-actions [data-deck-action="grid"] { grid-area: 1 / 1; }
  .help-actions [data-deck-action="fullscreen"] { grid-area: 2 / 1; }
  .help-theme { grid-area: 1 / 3; }
  .help-close { grid-area: 2 / 3; }
  .help-nav { grid-area: 2 / 2; }
  /* На узком экране кнопки ленты нет, клавиша L продолжает работать. */
  .help-panel .help-strip { display: none; }
}
.shortcut-key {
  position: absolute;
  z-index: 2;
  left: 50%; top: -.45rem;
  min-width: 1.65rem;
  padding: .28rem .4rem;
  transform: translate(-50%, -100%);
  border: 1px solid var(--line);
  background: var(--bg);
  color: var(--accent);
  font: 700 .75rem/1 var(--font-text);
  text-align: center;
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
}
.help-panel button:hover .shortcut-key,
.help-panel button:focus-visible .shortcut-key {
  transform: translate(-50%, -100%);
  opacity: 1;
  visibility: visible;
}
.help-panel[hidden] { display: none; }
.help-reveal-zone {
  position: fixed;
  right: 0; bottom: 0;
  z-index: 20;
  width: 7rem; height: 6rem;
  display: grid; place-items: end;
  padding: 0 .75rem .75rem 0;
  pointer-events: none;
}
.help-reveal {
  position: relative;
  width: 2.5rem; height: 2.5rem;
  padding: 0;
  display: grid; place-items: center;
  border: 1px solid var(--line);
  background: var(--bg);
  color: var(--text);
  cursor: pointer;
  outline: none;
  opacity: 0;
  pointer-events: none;
}
.help-reveal svg {
  width: 1rem; height: 1rem;
  fill: none;
  stroke: currentColor;
  stroke-width: 1.9;
  stroke-linecap: round;
  stroke-linejoin: round;
}
.help-reveal-zone.is-active .help-reveal,
.help-reveal:focus-visible {
  opacity: 1;
  pointer-events: auto;
}
.help-reveal:hover,
.help-reveal:focus-visible {
  border-color: var(--accent-mark);
  color: var(--accent);
}
.help-reveal:hover .shortcut-key,
.help-reveal:focus-visible .shortcut-key {
  transform: translate(-50%, -100%);
  opacity: 1;
  visibility: visible;
}
@media (hover: none), (pointer: coarse) {
  .help-reveal-zone { pointer-events: auto; }
  .help-reveal { opacity: 1; pointer-events: auto; }
  .help-reveal .shortcut-key { display: none; }
}
.help-reveal-zone:has(.help-reveal[hidden]) { display: none; }

/* ---------- пошаговое раскрытие ----------
   deck.js разворачивает каждое состояние в отдельную страницу.
   Между страницами меняется видимость.

   Движение — дело темы, и только на том, что раскрылось именно сейчас:
   deck.js помечает это место атрибутом data-reveal при переходе вперёд.
   Правило темы поэтому выглядит как `[data-reveal] .что-то { animation }`
   и само собой молчит на первом кадре, при возврате назад и в печати. */

.frag { opacity: 0; }
.frag[data-shown] { opacity: 1; }

/* ---------- печать в PDF ---------- */

/* Точный формат 16:9. Пара 297 × 167 мм чуть ниже нужной высоты:
   слайд с aspect-ratio занимал 167.0625 мм и в окне печати Chromium
   переносил остаток на отдельную белую страницу. */
@page { size: 320mm 180mm; margin: 0; }

/* Уменьшение движения описано в narrative.css. deck.js оставляет
   итоговые значения счётчиков, frame-video.js останавливает фон. */


@media print {
  /* Не отдаём браузеру право экономить краску: фоновые плоскости,
     градиентные дорожки и псевдоэлементы — часть композиции слайда. */
  *, *::before, *::after {
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
  }
  body { overflow: visible !important; background: oklch(99% .004 85); }
  /* Бумага и PDF — статические форматы: страница показывает конечный
     кадр. Анимации темы начинаются с пустого состояния, поэтому их
     снимаем, а не ждём. */
  *, *::before, *::after { animation: none !important; }
  .help-panel, .help-reveal-zone { display: none; }
  /* Режимы обзора имеют более специфичные селекторы вне media print.
     Сбрасываем их принудительно, чтобы печать из сетки или ленты
     оставалась обычной последовательностью страниц. */
  .deck {
    display: block !important;
    width: 100% !important;
    height: auto !important;
    padding: 0 !important;
    overflow: visible !important;
  }
  .slides {
    display: block !important;
    width: 100% !important;
    height: auto !important;
  }
  .slides::before, .slides::after { display: none !important; }
  .slide {
    display: block !important;
    width: 320mm !important;
    height: 180mm !important;
    max-width: none;
    aspect-ratio: auto;
    flex: none !important;
    break-after: page;
    break-inside: avoid;
    outline: none !important;
    transform: none !important;
  }
}
