/* ============================================================
   Library of Babel comics
   Белый зал, ЛЕНТА ОТДЕЛЬНЫХ коричневых шкафов с глубиной,
   чёрный контур, свой шрифт Comic Neue (лежит в /fonts —
   детерминированный, кросс-платформенный), аскетизм.
   ============================================================ */

/* локальный webfont: один и тот же везде, без внешних CDN */
@font-face {
  font-family: 'Comic Neue';
  src: url('fonts/ComicNeue-Regular.woff2') format('woff2');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}
@font-face {
  font-family: 'Comic Neue';
  src: url('fonts/ComicNeue-Bold.woff2') format('woff2');
  font-weight: 700;
  font-style: normal;
  font-display: swap;
}

* { margin: 0; padding: 0; box-sizing: border-box; }

html, body {
  width: 100%;
  height: 100%;
  overflow: hidden;
  /* стена зала: темнеет с глубиной (--wallBg ставит JS) */
  background: var(--wallBg, #fff);
}

body {
  font-family: 'Comic Neue', 'Comic Sans MS', 'Comic Sans', 'Chalkboard SE', cursive;
  color: #000;
  -webkit-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
}

[hidden] { display: none !important; }

input, select {
  -webkit-user-select: text;
  user-select: text;
}

button {
  font: inherit;
  font-size: 14px;
  color: #000;
  background: #fff;
  border: 2px solid #000;
  border-radius: 0;
  padding: 6px 14px;
  cursor: pointer;
  touch-action: manipulation;
}
button:hover:not(:disabled):not(:active) { background: #f1ede2; }
button:active { background: #000; color: #fff; }
button:disabled {
  color: #bbb;
  border-color: #bbb;
  background: #fff;
  cursor: default;
}
button:disabled:active { background: #fff; color: #bbb; }

/* ============================== ЗАЛ ============================== */

#hall {
  position: fixed;
  inset: 0;
  touch-action: none;
  cursor: grab;
}
#hall.dragging { cursor: grabbing; }

/* пол: шкафы стоят на нём */
#floor {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: var(--floorH, 14px);
  background: var(--floorBg, #E9E4DA);
  border-top: 3px solid #000;
}

/* лента шкафов: окно высотой в шкаф, секции едут внутри */
#cab {
  position: absolute;
  left: 0;
  right: 0;
  bottom: var(--floorH, 14px);
  height: var(--cabH, 520px);
  overflow: hidden;
}

#track {
  position: absolute;
  inset: 0;
}

/* один шкаф (секция ленты): ширина --bayW = шкаф + зазор */
.bay {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: var(--bayW, 560px);
  will-change: transform;
}

/* корпус шкафа: от пола до верха, коричневый, с контуром */
.cab-body {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: var(--cabW, 520px);
  background: var(--caseBg, #7C4A1E);
  border: 3px solid #000;
  border-bottom: none;
}

/* окно шкафа: сквозь него видны полки;
   свой контекст наложения (z-index:1) — каркас всегда поверх */
.cab-win {
  position: absolute;
  left: var(--stile, 26px);
  right: var(--stile, 26px);
  top: var(--cornice, 20px);
  bottom: var(--plinth, 24px);
  overflow: hidden;
  background: var(--winBg, #3A2410); /* тёмная задняя стенка — глубина */
  z-index: 1;
}

/* карниз: нависает над полками (нижняя губа — глубина) */
.cab-top {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: var(--cornice, 20px);
  background: var(--corniceBg, #8F5A26);
  border-bottom: 3px solid #000;
  z-index: 3;
}
.cab-top::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 100%;
  height: 5px;
  background: var(--edgeDarkBg, #4A2B10);
}

/* боковые стойки с тёмной внутренней фаской */
.cab-l, .cab-r {
  position: absolute;
  top: var(--cornice, 20px);
  bottom: var(--plinth, 24px);
  width: var(--stile, 26px);
  background: var(--stileBg, #8F5A26);
  z-index: 3;
}
.cab-l { left: 0; border-right: 3px solid #000; }
.cab-r { right: 0; border-left: 3px solid #000; }
.cab-l::after, .cab-r::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 5px;
  background: var(--edgeDarkBg, #4A2B10);
}
.cab-l::after { right: -3px; }
.cab-r::after { left: -3px; }

/* цоколь: нижние книги стоят на полке, не на полу */
.cab-plinth {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: var(--plinth, 24px);
  background: var(--plinthBg, #5B3A16);
  border-top: 3px solid #000;
  z-index: 3;
}

.shelfrow {
  position: relative;
  height: calc(100% / 5);
}

/* книги стоят на полке; передняя кромка доски перекрывает им низ.
   brightness — плавное потемнение ВСЕХ книг к концу библиотеки
   (максимум -30%, --bookBright ставит applyDark) */
.books {
  position: absolute;
  left: var(--padX, 12px);
  right: var(--padX, 12px);
  bottom: 7px;
  display: flex;
  align-items: flex-end;
  z-index: 1;
  filter: brightness(var(--bookBright, 1));
}

.board {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 9px;
  background: var(--boardBg, #93602A);
  border-top: 2px solid var(--boardEdgeBg, #B4793B); /* светлая фаска — грань доски */
  border-bottom: 3px solid #000;
  z-index: 2;
}

/* ---------- книга-комикс: псевдо-3D ---------- */

.book {
  position: relative;
  flex: 0 0 auto;
  width: var(--bkW, 12px);
  height: var(--bkH, 120px);
  margin-right: calc(var(--edge, 4px) - 1px); /* сосед чуть налегает на торец */
  background: #EFE7D2;
  border: 1px solid #000;
  cursor: pointer;
  z-index: 1;
  transition: transform 0.12s ease-out, box-shadow 0.12s ease-out;
}

/* торец: обрез страниц справа */
.book::after {
  content: '';
  position: absolute;
  top: 1px;
  bottom: 0;
  left: 100%;
  width: var(--edge, 4px);
  background: #EFE3C4;
  background-image: repeating-linear-gradient(0deg, #D9C69B 0 1px, transparent 1px 3px);
  border: 1px solid #000;
  border-left: none;
}

/* верхний торец страниц */
.book::before {
  content: '';
  position: absolute;
  top: -4px;
  left: 0;
  width: calc(100% + var(--edge, 4px));
  height: 4px;
  background: #F4EACB;
  background-image: repeating-linear-gradient(90deg, #E0CFA4 0 1px, transparent 1px 3px);
  border: 1px solid #000;
}

/* название: первые 20 символов кода, вертикально */
.book .t {
  position: absolute;
  inset: 0;
  writing-mode: vertical-rl;
  font-size: var(--codeFs, 7px);
  line-height: 1;
  padding-top: 3px;
  white-space: nowrap;
  overflow: hidden;
}
.book.t-dark .t { color: #000; }
.book.t-light .t { color: #fff; }

/* наведение: книга выдвигается вперёд из полки */
.book:hover {
  transform: translateY(-6px);
  z-index: 7;
  box-shadow: 0 7px 0 rgba(0, 0, 0, 0.35);
}

/* ---------- финал библиотеки: табличка как в Minecraft ---------- */

.finale {
  position: absolute;
  left: 0;
  bottom: 0;
  width: var(--cabW, 520px);
  height: 100%;
  pointer-events: none;
}

/* доска: широкая дубовая плашка с рамкой и текстом */
.finale-board {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 56%;
  width: min(300px, 78%);
  min-height: 96px;
  padding: 14px 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--signBg, #C9985A);
  border: 3px solid #000;
  box-shadow: inset 0 0 0 3px var(--signEdgeBg, #8A6430);
  z-index: 1;
}
.finale-board span {
  text-align: center;
  font-size: clamp(16px, 2.2vw, 24px);
  line-height: 1.25;
  color: var(--signFgBg, #4A2F10);
  word-break: break-word;
}

/* два столба от доски до пола */
.finale-post {
  position: absolute;
  bottom: 0;
  width: 12px;
  height: 56%;
  background: var(--signEdgeBg, #8A6430);
  border: 2px solid #000;
  z-index: 0;
}
.finale-post.l { left: calc(50% - 42px); }
.finale-post.r { right: calc(50% - 42px); }

/* search + position line: centered column, posline always below
   the buttons (never overlaps them, whatever wraps) */
#topbar {
  position: fixed;
  top: 14px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 7px;
  max-width: 96vw;
  z-index: 4;
  pointer-events: none;
}
#searchrow {
  display: flex;
  gap: 8px;
  align-items: stretch;
  justify-content: center;
  flex-wrap: wrap;
  max-width: 96vw;
  pointer-events: auto;
}
#search {
  flex: 0 1 auto;
  min-width: 0;
  width: min(360px, 48vw);
  padding: 7px 12px;
  border: 2px solid #000;
  border-radius: 0;
  background: #fff;
  color: #000;
  font: inherit;
  font-size: 16px;
  outline: none;
}
#finder-btn {
  flex: 0 0 auto;
  white-space: nowrap;
  font-size: 13px;
  padding: 7px 10px;
}
#depthbox {
  display: flex;
  gap: 0;
  align-items: stretch;
}
#depth {
  width: 92px;
  padding: 7px 8px;
  border: 2px solid #000;
  border-right: none;
  background: #fff;
  color: #000;
  font: inherit;
  font-size: 14px;
  outline: none;
  -moz-appearance: textfield;
  appearance: textfield;
}
#depth::-webkit-outer-spin-button,
#depth::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
#depth-go {
  font-size: 13px;
  padding: 7px 12px;
}

/* position line: number / depth / cabinet / shelf (под кнопками) */
#posline {
  text-align: center;
  font-size: 12px;
  color: var(--posFgBg, #6b6b6b);
  pointer-events: none;
  padding: 0 12px;
  max-width: 96vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* ============================ ЧИТАЛКА ============================ */
/* Книга как в жизни: закрытая — один прямоугольник с названием,
   раскрывается влево; слева изнанка обложки, справа страница. */

#reader { position: fixed; inset: 0; }

#rbar {
  position: fixed;
  top: 12px;
  left: 12px;
  right: 12px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  z-index: 6;
  pointer-events: none;
}
#rgroup {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
  pointer-events: auto;
  background: var(--tableBg, #efefef);
  border: 2px solid #000;
  padding: 8px;
  max-width: 96vw;
}
#rgroup button { white-space: nowrap; }

/* выпадающее меню: всё про скачивание/share — под одной кнопкой */
#morebox { position: relative; display: inline-block; }
#btn-more { min-width: 40px; }
#more-menu {
  position: absolute;
  top: calc(100% + 6px);
  right: 0;
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 200px;
  background: var(--tableBg, #efefef);
  border: 2px solid #000;
  padding: 8px;
  z-index: 30;
}
#more-menu button { text-align: left; white-space: nowrap; }

#scene {
  position: fixed;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* стол под книгой (в читалке тоже темнеет с глубиной) */
#table {
  background: var(--tableBg, #efefef);
  padding: 26px;
}

#book {
  position: relative;
  width: var(--bookW, 512px);
  height: var(--bookH, 384px);
  perspective: 1400px;
  touch-action: none;
  /* закрытая книга (правая половина) стоит по центру стола;
     раскрытая — по центру весь разворот */
  transform: translateX(-25%);
  transition: transform 0.3s ease-out;
}
#book:not(.closed) { transform: none; }

.slot {
  position: absolute;
  top: 0;
  width: 50%;
  height: 100%;
}
#slotL { left: 0; }
#slotR { right: 0; }
.slot canvas {
  display: block;
  width: 100%;
  height: 100%;
  border: 2px solid #000;
  background: #fff;
  image-rendering: crisp-edges;
  image-rendering: pixelated;
}
.slot.empty { visibility: hidden; }

/* подсветка найденного по образцу места: рамка поверх страницы,
   координаты в процентах задаёт JS */
.slot .hl {
  position: absolute;
  border: 3px solid #F83800;
  outline: 1px solid #000;
  background: rgba(248, 56, 0, 0.15);
  pointer-events: none;
  z-index: 3;
}

/* корешок-разделитель между страницами */
#gutter {
  position: absolute;
  top: 0;
  bottom: 0;
  left: calc(50% - 1px);
  width: 2px;
  background: #000;
  z-index: 1;
}

/* обложка поверх правой страницы: сплошной цвет + чип с названием */
#cover {
  position: absolute;
  left: 50%;
  top: 0;
  width: 50%;
  height: 100%;
  z-index: 2;
  cursor: pointer;
}
#cover canvas {
  display: block;
  width: 100%;
  height: 100%;
  border: 2px solid #000;
  background: #fff;
  image-rendering: crisp-edges;
  image-rendering: pixelated;
}
/* название на обложке: строки подаёт JS (fitChip) под размер обложки;
   ширина = 90% обложки (left+right), max-height — страховка от вылезания */
#cover-code {
  position: absolute;
  left: 5%;
  right: 5%;
  top: 50%;
  transform: translateY(-50%);
  max-height: 76%;
  overflow: hidden;
  text-align: center;
  word-break: break-all;
  white-space: pre-line;
  font-size: clamp(8px, 1.6vw, 14px);
  line-height: 1.3;
  padding: 6px 8px;
  background: var(--coverBg, #fff);
  border: 1px solid #000;
}
#book.inv #cover-code,
#book.inv #leaf span { color: #fff; }

/* перелистываемая страница: лист с двумя сторонами (3D) */
#leaf {
  position: absolute;
  top: 0;
  width: 50%;
  height: 100%;
  z-index: 5;
  transform-style: preserve-3d;
  will-change: transform;
  pointer-events: none;
}
#leaf .face {
  position: absolute;
  inset: 0;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
}
#leaf .face.back { transform: rotateY(180deg); }
#leaf canvas {
  display: block;
  width: 100%;
  height: 100%;
  border: 2px solid #000;
  background: #fff;
  image-rendering: crisp-edges;
  image-rendering: pixelated;
}
#leaf span {
  position: absolute;
  left: 5%;
  right: 5%;
  top: 50%;
  transform: translateY(-50%);
  max-height: 76%;
  overflow: hidden;
  text-align: center;
  word-break: break-all;
  white-space: pre-line;
  font-size: clamp(8px, 1.6vw, 14px);
  line-height: 1.3;
  padding: 6px 8px;
  background: var(--coverBg, #fff);
  border: 1px solid #000;
}

/* невидимые половины экрана: клик = перелистывание */
#hitL, #hitR {
  position: fixed;
  top: 0;
  bottom: 0;
  width: 50%;
  z-index: 5;
  cursor: pointer;
}
#hitL { left: 0; }
#hitR { right: 0; }
#hitL.dead { cursor: default; }

/* код комикса, счётчик разворотов */
#meta {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 12px;
  text-align: center;
  font-size: 12px;
  line-height: 1.5;
  pointer-events: none;
  z-index: 6;
  color: var(--metaFgBg, #000);
}
#code-label {
  word-break: break-all;
  max-width: 92vw;
  margin: 0 auto;
}
#code-line {
  color: var(--metaDimFgBg, #555);
  font-size: 11px;
  word-break: break-all;
  max-width: 92vw;
  margin: 0 auto;
}

/* ======================= ПОИСК ПО РИСУНКУ ======================= */

#finder {
  position: fixed;
  inset: 0;
  z-index: 10;
  background: #fff;
  overflow: auto;
  display: flex;
  padding: 24px 12px;
}

#fpanel {
  margin: auto;        /* центр по обеим осям, без обрезки */
  border: 2px solid #000;
  background: #fff;
  padding: 14px;
  max-width: min(560px, 96vw);
}

#fhead {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
  font-size: 16px;
}
#fhead button {
  padding: 2px 10px;
  font-size: 16px;
  line-height: 1.2;
}

#frow {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
  font-size: 13px;
}
#f-sizes {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}
#f-sizes button {
  padding: 3px 8px;
  font-size: 12px;
  border-width: 1px;
}
#f-sizes button.on { background: #000; color: #fff; }
#f-custom {
  display: flex;
  gap: 4px;
  align-items: center;
  color: #444;
}
#f-custom input {
  width: 52px;
  font: inherit;
  font-size: 13px;
  border: 1px solid #000;
  padding: 3px 4px;
  background: #fff;
  color: #000;
}
#f-custom em {
  font-style: normal;
  font-size: 12px;
}

#f-canvas {
  display: block;
  touch-action: none;
  cursor: crosshair;
  border: 1px solid #000;
  image-rendering: pixelated;
}

/* оболочка канвы: скролл при зуме, базовый размер вписан;
   flex + margin:auto центрирует холст и корректно работает
   с прокруткой, когда холст больше оболочки */
#f-canvas-wrap {
  max-width: 100%;
  max-height: 62vh;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  display: flex;
  background: #fafafa;
}
#f-canvas { margin: auto; }
#f-canvas-wrap::-webkit-scrollbar { height: 10px; width: 10px; }
#f-canvas-wrap::-webkit-scrollbar-thumb { background: #bbb; }

/* мини-пейнт: инструменты */
#f-tools {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  margin-bottom: 10px;
}
#f-tools button { padding: 3px 9px; font-size: 12px; border-width: 1px; }
#f-tools button.on { background: #000; color: #fff; }
#f-brushbox, #f-zoombox {
  display: flex;
  gap: 4px;
  align-items: center;
}
#f-brushbox em, #f-tools em {
  font-style: normal;
  font-size: 11px;
  color: #555;
  margin-right: 2px;
}
#f-brushbox button {
  min-width: 24px;
  text-align: center;
  padding: 3px 6px;
}
#f-zoombox button { min-width: 26px; text-align: center; }

#f-pal {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin: 10px 0;
}
.sw {
  width: 22px;
  height: 22px;
  padding: 0;
  border: 1px solid #000;
}
.sw.on {
  outline: 2px solid #000;
  outline-offset: 1px;
}

#fctl {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
}
#f-progress { font-size: 12px; }

/* вкладки рисовалки / загрузки */
#f-tabs {
  display: flex;
  gap: 6px;
  margin-bottom: 10px;
}
#f-tabs button {
  padding: 4px 12px;
  font-size: 13px;
  border-width: 1px;
}
#f-tabs button.on { background: #000; color: #fff; }

/* загрузка 32 страниц */
#f-files { font-size: 13px; margin-bottom: 10px; }
#f-up-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 10px;
}
#f-up-grid canvas {
  width: 40px;
  height: 60px;
  image-rendering: pixelated;
  border: 1px solid #000;
}
#f-up-row {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}
#f-up-info { font-size: 12px; line-height: 1.4; }

#f-results {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.fres {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  border: 1px solid #000;
  padding: 6px;
  background: #fff;
  cursor: pointer;
  width: 96px;
}
.fres canvas {
  width: 48px;
  height: 72px;
  image-rendering: pixelated;
  border: 1px solid #000;
}
.fres span {
  font-size: 10px;
  line-height: 1.3;
  text-align: center;
  word-break: break-all;
}

/* ======================= SHARE: экспорт/импорт ======================= */

#share {
  position: fixed;
  inset: 0;
  z-index: 20;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  padding: 24px 12px;
  overflow: auto;
}

#sh-panel {
  margin: auto;
  width: min(460px, 96vw);
  border: 2px solid #000;
  background: #fff;
  padding: 14px;
}

#sh-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
  font-size: 16px;
}
#sh-head button {
  padding: 2px 10px;
  font-size: 16px;
  line-height: 1.2;
}

#sh-panel > button { display: block; width: 100%; margin-bottom: 12px; }

#sh-import em {
  display: block;
  font-style: normal;
  font-size: 12px;
  color: #555;
  margin-bottom: 6px;
}
#sh-in {
  display: block;
  width: 100%;
  height: 88px;
  resize: vertical;
  border: 1px solid #000;
  background: #fff;
  color: #000;
  font: inherit;
  font-size: 13px;
  padding: 6px 8px;
  margin-bottom: 8px;
  outline: none;
}
#sh-file { font-size: 13px; margin-bottom: 8px; }
#sh-msg {
  font-size: 12px;
  color: #A81000;
  min-height: 15px;
}

/* ======================= ЗАГРУЗОЧНАЯ ШТОРКА =======================
   Белая страница, пока зал не готов; затем JS плавно растворяет.
   Анимация с задержкой — страховка: даже без JS шторка уйдёт сама. */

#boot {
  position: fixed;
  inset: 0;
  background: #fff;
  z-index: 999;
  pointer-events: none;
  opacity: 1;
  animation: bootAuto 1s ease 8s forwards;
}
#boot.gone {
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.7s ease, visibility 0s linear 0.7s;
}
@keyframes bootAuto {
  to {
    opacity: 0;
    visibility: hidden;
  }
}

/* ======================= МЕЛКИЕ ЭКРАНЫ ======================= */

@media (max-width: 640px) {
  #table { padding: 12px; }
  #rbar { left: 6px; right: 6px; }
  #rgroup { gap: 6px; padding: 6px; }
  button { font-size: 13px; padding: 5px 9px; }
  .fres { width: 84px; }
  #search { flex: 1 1 0; width: auto; min-width: 0; }
  #finder-btn { font-size: 12px; padding: 6px 8px; }
  #depth { width: 76px; font-size: 16px; } /* 16px: iOS не зумит поле */
  #posline { font-size: 10px; }
  .board { height: 7px; }
  .books { bottom: 5px; }
  #f-up-grid canvas { width: 28px; height: 42px; }
  #fpanel { padding: 10px; }
  #f-tools { gap: 5px; }
  .finale-board { width: 84%; min-height: 78px; padding: 10px 12px; }
  .finale-board span { font-size: 15px; }
  .finale-post.l { left: calc(50% - 30px); }
  .finale-post.r { right: calc(50% - 30px); }
  /* меню и share — во всю ширину, кнопки крупнее под палец */
  #more-menu {
    position: fixed;
    top: 58px;
    left: 12px;
    right: 12px;
    min-width: 0;
  }
  #more-menu button { padding: 9px 10px; }
  #share { padding: 12px 8px; }
  #sh-panel { padding: 10px; }
}
