/* Поле, карточки, переворот, исчезновение пар, экран победы. */

.board-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  width: 100%;
  min-width: 0;
  max-width: 100%;
  /* большое поле на узком экране прокручивается здесь,
     страница остаётся без горизонтального скролла */
  overflow-x: auto;
}

.board {
  --n: 6;
  --cell-min: 40px;
  display: grid;
  grid-template-columns: repeat(var(--n), 1fr);
  grid-auto-rows: 1fr;
  gap: 6px;
  width: min(100%, calc(100dvh - var(--header-h) - 120px));
  /* когда поле уже контейнера — центрируем; когда шире — прижато влево
     и доступно прокруткой целиком, без недоступного левого края */
  margin-inline: auto;
  aspect-ratio: 1;
  /* если клетки меньше минимума — прокручиваем, а не сжимаем */
  min-width: calc(var(--n) * (var(--cell-min) + 6px));
  overflow: auto;
  padding: 25px;
}

/* --- свободная центральная клетка --- */

.free-cell {
  container-type: size;            /* даёт единицы cqmin относительно самой клетки */
  display: flex;
  align-items: center;
  justify-content: center;
  aspect-ratio: 1;
  border-radius: 8px;
  border: none;
  /* мягкая впадина вместо пунктира: заметна, но не конкурирует с карточками */
  background: color-mix(in srgb, var(--line) 22%, transparent);
  box-shadow:
    inset 0 0 0 1px color-mix(in srgb, var(--line) 55%, transparent),
    inset 0 2px 6px rgba(0, 0, 0, 0.06);
}

.free-cell-star {
  font-size: 46cqmin;              /* ~46% меньшей стороны клетки, масштабируется с полем */
  line-height: 1;
  /* серый с лёгким оттенком акцента, чтобы взгляд цеплялся, но не кричал */
  color: color-mix(in srgb, var(--accent) 30%, var(--line));
  font-variant-emoji: text;        /* чтобы ★ не превращалась в цветной эмодзи на телефонах */
}

/* --- карточка и переворот --- */

.card {
  position: relative;
  aspect-ratio: 1;
  padding: 0;
  border: none;
  background: none;
  perspective: 600px;
  border-radius: 8px;
  cursor: pointer;
  touch-action: manipulation;
  -webkit-tap-highlight-color: transparent;
}

.card-inner {
  position: absolute;
  inset: 0;
  transform-style: preserve-3d;
  transition: transform 250ms ease;
}

.card.is-open .card-inner,
.card.is-matched .card-inner {
  transform: rotateY(180deg);
}

.card-face {
  position: absolute;
  inset: 0;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}


.card-back {
  background: linear-gradient(160deg, #f1e4cf 0%, #e6d3b5 100%);
  border: 1px solid #cdb996;
  box-shadow:
    inset 0 2px 0 rgba(255, 255, 255, 0.65),    /* верхний блик */
    inset 0 -3px 0 rgba(150, 110, 60, 0.18),    /* нижняя «толщина» плитки */
    0 1px 2px rgba(60, 40, 10, 0.18);           /* отрыв от фона поля */
}

.card-back::after {
  content: "";
  width: 60%;
  aspect-ratio: 1;
  background: url("../img/card-back-coin.svg") center / contain no-repeat;
  filter: drop-shadow(0 1px 1px rgba(90, 60, 20, 0.25));
}

.card-front {
  transform: rotateY(180deg);
  background: var(--card);
  border: 1px solid var(--line);
  container-type: size;
  padding: 6%;
}

/* карточка-картинка: изображение на всю лицевую сторону; рамку рисует .card-front */
.card-picture .card-front {
  padding: 0;
}

.card-art {
  width: 100%;
  height: 100%;
}

.card-art img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* карточка-иероглиф: иероглиф ~55% высоты клетки, пиньинь ~18% */
.card-hanzi {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4cqh;
  width: 100%;
  height: 100%;
}

.hanzi {
  font-family: "Noto Sans SC", "PingFang SC", "Microsoft YaHei",
    "Hiragino Sans GB", sans-serif;
  font-size: 55cqh;
  line-height: 1;
}

/* слова из нескольких иероглифов: кегль меньше, чтобы все знаки влезали */
.card-hanzi[data-hanzi-len="2"] .hanzi {
  font-size: 38cqh;
}

.card-hanzi[data-hanzi-len="3"] .hanzi {
  font-size: 27cqh;
}

.hanzi img {
  width: 100%;
  object-fit: contain;
}

.pinyin {
  font-size: 18cqh;
  color: var(--muted);
}

/* без пиньиня иероглиф остаётся по центру */
body.no-pinyin .pinyin {
  display: none;
}

/* --- совпавшая пара: короткая анимация-награда, затем исчезновение --- */

.card.is-matched {
  pointer-events: none;
  /* совпавшая пара поверх соседей: искры вылетают за пределы карточки
     и не должны прятаться за фоном соседних клеток */
  z-index: 5;
}

/*
 * Один keyframes на оба состояния: подтверждение (scale 1.06 + мягкое
 * свечение цветом темы, без контура), прыжок вверх с мягким возвратом,
 * исчезновение. Класс ставится на обе карточки одновременно — анимации
 * синхронны.
 */
@keyframes match-reward {
  /* 1. подтверждение: ~170 мс */
  0% {
    scale: 1;
    translate: 0 0;
    box-shadow: 0 0 0 0 transparent;
  }
  12% {
    scale: 1.06;
    box-shadow: 0 0 16px color-mix(in srgb, var(--accent) 35%, transparent);
  }
  25% {
    scale: 1.06;
  }
  /* 2. подпрыгивание: ~300 мс, мягкий easing задан в animation-timing-function */
  40% {
    translate: 0 -6px;
    scale: 1.02;
  }
  55% {
    translate: 0 0;
    scale: 1;
  }
  65% {
    translate: 0 0;
    scale: 1;
    box-shadow: 0 0 0 0 transparent;
  }
  /* 3. исчезновение: ~240 мс */
  100% {
    translate: 0 -4px;
    scale: 0.75;
    opacity: 0;
  }
}

.card.is-matched .card-inner {
  animation: match-reward 680ms cubic-bezier(0.3, 0, 0.4, 1) forwards;
}

/* искры: размер и путь заданы в долях карточки, поэтому масштабируются
   вместе с полем. Обёртка .spark несёт свечение (filter), звезда рисуется
   в ::before с clip-path — иначе обрезка вырежет тень. */

.spark {
  position: absolute;
  width: var(--s);
  aspect-ratio: 1;
  opacity: 0;
  pointer-events: none;
  filter:
    drop-shadow(0 0 4px rgba(246, 184, 60, 0.9))
    drop-shadow(0 1px 1px rgba(0, 0, 0, 0.25));
}

.spark::before {
  content: "";
  position: absolute;
  inset: 0;
  background: radial-gradient(circle at 35% 30%, #fff6c4, #f6b83c 55%, #e29a14);
  clip-path: polygon(50% 0, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%,
    21% 91%, 32% 57%, 2% 35%, 39% 35%);
}

/* --s: размер от стороны карточки; --dx/--dy: путь в долях размера самой искры */
.spark-1 {
  --s: 24%; --dx: -90%; --dy: -90%; --rot: -30deg; --delay: 170ms;
  top: 20%; left: 10%;
}

.spark-2 {
  --s: 16%; --dx: 120%; --dy: -70%; --rot: 35deg; --delay: 230ms;
  top: 30%; left: 72%;
}

.spark-3 {
  --s: 30%; --dx: 0%; --dy: -80%; --rot: 15deg; --delay: 200ms;
  top: 8%; left: 36%;
}

.card.is-matched .spark {
  animation: spark-fly 520ms ease-out var(--delay) forwards;
}

@keyframes spark-fly {
  0% {
    opacity: 0;
    transform: translate(0, 0) scale(0.2) rotate(0deg);
  }
  30% {
    opacity: 1;
    transform: translate(calc(var(--dx) * 0.5), calc(var(--dy) * 0.5))
      scale(1.25) rotate(calc(var(--rot) * 0.5));
  }
  70% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: translate(var(--dx), var(--dy)) scale(0.6) rotate(var(--rot));
  }
}

/* --- подпись под полем после совпадения --- */

.match-caption {
  min-height: 1.6em;
  margin: 0;
  font-size: 28px;
  opacity: 0;
  transition: opacity 200ms ease;
}

.match-caption.is-visible {
  opacity: 1;
}

/* --- экран победы --- */

.win-screen {
  position: fixed;
  inset: 0;
  z-index: 100;               /* поверх карточек с z-index: 5 */
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(43, 43, 51, 0.55);
  opacity: 0;
  transition: opacity 250ms ease;
}

.win-screen.is-shown {
  opacity: 1;
}

.win-screen.is-shown .win-card {
  opacity: 1;
  transform: translateY(0) scale(1);
}

/* строки очков и места занимают место с самого начала, пока ждём сервер */
.win-card p.win-points { min-height: 1.25em; }
.win-card p.win-place  { min-height: 1.3em; }
.win-card p.is-pending { visibility: hidden; }


.win-card {
  position: relative;
  overflow: hidden;

  background: var(--card);
  border: 1px solid var(--line);
  border-radius: 20px;

  padding: 32px 36px;
  text-align: center;

  display: flex;
  flex-direction: column;
  gap: 10px;

  box-shadow:
    0 16px 48px rgba(43, 43, 51, 0.18),
    0 4px 12px rgba(43, 43, 51, 0.08);

  /* max-width: calc(100vw - 32px); */

  width: min(380px, calc(100vw - 32px));
  overflow-wrap: anywhere;
  will-change: transform, opacity;

  transform: translateY(10px) scale(0.97);
  transition: transform 300ms ease;
}


/* Заголовок */
.win-card h2 {
  margin: 4px 0 8px;
  font-size: 28px;
  line-height: 1.2;
  color: var(--ink);
}

/* Основной текст */
.win-card p {
  margin: 0;
  font-size: 18px;
  color: var(--muted);
}

.win-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;

  margin: 0 0 6px;
  font-size: 26px;
}

.win-trophy {
  font-size: 32px;
  line-height: 1;
  flex-shrink: 0;
}

/* Очки */
.win-card p.win-points {
  font-size: 36px;
  font-weight: 600;
  color: var(--accent);
  margin: 8px 0;
  font-variant-numeric: tabular-nums;
}

/* Место в рейтинге */
.win-card p.win-place {
  font-size: 20px;
  font-weight: 600;
  color: #a56b43;
  margin: 4px 0 12px;
}

/* Кнопки */
.win-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.win-card .btn {
  margin-top: 12px;
}


/* --- меньше движения --- */

@media (prefers-reduced-motion: reduce) {
  .card-inner {
    transition: none;
  }

  /* без движения: короткая мягкая подсветка и быстрое исчезновение */
  .card.is-matched .card-inner {
    animation: none;
    box-shadow: 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
    opacity: 0;
    transition: opacity 150ms ease;
  }

  .card.is-matched .spark,
  .spark {
    display: none;
  }

  .match-caption {
    transition: none;
  }
}
