/**
 * ZarboWidget — стили.
 *
 * Полностью самодостаточный CSS без внешних зависимостей во время выполнения
 * (в отличие от demo/widget/widget.js, который на рантайме подключал
 * Tailwind CDN через `ensureTailwind()`). Решение по нюансу из P1-049:
 * рантайм-зависимость от стороннего CDN на боевом сайте заказчика — риск
 * доступности/производительности (сайт мог зависеть от CDN, который недоступен
 * или медленно отвечает, блокируя виджет). Все нужные утилитарные стили
 * перенесены сюда как обычные CSS-классы с префиксом `zt-`.
 *
 * Все селекторы либо скоуплены под #zt-widget-root, либо начинаются с zt- —
 * не должны конфликтовать с версткой хост-сайта (см. критерий готовности
 * P1-049).
 */

#zt-widget-root {
  /* Тема по умолчанию — переопределяется из конфига тенанта (P1-031,
   * "минимально — тема/тексты"), см. applyTheme() в widget.js. Значения
   * здесь — нейтральные дефолты платформы, а не бренд конкретного
   * заказчика (в отличие от захардкоженного #E30613 в demo/widget). */
  --zt-primary: #2563eb;
  --zt-primary-dark: #1d4ed8;
  --zt-primary-soft: #eff6ff;
  --zt-header-bg: #111827;
  --zt-accent: #22c55e;
  /* Множитель всех border-radius ниже (кроме индикаторов — точка "онлайн"
   * и точки анимации загрузки, у них своя UI-конвенция, не панель/кнопка,
   * остаются круглыми независимо от этой переменной). 1 — дефолт (текущий
   * скруглённый вид), 0 — квадратные углы (например, Archpole — см.
   * backend/apps/tenants/management/commands/seed_archpole.py,
   * widget_config.theme.radiusScale). Настраивается per-tenant так же, как
   * цвета — через applyTenantConfig() в widget.js. */
  --zt-radius-scale: 1;
  /* Отступ плавающей строки ввода от низа экрана (theme.bottomOffset) —
   * например, чтобы приподнять виджет над собственным нижним меню сайта
   * заказчика. Окно чата считает свой отступ от этой же переменной
   * (см. .zt-chat-win), чтобы взаимное расстояние между ними не менялось. */
  --zt-bar-bottom: 24px;
}

#zt-widget-root,
#zt-widget-root * {
  box-sizing: border-box;
  /* --zt-font-family (theme.fontFamily) — по умолчанию не задана, значит
   * используется этот же дефолтный стек через var()-fallback. */
  font-family: var(--zt-font-family, Inter, Manrope, system-ui, -apple-system, sans-serif);
}

#zt-widget-root a {
  color: inherit;
}

/* Ссылки внутри сообщений (markdown-ссылки в ответах ассистента, напр. на
 * статью блога) — глобальный сброс выше делает их `color: inherit` без
 * подчёркивания, из-за чего они сливаются с текстом и не читаются как
 * ссылка. Возвращаем им заметность: цвет темы + подчёркивание. Специфичность
 * `#zt-widget-root .zt-bubble a` (1,2,1) выше сброса `#zt-widget-root a`
 * (1,0,1), поэтому побеждает. */
#zt-widget-root .zt-bubble a {
  color: var(--zt-primary);
  text-decoration: underline;
  text-underline-offset: 2px;
  font-weight: 600;
}

#zt-widget-root .zt-bubble a:hover {
  text-decoration: none;
}

/* ── Input bar (плавающая строка ввода) ─────────────────────────────────── */

.zt-bar {
  position: fixed;
  bottom: var(--zt-bar-bottom);
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  z-index: 2147483647;
  padding: 0 16px;
}

.zt-bar-inner {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #fff;
  width: 100%;
  max-width: 576px;
  border-radius: calc(16px * var(--zt-radius-scale));
  padding: 8px;
  /* --zt-border-color (theme.borderColor) — не задан => прозрачная (нет
   * видимой границы, как раньше, только тень ниже). box-sizing: border-box
   * на #zt-widget-root означает, что толщина границы не меняет внешний
   * размер блока даже когда граница прозрачна. */
  border: 1px solid var(--zt-border-color, transparent);
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.06);
}

.zt-icon-btn {
  width: 36px;
  height: 36px;
  border-radius: calc(12px * var(--zt-radius-scale));
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  cursor: pointer;
  background: #fff;
  border: 2px solid var(--zt-primary);
  color: var(--zt-primary);
  padding: 0;
}

.zt-icon-btn[disabled],
.zt-icon-btn.zt-icon-btn--disabled {
  cursor: not-allowed;
  opacity: 0.4;
  border-color: #9ca3af;
  color: #9ca3af;
}

/* Специфичность `#zt-widget-root` + `!important` на сбросе — защита от
 * протечки глобального CSS хост-сайта в наш `<input>`. Виджет встраивается
 * на произвольные чужие сайты, у которых сплошь и рядом есть глобальные
 * стили `input { border-bottom / box-shadow / border-radius / appearance }`
 * — они перебивали обычный `.zt-input` (класс без `!important`), из-за чего
 * на сайте появлялась лишняя линия/рамка под полем ввода, которой нет в
 * изолированном превью личного кабинета (баг, найденный на archpole.ru). */
#zt-widget-root .zt-input {
  flex: 1;
  min-width: 0;
  font-size: 14px;
  color: #374151;
  padding: 0 8px;
  outline: none !important;
  border: none !important;
  border-radius: 0 !important;
  background: transparent !important;
  box-shadow: none !important;
  -webkit-appearance: none !important;
  appearance: none !important;
}

.zt-input::placeholder {
  color: #9ca3af;
}

.zt-input:disabled {
  opacity: 0.5;
}

.zt-send-btn {
  width: 36px;
  height: 36px;
  border-radius: calc(12px * var(--zt-radius-scale));
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  color: #fff;
  /* --zt-send-btn-color — отдельный, необязательный цвет кнопки отправки
   * (theme.sendButtonColor, см. applyTenantConfig() в widget.js). Не задан —
   * падает обратно на --zt-primary, как было раньше. */
  background: var(--zt-send-btn-color, var(--zt-primary));
  border: none;
  cursor: pointer;
  padding: 0;
  transition: opacity 0.15s;
}

.zt-send-btn:hover:not(:disabled) {
  opacity: 0.85;
}

.zt-send-btn:disabled {
  opacity: 0.35;
  cursor: not-allowed;
}

/* theme.invertSendButtonOnHover (дефолт — выключено, обычное затухание
 * прозрачности выше) — widget.js добавляет класс zt-invert-send-hover на
 * #zt-widget-root, если тенант это включил. Специфичность этого селектора
 * выше обычного :hover-правила выше, поэтому побеждает при наличии класса. */
#zt-widget-root.zt-invert-send-hover .zt-send-btn:hover:not(:disabled) {
  opacity: 1;
  background: #fff;
  color: var(--zt-send-btn-color, var(--zt-primary));
}

/* ── Chat window ──────────────────────────────────────────────────────── */

.zt-chat-win {
  position: fixed;
  /* Тот же относительный зазор (68px) над .zt-bar, что и в дефолте
   * (24px + 68px = 92px), но теперь считается от настраиваемого
   * --zt-bar-bottom, а не захардкожен. */
  bottom: calc(var(--zt-bar-bottom) + 68px);
  left: 50%;
  width: calc(100% - 32px);
  max-width: 576px;
  height: 500px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: calc(16px * var(--zt-radius-scale));
  background: #fff;
  border: 1px solid var(--zt-border-color, transparent);
  box-shadow: 0 24px 64px rgba(0, 0, 0, 0.16), 0 4px 16px rgba(0, 0, 0, 0.08);
  z-index: 2147483646;
  opacity: 0;
  transform: translateX(-50%) translateY(16px) scale(0.97);
  pointer-events: none;
  transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1), transform 0.25s cubic-bezier(0.16, 1, 0.3, 1);
}

.zt-chat-win--open {
  opacity: 1;
  transform: translateX(-50%) translateY(0) scale(1);
  pointer-events: all;
}

@media (max-width: 600px) {
  .zt-chat-win {
    /* Тот же принцип, что в десктопной версии выше — относительный зазор
     * (60px) над .zt-bar сохранён (24px + 60px = 84px в дефолте). */
    bottom: calc(var(--zt-bar-bottom) + 60px);
    height: 70vh;
  }
}

/* ── Header ───────────────────────────────────────────────────────────── */

.zt-header {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
  padding: 12px 16px;
  background: var(--zt-header-bg);
}

.zt-avatar {
  width: 36px;
  height: 36px;
  border-radius: calc(999px * var(--zt-radius-scale));
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background: rgba(255, 255, 255, 0.08);
  border: 2px solid var(--zt-primary);
  color: var(--zt-primary);
}

.zt-avatar--msg {
  background: #fff;
  grid-column: 1;
  grid-row: 2; /* тот же ряд, что у .zt-bubble — выравнивание по верху с пузырём, а не с meta */
  align-self: start;
}

/* Аватар-картинка/GIF заказчика (theme.avatarUrl) — рендерится вместо
 * SVG-иконки внутри .zt-avatar/.zt-avatar--msg/.zt-icon-btn, когда задан
 * (см. renderAvatarInto() в widget.js). Заполняет контейнер, наследует его
 * border-radius — размеры/рамка/фон берутся от родителя, не дублируются
 * здесь. GIF работает как обычный <img>, доп. логики не требуется. */
.zt-avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: inherit;
  display: block;
}

/* theme.avatarRound — круглый аватар независимо от общего radiusScale
 * (тенант может быть "квадратным" во всём, но хотеть круглую аватарку).
 * widget.js вешает класс zt-avatar-round на #zt-widget-root. Картинка
 * (.zt-avatar-img) наследует border-radius, поэтому тоже станет круглой.
 * `.zt-icon-btn` — аватар на плавающей строке ввода (свой класс, не
 * .zt-avatar), его тоже нужно скруглить. */
#zt-widget-root.zt-avatar-round .zt-avatar,
#zt-widget-root.zt-avatar-round .zt-icon-btn {
  border-radius: 999px;
}

/* Пока чат раскрыт (класс zt-chat-open на #zt-widget-root, см. openChat/
 * closeChat в widget.js) — аватар оставляем только в шапке. Аватар у
 * каждого сообщения и аватар на плавающей строке ввода прячем, чтобы не
 * дублировать (по просьбе — оставить только верхнюю аватарку). */
#zt-widget-root.zt-chat-open .zt-avatar--msg {
  display: none;
}
/* Ряд сообщения ассистента — grid `36px 1fr` (аватар | контент). Спрятать
 * аватар мало: пустая 36px-колонка сдвинула бы текст — схлопываем её в 0 и
 * убираем column-gap, чтобы контент занял всю ширину ряда. */
#zt-widget-root.zt-chat-open .zt-row--assistant {
  grid-template-columns: 0 1fr;
  column-gap: 0;
}
#zt-widget-root.zt-chat-open .zt-bar .zt-icon-btn {
  display: none;
}
/* Quick-кнопки выровнены под текст сообщения через margin-left: 48px (аватар
 * 36px + gap 12px). Когда аватар сообщения скрыт и текст сдвинулся влево,
 * отступ кнопок нужно тоже обнулить — иначе кнопки висят правее текста. */
#zt-widget-root.zt-chat-open .zt-quick-replies {
  margin-left: 0;
}

.zt-title-block {
  flex: 1;
  min-width: 0;
}

.zt-title {
  font-size: 14px;
  font-weight: 700;
  color: #fff;
  line-height: 1.3;
}

/* theme.uppercaseText (дефолт — выключено) — widget.js добавляет класс
 * zt-uppercase на #zt-widget-root, если тенант это включил. UPPERCASE —
 * только на брендовых элементах: заголовок чата и ПЛЕЙСХОЛДЕР поля ввода.
 * Сам вводимый пользователем текст (`.zt-input`, не `::placeholder`) НЕ
 * трансформируем — иначе клиент печатает сообщение и видит его капсом, что
 * выглядит как баг (text-transform не меняет отправляемое значение, только
 * визуал при наборе, но пользователя это путает). */
#zt-widget-root.zt-uppercase .zt-title,
#zt-widget-root.zt-uppercase .zt-input::placeholder {
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.zt-status {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 2px;
}

.zt-status-dot {
  width: 6px;
  height: 6px;
  border-radius: 999px;
  flex-shrink: 0;
  background: var(--zt-accent);
  box-shadow: 0 0 0 2px rgba(34, 197, 94, 0.3);
}

.zt-status-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.zt-header-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
}

.zt-consultant-btn {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(255, 255, 255, 0.25);
  border-radius: calc(999px * var(--zt-radius-scale));
  padding: 4px 10px;
  background: transparent;
  cursor: pointer;
  transition: background 0.15s;
}

.zt-consultant-btn:hover {
  background: rgba(255, 255, 255, 0.15);
}

.zt-close-btn {
  width: 28px;
  height: 28px;
  border-radius: calc(999px * var(--zt-radius-scale));
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background: rgba(255, 255, 255, 0.12);
  border: none;
  cursor: pointer;
  margin-left: 4px;
  padding: 0;
  transition: background 0.15s;
}

.zt-close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* ── Messages ─────────────────────────────────────────────────────────── */

.zt-msgs {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background: #f2f2f2;
  scroll-behavior: smooth;
}

.zt-msgs::-webkit-scrollbar {
  width: 4px;
}

.zt-msgs::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: calc(4px * var(--zt-radius-scale));
}

.zt-msgs::-webkit-scrollbar-track {
  background: transparent;
}

.zt-row {
  display: flex;
  gap: 12px;
  width: 100%;
}

.zt-row--user {
  flex-direction: row-reverse;
}

.zt-row--assistant {
  display: grid;
  grid-template-columns: 36px 1fr;
  gap: 4px 12px; /* row-gap 4px (как было между meta/bubble/products), column-gap 12px (как было между аватаркой и контентом) */
  justify-items: start; /* без этого grid-item'ы растягивались бы на всю колонку — раньше flex давал shrink-to-fit по контенту */
}

.zt-msg-body {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-width: 78%;
}

.zt-row--user .zt-msg-body {
  align-items: flex-end;
}

.zt-row--assistant .zt-msg-body {
  display: contents; /* meta/bubble/products становятся прямыми grid-item'ами .zt-row--assistant, а не вложенным flex-блоком — иначе grid не может развести их по разным рядам независимо от аватарки */
}

.zt-msg-meta {
  display: flex;
  align-items: baseline;
  gap: 8px;
  padding: 0 4px;
  grid-column: 2;
  grid-row: 1;
}

.zt-msg-author {
  font-size: 12px;
  font-weight: 600;
  color: #4b5563;
}

.zt-msg-time {
  font-size: 12px;
  color: #9ca3af;
}

.zt-bubble {
  font-size: 14px;
  line-height: 1.6;
  padding: 10px 16px;
  border-radius: calc(16px * var(--zt-radius-scale));
}

.zt-row--assistant .zt-bubble {
  grid-column: 2;
  grid-row: 2;
  max-width: 78%;
}

.zt-bubble--user {
  color: #fff;
  /* Раньше был захардкожен #1a1a1a, никак не привязан к теме — баг:
   * тенант с чёрным primaryColor (например, Archpole) не мог повлиять на
   * цвет своего же пузыря пользователя. Теперь тема управляет им, как и
   * остальными акцентными элементами. */
  background: var(--zt-primary);
  border: 1px solid var(--zt-border-color, transparent);
  border-top-right-radius: calc(4px * var(--zt-radius-scale));
}

.zt-bubble--assistant {
  color: #111827;
  background: #fff;
  /* Не задан --zt-border-color => прежний едва заметный серый бордер,
   * задан => используется он (например, чёрный у Archpole). */
  border: 1px solid var(--zt-border-color, #f3f4f6);
  border-top-left-radius: calc(4px * var(--zt-radius-scale));
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}

.zt-bubble--error {
  color: #dc2626;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-top-left-radius: calc(4px * var(--zt-radius-scale));
}

/* ── Loading dots ─────────────────────────────────────────────────────── */

.zt-loading-bubble {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 12px 16px;
}

@keyframes zt-bounce {
  0%,
  60%,
  100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-5px);
    opacity: 1;
  }
}

.zt-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #9ca3af;
  animation: zt-bounce 1.2s infinite ease-in-out;
}

.zt-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.zt-dot:nth-child(3) {
  animation-delay: 0.4s;
}

/* ── Quick replies ────────────────────────────────────────────────────── */

.zt-quick-replies {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 0 4px 4px;
  /* Тот же отступ, что у текста сообщения ассистента (аватар 36px + gap
   * 12px в .zt-row) — иначе кнопки визуально прижаты левее текста, на
   * который отвечают (см. скриншот с багом — стрелка на отсутствие отступа). */
  margin-left: 48px;
}

.zt-qr-btn {
  font-size: 12px;
  text-align: left;
  border: 1px solid var(--zt-primary);
  color: var(--zt-primary);
  background: #fff;
  border-radius: calc(999px * var(--zt-radius-scale));
  padding: 6px 12px;
  cursor: pointer;
  transition: background 0.15s;
}

.zt-qr-btn:hover {
  background: var(--zt-primary-soft);
}

/* ── Unavailable state (403 на инициализации, P1-052) ────────────────────
 * Виджет намеренно не строит обычное окно чата/строку ввода в "наполовину
 * рабочем" виде при недоступности — см. widget.js. Этот класс зарезервирован
 * на случай, если потребуется малозаметный статичный индикатор вместо
 * полного отсутствия DOM (сейчас не используется, см. widget.js). */
.zt-unavailable {
  display: none;
}

/* ── Backend response HTML styles (карточки товаров, сравнение, FAQ) ─────
 * Разметка приходит от бэкенда в html_content и вставляется через
 * DOMPurify — эти классы описывают её внешний вид. */

.zt-response-text {
  font-size: 14px;
  line-height: 1.6;
  color: #1a1a1a;
}

.zt-products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 10px;
  margin-top: 6px;
}

.zt-row--assistant .zt-products-grid {
  grid-column: 2;
  grid-row: 3;
  max-width: 78%;
}

.zt-product-specs {
  display: flex;
  flex-direction: column;
  gap: 3px;
  font-size: 12px;
  color: #7a7a7a;
}

.zt-product-specs b {
  color: #1a1a1a;
}

.zt-product-spec {
  line-height: 1.4;
}

.zt-product-card {
  display: flex;
  flex-direction: column;
  gap: 6px;
  border: 1px solid #e0e0e0;
  border-radius: calc(14px * var(--zt-radius-scale));
  padding: 10px;
  background: #fff;
  transition: box-shadow 0.15s;
}

.zt-product-card:hover {
  box-shadow: 0 4px 14px rgba(37, 99, 235, 0.1);
}

.zt-product-img {
  width: 100%;
  height: 120px;
  border-radius: calc(6px * var(--zt-radius-scale));
  object-fit: contain;
  display: block;
  background: #f2f2f2;
}

.zt-product-name {
  font-size: 13px;
  font-weight: 600;
  color: #1a1a1a;
  line-height: 1.4;
}

.zt-product-price {
  font-size: 14px;
  font-weight: 700;
  color: var(--zt-primary);
}

/* Специфичность `#zt-widget-root` в селекторе ниже — не стилистический
 * выбор, а необходимость: обычный `.zt-product-link { color: #fff; }`
 * проигрывает по специфичности глобальному сбросу `#zt-widget-root a { color:
 * inherit; }` (ID-селектор бьёт класс независимо от порядка объявления в
 * файле) — из-за этого текст кнопки наследовал тёмный цвет карточки и был
 * невидим на тёмном фоне кнопки (баг, найденный на теме Archpole с чёрным
 * primaryColor — чёрный текст на чёрной кнопке). */
#zt-widget-root .zt-product-link {
  display: inline-block;
  font-size: 12px;
  font-weight: 500;
  color: #fff;
  background: var(--zt-primary);
  border-radius: calc(999px * var(--zt-radius-scale));
  padding: 5px 12px;
  text-decoration: none;
  text-align: center;
  margin-top: auto;
  transition: background 0.15s;
}

#zt-widget-root .zt-product-link:hover {
  background: var(--zt-primary-dark);
  color: #fff;
  text-decoration: none;
}

.zt-compare-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12.5px;
  margin-top: 4px;
}

.zt-compare-table th,
.zt-compare-table td {
  padding: 7px 10px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.zt-compare-table th {
  background: var(--zt-primary-soft);
  font-weight: 600;
  color: var(--zt-primary);
}

.zt-compare-table tr:nth-child(even) td {
  background: #f2f2f2;
}

.zt-compare-table tr:last-child td {
  border-bottom: none;
}

.zt-faq-block {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.zt-faq-question {
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
}

.zt-faq-answer {
  font-size: 13.5px;
  color: #7a7a7a;
  line-height: 1.6;
}
