:root {
  --bg: #16181f;
  --panel: #1f2330;
  --panel-border: #2c3242;
  --text: #e8eaf0;
  --text-dim: #9aa1b2;
  --cell-gap: 3px;
  --cell-radius: 4px;
  --btn-bg: #2a3040;
  --btn-hover: #363e52;
  --btn-primary: #e0a33c;
  --btn-primary-hover: #edb45c;
  --cross-color: rgba(255, 255, 255, 0.92);
  --cross-shadow: 0 0 2px rgba(0, 0, 0, 0.7);
  --cat-ring: rgba(255, 255, 255, 0.8);
  --deducible-color: rgba(255, 255, 255, 0.85);
  --deducible-accent: rgba(255, 235, 130, 0.95);
}

* { box-sizing: border-box; }

html, body {
  margin: 0;
  padding: 0;
  background: var(--bg);
  color: var(--text);
  font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
}

body {
  /* dvh вторым объявлением: в iOS-webview (Telegram и др.) 100vh считается
     по максимальному вьюпорту и завышен; старые Safari строку игнорируют. */
  min-height: 100vh;
  min-height: 100dvh;
  -webkit-user-select: none;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
  /* Длинный тап не должен вызывать системную лупу/меню над клетками. */
  -webkit-touch-callout: none;
  touch-action: manipulation;
}

.app {
  max-width: 560px;
  margin: 0 auto;
  padding: 12px;
  /* Второе объявление побеждает там, где поддерживается env(): отступ
     учитывает «чёлку» и жестовую панель iPhone (важно для PWA-режима). */
  padding: 12px calc(12px + env(safe-area-inset-right, 0px))
           calc(12px + env(safe-area-inset-bottom, 0px))
           calc(12px + env(safe-area-inset-left, 0px));
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* ---------- HUD ---------- */

.hud {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  background: var(--panel);
  border: 1px solid var(--panel-border);
  border-radius: 10px;
  padding: 8px 12px;
  /* Свой слой композитинга: без него WebKit в iOS-webview иногда рисует
     кнопки шапки по старым координатам (поверх доски) после ресайза. */
  transform: translateZ(0);
}

.hud-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.hud-group.stats { gap: 16px; }

.hud-label {
  font-size: 12px;
  color: var(--text-dim);
  text-transform: uppercase;
  letter-spacing: 0.4px;
}

.difficulty {
  background: var(--btn-bg);
  color: var(--text);
  border: 1px solid var(--panel-border);
  border-radius: 6px;
  padding: 5px 8px;
  font-size: 13px;
  outline: none;
  cursor: pointer;
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 1.2;
}

.stat-value {
  font-size: 15px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

.actions {
  gap: 8px;
}

.btn {
  background: var(--btn-bg);
  color: var(--text);
  border: 1px solid var(--panel-border);
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.15s;
  white-space: nowrap;
}

.btn:hover { background: var(--btn-hover); }

.btn-primary {
  background: var(--btn-primary);
  border-color: var(--btn-primary);
  color: #201603;
  font-weight: 600;
}

.btn-mode-open {
  background: #4f86e0;
  border-color: #4f86e0;
  color: #fff;
}

/* Hover-стили только там, где есть курсор: на тач-экранах iOS :hover
   «залипает» после первого тапа и кнопки выглядят нажатыми. */
@media (hover: hover) and (pointer: fine) {
  .difficulty:hover { background: var(--btn-hover); }
  .btn:hover { background: var(--btn-hover); }
  .btn-primary:hover { background: var(--btn-primary-hover); }
  .btn-mode-open:hover { background: #6294e8; }
}

/* ---------- Board ---------- */

.board-wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.board {
  display: grid;
  grid-template-columns: repeat(var(--cols, 10), 1fr);
  gap: var(--cell-gap);
  width: 100%;
  max-width: 480px;
  background: var(--panel);
  border: 1px solid var(--panel-border);
  border-radius: 10px;
  padding: var(--cell-gap);
  touch-action: manipulation;
  /* Свой слой композитинга — защита от «залипшей» отрисовки в WebKit. */
  transform: translateZ(0);
}

.cell {
  position: relative;
  aspect-ratio: 1;
  border: none;
  border-radius: var(--cell-radius);
  cursor: pointer;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: calc(12px + 0.6vw);
  line-height: 1;
  padding: 0;
  transition: filter 0.25s, transform 0.08s;
}

.cell:not(.open):not(.done):active {
  transform: scale(0.94);
}

/* 12 контрастных цветов областей (котов не больше 12 — по числу строк поля) */
.region-0  { background: #e05252; }
.region-1  { background: #4f86e0; }
.region-2  { background: #50b55e; }
.region-3  { background: #e0a33c; }
.region-4  { background: #cfd4dc; }
.region-5  { background: #3fb9a8; }
.region-6  { background: #d66fb0; }
.region-7  { background: #6f7ff2; }
.region-8  { background: #8d6e63; }
.region-9  { background: #c2613f; }
.region-10 { background: #8fbf3f; }
.region-11 { background: #b8577f; }

/* Светлая область (серо-белая): белые метки на ней пропадают, поэтому внутри
   этой области крестик, рамка кота и подсветка «Вывода» перекрашены в тёмные. */
.region-4 {
  --cross-color: rgba(0, 0, 0, 0.6);
  --cat-ring: rgba(0, 0, 0, 0.5);
  --deducible-color: rgba(0, 0, 0, 0.8);
  --deducible-accent: rgba(0, 0, 0, 0.55);
}

/* Найденная область, включая стартовую, затемняется целиком. */
.cell.done {
  filter: saturate(0.25) brightness(0.55);
  cursor: default;
}

/* Найденный кот остаётся ярким на фоне своей затемнённой области. */
.cell.done.open.has-cat {
  filter: none;
}

/* Открытая пустая клетка */
.cell.open {
  cursor: default;
}

/* Кот выделяется рамкой, не подменяя цвет своей области. */
.cell.open.has-cat {
  box-shadow: inset 0 0 0 2px var(--cat-ring);
}

.cell.open.has-cat::after {
  content: "😺";
}

/* Клетка, выводимая логически прямо сейчас (режим «Вывод») */
.cell.deducible {
  outline: 2px dashed var(--deducible-color);
  outline-offset: -2px;
  animation: hint-pulse 1.4s ease-in-out infinite;
}

@keyframes hint-pulse {
  0%, 100% { outline-color: var(--deducible-color); }
  50% { outline-color: var(--deducible-accent); }
}

.hint-count {
  margin-top: 6px;
  max-width: 480px;
  text-align: center;
  font-size: 12px;
  color: var(--text-dim);
  min-height: 16px;
}

/* Крестик */
.cell.crossed::before {
  content: "";
  position: absolute;
  inset: 14%;
  background:
    linear-gradient(45deg, transparent 42%, var(--cross-color) 42%, var(--cross-color) 58%, transparent 58%),
    linear-gradient(-45deg, transparent 42%, var(--cross-color) 42%, var(--cross-color) 58%, transparent 58%);
  filter: drop-shadow(var(--cross-shadow));
  pointer-events: none;
}

/* Поражение: показать все котики */
.cell.reveal {
  box-shadow: inset 0 0 0 2px var(--cat-ring);
}

.cell.reveal::after {
  content: "😿";
}

/* ---------- Overlay ---------- */

/* fixed на весь экран, а не absolute внутри .board-wrap: карточка правил
   выше доски на телефоне и обрезалась краями контейнера. */
.overlay {
  position: fixed;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(10, 12, 18, 0.72);
  z-index: 10;
  animation: fade-in 0.25s ease;
  padding: calc(12px + env(safe-area-inset-top, 0px))
           calc(12px + env(safe-area-inset-right, 0px))
           calc(12px + env(safe-area-inset-bottom, 0px))
           calc(12px + env(safe-area-inset-left, 0px));
}

/* Атрибут hidden должен побеждать display:flex выше, иначе оверлей
   перекрывает поле сразу при загрузке страницы. */
.overlay[hidden] { display: none; }

@keyframes fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}

.overlay-card {
  background: var(--panel);
  border: 1px solid var(--panel-border);
  border-radius: 14px;
  padding: 28px 36px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
  max-width: 90%;
  /* Не выше вьюпорта с прокруткой внутри: правила на маленьких экранах
     не влезают целиком. */
  max-height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.overlay-emoji { font-size: 48px; line-height: 1; }

.overlay-card h2 {
  margin: 0;
  font-size: 24px;
}

.overlay-card p {
  margin: 0 0 6px;
  color: var(--text-dim);
  font-size: 14px;
}

/* ---------- Rules Overlay ---------- */

.rules-overlay {
  z-index: 20;
}

.rules-card {
  max-width: 420px;
  padding: 24px 28px;
  text-align: left;
  align-items: stretch;
}

.rules-card h2 {
  margin: 0 0 8px;
  font-size: 20px;
  text-align: center;
}

.rules-body {
  font-size: 14px;
  line-height: 1.6;
  color: var(--text);
}

.rules-body p {
  margin: 0 0 10px;
}

.rules-body ul {
  margin: 0 0 12px;
  padding-left: 20px;
}

.rules-body li {
  margin-bottom: 6px;
}

.rules-body strong {
  color: #fff;
}

/* ---------- Hint ---------- */

.hint {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 12px;
  color: var(--text-dim);
}

/* ---------- Mobile ---------- */

@media (max-width: 560px) {
  .app {
    padding: 8px;
    /* Второе объявление побеждает там, где поддерживается env():
       отступ учитывает «чёлку» и жестовую панель iPhone. */
    padding: 8px calc(8px + env(safe-area-inset-right, 0px))
             calc(8px + env(safe-area-inset-bottom, 0px))
             calc(8px + env(safe-area-inset-left, 0px));
    gap: 8px;
  }
  /* Шапка — явный grid вместо flex-колонки. Комбинация flex-wrap: wrap +
     flex-direction: column + вложенный grid рассинхронизирует раскладку и
     отрисовку в WebKit (iOS, in-app webview Telegram): место под кнопки
     резервируется в шапке, а сами кнопки рисуются ниже — под доской. */
  .hud {
    display: grid;
    grid-template-columns: minmax(0, 1fr);
    align-items: center;
    gap: 8px;
    padding: 8px;
  }
  .hud-group { justify-content: space-between; min-width: 0; }

  /* Кнопки строго по 2 в ряд; «Начать заново» занимает всю строку. */
  .actions {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 6px;
  }
  .actions .btn {
    width: 100%;
    padding: 10px 6px;
    min-height: 40px;
    white-space: normal;   /* «Перегенерировать» переносится на узких экранах */
  }
  #btn-restart { grid-column: 1 / -1; }

  /* iOS зумит вьюпорт при фокусе select с кеглем < 16px
     (user-scalable=no Safari игнорирует). */
  .difficulty { font-size: 16px; }

  .rules-card { padding: 16px; }
  .rules-body { font-size: 13px; }
  .hint { font-size: 11px; flex-direction: column; gap: 4px; align-items: center; }
  .hint > span:nth-child(2) { display: none; }  /* разделитель «•» в колонке не нужен */
  :root { --cell-gap: 2px; --cell-radius: 3px; }
}
