:root {
  --ic-primary: #ff3d62;
  --ic-primary-dark: #ff3d62;
  --ic-bg: #ffffff;
  --ic-body-bg: #f5f6fa;
  --ic-user-bubble: #ff3d62;
  --ic-bot-bubble: #ffffff;
  --ic-text: #1c1c28;
  --ic-muted: #8a8a9e;
  --ic-border: #ececf2;
  --ic-radius: 16px;
  --ic-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;

  /* Высота «экрана» виджета.
     ПРОБЛЕМА (было): height: 100vh. На iOS Safari 100vh = БОЛЬШОЙ вьюпорт (без учёта
     динамической адресной строки), поэтому нижнее поле ввода уезжало под панель браузера.
     РЕШЕНИЕ: динамическая высота 100dvh (следит за реальной видимой областью).
     Цепочка фолбэков: сначала 100vh (старые движки), затем переопределяем на 100dvh.
     На iOS дополнительно точную высоту задаёт JS из visualViewport (см. widget.js). */
  --ic-app-height: 100vh;
}
@supports (height: 100dvh) {
  :root { --ic-app-height: 100dvh; }
}

* { box-sizing: border-box; }

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: var(--ic-font);
  background: transparent;
  /* Не «пробрасывать» прокрутку наружу (резиновый скролл iOS). */
  overscroll-behavior: none;
}

.chat {
  display: flex;
  flex-direction: column;
  height: var(--ic-app-height);
  width: 100%;
  background: var(--ic-body-bg);
  overflow: hidden;
  position: relative; /* контекст для экрана согласия (.consent) */
}

/* Header */
.chat__header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  /* ПРОБЛЕМА: на iPhone с «чёлкой»/Dynamic Island верх контента уходил под вырез.
     РЕШЕНИЕ: safe-area сверху и по бокам (env работает только при viewport-fit=cover). */
  padding-top: calc(14px + env(safe-area-inset-top, 0px));
  padding-left: calc(16px + env(safe-area-inset-left, 0px));
  padding-right: calc(16px + env(safe-area-inset-right, 0px));
  background: linear-gradient(135deg, var(--ic-primary) 0%, var(--ic-primary-dark) 100%);
  color: #fff;
  flex-shrink: 0;
}
.chat__avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 14px;
  letter-spacing: 0.5px;
  flex-shrink: 0;
}
.chat__title { flex: 1; min-width: 0; }
.chat__name { font-weight: 600; font-size: 15px; }
.chat__status { display: flex; align-items: center; gap: 6px; font-size: 12px; opacity: 0.85; }
.chat__dot { width: 7px; height: 7px; border-radius: 50%; background: #4ade80; }
.chat__close {
  background: none; border: none; color: #fff; font-size: 26px;
  line-height: 1; cursor: pointer; opacity: 0.85;
  /* ПРОБЛЕМА: маленькая зона нажатия на мобильном. РЕШЕНИЕ: цель >= 44×44 px (Apple HIG). */
  width: 44px; height: 44px; display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
  touch-action: manipulation;            /* убирает задержку/двойной тап-зум */
  -webkit-tap-highlight-color: transparent;
}
.chat__close:hover { opacity: 1; }

/* Body */
.chat__body {
  flex: 1;
  /* ПРОБЛЕМА: flex-элемент по умолчанию имеет min-height:auto и не сжимается ниже
     своего контента — при длинной переписке лента «распирала» колонку, и низ
     (включая поле ввода) обрезался из-за overflow:hidden у .chat.
     РЕШЕНИЕ: min-height:0 разрешает элементу сжиматься и прокручиваться внутри. */
  min-height: 0;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  scroll-behavior: smooth;
  /* Прокрутка ленты не «утекает» в фон (важно при заблокированном фоне на iOS). */
  overscroll-behavior: contain;
}
.chat__body::-webkit-scrollbar { width: 6px; }
.chat__body::-webkit-scrollbar-thumb { background: #d3d3df; border-radius: 3px; }

/* Messages */
.msg {
  max-width: 82%;
  padding: 10px 14px;
  border-radius: var(--ic-radius);
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  white-space: pre-wrap;
  animation: pop 0.18s ease-out;
}
@keyframes pop { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

.msg--bot {
  align-self: flex-start;
  background: var(--ic-bot-bubble);
  color: var(--ic-text);
  border: 1px solid var(--ic-border);
  border-bottom-left-radius: 4px;
}
.msg--user {
  align-self: flex-end;
  background: var(--ic-user-bubble);
  color: #fff;
  border-bottom-right-radius: 4px;
}
.msg a { color: var(--ic-primary); }
.msg--user a { color: #fff; text-decoration: underline; }

/* Markdown в ответах бота: блоки рендерим сами, поэтому white-space: normal
   (у пользователя остаётся pre-wrap для простого текста). */
.msg--bot { white-space: normal; }
.msg p { margin: 0 0 8px; }
.msg p:last-child { margin-bottom: 0; }
.msg ul, .msg ol { margin: 6px 0; padding-left: 20px; }
.msg li { margin: 3px 0; }
.msg strong { font-weight: 700; }
.msg em { font-style: italic; }
.msg code {
  background: #f0f0f5; padding: 1px 5px; border-radius: 5px;
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px;
}

.msg__meta {
  font-size: 11px;
  color: var(--ic-muted);
  margin-top: 4px;
  align-self: flex-start;
}
.msg__source {
  display: inline-block;
  font-size: 10px;
  padding: 1px 7px;
  border-radius: 8px;
  background: #eef2ff;
  color: #ff3d62;
  margin-right: 6px;
}

/* Typing indicator */
.typing { display: flex; gap: 4px; align-items: center; padding: 14px; }
.typing span {
  width: 7px; height: 7px; border-radius: 50%; background: var(--ic-muted);
  animation: blink 1.2s infinite both;
}
.typing span:nth-child(2) { animation-delay: 0.2s; }
.typing span:nth-child(3) { animation-delay: 0.4s; }
@keyframes blink { 0%, 80%, 100% { opacity: 0.3; } 40% { opacity: 1; } }

/* Suggestions */
.chat__suggestions {
  display: flex;
  gap: 8px;
  padding: 0 16px 8px;
  padding-left: calc(16px + env(safe-area-inset-left, 0px));
  padding-right: calc(16px + env(safe-area-inset-right, 0px));
  flex-wrap: wrap;
  flex-shrink: 0;
}
.suggestion {
  font-size: 12.5px;
  padding: 8px 12px;
  min-height: 36px;
  border-radius: 14px;
  border: 1px solid var(--ic-border);
  background: #fff;
  color: var(--ic-primary);
  cursor: pointer;
  white-space: nowrap;
  transition: background 0.15s;
  touch-action: manipulation;
  -webkit-tap-highlight-color: transparent;
}
.suggestion:hover { background: #f3eefa; }

/* Статус повторных попыток + ошибка связи с кнопкой повтора */
.retry-note {
  align-self: center;
  font-size: 12px;
  color: var(--ic-muted);
  padding: 4px 0;
  text-align: center;
}
.msg--error { border-color: #ffd0d8; }
.msg__retry {
  display: inline-block;
  margin-top: 10px;
  font-size: 13px;
  padding: 8px 14px;
  min-height: 36px;
  border-radius: 12px;
  border: 1px solid var(--ic-primary);
  background: var(--ic-primary);
  color: #fff;
  cursor: pointer;
  transition: background 0.15s;
  touch-action: manipulation;
  -webkit-tap-highlight-color: transparent;
}
.msg__retry:hover { background: var(--ic-primary-dark); }

/* Form */
.chat__form {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  padding: 12px 16px;
  /* safe-area по бокам (ландшафт с «чёлкой»). Нижний инсет вешаем на футер —
     он самый нижний элемент; см. .chat__footer. */
  padding-left: calc(16px + env(safe-area-inset-left, 0px));
  padding-right: calc(16px + env(safe-area-inset-right, 0px));
  background: var(--ic-bg);
  border-top: 1px solid var(--ic-border);
  flex-shrink: 0;
}
.chat__input {
  flex: 1;
  resize: none;
  border: 1px solid var(--ic-border);
  border-radius: 20px;
  padding: 10px 14px;
  font-family: inherit;
  /* ПРОБЛЕМА: при font-size < 16px iOS Safari авто-зумит страницу на фокусе поля.
     РЕШЕНИЕ: ровно 16px (или больше) — зум не срабатывает, доступность сохранена. */
  font-size: 16px;
  line-height: 1.4;
  max-height: 120px;
  min-height: 44px;
  outline: none;
  background: var(--ic-body-bg);
}
.chat__input:focus { border-color: var(--ic-primary); }
.chat__send {
  /* Цель нажатия >= 44×44 px. */
  width: 44px; height: 44px; border-radius: 50%; border: none;
  background: var(--ic-primary); color: #fff; cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0; transition: background 0.15s;
  touch-action: manipulation;
  -webkit-tap-highlight-color: transparent;
}
.chat__send:hover { background: var(--ic-primary-dark); }
.chat__send:disabled { background: #c9c9d6; cursor: not-allowed; }

.chat__footer {
  text-align: center;
  font-size: 10.5px;
  color: var(--ic-muted);
  background: var(--ic-bg);
  flex-shrink: 0;
  padding-top: 8px;
  /* ПРОБЛЕМА: на Android системный жест-«ползунок» снизу перекрывал этот текст.
     1) env(safe-area-inset-bottom) на Android Chrome ДИНАМИЧЕСКИЙ и почти всегда 0
        (привязан к «подбородку» Chrome 135+, который уезжает при скролле — ровно
        когда пилюля накрывает контент).
     2) Внутри iframe на Chromium env() ВООБЩЕ не пробрасывается (всегда 0, баг W3C #4670).
     РЕШЕНИЕ: гарантированный нижний отступ через max(): floor 28px поднимает текст
     над жест-зоной на ЛЮБОМ Android (даже когда env=0), а env() даёт точные ~34px
     под home indicator на iOS. Единицы у обоих аргументов обязательны (28px, 0px). */
  padding-bottom: max(28px, env(safe-area-inset-bottom, 0px));
}
/* Прогрессивное улучшение (Chrome 135+, верхнеуровневая страница /widget/):
   стабильный максимум инсета — не «схлопывается», когда нижняя панель Android уезжает. */
@supports (padding-bottom: env(safe-area-max-inset-bottom)) {
  .chat__footer { padding-bottom: max(28px, env(safe-area-max-inset-bottom, 36px)); }
}

/* Узкий ландшафт / низкий экран (телефон горизонтально): экономим высоту,
   прячем футер. Тогда нижним становится поле ввода — переносим инсет на него. */
@media (max-height: 600px) {
  .chat__header { padding-top: calc(8px + env(safe-area-inset-top, 0px)); padding-bottom: 8px; }
  .chat__body { padding: 10px 16px; }
  .chat__footer { display: none; }
  /* В ландшафте футер скрыт → нижним становится поле ввода: тот же надёжный
     floor через max(), чтобы кнопка/поле не уходили под жест-«ползунок». */
  .chat__form { padding-bottom: max(16px, env(safe-area-inset-bottom, 0px)); }
}

/* ===== Экран согласия при первом запуске (152-ФЗ) ===== */
.consent {
  position: absolute;
  inset: 0;
  z-index: 10;
  background: rgba(28, 28, 40, 0.55);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  /* safe-area, чтобы карточка не уезжала под вырез/жест-зону */
  padding-top: calc(16px + env(safe-area-inset-top, 0px));
  padding-bottom: max(24px, env(safe-area-inset-bottom, 0px));
  overflow-y: auto;
}
.consent[hidden] { display: none; }
.consent__card {
  background: #fff;
  border-radius: 16px;
  padding: 20px;
  max-width: 360px;
  width: 100%;
  max-height: 100%;
  overflow-y: auto;
  overscroll-behavior: contain;
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.3);
  animation: pop 0.2s ease-out;
}
.consent__title { font-size: 17px; font-weight: 700; color: var(--ic-text); margin-bottom: 10px; }
.consent__text { font-size: 13.5px; line-height: 1.5; color: #44485a; }
.consent__links { margin: 12px 0; padding-left: 18px; }
.consent__links li { margin: 6px 0; font-size: 13.5px; }
.consent__links a { color: var(--ic-primary); text-decoration: underline; }
.consent__check {
  display: flex; gap: 8px; align-items: flex-start;
  font-size: 12.5px; color: #44485a; margin: 14px 0 16px; cursor: pointer;
}
.consent__check input {
  width: 18px; height: 18px; margin-top: 1px; flex-shrink: 0; accent-color: var(--ic-primary);
}
.consent__accept {
  width: 100%; min-height: 48px; padding: 13px; border: none; border-radius: 12px;
  background: var(--ic-primary); color: #fff; font-size: 15px; font-weight: 600;
  cursor: pointer; touch-action: manipulation; -webkit-tap-highlight-color: transparent;
}
.consent__accept:hover { background: var(--ic-primary-dark); }
.consent__decline {
  width: 100%; padding: 10px; margin-top: 4px; border: none; background: none;
  color: var(--ic-muted); font-size: 13px; cursor: pointer;
  touch-action: manipulation; -webkit-tap-highlight-color: transparent;
}
.consent__legal {
  font-size: 11px; color: var(--ic-muted); margin-top: 12px; line-height: 1.4; text-align: center;
}
