/* OWNS: .xf-aichat(__*) — панель веб-чата «ИИ-помощник X-Core» (issue #9).
   DOM строит js/aichat.js (footer.php не трогаем), сюда только стили. Токены —
   из tokens.css (тема наследуется автоматом: light по умолчанию, [data-theme=dark]).
   Бот — первая линия (#68), но поверхность панели держим нейтральной (Restrained):
   индиго только там, куда должен смотреть глаз — пузырь клиента, primary CTA,
   фокус (One-Voice ≤10%). Рифмуется с .xf-chat: тот же угол, те же радиусы/тени,
   тот же дух анимации входа. */

/* ─── Корневой док (fixed, правый нижний угол, поверх кружка) ──────────── */
.xf-aichat {
  position: fixed;
  right: 24px;
  bottom: 24px;
  z-index: 1200; /* выше FAB (100) и окна B24; ниже toast/consent-бара (9999) */
  width: 384px;
  max-width: calc(100vw - 32px);
  /* высота = min(желаемая, доступная над кружком/баром) — панель не вылезает
     за верх вьюпорта на низких экранах, внутренняя лента скроллится сама. */
  height: 560px;
  max-height: calc(100vh - 48px);
  display: none;
  /* bottom анимируется для подъёма над consent-баром (зеркалит .xf-chat). */
  transition: bottom .3s ease;
}
.xf-aichat.is-open { display: block; }

/* Подъём над consent-баром — переиспользуем runtime-переменную из app.js
   (initBotCookieClearance), тот же контракт, что у FAB и toast'ов. */
body.xf-cookie-up .xf-aichat { bottom: calc(var(--xf-cookie-h, 72px) + 24px); }

/* На конфигураторе весь чат-док скрыт (chat.css) — прячем и панель заодно. */
body.page-configurator .xf-aichat { display: none !important; }

/* ─── Карточка панели ─────────────────────────────────────────────────── */
.xf-aichat__panel {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 18px;
  box-shadow: var(--shadow-card), 0 2px 8px -4px oklch(0.2 0.03 285 / 0.25);
  transform-origin: bottom right;
}

/* Появление — тем же духом, что xf-chat-in: fade + подъём + лёгкий scale. */
.xf-aichat.is-open .xf-aichat__panel { animation: xf-aichat-in .24s cubic-bezier(0.22, 1, 0.36, 1); }
.xf-aichat.is-closing .xf-aichat__panel { animation: xf-aichat-out .16s ease forwards; }

@keyframes xf-aichat-in {
  from { opacity: 0; transform: translateY(14px) scale(.97); }
  to   { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes xf-aichat-out {
  from { opacity: 1; transform: translateY(0) scale(1); }
  to   { opacity: 0; transform: translateY(10px) scale(.98); }
}

/* ─── Шапка ───────────────────────────────────────────────────────────── */
.xf-aichat__header {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 12px 12px 16px;
  border-bottom: 1px solid var(--line-soft);
  background: var(--surface);
}
.xf-aichat__avatar {
  flex: 0 0 auto;
  width: 40px;
  height: 40px;
  border-radius: 12px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  /* мягкая accent-подложка, НЕ solid: бот остаётся нейтрально-статусным,
     но аватар даёт узнаваемый «искристый» акцент (sparkle из icons.php). */
  background: var(--accent-dim);
  color: var(--accent-2);
}
.xf-aichat__ident { display: flex; flex-direction: column; min-width: 0; margin-right: auto; line-height: 1.25; }
/* nowrap: имя — первое, что видит клиент; перенос «X-Core» на вторую строку
   ломал шапку (P1 критики). Telegram-мост ужат до иконки, места хватает. */
.xf-aichat__name {
  font-size: 15px;
  font-weight: 600;
  letter-spacing: -0.2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.xf-aichat__status {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--text-2);
  margin-top: 1px;
}
.xf-aichat__status::before {
  content: "";
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--success);
  box-shadow: 0 0 0 3px oklch(0.65 0.17 155 / 0.16);
}
/* Сбой API: шапка не спорит с карточкой «недоступен» (P1) — точка гаснет. */
.xf-aichat__status.is-off::before {
  background: var(--text-3);
  box-shadow: none;
}

.xf-aichat__act {
  flex: 0 0 auto;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  padding: 0;
  border: none;
  border-radius: 10px;
  background: none;
  color: var(--text-2);
  font: inherit;
  text-decoration: none;
  cursor: pointer;
  transition: background-color .15s ease, color .15s ease;
}
@media (hover: hover) {
  .xf-aichat__act:hover { background: var(--surface-2); color: var(--text); }
}
.xf-aichat__act:active { background: var(--surface-3); }
.xf-aichat__act:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
/* Telegram-мост в шапке — иконка с aria-label/title на всех ширинах: текстовая
   подпись отжимала место у имени бота (P1). Не accent: alt-канал, не CTA. */
.xf-aichat__tg { color: var(--text-2); }

/* ─── Тело / лента ────────────────────────────────────────────────────── */
.xf-aichat__body {
  flex: 1 1 auto;
  min-height: 0;
  overflow-y: auto;
  overscroll-behavior: contain;
  padding: 16px 16px 8px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  scroll-behavior: smooth;
  /* Плоская поверхность: radial-градиент в фоне ленты нарушал бы
     Ambient-Is-Mood-Not-Structure (градиенты — только на body::before). */
  background: var(--bg);
}
@media (prefers-reduced-motion: reduce) { .xf-aichat__body { scroll-behavior: auto; } }

/* Тонкая приписка при первом открытии. */
.xf-aichat__note {
  font-size: 11.5px;
  line-height: 1.5;
  color: var(--text-3);
  text-align: center;
  padding: 2px 10px 6px;
  margin: 0 auto;
  max-width: 32ch;
}

/* Строка сообщения — задаёт сторону и максимум ширины пузыря. */
/* min-width:0 обязателен (issue #167): дефолтный min-width:auto флекс-элемента
   не даёт ряду ужаться ниже неразрывной строки (nowrap-ссылка) — пузырь
   распирало шире панели. */
.xf-aichat__row { display: flex; flex-direction: column; max-width: 86%; min-width: 0; }
.xf-aichat__row--bot  { align-self: flex-start; align-items: flex-start; }
.xf-aichat__row--user { align-self: flex-end;   align-items: flex-end; }

.xf-aichat__bubble {
  padding: 9px 13px;
  border-radius: 14px;
  font-size: 14px;
  line-height: 1.5;
  /* reply — plain text с \n: сохраняем переносы/структуру каталога как есть. */
  white-space: pre-wrap;
  overflow-wrap: anywhere;
  word-break: break-word;
  /* Пара к min-width:0 у ряда: пузырь не шире ряда даже с nowrap-контентом. */
  max-width: 100%;
  min-width: 0;
}
/* Ссылка в ответе бота (issue #167): длинные URL каталога не ломаем по буквам —
   одна строка с многоточием; ellipsis требует block-контейнера, поэтому
   inline-block + max-width. Клик открывает вкладку, long-press копирует. */
.xf-aichat__link {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: bottom;
  color: var(--accent);
  text-decoration: underline;
  text-underline-offset: 2px;
}
.xf-aichat__link:hover { text-decoration: none; }
/* Бот — «бумага на верстаке»: карточка светлее фона ленты (Card-On-Cream). */
.xf-aichat__row--bot .xf-aichat__bubble {
  background: var(--surface);
  color: var(--text);
  border: 1px solid var(--line-soft);
  border-bottom-left-radius: 5px;
}
/* Клиент — единственный accent-элемент ленты (свои реплики, как в мессенджерах).
   Без тени: flat-by-default, тень в панели только у самой панели и toast'а. */
.xf-aichat__row--user .xf-aichat__bubble {
  background: var(--accent);
  color: #fff;
  border-bottom-right-radius: 5px;
}
/* В dark --accent осветлён под роль ПЕРЕДНЕГО плана (текст/фокус) — как
   заливка под белым текстом он давал 3.2:1 (P2 критики). Берём глубокий тон. */
html[data-theme="dark"] .xf-aichat__row--user .xf-aichat__bubble {
  background: var(--accent-3);
}
.xf-aichat__row + .xf-aichat__row { margin-top: 0; }
/* Плотнее группируем подряд идущие реплики одного автора. */
.xf-aichat__row--bot + .xf-aichat__row--bot,
.xf-aichat__row--user + .xf-aichat__row--user { margin-top: -4px; }

/* Индикатор набора — три точки в пузыре-боте. */
.xf-aichat__typing {
  align-self: flex-start;
  display: inline-flex;
  gap: 4px;
  padding: 12px 14px;
  background: var(--surface-2);
  border: 1px solid var(--line-soft);
  border-radius: 14px;
  border-bottom-left-radius: 5px;
}
.xf-aichat__typing span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--text-3);
  animation: xf-aichat-blink 1.2s infinite ease-in-out;
}
.xf-aichat__typing span:nth-child(2) { animation-delay: .18s; }
.xf-aichat__typing span:nth-child(3) { animation-delay: .36s; }
@keyframes xf-aichat-blink {
  0%, 60%, 100% { opacity: .3; transform: translateY(0); }
  30%           { opacity: 1;  transform: translateY(-3px); }
}

/* ─── Быстрые ответы (чипсы) ──────────────────────────────────────────── */
.xf-aichat__chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-self: flex-start;
  max-width: 100%;
  margin-top: 2px;
}
/* Чипсы — ДЕЙСТВИЯ, поэтому не pill (Pill-Is-Not-Button): радиус кнопочный,
   как у .xf-aichat__btn, accent-текст говорит «это продолжение диалога». */
.xf-aichat__chip {
  display: inline-flex;
  align-items: center;
  max-width: 100%;
  padding: 8px 13px;
  border-radius: 10px;
  border: 1px solid var(--accent-line);
  background: var(--surface);
  color: var(--accent-2);
  font-family: var(--font-sans);
  font-size: 13px;
  font-weight: 500;
  line-height: 1.2;
  text-align: left;
  cursor: pointer;
  transition: background-color .15s ease, border-color .15s ease, transform .1s ease;
}
@media (hover: hover) {
  .xf-aichat__chip:hover { background: var(--accent-dim); border-color: var(--accent); }
}
.xf-aichat__chip:active { transform: scale(.97); }
.xf-aichat__chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.xf-aichat__chip[disabled] { opacity: .5; cursor: default; }

/* ─── Резюме заявки: подтверждение (final_summary) ────────────────────── */
.xf-aichat__confirm {
  align-self: stretch;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 2px;
}
.xf-aichat__btn {
  flex: 1 1 auto;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  min-height: 40px;
  padding: 10px 14px;
  border-radius: 11px;
  font-family: var(--font-sans);
  font-size: 13.5px;
  font-weight: 600;
  cursor: pointer;
  /* Кнопкой бывает и <a> (мост в Telegram из карточки сбоя) — без подчёркивания. */
  text-decoration: none;
  transition: transform .12s ease, box-shadow .15s ease, background-color .15s ease, border-color .15s ease;
}
.xf-aichat__btn--primary {
  background: var(--accent);
  color: #fff;
  border: 1px solid transparent;
  box-shadow: 0 6px 18px -8px var(--accent);
}
@media (hover: hover) { .xf-aichat__btn--primary:hover { transform: translateY(-1px); } }
.xf-aichat__btn--ghost {
  background: var(--surface);
  color: var(--text);
  border: 1px solid var(--line);
  flex: 0 1 auto;
}
@media (hover: hover) { .xf-aichat__btn--ghost:hover { background: var(--surface-2); } }
.xf-aichat__btn:active { transform: scale(.98); }
.xf-aichat__btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.xf-aichat__btn[disabled] { opacity: .55; cursor: default; transform: none; }

/* ─── Системная плашка (сессия устарела / заявка отправлена) ───────────── */
.xf-aichat__system {
  align-self: center;
  max-width: 90%;
  text-align: center;
  font-size: 12px;
  color: var(--text-3);
  padding: 4px 12px;
}

/* ─── Оценка помощника после заявки (issue #81 бот-репо) ──────────────────
   В духе чипсов/кнопок: нейтральная поверхность (оценка — не CTA), accent
   приходит только на hover/focus. Тёмная тема — через те же токены. */
.xf-aichat__rate {
  align-self: stretch;
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 2px;
  padding: 12px;
  border: 1px solid var(--line-soft);
  border-radius: 12px;
  background: var(--surface);
}
.xf-aichat__rate-prompt {
  font-size: 13px;
  color: var(--text-2);
  text-align: center;
}
.xf-aichat__rate-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}
/* 👍/👎 — крупная тап-цель, нейтральная рамка; accent только на hover/focus. */
.xf-aichat__rate-btn {
  flex: 0 0 auto;
  min-width: 56px;
  min-height: 40px;
  padding: 8px 16px;
  border-radius: 10px;
  border: 1px solid var(--line);
  background: var(--surface-2);
  font-size: 20px;
  line-height: 1;
  cursor: pointer;
  transition: background-color .15s ease, border-color .15s ease, transform .1s ease;
}
@media (hover: hover) {
  .xf-aichat__rate-btn:hover { background: var(--accent-dim); border-color: var(--accent); }
}
.xf-aichat__rate-btn:active { transform: scale(.94); }
.xf-aichat__rate-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
/* Поле причины (👎-путь) — как композер, но компактнее и внутри блока. */
.xf-aichat__rate-input {
  width: 100%;
  resize: none;
  padding: 9px 12px;
  border-radius: 10px;
  border: 1px solid var(--line);
  background: var(--surface-2);
  color: var(--text);
  font-family: var(--font-sans);
  font-size: 14px;
  line-height: 1.45;
  transition: border-color .15s ease, box-shadow .15s ease;
}
.xf-aichat__rate-input::placeholder { color: var(--text-3); }
.xf-aichat__rate-input:focus {
  outline: none;
  border-color: var(--accent);
  box-shadow: 0 0 0 3px var(--accent-dim);
}

/* ─── Карточка ошибки (unavailable на старте) ─────────────────────────── */
.xf-aichat__fault {
  margin: auto 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 12px;
  padding: 24px 20px;
}
.xf-aichat__fault-icon {
  width: 46px;
  height: 46px;
  border-radius: 13px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: var(--surface-2);
  color: var(--text-3);
}
.xf-aichat__fault-title { font-size: 15px; font-weight: 600; }
.xf-aichat__fault-text { font-size: 13px; line-height: 1.5; color: var(--text-2); max-width: 30ch; }
.xf-aichat__fault .xf-aichat__btn { flex: 0 0 auto; padding: 10px 18px; }

/* ─── Композер (ввод) ─────────────────────────────────────────────────── */
.xf-aichat__composer {
  flex: 0 0 auto;
  display: flex;
  align-items: flex-end;
  gap: 8px;
  padding: 10px 12px calc(10px + env(safe-area-inset-bottom, 0px));
  border-top: 1px solid var(--line-soft);
  background: var(--surface);
}
.xf-aichat__field {
  flex: 1 1 auto;
  min-width: 0;
  resize: none;
  max-height: 112px; /* ~4 строки; авто-рост считает js/aichat.js */
  padding: 10px 14px;
  border-radius: 12px;
  border: 1px solid var(--line);
  background: var(--surface-2);
  color: var(--text);
  font-family: var(--font-sans);
  font-size: 14px;
  line-height: 1.45;
  transition: border-color .15s ease, box-shadow .15s ease, background-color .15s ease;
}
.xf-aichat__field::placeholder { color: var(--text-3); }
.xf-aichat__field:focus {
  outline: none;
  border-color: var(--accent);
  background: var(--surface);
  box-shadow: 0 0 0 3px var(--accent-dim);
}
.xf-aichat__field:disabled { opacity: .6; cursor: not-allowed; }

.xf-aichat__send {
  flex: 0 0 auto;
  width: 40px;
  height: 40px;
  padding: 0;
  border: none;
  border-radius: 12px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: var(--accent);
  color: #fff;
  cursor: pointer;
  box-shadow: 0 6px 18px -10px var(--accent);
  transition: transform .12s ease, background-color .15s ease, opacity .15s ease;
}
@media (hover: hover) { .xf-aichat__send:hover { transform: translateY(-1px); } }
.xf-aichat__send:active { transform: scale(.94); }
.xf-aichat__send:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.xf-aichat__send:disabled {
  background: var(--surface-3);
  color: var(--text-3);
  box-shadow: none;
  cursor: default;
  transform: none;
}
/* Иконка «отправить» → спиннер, пока ждём ответ. */
.xf-aichat__send.is-busy .xf-aichat__send-arrow { display: none; }
.xf-aichat__send:not(.is-busy) .xf-aichat__send-spin { display: none; }
.xf-aichat__send-spin {
  width: 17px;
  height: 17px;
  border: 2px solid oklch(1 0 0 / 0.35);
  border-top-color: #fff;
  border-radius: 50%;
  animation: xf-aichat-spin .6s linear infinite;
}

/* ─── Локальный toast (rate_limited) — свой, showToast из app.js в IIFE ── */
.xf-aichat__toast {
  position: absolute;
  left: 16px;
  right: 16px;
  bottom: 74px;
  z-index: 2;
  padding: 10px 14px;
  border-radius: 12px;
  background: var(--surface);
  border: 1px solid var(--line);
  box-shadow: var(--shadow-card);
  font-size: 13px;
  font-weight: 500;
  color: var(--text);
  text-align: center;
  opacity: 0;
  transform: translateY(8px);
  pointer-events: none;
  transition: opacity .2s ease, transform .2s ease;
}
.xf-aichat__toast.is-shown { opacity: 1; transform: translateY(0); }

@keyframes xf-aichat-spin { to { transform: rotate(360deg); } }

/* ─── Reduced motion ──────────────────────────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
  .xf-aichat,
  .xf-aichat__panel,
  .xf-aichat__typing span,
  .xf-aichat__send-spin,
  .xf-aichat__toast { animation: none !important; transition: none !important; }
  .xf-aichat.is-open .xf-aichat__panel,
  .xf-aichat.is-closing .xf-aichat__panel { animation: none; }
}

/* ─── Мобайл: на весь экран с безопасными отступами ───────────────────── */
@media (max-width: 640px) {
  .xf-aichat {
    right: 0;
    bottom: 0;
    left: 0;
    top: 0;
    width: 100%;
    max-width: none;
    height: 100%;
    /* dvh (где поддержан) сжимается вместе с экранной клавиатурой — композер
       остаётся видимым НАД ней, а не прятался под (скрины владельца, iOS).
       top:0 + height задают геометрию, bottom игнорируется — так и задумано. */
    height: 100dvh;
    max-height: none;
  }
  /* На мобайле консент-бар раскрывается почти на всю ширину поверх — панель
     и так на весь экран, лифт не нужен; сбрасываем десктопный подъём. */
  body.xf-cookie-up .xf-aichat { bottom: 0; }
  .xf-aichat__panel {
    border-radius: 0;
    border: 0;
    /* верхний safe-area gutter (чёлка) — паддингом шапки. */
  }
  .xf-aichat__header { padding-top: calc(12px + env(safe-area-inset-top, 0px)); }
  .xf-aichat__row { max-width: 90%; }
  /* 16px, не 14: iOS Safari принудительно ЗУМИТ страницу при фокусе поля со
     шрифтом мельче 16px — владелец ловил «приблизило, надо отзумивать». */
  .xf-aichat__field,
  .xf-aichat__rate-input { font-size: 16px; }
  /* Подложка под панелью: при анимации клавиатуры iOS панель на кадры
     разъезжается с видимой областью — фон гасит мелькание каталога в щели. */
  .xf-aichat { background: var(--bg); }
}

/* Замок скролла страницы под открытой панелью (ставит/снимает js/aichat.js,
   только мобайл): iOS иначе скроллит САЙТ под клавиатуру, и в зазоре между
   панелью и клавиатурой мелькал каталог (скрин владельца). top задаётся
   инлайном (-scrollY), позиция восстанавливается при снятии. Медиа-обёртка —
   второй рубеж к JS-реконсиляции: даже залипший класс не заморозит десктоп. */
@media (max-width: 640px) {
  body.xf-aichat-lock {
    position: fixed;
    left: 0;
    right: 0;
    width: 100%;
    overflow: hidden;
  }
}
