/* Общий чат-виджет priglas.online — плавающая кнопка + панель диалога.
   Разметку строит chat-widget.js, подключается на лендинге и во всех страницах блога.
   На мобильном (≤860px) при открытии панель разворачивается на весь экран (как в
   Intercom/WhatsApp Web) — высоту/отступ сверху подгоняет JS через visualViewport,
   чтобы клавиатура не ломала пропорции. Позиционирование кнопки внутри нижнего меню
   блога — в blog-bar.css.
   Открытое состояние панели триггерится классом .is-open НА САМОЙ .chat-panel, а не
   через родителя .chat-widget.is-open — на блоге при открытии на мобилке JS переносит
   панель прямо в <body> (см. chat-widget.js), потому что нижняя полоса блога использует
   backdrop-filter, а он создаёт containing block для потомков с position:fixed — вложенная
   "полноэкранная" панель зажималась бы внутри 68px полосы, а не разворачивалась на экран. */

.chat-widget { position: fixed; right: max(16px, calc((100% - var(--container-max)) / 2 - var(--space-4) - 56px)); bottom: var(--space-5); z-index: 50; }

/* Кнопка 56px с белой каёмкой и зелёным свечением — читается на любом фоне (2026-10-27: «значок не видно») */
.chat-toggle {
  position: relative; width: 56px; height: 56px; border-radius: 50%;
  background: var(--color-green); color: var(--color-on-green);
  display: inline-flex; align-items: center; justify-content: center; border: none; cursor: pointer; flex-shrink: 0;
  box-shadow: 0 0 0 3px var(--color-ground), var(--shadow-glow-green);
  transition: transform var(--duration-fast) var(--ease-out), background var(--duration-fast) var(--ease-standard);
}
.chat-toggle:hover { transform: scale(1.06); background: var(--color-green-deep); }
.chat-toggle svg { width: 25px; height: 25px; }
/* Непрочитанные (2026-10-27): красный кружок с числом, пока панель закрыта. Красного токена в design-tokens.css нет —
   единственный красный в системе — #c0392b (ошибка загрузки файла ниже), его и берём. Белая каёмка — как у самой кнопки. */
.chat-toggle__badge {
  position: absolute; top: -4px; right: -4px; z-index: 1; min-width: 22px; height: 22px; padding: 0 6px; box-sizing: border-box;
  border-radius: 11px; background: #c0392b; color: #fff; box-shadow: 0 0 0 2px var(--color-ground);
  font-family: inherit; font-size: 12px; line-height: 22px; font-weight: 600; text-align: center; font-variant-numeric: tabular-nums; pointer-events: none;
}
.chat-toggle__badge[hidden] { display: none; }
/* Привлечение внимания (2026-10-27, активнее по просьбе владельца): двойная волна каждые 2,4 с без остановки,
   раз в 4,8 с значок подпрыгивает и покачивается. После первого открытия — только редкая волна раз в 6 с. */
.chat-toggle::before, .chat-toggle::after { content: ""; position: absolute; inset: 0; border-radius: 50%; pointer-events: none; }
.chat-widget:not(.is-open):not(.was-opened) .chat-toggle:not(:hover) { animation: chatNudgePop 4.8s var(--ease-out) 1.5s infinite; }
.chat-widget:not(.is-open):not(.was-opened) .chat-toggle:not(:hover) svg { animation: chatNudgeWiggle 4.8s var(--ease-standard) 1.5s infinite; }
.chat-widget:not(.is-open):not(.was-opened) .chat-toggle::after { animation: chatNudgeRing 2.4s var(--ease-out) 0.6s infinite; }
.chat-widget:not(.is-open):not(.was-opened) .chat-toggle::before { animation: chatNudgeRing 2.4s var(--ease-out) 1.4s infinite; }
.chat-widget.was-opened:not(.is-open) .chat-toggle::after { animation: chatNudgeRing 6s var(--ease-out) 3s infinite; }
@keyframes chatNudgePop {
  0%, 14%, 100% { transform: scale(1); }
  4% { transform: scale(1.14); }
  8% { transform: scale(0.96); }
  11% { transform: scale(1.04); }
}
@keyframes chatNudgeWiggle {
  0%, 14%, 100% { transform: rotate(0); }
  3% { transform: rotate(-16deg); }
  6% { transform: rotate(14deg); }
  9% { transform: rotate(-9deg); }
  12% { transform: rotate(5deg); }
}
@keyframes chatNudgeRing {
  0% { box-shadow: 0 0 0 0 rgba(47, 158, 92, 0.6); }
  70%, 100% { box-shadow: 0 0 0 22px rgba(47, 158, 92, 0); }
}
@media (prefers-reduced-motion: reduce) {
  .chat-toggle, .chat-toggle svg, .chat-toggle::before, .chat-toggle::after { animation: none !important; }
}

/* ---------- Панель (десктоп — плавающий попап) ---------- */
/* Размеры текста внутри чата — буквальные px, не токены ×0.8: как и текст статей блога
   (см. DESIGN.md «Размер текста для чтения»), переписка — это чтение, 11.2px слишком мелко. */
.chat-panel {
  position: absolute; right: 0; bottom: 60px; width: 380px; height: min(72vh, 580px);
  display: flex; flex-direction: column;
  background: var(--color-ground); border: 1px solid var(--color-line); border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lifted); overflow: hidden;
  opacity: 0; transform: translateY(8px) scale(0.98); pointer-events: none;
  transition: opacity var(--duration-base) var(--ease-standard), transform var(--duration-base) var(--ease-standard);
}
.chat-panel.is-open { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }

.chat-panel__header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 16px 16px 14px 20px; border-bottom: 1px solid var(--color-line); flex-shrink: 0; }
.chat-panel__title { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.chat-panel__title .wordmark { font-size: 17px; line-height: 20px; }
.chat-panel__status { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; line-height: 16px; color: var(--color-ink-faint); }
.chat-panel__status::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--color-green); flex-shrink: 0; }
.chat-panel__close { width: 36px; height: 36px; border-radius: 50%; border: none; background: transparent; color: var(--color-ink-soft); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; flex-shrink: 0; transition: background var(--duration-fast) var(--ease-standard); }
.chat-panel__close:hover { background: var(--color-surface); }
.chat-panel__close svg { width: 18px; height: 18px; }

/* Лента прижата к низу (первое сообщение с margin-top:auto), как в мессенджерах —
   иначе на высоком экране короткая переписка висит сверху над пустотой. */
.chat-panel__messages { flex: 1; min-height: 0; overflow-y: auto; -webkit-overflow-scrolling: touch; overscroll-behavior: contain; padding: 20px 16px; display: flex; flex-direction: column; gap: 4px; }
.chat-panel__messages > :first-child { margin-top: auto; }

.chat-msg { display: flex; }
.chat-msg--bot { justify-content: flex-start; }
.chat-msg--user { justify-content: flex-end; }
/* Подряд от одного автора — 4px, смена автора — 14px: реплики читаются группами */
.chat-msg--bot + .chat-msg--user, .chat-msg--user + .chat-msg--bot { margin-top: 10px; }
/* Согласие на ПДн под приветствием: мелко и тихо, не пузырь */
.chat-consent { margin: 2px 0 6px; padding-left: 4px; font-size: 11px; line-height: 15px; color: var(--color-ink-faint); }
.chat-panel .chat-consent a, .chat-panel .chat-consent a:visited { color: inherit; text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 2px; }
.chat-msg__bubble { max-width: 82%; padding: 10px 14px; border-radius: 18px; font-size: 14px; line-height: 20px; overflow-wrap: break-word; }
.chat-msg--bot .chat-msg__bubble { background: var(--color-surface); color: var(--color-ink); border-bottom-left-radius: var(--radius-sm); }
.chat-msg--user .chat-msg__bubble { background: var(--color-green); color: var(--color-on-green); border-bottom-right-radius: var(--radius-sm); }
/* Ссылки в ответах бота. В блоге глобально a { color: inherit; text-decoration: none } — перебиваем специфичностью
   через .chat-panel (на мобилке панель переезжает в <body>, но класс остаётся) */
.chat-panel .chat-msg__bubble a, .chat-panel .chat-msg__bubble a:visited {
  color: var(--color-green-deep); text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 3px; cursor: pointer; overflow-wrap: anywhere;
}
.chat-panel .chat-msg__bubble a:hover { color: var(--color-green); text-decoration-thickness: 2px; }
.chat-msg__note { display: block; margin-top: 8px; color: var(--color-ink-faint); font-size: 12px; line-height: 17px; }
/* Кнопки перехода после брифа (этап 8 plans/crm.md): Telegram / ВКонтакте / «Продолжим здесь». Стиль — .btn-outline дизайн-системы, уменьшенный под чат */
.chat-handoff { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
.chat-panel .chat-handoff__btn, .chat-panel .chat-msg__bubble a.chat-handoff__btn, .chat-panel .chat-msg__bubble a.chat-handoff__btn:visited {
  font-family: var(--font-display); font-weight: var(--fw-semibold); font-size: 14px; line-height: 20px;
  border-radius: var(--radius-pill); padding: 7px 14px; border: 1.5px solid var(--color-ink); background: transparent; color: var(--color-ink);
  text-decoration: none; cursor: pointer; transition: background var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard);
}
.chat-panel .chat-handoff__btn:hover, .chat-panel .chat-msg__bubble a.chat-handoff__btn:hover { background: var(--color-ink); color: var(--color-ground); }
.chat-handoff.is-done .chat-handoff__btn--stay { display: none; }
/* «Получить бесплатный разбор» — главная кнопка, залитая; нажатые кнопки-ответы гаснут (2026-10-28) */
.chat-panel .chat-handoff__btn--offer { background: var(--color-green); border-color: var(--color-green); color: var(--color-ground); }
.chat-panel .chat-handoff__btn--offer:hover { background: var(--color-green-deep); border-color: var(--color-green-deep); color: var(--color-ground); }
/* то же для ссылки-кнопки (в пузыре ссылки перекрашены правилом выше): «Открыть Telegram» после формы — главная кнопка */
.chat-panel .chat-msg__bubble a.chat-handoff__btn--offer, .chat-panel .chat-msg__bubble a.chat-handoff__btn--offer:visited { background: var(--color-green); border-color: var(--color-green); color: var(--color-ground); }
.chat-panel .chat-msg__bubble a.chat-handoff__btn--offer:hover { background: var(--color-green-deep); border-color: var(--color-green-deep); color: var(--color-ground); }
.chat-handoff.is-done [data-say] { opacity: .45; pointer-events: none; }

/* Форма выбора связи (2026-11-04): канал кнопкой, ник/почта/номер — поле, для Telegram — строка о передаче переписки за рубеж (нажатие «Продолжить» = согласие, 2026-11-05).
   Кнопки — те же .chat-handoff__btn; выбранная заливается чернилами, готовая форма гаснет */
.chat-cf { display: block; margin-top: 10px; }
.chat-cf__row { display: flex; flex-wrap: wrap; gap: 8px; }
.chat-panel .chat-cf__row .chat-handoff__btn.is-active { background: var(--color-ink); color: var(--color-ground); }
.chat-cf__panel:empty { display: none; }
.chat-cf__form { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; align-items: flex-start; }
.chat-panel .chat-cf__input {
  box-sizing: border-box; width: 100%; height: 40px; padding: 8px 14px; border: 1px solid var(--color-line); border-radius: 20px;
  background: var(--color-ground); color: var(--color-ink); font-family: inherit;
  /* 16px — порог iOS Safari: ниже него страница зумится при фокусе на поле */
  font-size: 16px; line-height: 22px;
}
.chat-panel .chat-cf__input::placeholder { color: var(--color-ink-faint); }
.chat-panel .chat-cf__input:focus, .chat-panel .chat-cf__input:focus-visible { outline: none; border-color: var(--color-green); }
.chat-cf__note { font-size: 12px; line-height: 17px; color: var(--color-ink-soft, var(--color-ink)); }
.chat-cf__err { font-size: 12px; line-height: 17px; color: #c0392b; }
.chat-cf__err[hidden] { display: none; }
.chat-cf.is-busy { opacity: .6; }
.chat-cf.is-done .chat-cf__row { opacity: .45; pointer-events: none; }
.chat-cf.is-done .chat-cf__panel { display: none; }
.chat-cf__lead { display: block; margin-bottom: 8px; font-weight: 600; }
/* картинка в реплике бота (памятка в чате): целиком и крупнее квадрата 120 px, нажатие открывает полный размер */
.chat-msg--bot .chat-msg__files { margin: 4px 0 8px; }
.chat-msg--bot .chat-msg__files img { width: 100%; max-width: 240px; height: auto; object-fit: contain; }
.chat-msg__zoom { display: block; }
/* QR для компьютера: бот открывается с телефона. Белая подложка и тихая зона внутри SVG нужны сканеру, тему страницы не повторяем */
.chat-qr { display: flex; gap: 12px; align-items: center; margin-top: 12px; }
.chat-qr__box { flex: none; width: 116px; height: 116px; border-radius: var(--radius-sm); overflow: hidden; background: #fff; border: 1px solid var(--color-line); }
.chat-qr__box svg { display: block; width: 100%; height: 100%; }
.chat-qr:not(.is-painted) .chat-qr__box { background: var(--color-surface); }
.chat-qr__hint { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; font-size: 12px; line-height: 17px; color: var(--color-ink-soft, var(--color-ink)); }
.chat-panel .chat-qr__copy { padding: 0; border: none; background: none; font: inherit; color: var(--color-green-deep); text-decoration: underline; text-underline-offset: 3px; cursor: pointer; }

.chat-typing { display: inline-flex; gap: 4px; align-items: center; height: 20px; }
.chat-typing span { width: 6px; height: 6px; border-radius: 50%; background: var(--color-ink-faint); display: block; animation: chatTypingDot 1.1s var(--ease-standard) infinite; }
.chat-typing span:nth-child(2) { animation-delay: 0.15s; }
.chat-typing span:nth-child(3) { animation-delay: 0.3s; }
@keyframes chatTypingDot { 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); } }
@media (prefers-reduced-motion: reduce) { .chat-typing span { animation: none; opacity: 0.6; } }

.chat-panel__input-row { display: flex; align-items: flex-end; gap: 8px; padding: 12px 12px 12px 16px; border-top: 1px solid var(--color-line); flex-shrink: 0; }
/* Поле без рамки на кремовой подложке; фокус — зелёная рамка самого поля вместо общего
   фокус-кольца с отступом 3px, которое на pill-инпуте читается как двойная обводка */
.chat-panel__input {
  /* textarea: одна строка 42px, растёт до трёх строк (высоту ставит JS), дальше прокрутка внутри */
  flex: 1; min-width: 0; height: 42px; min-height: 42px; border: 1px solid transparent; border-radius: 21px;
  padding: 9px 16px; line-height: 22px; resize: none; overflow-y: hidden; display: block; font-family: inherit; color: var(--color-ink); background: var(--color-surface);
  /* 16px, не токен шкалы: ниже этого iOS Safari зумит страницу при фокусе на поле — фиксированный порог браузера, не дизайн-решение */
  font-size: 16px;
  transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
}
.chat-panel__input::placeholder { color: var(--color-ink-faint); }
.chat-panel__input:focus, .chat-panel__input:focus-visible { outline: none; border-color: var(--color-green); background: var(--color-ground); }
/* Общее правило фокуса лендинга (index.html) ставит border-radius: 3px — круглые кнопки чата в фокусе не должны становиться квадратными */
.chat-toggle:focus-visible, .chat-panel__close:focus-visible, .chat-panel__send:focus-visible { border-radius: 50%; }
.chat-panel__send { width: 42px; height: 42px; border-radius: 50%; border: none; background: var(--color-green); color: var(--color-on-green); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; flex-shrink: 0; transition: background var(--duration-fast) var(--ease-standard), opacity var(--duration-fast) var(--ease-standard); }
.chat-panel__send:hover { background: var(--color-green-deep); }
.chat-panel__send svg { width: 18px; height: 18px; margin-left: -2px; }
/* Пока поле пустое — кнопка приглушена (отправлять нечего) */
.chat-panel__input:placeholder-shown + .chat-panel__send { opacity: 0.45; }
.chat-panel__input-row.has-files .chat-panel__send { opacity: 1; }

/* Скрепка: картинки, которые нравятся, или PDF */
.chat-panel__attach { width: 36px; height: 42px; margin-left: -6px; border: none; background: none; color: var(--color-ink-faint); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; flex-shrink: 0; border-radius: 50%; transition: color var(--duration-fast) var(--ease-standard); }
.chat-panel__attach:hover { color: var(--color-green); }
.chat-panel__attach svg { width: 20px; height: 20px; }
/* Выбранные файлы над полем: превью с крестиком, пока грузится — полупрозрачное */
.chat-panel__files { display: flex; gap: 8px; padding: 10px 12px 0 16px; overflow-x: auto; flex-shrink: 0; border-top: 1px solid var(--color-line); }
.chat-panel__files:not([hidden]) + .chat-panel__input-row { border-top: none; }
.chat-file { position: relative; flex-shrink: 0; width: 56px; height: 56px; border-radius: var(--radius-sm); background: var(--color-surface); overflow: hidden; display: flex; align-items: center; justify-content: center; }
.chat-file img { width: 100%; height: 100%; object-fit: cover; }
.chat-file__name { font-size: 11px; line-height: 13px; padding: 4px; color: var(--color-ink-soft, var(--color-ink)); overflow: hidden; text-overflow: ellipsis; word-break: break-all; max-height: 100%; }
.chat-file.is-loading { opacity: 0.5; }
.chat-file.is-error { outline: 2px solid #c0392b; outline-offset: -2px; }
.chat-file__remove { position: absolute; top: 2px; right: 2px; width: 20px; height: 20px; border-radius: 50%; border: none; background: rgba(0,0,0,0.55); color: #fff; font-size: 14px; line-height: 20px; padding: 0; cursor: pointer; }
.chat-msg__files { display: flex; flex-wrap: wrap; gap: 6px; margin: -4px -8px 6px; }
.chat-msg__files:only-child { margin-bottom: -4px; }
.chat-msg__files img { width: 120px; height: 120px; object-fit: cover; border-radius: 12px; display: block; }
.chat-msg__file { font-size: 13px; }

/* ---------- Мобильный полноэкранный режим ---------- */
/* Точную высоту/отступ сверху (с учётом клавиатуры) выставляет JS через visualViewport —
   здесь только базовая раскладка на весь экран и запасной размер до первого JS-тика. */
@media (max-width: 860px) {
  .chat-widget.is-open .chat-toggle { display: none; }
  /* Пока на телефоне показана плашка cookie (карточка во всю ширину, ~154px), кнопка чата встаёт над ней, а не под ней.
     В блоге кнопка живёт в нижней полосе, а плашка и так поднята над полосой. */
  .chat-widget { transition: bottom var(--duration-base, 240ms) var(--ease-out); }
  body:has(.consent.is-shown) > .chat-widget, body:has(.consent.is-shown) .chat-widget:not(.blog-bar .chat-widget) { bottom: calc(12px + 154px + 16px + env(safe-area-inset-bottom)); }
  /* position:fixed/inset — безусловно, а не только при .is-open: если менять position
     дискретно в момент открытия/закрытия, он не анимируется (в отличие от opacity/transform)
     и на закрытии панель на кадр "схлопывается" в десктопный попап посреди затухания.
     Закрытое состояние просто уезжает за нижний край экрана своей же высотой. */
  .chat-panel {
    position: fixed; inset: 0; width: 100%; height: 100dvh; border-radius: 0; box-shadow: none;
    transform: translateY(100%); z-index: 60;
  }
  .chat-panel.is-open { transform: translateY(0); }
  .chat-panel { border: none; }
  .chat-panel__header { padding: max(12px, env(safe-area-inset-top)) 8px 12px 20px; }
  .chat-panel__title .wordmark { font-size: 18px; line-height: 22px; }
  .chat-panel__status { font-size: 13px; }
  .chat-panel__close { width: 44px; height: 44px; }
  .chat-panel__close svg { width: 20px; height: 20px; }
  .chat-panel__messages { padding: 16px; }
  .chat-msg__bubble { font-size: 16px; line-height: 22px; max-width: 85%; }
  .chat-msg__note { font-size: 13px; line-height: 18px; }
  .chat-panel__input-row { padding: 10px 12px max(10px, env(safe-area-inset-bottom)) 16px; }
  .chat-panel__input { height: 44px; min-height: 44px; padding-block: 10px; border-radius: 22px; }
  .chat-panel__attach { height: 44px; }
  .chat-panel__send { width: 44px; height: 44px; }
}
