/* ================================================================
   Saccade · sheets-engine.css
   Стили для редакторов листов A4 (КП и портфолио).
   Используется в редакторах КП и портфолио и на публичной странице портфолио.
   ================================================================ */

/* ===== Лист A4 ===== */
.sheet {
  width: 210mm; height: 297mm;
  background: var(--paper, #fff);
  box-shadow: 0 4px 24px rgba(0,0,0,.18);
  position: relative;
  overflow: hidden;
  page-break-after: always;
  break-after: page;
}
.sheet:last-child { page-break-after: auto; break-after: auto; }

/* Углы — 4 редактируемых лейбла.
   Размер выровнен с public-portfolio.html (.corner = 10px): раньше было
   9pt (≈12px), на public смотрелось крупнее чем нужно. */
.sheet .corner {
  position: absolute;
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 10px;
  letter-spacing: .14em; text-transform: uppercase;
  color: var(--ink, #0f1a4d);
  white-space: nowrap;
}
.sheet .corner.tl { top: 12mm; left: 12mm; }
.sheet .corner.tr { top: 12mm; right: 12mm; }
.sheet .corner.bl { bottom: 12mm; left: 12mm; }
.sheet .corner.br { bottom: 12mm; right: 12mm; }

/* Вертикальные spine — слева/справа.
   ОБЕ стороны читаются сверху вниз (vertical-rl без rotate).
   Центрирование — top:50% + translateY(-50%): геометрически, работает
   и на экране и в Chrome print. text-align:center / flex в print
   ломались (текст уезжал к верху страницы). */
.sheet .spine {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  writing-mode: vertical-rl;
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 9px;
  letter-spacing: .18em; text-transform: uppercase;
  color: var(--ink, #0f1a4d); opacity: .85;
  white-space: nowrap;
}
.sheet .spine.left  { left: 6mm;  }
.sheet .spine.right { right: 6mm; }

/* Content area — основная зона между углами и spine */
.sheet .sheet-content {
  position: absolute;
  top: 25mm; bottom: 25mm; left: 18mm; right: 18mm;
}

/* Контейнер для всех листов — стек на экране */
.sheets-stack {
  display: flex; flex-direction: column; gap: 24px; align-items: center;
}

/* ===== Слоты изображений ===== */
.img-slot {
  background-color: rgba(15,26,77,.06);
  background-position: center; background-size: cover; background-repeat: no-repeat;
  position: relative;
  cursor: pointer;
  transition: background-color .15s;
}
.img-slot:hover { background-color: rgba(15,26,77,.1); }
.img-slot.has-image { cursor: default; }
.img-slot.has-image:hover { background-color: rgba(15,26,77,.06); }
.img-slot .placeholder {
  position: absolute; inset: 0;
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  gap: 6mm;
  font-family: var(--mono, 'JetBrains Mono', monospace);
  color: var(--ink, #0f1a4d);
  pointer-events: none;
}
.img-slot.has-image .placeholder { display: none; }
.img-slot .placeholder .plus {
  width: 16mm; height: 16mm; border: 1.5px solid currentColor;
  border-radius: 50%; opacity: .35;
  display: flex; align-items: center; justify-content: center;
  font-size: 18pt;
}
.img-slot .placeholder .ar {
  font-size: 10pt; letter-spacing: .14em; opacity: .45;
}
.img-slot .remove {
  position: absolute; top: 4mm; right: 4mm;
  width: 8mm; height: 8mm; border-radius: 50%;
  background: rgba(15,26,77,.7); color: #fff;
  display: none; align-items: center; justify-content: center;
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 9pt;
  cursor: pointer; user-select: none;
}
.img-slot.has-image:hover .remove { display: flex; }
.img-slot input[type=file] { display: none; }

/* Кнопка кадрирования — карандаш в круге, в дизайне «×», слева от него. */
.img-slot .crop-btn {
  position: absolute; top: 4mm; right: 14mm;
  width: 8mm; height: 8mm; border-radius: 50%;
  background: rgba(15,26,77,.7); color: #fff;
  display: none; align-items: center; justify-content: center;
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 9pt;
  cursor: pointer; user-select: none;
}
.img-slot.has-image:hover .crop-btn { display: flex; }

/* ===== Режим кадрирования ===== */
.img-slot.cropping { overflow: visible; z-index: 20; cursor: default; }
.img-slot.cropping .placeholder,
.img-slot.cropping .remove,
.img-slot.cropping .crop-btn { display: none !important; }
/* Слой-картинка целиком, поверх слота, может вылезать за границы. */
.img-slot .crop-layer {
  position: absolute; z-index: 10; max-width: none; height: auto;
  cursor: move; user-select: none; touch-action: none;
  -webkit-user-drag: none;
}
/* Рамка = размер слота; вокруг — бледная маска (box-shadow), клипается .sheet. */
.img-slot .crop-frame {
  position: absolute; inset: 0; z-index: 11; pointer-events: none;
  outline: 1px solid var(--ink, #0f1a4d);
  box-shadow: 0 0 0 9999px rgba(255,255,255,.62);
}
.img-slot .crop-handle {
  position: absolute; right: -8px; bottom: -8px;
  width: 16px; height: 16px; border-radius: 3px;
  background: #fff; border: 1px solid var(--ink, #0f1a4d);
  pointer-events: auto; cursor: nwse-resize; z-index: 12;
}
.img-slot .crop-bar {
  position: absolute; left: 50%; bottom: 4mm; transform: translateX(-50%);
  z-index: 13; pointer-events: auto;
}
.img-slot .crop-bar .crop-done {
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 9pt;
  padding: 5px 14px; border: none; border-radius: 4px; cursor: pointer;
  background: var(--ink, #0f1a4d); color: #fff;
}

/* ===== Контентные блоки в листах =====
   Размеры выровнены с public-portfolio.html (там .heading/.subtext с
   определёнными px-значениями). До этого editor использовал pt-значения
   которые на public ощущались несимметрично — пользователь видел разный
   масштаб надписей в редакторе и в опубликованной версии. Сейчас оба
   используют одинаковые размеры. */
.sheet .heading {
  font-family: var(--serif, Fraunces, Georgia, serif); font-weight: 400;
  font-size: 64px; line-height: 1.02; letter-spacing: -.03em;
  color: var(--ink, #0f1a4d);
  white-space: pre-line;
  margin: 0;
}
.sheet .heading.huge  { font-size: 140px; line-height: .9; letter-spacing: -.04em; }
.sheet .heading.large { font-size: 96px; line-height: .92; }

.sheet .subtitle {
  font-family: var(--sans, Montserrat, system-ui, sans-serif);
  font-size: 15px; line-height: 1.55;
  max-width: 170mm; white-space: pre-line;
  margin-top: 8mm;
}
.sheet .subtitle.small { font-size: 13px; }

.sheet .caption {
  font-family: var(--sans, Montserrat, system-ui, sans-serif);
  font-size: 10pt; line-height: 1.5;
  white-space: pre-line; padding-top: 3mm;
  border-top: 1px solid rgba(15,26,77,.18);
}

.sheet .cols {
  display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8mm;
  font-family: var(--sans, Montserrat, system-ui, sans-serif);
  font-size: 11pt; line-height: 1.55;
}
.sheet .cols > div { white-space: pre-line; }
.sheet .cols .col-num {
  display: block; font-family: var(--mono, 'JetBrains Mono', monospace);
  font-size: 22pt; margin-bottom: 4mm; letter-spacing: -.02em;
}

.sheet .quote {
  font-family: var(--serif, Fraunces, Georgia, serif); font-style: italic;
  font-size: 28pt; line-height: 1.25; letter-spacing: -.01em;
  white-space: pre-line;
}
.sheet .quote-author {
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 10pt;
  letter-spacing: .14em; text-transform: uppercase;
  opacity: .6; margin-top: 8mm;
}

/* ===== Layout-specific ===== */
.layout-image-1 .sheet-content { padding: 0; }
.layout-image-1 .img-slot { width: 100%; height: 100%; }

.layout-image-2-row .sheet-content {
  display: flex; gap: 6mm; padding: 0;
}
.layout-image-2-row .img-slot { flex: 1; min-width: 0; }

.layout-image-2-col .sheet-content {
  display: flex; flex-direction: column; gap: 6mm; padding: 0;
}
.layout-image-2-col .img-slot { flex: 1; min-height: 0; }

.layout-image-3-row .sheet-content {
  display: flex; gap: 5mm; padding: 0;
}
.layout-image-3-row .img-slot { flex: 1; min-width: 0; }

.layout-image-3a .sheet-content {
  display: grid; grid-template-columns: 1.4fr 1fr; gap: 5mm; padding: 0;
}
.layout-image-3a .img-slot:first-child { grid-row: 1 / span 2; }

.layout-image-3b .sheet-content {
  display: grid; grid-template-rows: 1.4fr 1fr; gap: 5mm; padding: 0;
}
/* БЫЛО: .layout-image-3b .img-slot:first-child { grid-column: 1 / -1; }
   Проблема: селектор `:first-child` без `>` ловил также `.img-slot` внутри
   .row-2 (small1 — first-child своего родителя). small1 получал grid-column
   1/-1 и расползался на оба столбца row-2 → small2 уезжал в новую строку.
   Сейчас правило не нужно: .sheet-content одноколоночный grid, big и
   так растягивается на всю ширину. .row-2 со своими columns:1fr 1fr
   корректно делит small1/small2. */
.layout-image-3b .row-2 {
  display: grid; grid-template-columns: 1fr 1fr; gap: 5mm;
}

.layout-image-3c .sheet-content {
  display: grid; grid-template-columns: 1fr 1.4fr; gap: 5mm; padding: 0;
}
.layout-image-3c .img-slot.big { grid-column: 2; grid-row: 1 / span 2; }

.layout-image-4-grid .sheet-content {
  display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; gap: 5mm; padding: 0;
}

/* 3 × 16:9 в столбик.
   Раньше было flex column + width:100% + aspect-ratio:16/9 — каждый слот
   получал ширину sheet-content (174mm) и высоту 174×9/16≈98mm, тройка
   занимала 3×98 + 10gap = 304mm, что больше 247mm высоты sheet-content
   → крайние слоты уезжали за лист.
   Сейчас: explicit 3-row grid (1fr 1fr 1fr) → каждая row = 79mm. Слот
   с height:100% + aspect-ratio:16/9 → 79mm high, 79×16/9≈140mm wide.
   max-width клампит. align/justify-items центрируют. Итого: 3×79+10gap
   = 247mm — ровно влезает. */
.layout-image-3-stack .sheet-content {
  display: grid; grid-template-rows: 1fr 1fr 1fr; gap: 5mm; padding: 0;
  align-items: center; justify-items: center;
}
.layout-image-3-stack .img-slot {
  height: 100%; aspect-ratio: 16 / 9; max-width: 100%;
}

/* «Мозаика · большая низ» — зеркальный вариант image-3b:
   две маленькие в ряд сверху, большая снизу. */
.layout-image-3-big-bottom .sheet-content {
  display: grid; grid-template-rows: 1fr 1.4fr; gap: 5mm; padding: 0;
}
.layout-image-3-big-bottom .row-2 {
  display: grid; grid-template-columns: 1fr 1fr; gap: 5mm;
}

/* 2 квадратных рядом. Аспект 1:1 заставляет browser сжимать высоту, чтобы
   вместе с .sheet-content padding'ом помещались по центру. */
.layout-image-2-square .sheet-content {
  display: flex; gap: 6mm; padding: 0;
  align-items: center; justify-content: center;
}
.layout-image-2-square .img-slot {
  flex: 1 1 0; aspect-ratio: 1 / 1; max-width: 50%;
}

/* 4 квадратных в сетке 2×2 (с явным aspect-ratio в отличие от image-4-grid,
   который натягивается на 1fr 1fr и принимает любую форму). */
.layout-image-4-square .sheet-content {
  display: grid; grid-template-columns: 1fr 1fr; gap: 6mm; padding: 0;
  align-items: center; justify-items: center;
}
.layout-image-4-square .img-slot {
  width: 100%; aspect-ratio: 1 / 1;
}

/* 1 портрет 4:5 — узкий вертикальный кадр по центру.
   ВАЖНО: width:100% + aspect-ratio даёт ровно 4:5. Раньше было
   height:100% + max-width:100% — height фиксировал на полную высоту
   sheet-content (247mm), а max-width клампил ширину до 174mm. Aspect
   при конфликте размеров игнорируется → выходило 174×247 ≈ 5:7 вместо
   ожидаемого 4:5. Фикс: ставим только width, высота вычисляется. */
.layout-image-1-portrait .sheet-content {
  display: flex; padding: 0;
  align-items: center; justify-content: center;
}
.layout-image-1-portrait .img-slot {
  width: 100%; aspect-ratio: 4 / 5; max-height: 100%;
}

/* 4 портрета 4:5 в сетке 2×2 — раньше был ряд из 4, кадры получались
   очень узкими (~40mm). 2×2 даёт каждому портрету ~83mm × 104mm —
   гораздо удобнее для лиц / архитектурных вертикалей. */
.layout-image-4-portrait .sheet-content {
  display: grid; grid-template-columns: 1fr 1fr; gap: 8mm; padding: 0;
  align-items: center; justify-items: center;
}
.layout-image-4-portrait .img-slot {
  width: 100%; aspect-ratio: 4 / 5;
}

.layout-image-1-cap .sheet-content {
  display: flex; flex-direction: column; gap: 6mm; padding: 0;
}
.layout-image-1-cap .img-slot { flex: 1; min-height: 0; }
.layout-image-1-cap .caption { max-height: 30mm; }

.layout-text-title .sheet-content {
  display: flex; flex-direction: column; align-items: flex-start; justify-content: center;
}
.layout-text-3-cols .sheet-content {
  display: flex; flex-direction: column; justify-content: space-between;
}
.layout-text-3-cols .cols { margin-top: 12mm; }
.layout-text-quote .sheet-content {
  display: flex; flex-direction: column; justify-content: center;
}
.layout-image-text-side .sheet-content {
  display: grid; grid-template-columns: 1fr 1fr; gap: 8mm; padding: 0;
  align-items: center;
}
.layout-image-text-side .img-slot { height: 100%; min-height: 200mm; }
.layout-image-text-side .text-block { padding: 0 8mm; }

/* =================================================================
   layout-portfolio-studio-team — копия legacy `layout-studio-full`
   из public/portfolio.html. Структура: heading + subtext + 2 фото
   с текстом справа + 3 колонки внизу с border-top.
   ================================================================= */
.layout-portfolio-studio-team .sheet-content { padding: 0; }
.layout-portfolio-studio-team .studio-full {
  display: flex; flex-direction: column; gap: 6mm;
  height: 100%;
}
.layout-portfolio-studio-team .members {
  display: grid; grid-template-columns: 1fr 1fr; gap: 8mm;
}
.layout-portfolio-studio-team .member {
  display: grid; grid-template-columns: 35mm 1fr; gap: 5mm; align-items: start;
}
.layout-portfolio-studio-team .member .img-slot.photo {
  aspect-ratio: 3 / 4;
  width: 35mm;
}
.layout-portfolio-studio-team .name {
  font-family: var(--serif, Fraunces, Georgia, serif); font-weight: 400;
  font-size: 20px; line-height: 1.1; letter-spacing: -.02em;
  white-space: pre-line;
}
.layout-portfolio-studio-team .role {
  font-family: var(--mono, 'JetBrains Mono', monospace);
  font-size: 9px; letter-spacing: .14em; text-transform: uppercase;
  opacity: .65; margin-top: 3px;
}
.layout-portfolio-studio-team .bio {
  font-family: var(--sans, Montserrat, system-ui, sans-serif); font-weight: 400;
  font-size: 10px; line-height: 1.5; margin-top: 3mm;
  white-space: pre-line;
}
/* Переопределяем общее .sheet .cols под легаси-параметры studio-full */
.layout-portfolio-studio-team .cols {
  margin-top: 4mm; padding-top: 5mm;
  border-top: 1px solid var(--rule, rgba(15,26,77,.18));
  grid-template-columns: 1fr 1fr 1fr; gap: 6mm;
  font-family: var(--sans, Montserrat, system-ui, sans-serif);
  font-size: 11px; line-height: 1.55;
}
.layout-portfolio-studio-team .cols > div { white-space: pre-line; }
.layout-portfolio-studio-team .cols .col-num {
  display: block; margin-bottom: 3mm;
  font-family: var(--mono, 'JetBrains Mono', monospace);
  font-size: 18px; font-weight: 400; letter-spacing: -.02em;
}

/* =================================================================
   layout-cover-portfolio-image — копия legacy `layout-cover.img-top`
   из public/portfolio.html. Image сверху flex:1 (min 80mm max 160mm),
   heading.huge снизу + subtext. justify-content:center центрирует
   контент в content-area. flex:1 на img даёт ему занять оставшееся.
   ================================================================= */
.layout-cover-portfolio-image .cover-portfolio-image {
  display: flex; flex-direction: column;
  align-items: flex-start; justify-content: center;
  gap: 8mm;
  height: 100%;
}
.layout-cover-portfolio-image .cover-portfolio-image .img-slot.cover-img {
  width: 100%; flex: 1;
  min-height: 80mm; max-height: 160mm;
}

/* =================================================================
   layout-portfolio-outro — копия legacy `layout-outro`. heading.large +
   subtext + outro-contacts (2-col grid с border-top, Montserrat 14px,
   label JBM 10px caps). ================================================================= */
.layout-portfolio-outro .outro-portfolio {
  display: flex; flex-direction: column;
  justify-content: space-between;
  gap: 8mm;
  height: 100%;
}
.layout-portfolio-outro .outro-contacts {
  display: grid; grid-template-columns: repeat(2, 1fr); gap: 8mm 16mm;
  padding-top: 8mm;
  border-top: 1px solid var(--rule, rgba(15,26,77,.18));
}
.layout-portfolio-outro .outro-contacts > div { white-space: pre-line; }
.layout-portfolio-outro .outro-contacts .label {
  font-family: var(--mono, 'JetBrains Mono', monospace);
  font-size: 10px; letter-spacing: .14em; text-transform: uppercase;
  opacity: .55; margin-bottom: 6px;
}
/* Значения — моно JBM, uppercase, letter-spacing.  Всё кликабельно через
   <a>: href строится из текста (tel/mailto/instagram/site/yandex-maps);
   tg — захардкоженный t.me/Spilery с label НАПИСАТЬ/SEND MESSAGE. */
.layout-portfolio-outro .outro-contacts .val,
.layout-portfolio-outro .outro-contacts .tg-link {
  font-family: var(--mono, 'JetBrains Mono', monospace);
  font-size: 10pt; line-height: 1.4;
  letter-spacing: .06em; text-transform: uppercase;
  color: inherit; text-decoration: none;
  display: inline-block;
  white-space: pre-line;
}
.layout-portfolio-outro .outro-contacts .val:hover,
.layout-portfolio-outro .outro-contacts .tg-link:hover {
  text-decoration: underline; opacity: .85;
}

/* ===== Letterhead-шаблон =====
   Перекраиваем стандартный .sheet-content (top:25mm bottom:25mm) на весь
   лист, потому что в эталонном бланке head на
   16mm от верха, foot на 16mm от низа — иначе подвал будет «висеть»
   внутри content-area, не прижатый к краю страницы.
   Селектор .sheet.layout-letterhead — повышенная специфичность,
   чтобы перебить базовое .sheet .sheet-content. */
.sheet.layout-letterhead .sheet-content {
  top: 0; bottom: 0; left: 0; right: 0;
  padding: 16mm 24mm;
}
.layout-letterhead .lh-wrap {
  position: relative;
  width: 100%; height: 100%;
}
.layout-letterhead .lh-head {
  display: flex; justify-content: space-between; align-items: flex-start;
  padding-bottom: 6mm;
  border-bottom: 1px solid var(--rule, rgba(15,26,77,.16));
}
.layout-letterhead .lh-logo {
  display: inline-flex; align-items: baseline; gap: .35em;
  font-size: 24pt; line-height: 1;
}
.layout-letterhead .lh-logo .logo-mark {
  display: inline-flex; align-items: baseline; gap: .2em;
  font-family: var(--serif, 'Fraunces', Georgia, serif);
  font-weight: 400; font-style: italic; line-height: 1;
}
.layout-letterhead .lh-logo .logo-mark::after {
  content: '';
  width: .14em; height: .14em; border-radius: 50%;
  background: currentColor; display: inline-block;
  transform: translateY(-.06em);
}
.layout-letterhead .lh-logo .logo-wordmark {
  font-family: var(--serif, 'Fraunces', Georgia, serif);
  font-weight: 400; letter-spacing: -.03em;
}
.layout-letterhead .lh-meta {
  font-family: var(--mono, 'JetBrains Mono', monospace);
  font-size: 8pt; letter-spacing: .14em; text-transform: uppercase;
  text-align: right; line-height: 1.6; opacity: .65;
  min-width: 60mm;
}
.layout-letterhead .lh-body {
  margin-top: 14mm;
  /* padding-bottom оставляет место под абсолютный подвал, чтобы текст
     не наезжал на него при длинном письме. ~30mm = высота подвала + зазор. */
  padding-bottom: 30mm;
  max-width: 150mm;
}
.layout-letterhead .lh-body-text {
  font-family: var(--sans, 'Montserrat', system-ui, sans-serif);
  font-size: 11pt; line-height: 1.55;
  white-space: pre-wrap;       /* переносы строк из innerText сохраняются */
  min-height: 100mm;
}
.layout-letterhead .lh-foot {
  position: absolute;
  bottom: 0; left: 0; right: 0;
  padding-top: 6mm;
  border-top: 1px solid var(--rule, rgba(15,26,77,.16));
  display: flex; justify-content: space-between;
  font-family: var(--mono, 'JetBrains Mono', monospace);
  font-size: 8pt; letter-spacing: .14em; text-transform: uppercase;
  opacity: .65;
}

/* ===== Editable styling ===== */
.sheet [contenteditable="true"]:hover { background: rgba(15,26,77,.04); }
.sheet [contenteditable="true"]:focus {
  background: rgba(15,26,77,.08); outline: none;
  box-shadow: inset 0 0 0 1px rgba(15,26,77,.4);
}
/* Placeholder для пустых редактируемых полей.
   Реализуется через :empty::before — это надёжный паттерн без
   placeholder-as-content (где textContent заменяется на текст-плейсхолдер
   и потом стирается на focus — там были глюки с курсором и вводом).
   Сейчас элемент остаётся ДЕЙСТВИТЕЛЬНО пустым, а текст идёт из ::before.

   ВАЖНО: pointer-events НЕ ставим в none на ::before. Иначе для пустого
   absolute-позиционированного .corner / .spine (нулевая собственная
   ширина/высота) единственная видимая область — это painted-area от
   ::before. С pointer-events:none клик проваливается СКВОЗЬ pseudo на
   .sheet под ним → contenteditable не получает focus, курсор не ставится.
   user-select:none оставляем — текст-плейсхолдер не должен выделяться. */
.sheet [contenteditable="true"]:empty::before {
  content: attr(data-placeholder);
  opacity: .22;
  user-select: none;
}
/* Минимальная click-area для пустых corners/spines — ТОЛЬКО НА ЭКРАНЕ.
   Без неё absolute-элемент с пустым содержимым имеет размер 0×0 и
   клик в видимый placeholder может попадать ровно в гэп между pseudo
   и parent. В print эти размеры приводили к ПЕЧАТНОМУ серому
   прямоугольнику для каждого незаполненного поля — поэтому screen-only. */
@media screen {
  .sheet .corner:empty,
  .sheet .spine:empty {
    min-width: 24px;
    min-height: 14px;
  }
  .sheet .spine:empty {
    min-width: 14px;
    min-height: 80px;
  }
}

/* === Ссылки внутри листов ===
   Все <a> (как hardcoded в кп-cover, так и инжектированные linkify'ем
   перед window.print()) показываются как обычный текст: цвет наследуется,
   нет подчёркивания. Hover в редакторе даёт мягкий underline. В PDF
   это даёт «невидимые но кликабельные» ссылки — то что нужно для
   полиграфии. Раньше в редакторе портфолио и в его PDF получались
   синие подчёркнутые из-за отсутствия этого правила. */
.sheet a, .sheet a:link, .sheet a:visited {
  color: inherit;
  text-decoration: none;
}
.sheet a:hover { text-decoration: underline; opacity: .85; }

/* ===== Sheet card (с header'ом-toolbar внутри) =====
   Раньше toolbar был absolute top: -28px — на узких экранах уезжал
   под sticky-тулбар сайта. Сейчас он внутри карточки, в обычном flow. */
.sheet-card {
  position: relative;
  display: flex; flex-direction: column;
  width: 210mm;  /* совпадает с .sheet чтобы toolbar не растягивался */
}
.sheet-card .sheet-toolbar {
  display: flex; gap: 6px; align-items: center;
  padding: 6px 8px; margin-bottom: 6px;
  background: rgba(0,0,0,.08); border-radius: 4px;
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 10px;
  letter-spacing: .08em; text-transform: uppercase;
  color: rgba(0,0,0,.6);
}
.sheet-card .sheet-toolbar .grip {
  cursor: grab; user-select: none; padding: 3px 6px;
  background: rgba(0,0,0,.1); border-radius: 3px;
}
.sheet-card .sheet-toolbar .grip:active { cursor: grabbing; }
.sheet-card .sheet-toolbar .num { opacity: .55; padding: 2px 4px; }
.sheet-card .sheet-toolbar .layout-name { flex: 1; opacity: .65; padding: 0 4px; }
.sheet-card .sheet-toolbar .collapse,
.sheet-card .sheet-toolbar .delete {
  cursor: pointer; padding: 3px 8px; border-radius: 3px;
  user-select: none;
}
.sheet-card .sheet-toolbar .collapse { background: rgba(0,0,0,.05); }
.sheet-card .sheet-toolbar .collapse:hover { background: rgba(0,0,0,.12); }
.sheet-card .sheet-toolbar .delete {
  background: rgba(184,72,58,.15); color: #b8483a;
}
.sheet-card .sheet-toolbar .delete:hover { background: rgba(184,72,58,.3); }

/* Свёрнутая карточка — показывает только toolbar, сам лист скрыт.
   Удобно когда листов много и надо переставить порядок. */
.sheet-card.collapsed > .sheet,
.sheet-card.collapsed > .page {
  display: none;
}
.sheet-card.collapsed {
  background: rgba(0,0,0,.04); padding: 4px;
  border-radius: 6px;
}
.sheet-card.collapsed .sheet-toolbar { margin-bottom: 0; }

.sheet-card.dragging { opacity: .4; }
.sheet-card.drop-target { box-shadow: 0 0 0 3px #0f1a4d; }

/* ===== Sidebar с шаблонами ===== */
.templates-sidebar {
  width: 220px; flex-shrink: 0;
  background: #fff;
  border: 1px solid rgba(15,26,77,.16); border-radius: 8px;
  padding: 14px;
  max-height: calc(100vh - 80px); overflow: auto;
  position: sticky; top: 60px;
}
.templates-sidebar h3 {
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 10px;
  letter-spacing: .14em; text-transform: uppercase;
  opacity: .55; margin: 0 0 12px;
}
.templates-grid {
  display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
}
.template-card {
  background: rgba(15,26,77,.03);
  border: 1px solid rgba(15,26,77,.1); border-radius: 4px;
  padding: 6px;
  cursor: pointer;
  transition: background .15s, transform .15s;
  display: flex; flex-direction: column; gap: 4px;
  align-items: center;
}
.template-card:hover {
  background: rgba(15,26,77,.08);
  transform: translateY(-1px);
}
.template-card:active { transform: translateY(0); }
.template-card svg {
  display: block; width: 100%; height: auto;
  aspect-ratio: 210 / 297;  /* A4 portrait */
}
.template-card .tname {
  font-family: var(--mono, 'JetBrains Mono', monospace); font-size: 9px;
  letter-spacing: .04em; text-align: center;
  color: var(--ink, #0f1a4d); opacity: .7;
  line-height: 1.3;
  word-break: break-word;
}

/* ===== Layout (sidebar + main) ===== */
.editor-layout {
  display: grid; grid-template-columns: 220px 1fr; gap: 20px;
  align-items: start;
}

/* ===== Mobile =====
   Лист = 100vw (ровно как шапка) через transform:scale.
   iOS Safari НЕ парсит calc()+vw в zoom — transform умеет.
     1. .sheet-card обёртка 100vw × A4-пропорция, overflow:hidden.
     2. .page/.sheet position:absolute, transform:scale(calc(100vw/794)). */
@media (max-width: 900px) {
  .editor-layout { grid-template-columns: 1fr; }
  .templates-sidebar {
    position: static; max-height: 50vh;
    width: 100%;
  }
  .templates-sidebar.collapsed { display: none; }

  .sheet-card .sheet-toolbar { display: none !important; }

  .sheets-stack { zoom: 1 !important; gap: 14px; width: 100%; padding: 0; }
  .sheets-stack > .sheet-card {
    width: 100vw !important;
    max-width: 100vw !important;
    height: calc(100vw * 297 / 210);
    margin: 0 !important;
    padding: 0 !important;
    overflow: hidden;
    position: relative;
    transform: none !important;
    zoom: 1 !important;
  }
  .sheets-stack > .sheet-card > .sheet,
  .sheets-stack > .sheet-card > .page {
    width: 210mm !important;
    height: 297mm !important;
    /* var(--vw,0) — unitless (см. JS-updater). 100vw в scale() Safari игнорирует. */
    transform: scale(calc(var(--vw, 0) / 794));
    transform-origin: top left;
    position: absolute;
    top: 0; left: 0;
    margin: 0 !important;
    box-shadow: none !important;
  }
}

/* ===== Print =====
   Стандартный print-CSS. Колонтикулы iOS не отключаются — для них есть
   кнопка "Скачать PDF" (html2pdf-based, минует print-диалог). */
@media print {
  /* Жёсткий сброс мобильных scale-трюков (обёртка-маска + transform). */
  .templates-sidebar, .sheet-card .sheet-toolbar { display: none !important; }
  .sheets-stack {
    zoom: 1 !important; gap: 0 !important;
    width: auto !important; padding: 0 !important;
  }
  .sheets-stack > .sheet-card {
    width: 210mm !important; max-width: 210mm !important;
    height: auto !important;
    margin: 0 !important; padding: 0 !important;
    overflow: visible !important; position: static !important;
    transform: none !important; zoom: 1 !important;
  }
  .sheets-stack > .sheet-card > .sheet,
  .sheets-stack > .sheet-card > .page {
    box-shadow: none !important; margin: 0 !important;
    /* НЕ ровно 297mm: лист ровно в страницу даёт суб-пиксельный перелив и
       ПУСТУЮ страницу между листами при печати. На 1px короче — незаметно,
       перелива нет. overflow:hidden — на всякий случай клипает остаток. */
    width: 210mm !important; height: calc(297mm - 1px) !important;
    overflow: hidden !important;
    transform: none !important;
    position: relative !important;
    top: auto !important; left: auto !important;
  }
  .img-slot .placeholder, .img-slot .remove, .img-slot .crop-btn,
  .img-slot .crop-frame, .img-slot .crop-layer, .img-slot .crop-bar { display: none !important; }
  /* Глушим placeholder-тексты у пустых полей. Min-width/min-height в
     screen-блоке (см. выше @media screen), поэтому в print corner/spine
     схлопываются в 0×0 натурально — отдельный override не нужен. Старый
     pattern [data-empty="1"] оставлен на случай legacy-данных. */
  .sheet [contenteditable="true"]:empty::before { content: none !important; }
  [data-empty="1"] { display: none !important; }
  /* Spine принудительный сброс на случай если transform/position
     обёртки перетёрли spine-стили. top:50%+translateY(-50%) — это
     геометрия, работает и в print. */
  .sheet .spine {
    position: absolute !important;
    top: 50% !important;
    bottom: auto !important;
    transform: translateY(-50%) !important;
    writing-mode: vertical-rl !important;
    display: block !important;
  }
  .sheet .spine.left {
    left: 6mm !important; right: auto !important;
  }
  .sheet .spine.right {
    right: 6mm !important; left: auto !important;
  }
  @page { size: A4 portrait; margin: 0; }
}
