/* AI-Таро — «Стол при свече»: деревянный стол в тёмной комнате, свеча за кадром.
   Карты и листы бумаги лежат НА столе. Токены — из design/stitch_run2/DESIGN.md. */
:root {
  /* стол */
  --table: #18120e;
  --table-deep: #120d09;
  --wood: #201b16;
  --wood-lit: #241f1a;
  --wood-high: #2f2924;
  /* свет свечи — единственный акцент */
  --glow: #fbb980;
  --glow-deep: #704214;
  /* текст на дереве */
  --on-wood: #ece0d8;
  --on-wood-dim: #d6c3b6;
  --on-wood-faint: #9e8e82;
  /* бумага */
  --paper: #eae3d3;
  --paper-2: #e2dac8;
  --ink: #241f1a;
  --ink-soft: #4a423a;
  --red: #8c3a2e;
  /* волосяные линии */
  --hair: #51443a;

  --display: "Bricolage Grotesque", "Segoe UI", system-ui, sans-serif;
  --body: "Literata", Georgia, "Times New Roman", serif;

  --r-sm: .5rem;
  --r: 1rem;
  --r-lg: 2rem;
}

* { box-sizing: border-box; margin: 0; padding: 0; }
/* display у .waiting/.result перебивает атрибут hidden — возвращаем ему силу,
   иначе скрытый оверлей ожидания висит поверх страницы и съедает клики */
[hidden] { display: none !important; }

body {
  font-family: var(--body);
  color: var(--on-wood);
  min-height: 100vh;
  background:
    /* свет свечи сверху слева, затухание к правому нижнему углу */
    radial-gradient(120% 90% at 12% 6%, rgba(251,185,128,.13) 0%, transparent 58%),
    radial-gradient(90% 70% at 88% 96%, rgba(0,0,0,.55) 0%, transparent 62%),
    linear-gradient(158deg, var(--wood) 0%, var(--table) 46%, var(--table-deep) 100%);
  background-attachment: fixed;
  padding: env(safe-area-inset-top) env(safe-area-inset-right)
           env(safe-area-inset-bottom) env(safe-area-inset-left);
}

/* ── угли: фоновый ролик ─────────────────────────────────────────
   Жар стоит в ШАПКЕ: свет падает сверху — там же, где светит свеча
   в градиенте стола, поэтому источник света на странице остаётся один.
   Ролик портретный, жар в нём сидит полосой на 57–83% высоты кадра —
   отсюда object-position, иначе в окно попадёт тёмная зона над углями. */
.bg-video {
  position: fixed; inset: 0 0 auto 0; z-index: 0;
  /* полоса ниже, чем была (46vh): кадр прижат нижней кромкой, поэтому
     укоротить окно = подтянуть жар вверх, к заголовку */
  width: 100%; height: 38vh;
  /* center bottom: кадр прижат нижней кромкой окна, поэтому жар
     (57–83% кадра) на мобильном ложится на 16–190px от верха — за
     заголовком, а не под листом расклада */
  object-fit: cover; object-position: center bottom;
  pointer-events: none;
  /* затемнений у ролика больше нет ни одного: ни прозрачности, ни тени,
     ни гашения по маске — кадр показывается таким, каким снят.
     Маска оставлена ТОЛЬКО как стык: последние 12% высоты растворяют
     нижнюю кромку, иначе кадр обрывается прямой линией поперёк экрана. */
  opacity: 1;
  filter: saturate(.85);
  -webkit-mask-image: linear-gradient(to bottom, #000 88%, transparent 100%);
          mask-image: linear-gradient(to bottom, #000 88%, transparent 100%);
}
/* на широком экране кадр раздувается втрое — там свой горизонтальный кроп
   (выбирает app.js), и жар в нём занимает весь кадр */
@media (orientation: landscape) {
  .bg-video { height: 34vh; }
}
/* ролик и шейдер спорят за один и тот же свет — шейдеру остаётся дым */
#candle { opacity: .22; }
body.is-waiting #candle { opacity: .45; }

/* шейдер свечи: мерцание + дым. Лежит под всем, поверх фона стола. */
#candle {
  position: fixed; inset: 0; z-index: 0;
  width: 100%; height: 100%; display: block;
  pointer-events: none;
  transition: opacity .9s ease;
}

/* волокно дерева: тонкая полосатая текстура поверх заливки */
.grain {
  position: fixed; inset: 0; z-index: 0; pointer-events: none;
  opacity: .5; mix-blend-mode: overlay;
  background:
    repeating-linear-gradient(96deg,
      rgba(255,255,255,.015) 0px, rgba(255,255,255,.015) 1px,
      transparent 1px, transparent 3px),
    repeating-linear-gradient(93deg,
      rgba(0,0,0,.05) 0px, rgba(0,0,0,.05) 2px,
      transparent 2px, transparent 9px);
}

.wrap {
  position: relative; z-index: 1;
  max-width: 620px; margin: 0 auto;
  padding: 44px 16px 40px;
}

/* ── стеклянная рамка ─────────────────────────────────
   Гасим ПОД самими буквами, а не над фоном, — угли остаются в полную силу,
   а надпись получает свою подложку. Стекло, а не лист бумаги: сквозь него
   виден жар, кромка ловит свет свечи.
   🔴 На экране расклада она обязательна: ролик приклеен к окну
   (position:fixed), поэтому при прокрутке под жар проезжает любая надпись —
   подпись позиции над картой давала на углях 1.12. */
.hero h1,
.result h2,
.card .pos {
  border: 1px solid rgba(251,185,128,.20);
  border-radius: var(--r-sm);
  background: rgba(14,10,7,.62);
  backdrop-filter: blur(2px);
  -webkit-backdrop-filter: blur(2px);
  box-shadow: inset 0 1px 0 rgba(251,185,128,.06);
}

/* ── шапка ───────────────────────────────────────────── */
/* отступ держит зазор, который раньше занимал подзаголовок: без него блок
   вопроса поднимается прямо в жар и «ТВОЙ ВОПРОС» теряет контраст (3.02) */
.hero { text-align: center; margin-bottom: 116px; }
/* inline-block — рамка садится по ширине названия, а не во всю колонку */
.hero h1 {
  display: inline-block;
  font-family: var(--display);
  /* кегль сбавлен (было 2–2.9rem): в рамке крупная надпись читается вывеской,
     мелкая — табличкой на двери, что ближе к столу при свече */
  font-weight: 700; font-size: clamp(1.35rem, 5.2vw, 1.75rem);
  /* при мелком кегле буквы перестают слипаться от отрицательного трекинга —
     наоборот, лёгкая разрядка держит слово ровным */
  letter-spacing: .04em; line-height: 1.15;
  color: var(--glow);
  /* мягкий разлив света от букв, без «золотого» градиента */
  text-shadow: 0 0 18px rgba(251,185,128,.22);
  /* поля кратны кеглю и разведены по вертикали 1:1 — рамка сидит плотно */
  padding: 9px 20px 10px;
  box-shadow: inset 0 1px 0 rgba(251,185,128,.06), 0 10px 30px rgba(0,0,0,.35);
}

/* ── общий вид листа бумаги на столе ─────────────────── */
.sheet {
  position: relative;
  background: linear-gradient(174deg, var(--paper) 0%, var(--paper-2) 100%);
  color: var(--ink);
  border-radius: 3px;
  padding: 24px 22px;
  /* тень под листом + тёмная кромка = толщина бумаги */
  box-shadow:
    0 1px 0 rgba(0,0,0,.5),
    0 14px 34px rgba(0,0,0,.5),
    0 3px 10px rgba(0,0,0,.35);
}
/* лист лежит на столе неровно */
.sheet.tilt-l { transform: rotate(-1.1deg); }
.sheet.tilt-r { transform: rotate(.9deg); }

/* ── поле вопроса: выемка, выцарапанная в дереве ─────── */
.groove-label {
  display: block; font-size: 12px; font-weight: 600;
  letter-spacing: .05em; text-transform: uppercase;
  /* --on-wood-faint давал 4.01 на столе — ниже планки 4.5 для мелкого текста */
  color: var(--on-wood-dim); margin-bottom: 8px;
}
textarea, #more-input {
  width: 100%; font-family: var(--body); font-size: 16px; /* 16px = без зума на iOS */
  color: var(--on-wood); background: var(--table-deep);
  border: none; border-radius: var(--r-sm);
  padding: 13px 15px; resize: vertical; line-height: 1.5;
  /* вдавленность: тёмная тень внутрь + светлая кромка снизу */
  box-shadow:
    inset 0 2px 7px rgba(0,0,0,.75),
    inset 0 -1px 0 rgba(251,185,128,.07);
}
textarea::placeholder, #more-input::placeholder { color: var(--on-wood-faint); opacity: .75; }
textarea:focus, #more-input:focus {
  outline: none;
  box-shadow:
    inset 0 2px 7px rgba(0,0,0,.75),
    inset 0 -1px 0 rgba(251,185,128,.10),
    0 0 0 1px rgba(251,185,128,.35),
    0 0 18px rgba(251,185,128,.15);
}

/* ── оглавление раскладов на листе бумаги ────────────── */
.toc { margin: 22px 0 24px; padding: 26px 22px 22px; }
.toc-label {
  text-align: center; font-size: 12px; font-weight: 600;
  letter-spacing: .18em; text-transform: uppercase;
  color: var(--ink-soft); margin-bottom: 14px;
}
.toc-list { list-style: none; }
.toc-row {
  /* строка оглавления: имя · выноска точками · число карт */
  display: flex; align-items: baseline; gap: 8px;
  width: 100%; padding: 11px 0 11px 20px;
  background: none; border: none; cursor: pointer;
  font-family: var(--body); color: var(--ink); text-align: left;
}
/* «поцарапанный» разделитель — не достаёт до краёв листа */
.toc-list li + li .toc-row { border-top: 1px solid rgba(36,31,26,.16); }
.toc-name {
  font-size: 16px; white-space: nowrap; /* имена не переносятся */
  transition: font-weight .15s ease;
}
.toc-dots {
  flex: 1 1 auto; min-width: 14px;
  /* выноска точками, посаженная на базовую линию */
  border-bottom: 2px dotted rgba(36,31,26,.32);
  transform: translateY(-4px);
}
.toc-num {
  font-size: 15px; color: var(--red); font-variant-numeric: tabular-nums;
  min-width: 1.6em; text-align: right;
}
/* выбранная строка: жирнее + красная манипула в поле слева */
.toc-row[aria-checked="true"] .toc-name { font-weight: 600; }
.toc-row[aria-checked="true"]::before {
  content: ""; position: absolute; left: 0;
  /* нарисованный треугольник вместо глифа ☞ — шрифты его часто не содержат */
  border: 5px solid transparent; border-left: 8px solid var(--red);
  transform: translateY(.35em);
}
.toc-row { position: relative; }
.toc-row:focus-visible { outline: 2px solid var(--red); outline-offset: 2px; }
@media (hover: hover) {
  .toc-row:hover .toc-name { color: #000; }
  .toc-row:hover .toc-dots { border-bottom-color: rgba(36,31,26,.5); }
}

/* закладки разделов: шапка листа с оглавлением */
.tabs {
  display: flex; flex-wrap: wrap; justify-content: center; gap: 2px;
  margin: 0 -4px 6px; padding-bottom: 6px;
  border-bottom: 1px solid rgba(36,31,26,.18);
}
.tab {
  position: relative; padding: 6px 10px;
  background: none; border: none; cursor: pointer;
  font-family: var(--display); font-size: 12px; font-weight: 600;
  letter-spacing: .12em; text-transform: uppercase;
  color: var(--ink-soft);
}
/* выбранная закладка: тёмная краска и красное подчёркивание вместо фона —
   фоновая плашка на бумаге читалась бы наклейкой, а не разделом */
.tab[aria-selected="true"] { color: var(--ink); font-weight: 700; }
.tab[aria-selected="true"]::after {
  content: ""; position: absolute; left: 8px; right: 8px; bottom: -7px;
  height: 2px; background: var(--red);
}
.tab:focus-visible { outline: 2px solid var(--red); outline-offset: 2px; }
@media (hover: hover) { .tab:hover { color: #000; } }

/* лист с датой рождения — появляется только под нумерологию */
.birth {
  margin: -8px 0 24px; padding: 18px 22px;
  display: flex; align-items: center; justify-content: center;
  gap: 14px; flex-wrap: wrap;
}
.birth-label {
  font-size: 12px; font-weight: 600; letter-spacing: .18em;
  text-transform: uppercase; color: var(--ink-soft);
}
/* поле на бумаге: не коробка, а строка с пунктиром, как в бланке.
   16px обязательны — на меньшем iOS зумит страницу при фокусе */
#birth-date {
  font-family: var(--body); font-size: 16px; color: var(--ink);
  background: none; border: none;
  border-bottom: 2px dotted rgba(36,31,26,.45);
  padding: 3px 6px;
}
#birth-date:focus-visible { outline: 2px solid var(--red); outline-offset: 3px; }

/* ── кнопки ──────────────────────────────────────────── */
.btn-primary {
  display: block; width: 100%; padding: 15px;
  font-family: var(--display); font-weight: 700; font-size: .95rem;
  letter-spacing: .06em; text-transform: uppercase;
  color: #2e1500; cursor: pointer; border: none; border-radius: 999px;
  background: linear-gradient(180deg, #a4682a 0%, var(--glow-deep) 100%);
  box-shadow:
    inset 0 1px 0 rgba(255,220,193,.45),
    0 8px 24px rgba(0,0,0,.45),
    0 0 26px rgba(251,185,128,.12);
  transition: filter .18s ease, box-shadow .25s ease, transform .12s ease;
}
.btn-primary:hover { filter: brightness(1.1); box-shadow: inset 0 1px 0 rgba(255,220,193,.5), 0 8px 26px rgba(0,0,0,.5), 0 0 34px rgba(251,185,128,.28); }
.btn-primary:active { transform: translateY(1px); }
.btn-primary:disabled { opacity: .55; cursor: wait; filter: none; }

.link-quiet {
  display: block; margin: 26px auto 0; padding: 8px 14px;
  background: none; border: none; cursor: pointer;
  font-family: var(--body); font-size: .9rem; letter-spacing: .04em;
  color: var(--on-wood-faint); text-transform: uppercase;
}
.link-quiet:hover { color: var(--glow); }

/* ── расклад: карты лежат на столе ───────────────────── */
.result { position: relative; margin-top: 40px; padding-top: 36px; }
/* «поцарапанный» разделитель на дереве — не достаёт до краёв экрана */
.result::before {
  content: ""; position: absolute; top: 0; left: 15%; right: 15%;
  height: 1px; background: linear-gradient(90deg,
    transparent, rgba(158,142,130,.30) 22%, rgba(158,142,130,.30) 78%, transparent);
}
.result h2 {
  font-family: var(--display); font-weight: 700; font-size: 1.35rem;
  text-align: center; color: var(--on-wood); margin-bottom: 20px;
  /* fit-content + авто-поля: рамка садится по названию расклада и остаётся
     по центру, при этом разметку трогать не пришлось */
  width: fit-content; margin-left: auto; margin-right: auto;
  padding: 7px 16px 8px;
}
.cards {
  display: flex; flex-wrap: wrap; gap: 12px; justify-content: center;
  margin: 0 auto 26px; max-width: 440px;
}
.card {
  flex: 0 1 calc((100% - 24px) / 3); min-width: 84px; max-width: 130px;
  display: flex; flex-direction: column; align-items: center; gap: 6px;
  text-align: center;
  /* содержимое прижато к низу: подпись позиции бывает и в одну строку, и в три
     («8 дом — кризисы и чужие деньги»), и при верхнем выравнивании карты
     в ряду разъезжались по высоте. Снизу же всё совпадает при любой подписи */
  justify-content: flex-end;
  /* карты положены на стол неровно */
  transform: rotate(var(--tilt, 0deg));
  animation: lay .5s ease both var(--d, 0s);
}
@keyframes lay {
  from { opacity: 0; transform: translateY(12px) rotate(var(--tilt, 0deg)); }
  to   { opacity: 1; transform: rotate(var(--tilt, 0deg)); }
}
.card .pos {
  font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase;
  /* --on-wood-faint на подложке давал 3.25 — для 11px этого мало даже со
     стеклом под буквами, поэтому подпись поднята на тон */
  color: var(--on-wood-dim); min-height: 2.6em;
  display: flex; align-items: center; justify-content: center; text-align: center;
  line-height: 1.3;
  padding: 3px 6px;
  /* высота коробки — по ТРЁМ строкам, а не по двум: подписи в ряду разной
     длины, и пока рамки не было, разнобой не бросался в глаза. Теперь рамки
     обязаны стоять на одной линии, иначе ряд едет ступеньками */
  min-height: calc(3.9em + 8px);
}
/* пропорции сканов Райдера–Уэйта: 500×~863 (0.579). Ставим ту же коробку,
   иначе object-fit:cover срезает ~7% высоты вместе с рамкой и подписью карты */
.card .art { width: 100%; aspect-ratio: 500 / 863; perspective: 900px; }
.card .art-inner {
  position: relative; width: 100%; height: 100%;
  transform-style: preserve-3d; transform: rotateY(180deg);
  animation: cardflip .9s cubic-bezier(.2,.75,.25,1) both calc(var(--d, 0s) + .18s);
}
@keyframes cardflip { from { transform: rotateY(180deg); } to { transform: rotateY(0); } }
.card .art .front, .card .art .back {
  position: absolute; inset: 0; border-radius: 4px; overflow: hidden;
  -webkit-backface-visibility: hidden; backface-visibility: hidden;
  box-shadow: 0 6px 18px rgba(0,0,0,.55), inset 0 0 0 1px rgba(158,142,130,.28);
}
.card .art .front { background: var(--wood-lit); }
.card .art .front img { width: 100%; height: 100%; object-fit: cover; display: block; }
.card.rev .art .front img { transform: rotate(180deg); }
/* рубашка: гравированный узор по тёмному дереву, ЗАЛИТАЯ (не прозрачная) */
.card .art .back {
  transform: rotateY(180deg);
  background:
    linear-gradient(150deg, rgba(251,185,128,.07), transparent 55%),
    repeating-linear-gradient(45deg,
      var(--wood-lit) 0px, var(--wood-lit) 7px,
      #2a231d 7px, #2a231d 14px);
  box-shadow: 0 6px 18px rgba(0,0,0,.55), inset 0 0 0 1px rgba(112,66,20,.7);
}
/* тонкая рамка внутри рубашки — как тиснение на картоне */
.card .art .back::after {
  content: ""; position: absolute; inset: 7px;
  border: 1px solid rgba(112,66,20,.85); border-radius: 2px;
}
.card .art .front.noimg {
  background: repeating-linear-gradient(45deg,
    var(--wood-lit) 0px, var(--wood-lit) 7px, #2a231d 7px, #2a231d 14px);
}
.card .name {
  font-size: .88rem; font-weight: 600; color: var(--on-wood); line-height: 1.2;
  /* место под две строки: у длинных имён («Девятка Пентаклей») подпись переносится
     и сбивает положение слова «прямая» — в ряду это видно как рваную нижнюю линию */
  min-height: 2.4em;
  opacity: 0; animation: reveal .45s ease both calc(var(--d, 0s) + .74s);
}
.card .orient {
  font-size: .8rem; font-style: italic; color: var(--on-wood-faint);
  opacity: 0; animation: reveal .45s ease both calc(var(--d, 0s) + .82s);
}
.card.rev .orient { color: #e0976b; }
/* нумерология печатает в этом слоте расчёт («15 + 3 + 1990 = 2008 → 10»):
   он бывает в одну строку и в две, а карты выровнены по низу — без места
   под вторую строку соседние карты в ряду разъезжаются по высоте */
#cards.calc .orient { min-height: 3em; font-style: normal; }
@keyframes reveal { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }

/* ── трактовка на бумаге ─────────────────────────────── */
.reading { font-size: 1.06rem; line-height: 1.62; }
/* отступ между абзацами нужен и в трактовке, и в листах ответа: глобальный
   сброс margin обнуляет <p>, иначе ответ модели слипается в стену текста */
.reading p, .msg.bot p { margin-bottom: 15px; }
.reading p:last-child, .msg.bot p:last-child { margin-bottom: 0; }
/* если первый абзац короткий, буквица заезжает в следующий — сбрасываем обтекание */
.reading p + p { clear: left; }
/* буквица красной краской */
.reading p:first-child::first-letter {
  font-family: var(--display); font-weight: 800; font-size: 3.1rem; line-height: .82;
  float: left; margin: 6px 9px 0 0; color: var(--red);
}

/* пока модель печатает — тлеющий курсор той же краской, что и буквица */
.streaming p:last-child::after {
  content: ""; display: inline-block;
  width: .42em; height: 1.02em;
  margin-left: .1em; vertical-align: -.16em;
  background: var(--red); opacity: .75;
  animation: caret 1.05s steps(1) infinite;
}
@keyframes caret { 50% { opacity: 0; } }

/* ── диалог по раскладу ──────────────────────────────── */
.followup { margin-top: 26px; }
.chat { display: flex; flex-direction: column; gap: 20px; }

/* вопрос ВЫРЕЗАН в дереве: не бумага, не контейнер */
.msg.user {
  align-self: flex-end; max-width: 88%;
  font-style: italic; font-size: 1.02rem; line-height: 1.5;
  text-align: right; color: var(--on-wood-dim);
  /* тёмная тень сверху + светлая снизу = врезано в поверхность */
  text-shadow: 0 -1px 1px rgba(0,0,0,.9), 0 1px 0 rgba(251,185,128,.13);
}
/* ответ — свежий лист, положенный поверх стопки */
.msg.bot {
  align-self: flex-start; max-width: 94%;
  background: linear-gradient(174deg, var(--paper) 0%, var(--paper-2) 100%);
  color: var(--ink); border-radius: 3px; padding: 20px 20px 18px;
  font-size: 1.02rem; line-height: 1.6;
  box-shadow: 0 1px 0 rgba(0,0,0,.5), 0 12px 30px rgba(0,0,0,.5);
}
/* листы ложатся попеременно, чуть внахлёст */
.msg.bot:nth-of-type(4n+2) { transform: rotate(-.9deg); }
.msg.bot:nth-of-type(4n+4) { transform: rotate(.7deg); }
/* красная черта в верхнем поле листа */
.msg.bot::before {
  content: ""; display: block; width: 52px; height: 2px;
  background: var(--red); opacity: .8; margin-bottom: 14px;
}
/* ответ пишется: три чернильные точки */
.msg.bot.pending { color: var(--ink-soft); }
.dots { display: inline-flex; gap: 6px; }
.dots i {
  width: 5px; height: 5px; border-radius: 50%; background: var(--ink-soft);
  animation: inkdot 1.3s ease-in-out infinite;
}
.dots i:nth-child(2) { animation-delay: .18s; }
.dots i:nth-child(3) { animation-delay: .36s; }
@keyframes inkdot { 0%, 100% { opacity: .25; } 50% { opacity: .9; } }

/* строка «спросить ещё» — на дереве под стопкой */
.ask-more { display: flex; gap: 10px; align-items: center; margin-top: 22px; }
.ask-more #more-input { flex: 1; min-width: 0; }
#more-btn {
  flex: 0 0 auto; width: 54px; height: 46px;
  font-size: 1.3rem; color: #2e1500; cursor: pointer;
  border: none; border-radius: 999px;
  background: linear-gradient(180deg, #a4682a 0%, var(--glow-deep) 100%);
  box-shadow: inset 0 1px 0 rgba(255,220,193,.4), 0 6px 18px rgba(0,0,0,.45);
}
#more-btn:hover { filter: brightness(1.1); }

/* ── экран ожидания ──────────────────────────────────── */
.waiting {
  position: fixed; inset: 0; z-index: 5;
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  gap: 48px; background: rgba(18,13,9,.975);
  backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px);
  animation: fadein .4s ease both;
}
@keyframes fadein { from { opacity: 0; } to { opacity: 1; } }
.waiting .backs { display: flex; gap: 14px; align-items: center; }
/* три рубашки на столе под разными углами, дальняя тонет в тени */
.waiting .back-card {
  width: 78px; aspect-ratio: 500 / 863; border-radius: 4px;
  transform: rotate(var(--tilt));
  background:
    linear-gradient(150deg, rgba(251,185,128,.08), transparent 55%),
    repeating-linear-gradient(45deg,
      var(--wood-high) 0px, var(--wood-high) 7px, var(--wood-lit) 7px, var(--wood-lit) 14px);
  box-shadow: 0 10px 26px rgba(0,0,0,.6), inset 0 0 0 1px rgba(112,66,20,.75);
  opacity: var(--lit);
}
.waiting .back-card::after {
  content: ""; position: absolute; inset: 7px;
  border: 1px solid rgba(112,66,20,.85); border-radius: 2px;
}
.waiting .back-card { position: relative; }
.waiting p {
  font-style: italic; font-size: 1.15rem; color: var(--on-wood-dim);
  animation: breathe 3.4s ease-in-out infinite;
}
@keyframes breathe { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }


/* ── карта крупно: поднята со стола к свече ──────────── */
/* плитка кликабельна — курсор и лёгкий подъём подсказывают это */
.card .art { cursor: zoom-in; }
/* поднимаем саму .art, а не .art-inner: у неё transform занят анимацией переворота */
.card .art:hover { transform: translateY(-3px); }
.card .art:focus-visible { outline: 2px solid var(--glow); outline-offset: 3px; }

.viewer {
  position: fixed; inset: 0; z-index: 6;
  display: flex; align-items: center; justify-content: center;
  padding: calc(env(safe-area-inset-top) + 46px) 18px
           calc(env(safe-area-inset-bottom) + 18px);
  background:
    radial-gradient(70% 55% at 50% 34%, rgba(251,185,128,.10) 0%, transparent 70%),
    rgba(10,7,5,.955);
  backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
  animation: fadein .25s ease both;
}
.viewer-card { display: flex; flex-direction: column; align-items: center; gap: 14px; }
.viewer-card img {
  display: block; width: auto; height: auto;
  max-width: min(92vw, 460px);
  /* высота — весь экран минус подпись и отступы. Пропорции НЕ навязываем:
     у сканов Райдера–Уэйта они гуляют 0.568–0.596, и cover срезал бы кромку
     с римской цифрой — в плитке это незаметно, в полный экран лезет в глаза */
  /* 240 = подпись в три строки: имя, позиция и ключевые слова (на телефоне — в две) */
  max-height: calc(100dvh - 240px);
  border-radius: 6px;
  /* поворот перевёрнутой карты держим переменной: иначе анимация появления
     подхватывает rotate(180deg) как конечное состояние и карта закручивается */
  transform: rotate(var(--rot, 0deg));
  box-shadow: 0 26px 60px rgba(0,0,0,.7), 0 0 44px rgba(251,185,128,.13),
              inset 0 0 0 1px rgba(158,142,130,.3);
  animation: raise .35s cubic-bezier(.2,.75,.25,1) both;
}
/* пока грузится крупный скан, в кадре стоит плитка из кеша — мягко размываем её,
   чтобы подмена на резкий скан читалась как наводка резкости, а не как рывок */
.viewer-card img.loading { filter: blur(6px) saturate(.9); }
.viewer-card img { transition: filter .3s ease; }
.viewer-card img.rev { --rot: 180deg; }
@keyframes raise {
  from { opacity: 0; transform: translateY(14px) scale(.97) rotate(var(--rot, 0deg)); }
}
.viewer-card figcaption {
  text-align: center; display: flex; flex-direction: column; gap: 3px;
}
.viewer-name {
  font-family: var(--display); font-size: 1.25rem; font-weight: 700;
  color: var(--on-wood); letter-spacing: .01em;
}
.viewer-orient { font-style: italic; color: var(--on-wood-faint); font-size: .92rem; }
.viewer.is-rev .viewer-orient { color: #e0976b; }
/* суть карты по Уэйту — под подписью, узкой колонкой, чтобы не растягивалась в строку на всю ширину */
.viewer-keys {
  max-width: 34ch; margin: 4px auto 0; font-family: var(--body);
  font-size: .95rem; line-height: 1.35; color: var(--on-wood-dim);
}
.viewer-keys:empty { display: none; }
.viewer-close {
  position: absolute; top: calc(env(safe-area-inset-top) + 10px); right: 14px;
  width: 42px; height: 42px; border: none; border-radius: 999px;
  background: rgba(47,41,36,.8); color: var(--on-wood-dim);
  font-size: 1.6rem; line-height: 1; cursor: pointer;
}
.viewer-close:hover { color: var(--glow); }
/* пока карта открыта, стол под ней не прокручивается */
body.is-viewing { overflow: hidden; }

/* ошибка живёт на бумажном листе, поэтому тёмная краска на светлой плашке:
   прежний светло-розовый текст на розовом фоне почти не читался */
.error {
  color: var(--red); text-align: center; padding: 14px;
  font-style: italic;
  background: rgba(140,58,46,.1); border: 1px solid rgba(140,58,46,.28);
  border-radius: var(--r-sm);
}
.msg.bot .error { color: #93000a; background: none; padding: 0; text-align: left; }

.foot {
  text-align: center; color: var(--on-wood-faint); font-size: .76rem;
  margin-top: 34px; line-height: 1.5;
}

/* ── узкие телефоны ──────────────────────────────────── */
/* Пять закладок должны лечь в ОДНУ строку: одинокая пятая на втором ряду
   читается как ошибка вёрстки, а не как раздел. Порог 620px — там полоса
   перестаёт вмещать закладки в 12px, задолго до общего мобильного 420px. */
@media (max-width: 620px) {
  .tab { font-size: 10.5px; padding: 6px 5px; letter-spacing: .04em; }
}
/* Шесть закладок в одну строку на телефон не влезают. Ряд 4+2 читается
   как случайный перенос, поэтому ниже 450px раскладываем их сеткой 3×2:
   ровные колонки выглядят задуманными. row-gap держит место под красное
   подчёркивание выбранной закладки — оно висит на 7px ниже кнопки. */
@media (max-width: 450px) {
  .tabs { display: grid; grid-template-columns: repeat(3, 1fr); row-gap: 12px; }
}
@media (max-width: 380px) {
  .tabs { gap: 0; row-gap: 12px; }
  .tab { font-size: 10px; padding: 6px 3px; }
}

@media (max-width: 420px) {
  .wrap { padding: 30px 14px 32px; }
  .toc { padding: 22px 16px 18px; }
  /* на узком экране длинное имя расклада с nowrap выталкивало число карт
     за край листа (было и до закладок: «Прошлое — Настоящее — Будущее») */
  .toc-name { font-size: 14px; white-space: normal; }
  .toc-row { padding-left: 17px; }
  .sheet { padding: 20px 17px; }
  .card { min-width: 76px; }
  .card .pos { font-size: 10px; }
  .viewer { padding-left: 12px; padding-right: 12px; }
  .viewer-name { font-size: 1.12rem; }
  .waiting { gap: 40px; }
  .waiting .back-card { width: 66px; }
}

/* ── уважение к «меньше движения» ────────────────────── */
@media (prefers-reduced-motion: reduce) {
  .card, .card .art-inner, .card .name, .card .orient,
  .waiting, .waiting p, .dots i, #candle, .streaming p:last-child::after,
  .viewer, .viewer-card img {
    animation: none !important;
    transition: none !important;
  }
  /* без анимации сразу показываем лицо карты и подписи */
  .card .art-inner { transform: none !important; }
  .card .name, .card .orient { opacity: 1 !important; }
}
