/* Редизайн: дизайн-система на CSS custom properties (:root), тёмный фон страницы,
   белые карточки, скелетон-загрузка, цветовые бейджи distance, раскрытие блоков
   через grid-template-rows, адаптив (<768 / 768–1120 / >1120), reduced motion. */

:root {
  --bg-page: #1f232a;
  --bg-card: #ffffff;
  --bg-muted: #f6f7f9;
  --text: #1f2937;
  --text-muted: #6b7280;
  --text-on-dark: #e5e7eb;
  --text-on-dark-muted: #9ca3af;
  --border: #e2e5ea;
  --border-input: #d1d5db;
  --accent: #2563eb;
  --accent-dark: #1d4ed8;
  --accent-soft: rgba(37, 99, 235, 0.12);
  --success: #16a34a;
  --success-soft: #f0fdf4;
  --warning: #d97706;
  --warning-soft: #fff7ed;
  --warning-border: #fed7aa;
  --error: #dc2626;
  --error-soft: #fef2f2;
  --radius-sm: 6px;
  --radius: 8px;
  --radius-lg: 12px;
  --shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  --shadow-lg: 0 4px 12px rgba(0, 0, 0, 0.12);
  --sp-1: 4px;
  --sp-2: 8px;
  --sp-3: 12px;
  --sp-4: 16px;
  --sp-5: 24px;
  --sp-6: 32px;
  --tr: 0.2s ease;
}

*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

body {
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  font-size: 16px;
  background: var(--bg-page);
  color: var(--text);
  line-height: 1.5;
  max-width: 1240px;
  margin: 0 auto;
  padding: var(--sp-5) var(--sp-4);
}

/* ===== Раскладка ===== */
.layout {
  display: grid;
  grid-template-columns: minmax(0, 800px);
  justify-content: center;
  align-items: start;
  gap: var(--sp-5);
}
.main-col { min-width: 0; }
/* Чат — отдельной секцией в самом низу основной колонки. */
.chat-section { margin-bottom: var(--sp-5); }
.add-to-chat { width: auto; margin: 0; padding: 4px 10px; font-size: 0.8rem; background: #edf4ff; color: #5377a6; border: 1px solid #d8e5f5; box-shadow: none; }
.add-to-chat:hover:not(:disabled) { background: #e2edfc; }
.add-to-chat:disabled { background: #f2f6fc; color: #8297b2; border-color: #e3ebf5; cursor: default; }
.section-exclusions .add-to-chat { display: none; }
.chat-notice { padding: 10px 14px; border: 1px solid var(--accent); border-radius: var(--radius-sm); background: #f0f4ff; color: #333; }

/* ===== Шапка ===== */
.header { display: flex; align-items: center; gap: var(--sp-3); margin-bottom: var(--sp-4); position: relative; }
h1 { font-size: 1.4rem; font-weight: 700; color: var(--text-on-dark); margin-bottom: 0; }

.info-btn {
  flex: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 1px solid var(--text-on-dark-muted);
  background: transparent;
  color: var(--text-on-dark-muted);
  font-size: 0.65rem;
  font-weight: 700;
  line-height: 1;
  cursor: help;
  transition: color var(--tr), border-color var(--tr), background var(--tr);
  padding: 0;
}
.info-btn:hover { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }

/* Ссылка на страницу /graph — дерево позиций контрольных списков. */
.graph-link {
  margin-left: auto;
  flex: none;
  padding: 4px 10px;
  border: 1px solid var(--text-on-dark-muted);
  border-radius: 999px;
  color: var(--text-on-dark-muted);
  text-decoration: none;
  font-size: 0.78rem;
  white-space: nowrap;
  transition: color var(--tr), border-color var(--tr), background var(--tr);
}
.graph-link:hover { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }

/* Кнопка «Сохранить в PDF» в шапке — ненавязчивая ссылка-призрак рядом с
   «Граф позиций». Видна на любом этапе, если включён ENABLE_SAVE_PDF
   (атрибут hidden снимает app.js по ответу /config), в саму печать не
   попадает. */
.export-btn {
  flex: none;
  margin: 0;
  padding: 2px 9px;
  border: 1px solid transparent;
  border-radius: 999px;
  background: transparent;
  color: var(--text-on-dark-muted);
  font-size: 0.78rem;
  font-weight: 500;
  line-height: 1.4;
  box-shadow: none;
  white-space: nowrap;
  transition: color var(--tr), border-color var(--tr), background var(--tr);
}
.export-btn:hover:not(:disabled) {
  color: var(--accent);
  border-color: var(--border);
  background: var(--accent-soft);
}
.export-btn[hidden] { display: none; }

/* Переход к позиции в дереве — из карточки оценки и из списка кандидатов. */
.graph-jump {
  margin-left: auto;
  flex: none;
  padding: 2px 8px;
  border: 1px solid var(--border);
  border-radius: 999px;
  color: var(--accent);
  background: var(--bg-muted);
  text-decoration: none;
  font-size: 0.72rem;
  white-space: nowrap;
  transition: color var(--tr), border-color var(--tr), background var(--tr);
}
.graph-jump:hover { border-color: var(--accent); background: var(--accent-soft); }

.candidate-header { display: grid; grid-template-columns: minmax(0, 1fr) max-content; align-items: start; gap: 12px; }
.candidate-header-content { display: flex; align-items: baseline; flex-wrap: wrap; gap: 6px; min-width: 0; overflow-wrap: anywhere; }
.candidate-actions { display: flex; flex-direction: column; align-items: stretch; gap: 6px; }
.candidate-actions .graph-jump { margin-left: 0; text-align: center; }
.candidate-actions .add-to-chat { white-space: nowrap; }

/* ===== Инфо-панель — popover при наведении на ℹ️ ===== */
.info-panel {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  width: 440px;
  max-width: calc(100vw - var(--sp-4) * 2);
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transition: opacity 0.2s, visibility 0.2s;
  z-index: 1001;
  display: block;
  margin-bottom: 0;
}
.info-panel.open {
  opacity: 1;
  visibility: visible;
  pointer-events: auto;
}
.info-panel-inner { overflow: visible; min-height: 0; }
.info-panel-content {
  background: #fffdf5;
  border: 1px solid #e8e0c0;
  border-radius: var(--radius);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  padding: var(--sp-4);
  font-size: 0.85rem;
  line-height: 1.6;
  color: #444;
}
.info-panel-content p { margin-bottom: var(--sp-2); font-size: 0.85rem; }
.info-panel-content b:first-child { display: block; font-size: 0.95rem; font-weight: 700; margin-bottom: var(--sp-2); color: var(--text); }
.info-panel-content ol { padding-left: 20px; margin-bottom: var(--sp-2); }
.info-panel-content li { margin-bottom: var(--sp-1); font-size: 0.85rem; }
.info-panel-content .warning { color: var(--warning); font-size: 0.8rem; margin-top: var(--sp-2); }

/* ===== Форма ===== */
form {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow);
  padding: var(--sp-5);
  margin-bottom: var(--sp-5);
}
label { display: block; font-size: 0.9rem; font-weight: 600; margin-bottom: var(--sp-1); margin-top: 0; }
.field-group, #access-key-group { margin-top: var(--sp-3); }
form > :first-child { margin-top: 0; }
.hint { font-weight: 400; font-size: 0.85rem; color: var(--text-muted); }

input, textarea {
  width: 100%;
  padding: 10px 12px;
  font-size: 0.95rem;
  border: 1px solid var(--border-input);
  border-radius: var(--radius-sm);
  font-family: inherit;
  background: var(--bg-card);
  color: var(--text);
  transition: border-color var(--tr), box-shadow var(--tr);
}
input:hover, textarea:hover { border-color: #b6bdc9; }
input:focus, textarea:focus {
  outline: none;
  border-color: var(--accent);
  box-shadow: 0 0 0 3px var(--accent-soft);
}
textarea { resize: vertical; min-height: 60px; }

input:focus-visible, textarea:focus-visible, button:focus-visible {
  outline: 2px solid var(--accent);
  outline-offset: 2px;
}

button {
  margin-top: var(--sp-4);
  padding: 10px 24px;
  font-size: 0.95rem;
  font-weight: 600;
  background: var(--accent);
  color: #fff;
  border: none;
  border-radius: var(--radius-sm);
  cursor: pointer;
  transition: background var(--tr), transform var(--tr), box-shadow var(--tr);
}
button:hover { background: var(--accent-dark); }
button:disabled { background: #93b4f5; cursor: not-allowed; transform: none; box-shadow: none; }

#submit-btn {
  width: 100%;
  padding: 12px 24px;
  background: linear-gradient(135deg, #2563eb, #4f46e5);
  box-shadow: var(--shadow);
}
#submit-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #1d4ed8, #4338ca);
  transform: scale(1.02);
  box-shadow: var(--shadow-lg);
}

.key-hint { font-size: 0.85rem; margin-top: var(--sp-1); min-height: 1.2em; }
.key-hint.ok { color: var(--success); }
.key-hint.bad { color: var(--error); }
.key-hint.neutral { color: var(--text-muted); }

/* ===== Прогресс ===== */
.progress-container {
  display: none;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow);
  padding: var(--sp-4);
  margin-bottom: var(--sp-5);
}
.progress-header { display: flex; align-items: center; gap: 10px; }

/* Прогресс справа от «Выполняется классификация...». Шкала определённая —
   заполнение считается по стадиям пайплайна из живых логов задачи, а не по
   таймеру. Финальное голосование занимает большую часть времени, поэтому
   поверх заполнения бежит блик: иначе долгая последняя стадия читается как
   зависшая. */
.progress-bar {
  flex: 1;
  min-width: 80px;
  height: 6px;
  border-radius: 999px;
  background: var(--bg-muted);
  overflow: hidden;
}
.progress-bar-fill {
  position: relative;
  width: 0;
  height: 100%;
  border-radius: inherit;
  background: var(--accent);
  transition: width 0.4s ease;
}
.progress-bar-fill::after {
  content: "";
  position: absolute;
  inset: 0;
  background: linear-gradient(90deg,
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 0.55) 50%,
    rgba(255, 255, 255, 0) 100%);
  animation: progress-shimmer 1.4s linear infinite;
}
@keyframes progress-shimmer {
  from { transform: translateX(-100%); }
  to { transform: translateX(100%); }
}
.progress-stage {
  flex-shrink: 0;
  min-width: 8ch;
  text-align: right;
  font-size: 0.8rem;
  color: var(--text-muted);
}
@media (prefers-reduced-motion: reduce) {
  .progress-bar-fill { transition: none; }
  .progress-bar-fill::after { animation: none; }
  .spinner { animation-duration: 3s; }
}
@media (max-width: 560px) {
  .progress-header { flex-wrap: wrap; }
  .progress-bar { order: 3; flex-basis: 100%; }
  .progress-stage { margin-left: auto; }
}
.spinner {
  width: 22px;
  height: 22px;
  flex-shrink: 0;
  border: 3px solid #e0e0e0;
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.progress-text { font-size: 0.9rem; color: #555; }

/* Живые логи задачи под прогрессом: приглушённые, моноширинные, со скроллом. */
.progress-logs {
  max-height: 150px;
  overflow-y: auto;
  overflow-wrap: anywhere;
  margin-top: 10px;
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  font-size: 0.75rem;
  line-height: 1.5;
  color: var(--text-muted);
}
.progress-logs:empty { display: none; }

.waiting-msg {
  display: none;
  font-size: 0.85rem;
  color: var(--warning);
  background: var(--warning-soft);
  border: 1px solid var(--warning-border);
  border-radius: var(--radius-sm);
  padding: var(--sp-2) var(--sp-3);
  margin-bottom: 10px;
}
.waiting-msg::before { content: "⏳ "; }

/* Одна актуальная строка лога под шкалой: в свёрнутой панели видно, чем занят
   пайплайн сейчас; полный список — в «Деталях». */
.progress-live {
  margin-top: var(--sp-2);
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  font-size: 0.7rem;
  line-height: 1.4;
  color: var(--text-muted);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.progress-live:empty { display: none; }

.progress-details { margin-top: var(--sp-2); }
/* Пустые логи — нечего раскрывать. */
.progress-details:has(.progress-logs:empty) { display: none; }
.progress-details-summary {
  cursor: pointer;
  list-style: none;
  font-size: 0.75rem;
  color: var(--text-muted);
}
.progress-details-summary::-webkit-details-marker { display: none; }
.progress-details-summary::before {
  content: "▸";
  display: inline-block;
  width: 1em;
  transition: transform var(--tr);
}
.progress-details[open] > .progress-details-summary::before { transform: rotate(90deg); }
.progress-details-summary:hover { color: var(--accent); }

/* Закреплённая панель: только когда слева от колонки 800px есть свободный
   жёлоб (от 1440px зазор ≥24px). z-index ниже тултипов (1000) и инфо-панели
   (1001), чтобы те перекрывали панель. */
@media (min-width: 1440px) {
  .progress-container {
    position: fixed;
    top: var(--sp-4);
    left: var(--sp-4);
    width: 280px;
    max-height: calc(100vh - var(--sp-6));
    overflow-y: auto;
    margin-bottom: 0;
    padding: var(--sp-3);
    z-index: 900;
    box-shadow: var(--shadow-lg);
  }
  /* В 280px шапка не помещается в строку: спиннер и текст — первая строка,
     шкала — вторая во всю ширину, стадия прижата вправо. */
  .progress-container .progress-header { flex-wrap: wrap; gap: var(--sp-2); }
  .progress-container .progress-bar { order: 3; flex-basis: 100%; min-width: 0; }
  .progress-container .progress-stage { margin-left: auto; }
  .progress-container .spinner { width: 16px; height: 16px; border-width: 2px; }
  .progress-container .progress-text { font-size: 0.8rem; }
  .progress-container .progress-stage { font-size: 0.72rem; }
  .progress-container .progress-logs { max-height: 120px; font-size: 0.7rem; }
}

/* ===== Скелетон-загрузка ===== */
.skeleton-section {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow);
  padding: var(--sp-4);
  margin-bottom: var(--sp-4);
}
.skeleton-line {
  height: 14px;
  border-radius: var(--radius-sm);
  background: #e5e7eb;
  margin-bottom: var(--sp-3);
  animation: pulse 1.2s ease-in-out infinite;
}
.skeleton-line:last-child { margin-bottom: 0; }
.skeleton-line.w40 { width: 40%; }
.skeleton-line.w70 { width: 70%; }
.skeleton-line.w90 { width: 90%; }
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.45; }
}

/* ===== Результаты ===== */
.result-container { display: none; }
.result-container.visible { animation: fadeIn 0.3s ease; }
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(6px); }
  to { opacity: 1; transform: translateY(0); }
}

.section {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow);
  padding: var(--sp-4);
  margin-bottom: var(--sp-4);
}
h2 {
  font-size: 1.1rem;
  font-weight: 700;
  margin-bottom: var(--sp-3);
  border-bottom: 1px solid var(--border);
  padding-bottom: var(--sp-2);
}
.field { margin-bottom: var(--sp-1); }
.field-label { font-weight: 600; }

/* Входные данные: три поля в строку */
.input-grid { display: flex; gap: var(--sp-5); flex-wrap: wrap; }
.input-grid .field { flex: 1 1 180px; min-width: 0; margin-bottom: 0; }

/* Обогащение */
.param-chip {
  display: inline-block;
  background: var(--bg-muted);
  border: 1px solid var(--border);
  border-radius: 999px;
  padding: 2px 10px;
  font-size: 0.82rem;
  color: var(--text);
  margin: 2px 4px 2px 0;
}
.field-military {
  margin-top: var(--sp-2);
  padding: var(--sp-2) 10px;
  background: var(--warning-soft);
  border: 1px solid var(--warning-border);
  border-radius: var(--radius-sm);
}
.military-uses { margin: var(--sp-1) 0 0 20px; }
.military-uses li { margin-bottom: 4px; }
.military-uses a { color: var(--accent); text-decoration: none; white-space: nowrap; }
.military-uses a:hover { text-decoration: underline; }

/* Выбранные контрольные списки: полные названия занимают до 400 символов,
   поэтому это пункты с висячим отступом, а не строка через запятую. */
.chosen-lists {
  list-style: none;
  margin: var(--sp-2) 0 0;
  padding: 0;
}
.chosen-lists li {
  position: relative;
  padding-left: 16px;
  margin-bottom: 6px;
  font-size: 0.88rem;
  line-height: 1.45;
  color: var(--text);
}
.chosen-lists li:last-child { margin-bottom: 0; }
.chosen-lists li::before {
  content: "";
  position: absolute;
  left: 4px;
  top: 0.55em;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: var(--accent);
}

.enrichment-empty {
  color: var(--text-muted);
  font-size: 0.9rem;
  padding: var(--sp-3);
  background: var(--bg-muted);
  border-radius: var(--radius-sm);
  text-align: center;
}

.source {
  font-size: 0.85rem;
  color: var(--text-muted);
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.source-link {
  color: var(--accent);
  text-decoration: none;
}
.source-link::after {
  content: " ↗";
  font-size: 0.75rem;
  color: var(--text-muted);
}
.source-link:hover { text-decoration: underline; }

.source-num { color: var(--text-muted); font-weight: 400; margin-right: 2px; }
.source a { color: var(--accent); text-decoration: none; white-space: nowrap; }
.source a:hover { text-decoration: underline; }

.count { font-size: 0.85rem; color: var(--text-muted); margin-bottom: var(--sp-2); }
.error-msg {
  color: var(--error);
  font-size: 0.9rem;
  background: var(--error-soft);
  border: 1px solid #fecaca;
  border-radius: var(--radius-lg);
}

/* ===== Кандидаты ===== */
.candidate {
  padding: var(--sp-2) 10px;
  border-bottom: 1px solid #eee;
  border-radius: var(--radius-sm);
  transition: background var(--tr);
}
.candidate:last-child { border-bottom: none; }
/* Кликабелен весь заголовок позиции, включая строку полного названия
   списка (она лежит внутри .candidate-header): ховер-аффорданс совпадает
   с кликабельной зоной, а выделение/копирование текста развёрнутого
   описания позицию не сворачивает. */
.candidate-header { cursor: pointer; border-radius: var(--radius-sm); }
.candidate-header:hover { background: #f0f4ff; }
.candidate-header { font-size: 0.9rem; }
.candidate-num { color: var(--text-muted); font-weight: 600; margin-right: 2px; }
/* Полное название списка: длинное (до 400 символов), поэтому отдельной
   строкой внизу заголовка (flex-basis заставляет flex-контейнер перенести
   её с первой строки) и приглушённым мелким шрифтом — заголовок должен
   оставаться сканируемым. */
.cl {
  flex-basis: 100%;
  font-size: 0.78rem;
  line-height: 1.35;
  color: var(--text-muted);
  margin-top: 2px;
  padding-left: 18px;
}
.position { color: var(--accent); font-weight: 600; }

/* Старые сохранённые секции могут ещё содержать числовую дистанцию. */
.candidate .distance { display: none; }

/* Перечень исключений: полярность обратная контрольным спискам, поэтому
   секция отделена рамкой — чтобы её кандидаты не читались как основание
   для контроля. */
.section-exclusions { border-left: 3px solid var(--success); }

/* Свёрнутые секции кандидатов. Заголовок вместе со счётчиком живёт в
   <summary> — свёрнутая секция должна сообщать, сколько в ней позиций,
   иначе непонятно, стоит ли её разворачивать. */
.section-collapsible { padding-bottom: var(--sp-2); }
.section-collapsible > .section-summary {
  display: flex;
  align-items: baseline;
  gap: var(--sp-3);
  cursor: pointer;
  list-style: none;
}
.section-collapsible > .section-summary::-webkit-details-marker { display: none; }
.section-collapsible > .section-summary h2 {
  flex: 1;
  margin-bottom: 0;
  border-bottom: none;
  padding-bottom: 0;
}
.section-collapsible > .section-summary h2::before {
  content: "▸";
  display: inline-block;
  width: 1em;
  margin-right: var(--sp-1);
  color: var(--text-muted);
  transition: transform var(--tr);
}
.section-collapsible[open] > .section-summary h2::before { transform: rotate(90deg); }
.section-collapsible > .section-summary:hover h2 { color: var(--accent); }
.section-collapsible > .section-summary .count-inline { margin-bottom: 0; }
.section-collapsible[open] > .section-summary {
  margin-bottom: var(--sp-3);
  border-bottom: 1px solid var(--border);
  padding-bottom: var(--sp-2);
}

/* Плашки «итоговой оценки нет»: финальное голосование не состоялось и/или
   все найденные позиции отсеял предварительный отбор. Оба случая выглядят
   в выдаче одинаково — секции с оценкой просто нет, — поэтому причину
   проговариваем явно. */
.section-notice {
  border-left: 3px solid var(--warning);
  background: var(--warning-soft);
}
.notice-title {
  font-size: 0.95rem;
  font-weight: 700;
  margin-bottom: var(--sp-2);
}
.notice-text { font-size: 0.9rem; color: var(--text); }
.notice-text + .notice-text { margin-top: var(--sp-2); color: var(--text-muted); }

/* Аналитические заключения по выбору пользователя: каждая позиция —
   свёрнутая карточка <details>; заголовок кликабелен, у открытой позиции
   маркер повёрнут. */
.section-analysis { border-left: 3px solid var(--accent); }
.analysis-item {
  border: 1px solid var(--border);
  border-radius: var(--radius-sm);
  padding: 8px 12px;
  margin-bottom: 8px;
  background: var(--bg-card);
}
.analysis-item > .analysis-head {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
  gap: 6px;
  cursor: pointer;
  list-style: none;
}
.analysis-item > .analysis-head::-webkit-details-marker { display: none; }
.analysis-item > .analysis-head .position::before {
  content: "▸";
  display: inline-block;
  width: 1em;
  margin-right: 2px;
  color: var(--text-muted);
  transition: transform var(--tr);
}
.analysis-item[open] > .analysis-head .position::before { transform: rotate(90deg); }
.analysis-item > .analysis-head:hover .position { color: var(--accent-dark); }
.analysis-body { margin-top: 4px; }
.analysis-text { color: var(--text); font-size: 0.92rem; }
.analysis-text > :first-child { margin-top: 0; }
.analysis-text > :last-child { margin-bottom: 0; }
.analysis-text p { margin: var(--sp-1) 0; }
.analysis-text ul, .analysis-text ol { margin: var(--sp-1) 0 var(--sp-1) 20px; }
.analysis-text li { margin-bottom: 2px; }
.analysis-text strong { font-weight: 700; }
.analysis-text h1, .analysis-text h2, .analysis-text h3,
.analysis-text h4, .analysis-text h5, .analysis-text h6 {
  font-weight: 600;
  margin: var(--sp-2) 0 var(--sp-1);
  font-size: 0.95rem;
}
.analysis-text code {
  background: #eef;
  padding: 1px 4px;
  border-radius: 3px;
  font-size: 0.85rem;
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.analysis-text pre {
  background: #f0f0f5;
  padding: var(--sp-2) 10px;
  border-radius: var(--radius-sm);
  overflow-x: auto;
  margin: 6px 0;
}
.analysis-text pre code { background: none; padding: 0; }
.analysis-text a { color: var(--accent); word-break: break-all; }
/* Markdown-таблицы заключений: markdown-it рендерит их как <table>, без
   стилей они нечитаемы. display:block + width:max-content/max-width — приём
   GitHub: таблица растягивается по контенту, а на узком экране скроллится
   внутри карточки, не распирая её. */
.analysis-text table {
  display: block;
  width: max-content;
  max-width: 100%;
  overflow-x: auto;
  border-collapse: collapse;
  margin: var(--sp-2) 0;
  font-size: 0.85rem;
}
.analysis-text th, .analysis-text td {
  border: 1px solid var(--border);
  padding: 4px 8px;
  text-align: left;
  vertical-align: top;
  overflow-wrap: anywhere;
}
.analysis-text th { background: var(--bg-muted); font-weight: 600; }
.analysis-error {
  margin-top: 4px;
  padding: 6px 10px;
  border-radius: var(--radius-sm);
  font-size: 0.85rem;
  color: #9b2c34;
  background: #f8e7e9;
}
/* Подсекции секции постановлений («Общие позиции» / «Конкретные позиции»):
   <details> с лёгким приглушённым заголовком-переключателем; конкретные
   позиции развёрнуты, общие свёрнуты. */
.subsection { margin: var(--sp-3) 0 var(--sp-2); }
.subsection > .subsection-title {
  font-size: 0.85rem;
  font-weight: 600;
  color: var(--text-muted);
  cursor: pointer;
  list-style: none;
  padding: 2px 0;
}
.subsection > .subsection-title::-webkit-details-marker { display: none; }
.subsection > .subsection-title::before {
  content: "▸";
  display: inline-block;
  width: 1em;
  margin-right: 2px;
  transition: transform var(--tr);
}
.subsection[open] > .subsection-title::before { transform: rotate(90deg); }
.subsection > .subsection-title:hover { color: var(--accent); }
/* Бейдж score Jev в квадратных скобках — моноширинный, левый верхний угол
   заголовка позиции. */
.jev-score {
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  font-size: 0.78rem;
  font-weight: 600;
  color: var(--accent-dark);
  background: var(--accent-soft);
  border-radius: var(--radius-sm);
  padding: 0 4px;
}
/* Чекбокс выбора позиции для анализа. */
.analyze-check { width: 15px; height: 15px; accent-color: var(--accent); cursor: pointer; }
/* Пометка исключённой позиции. */
.excluded-badge {
  display: inline-block;
  font-size: 0.72rem;
  font-weight: 600;
  letter-spacing: 0.03em;
  padding: 1px 6px;
  border-radius: 10px;
  vertical-align: middle;
  color: #9b2c34;
  background: #f8e7e9;
}
/* Кандидат, которого нашёл только словарь ключевых слов позиции: по
   близости он заведомо далеко, и без пометки непонятно, почему он в выдаче.
   Тег стоит отдельной строкой над позицией — это пометка обо всей позиции,
   а не ещё один значок в ряду с дистанцией и оценкой близости. */
.alias-line { margin-bottom: 4px; }

.alias-badge {
  display: inline-block;
  font-size: 0.72rem;
  font-weight: 600;
  letter-spacing: 0.03em;
  padding: 1px 6px;
  border-radius: 10px;
  vertical-align: middle;
  color: var(--accent-dark);
  background: var(--accent-soft);
  cursor: help;
}

/* Тег источника позиции в блоке «Предварительный поиск» («семантика: ввод»,
   «ТН ВЭД»…) — диагностика ретривала, поэтому приглушённый, как «общая». */
.src-badge {
  display: inline-block;
  font-size: 0.72rem;
  font-weight: 600;
  letter-spacing: 0.03em;
  padding: 1px 6px;
  border-radius: 10px;
  vertical-align: middle;
  color: var(--text-muted);
  background: var(--bg-muted);
  cursor: help;
}

/* Общая (родительская) позиция: не лист и без кода ТН ВЭД. Пометка
   приглушённая, как у «исключено», — это свойство позиции, а не оценка. */
.general-badge {
  display: inline-block;
  font-size: 0.72rem;
  font-weight: 600;
  letter-spacing: 0.03em;
  padding: 1px 6px;
  border-radius: 10px;
  vertical-align: middle;
  color: var(--text-muted);
  background: var(--bg-muted);
  cursor: help;
}

/* Цветная полоса на всей карточке: уровень видно, не вчитываясь в бейдж.
   inset-тень вместо border-left — не сдвигает содержимое карточки. */
.candidate-good { box-shadow: inset 3px 0 0 #48a366; }
.candidate-warn { box-shadow: inset 3px 0 0 #c08a32; }
.candidate-bad { box-shadow: inset 3px 0 0 #cc6268; }
.candidate-na { box-shadow: inset 3px 0 0 var(--bg-muted); }

/* Раскрытие описания кандидата (grid-rows, без max-height-хаков) */
.candidate-body { display: grid; grid-template-rows: 0fr; transition: grid-template-rows 0.25s ease; }
.candidate-body.open { grid-template-rows: 1fr; }
.candidate-body-inner { overflow: hidden; min-height: 0; }
.candidate-body-content {
  margin-top: 6px;
  padding-left: var(--sp-3);
  font-size: 0.9rem;
  color: #444;
  border-left: 3px solid var(--accent);
}
.candidate-body-content a { color: var(--accent); word-break: break-all; }

/* ===== Плавающая панель анализа выбранных позиций ===== */
.analyze-panel {
  position: fixed;
  left: 50%;
  bottom: var(--sp-4);
  transform: translateX(-50%);
  z-index: 1002;
  display: flex;
  align-items: center;
  gap: var(--sp-3);
  padding: var(--sp-2) var(--sp-4);
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  font-size: 0.9rem;
}
.analyze-panel button {
  padding: 6px 14px;
  border: 1px solid var(--accent);
  border-radius: var(--radius-sm);
  background: var(--accent);
  color: #fff;
  font-size: 0.88rem;
  cursor: pointer;
  transition: background var(--tr);
}
.analyze-panel button:hover { background: var(--accent-dark); }
.analyze-panel button:disabled { opacity: 0.6; cursor: default; }
.analyze-panel #analyze-reset {
  background: var(--bg-card);
  color: var(--text);
  border-color: var(--border-input);
}
.analyze-panel #analyze-reset:hover { background: var(--bg-muted); }
.analyze-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid var(--accent-soft);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: analyze-spin 0.8s linear infinite;
}
@keyframes analyze-spin { to { transform: rotate(360deg); } }
.analyze-note { color: #9b2c34; font-size: 0.82rem; max-width: 320px; }
/* Панель фиксирована внизу — контент не должен прятаться за ней. */
body.analyze-panel-open { padding-bottom: 80px; }

/* ===== Чат ===== */
.chat-history {
  max-height: 62vh;
  min-height: 200px;
  overflow-y: auto;
  margin-bottom: 10px;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  padding: 10px;
  background: var(--bg-muted);
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.chat-msg {
  max-width: 88%;
  padding: var(--sp-2) var(--sp-3);
  border-radius: var(--radius);
  border-left: 3px solid #ccc;
}
.chat-user {
  align-self: flex-end;
  background: #eef4ff;
  border-left: none;
  border-right: 3px solid var(--accent);
}
.chat-ai {
  align-self: flex-start;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-left: 3px solid var(--success);
}
.chat-role { font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 3px; }
.chat-user .chat-role { color: var(--accent); }
.chat-ai .chat-role { color: var(--success); }

.chat-content > :first-child { margin-top: 0; }
.chat-content > :last-child { margin-bottom: 0; }
.chat-msg .chat-p { margin: var(--sp-1) 0; }
.chat-msg .chat-h { font-weight: 600; margin: var(--sp-2) 0 var(--sp-1); font-size: 0.95rem; }
.chat-msg ul, .chat-msg ol { margin: var(--sp-1) 0 var(--sp-1) 20px; }
.chat-msg li { margin-bottom: 2px; }
.chat-msg code {
  background: #eef;
  padding: 1px 4px;
  border-radius: 3px;
  font-size: 0.85rem;
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.chat-msg pre { background: #f0f0f5; padding: var(--sp-2) 10px; border-radius: var(--radius-sm); overflow-x: auto; margin: 6px 0; }
.chat-msg pre code { background: none; padding: 0; }
.chat-msg a { color: var(--accent); word-break: break-all; }

.chat-input-row { display: flex; gap: var(--sp-2); align-items: flex-start; }
.chat-input-wrap { position: relative; flex: 1; min-width: 0; }
.chat-input { width: 100%; box-sizing: border-box; resize: none; overflow-y: hidden; min-height: 52px; max-height: 200px; }
.chat-mention-suggest { position: absolute; z-index: 20; left: 0; right: 0; bottom: calc(100% + 5px); max-height: 260px; overflow-y: auto; background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-sm); box-shadow: var(--shadow-lg); }
.chat-mention-suggest[hidden] { display: none; }
.chat-mention-option { display: block; width: 100%; margin: 0; padding: 8px 10px; border: 0; border-radius: 0; background: transparent; color: var(--text); text-align: left; font-size: 0.83rem; font-weight: 400; }
.chat-mention-option:hover, .chat-mention-option.active { background: var(--accent-soft); }
.chat-mention-option strong { color: var(--accent); margin-right: 6px; }
.chat-mention-option small { display: block; color: var(--text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.chat-mention-empty { padding: 9px 10px; color: var(--text-muted); font-size: 0.82rem; }
.chat-send { margin-top: 0 !important; padding: 8px 16px !important; }
.chat-send:hover:not(:disabled) { transform: scale(1.02); }

/* Бейдж остатка токенов контекста в заголовке чата */
.chat-tokens {
  display: inline-flex;
  align-items: center;
  font-size: 0.72rem;
  font-weight: 600;
  padding: 2px 10px;
  border-radius: 999px;
  border: 1px solid transparent;
  vertical-align: middle;
}
.chat-tokens.tokens-ok { background: #e6f4ea; color: #1a7f37; border-color: #b7dfc2; }
.chat-tokens.tokens-warn { background: #fff3cd; color: #7a5b00; border-color: #e0a800; }
.chat-tokens.tokens-low { background: #fdecea; color: #a12622; border-color: #f5c6c6; }

#chat-input:disabled {
  background: var(--bg-muted);
  color: #999;
  cursor: not-allowed;
}
#chat-send:disabled { opacity: 0.55; cursor: not-allowed; }

#chat-loading { align-items: center; gap: var(--sp-2); }
.typing-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: var(--accent);
  animation: blink 1s ease-in-out infinite;
}
@keyframes blink {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.35; transform: scale(0.8); }
}

/* ===== Адаптив ===== */
@media (max-width: 1120px) {
  .layout { grid-template-columns: minmax(0, 800px); }
}
@media (max-width: 768px) {
  body { padding: var(--sp-4) var(--sp-3); }
  h1 { font-size: 1.15rem; }
  form { padding: var(--sp-4); }
  .input-grid { flex-direction: column; gap: var(--sp-2); }
  .chat-msg { max-width: 100%; }
}

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}

/* ===== Тултипы (CSS-only, data-tooltip) ===== */
[data-tooltip] { position: relative; }
[data-tooltip]::after,
[data-tooltip]::before {
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  position: absolute;
  z-index: 1000;
  transition: opacity 0.15s ease, visibility 0.15s ease;
}
[data-tooltip]::after {
  content: attr(data-tooltip);
  bottom: calc(100% + 6px);
  left: 50%;
  transform: translateX(-50%);
  background: #e5e7eb;
  color: #111827;
  font-size: 0.78rem;
  font-weight: 400;
  border-radius: 6px;
  padding: 6px 10px;
  max-width: 400px;
  white-space: normal;
  word-wrap: break-word;
  overflow-wrap: break-word;
  line-height: 1.4;
  text-align: left;
}
[data-tooltip]::before {
  content: "";
  bottom: calc(100% + 1px);
  left: 50%;
  transform: translateX(-50%);
  border: 5px solid transparent;
  border-top-color: #e5e7eb;
}
[data-tooltip]:hover::after,
[data-tooltip]:hover::before,
[data-tooltip].tooltip-open::after,
[data-tooltip].tooltip-open::before {
  opacity: 1;
  visibility: visible;
}

/* Иконка (?) для полей формы */
.tooltip-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border: 1px solid var(--text-muted);
  color: var(--text-muted);
  font-size: 0.62rem;
  font-weight: 700;
  cursor: help;
  vertical-align: middle;
  margin-left: 3px;
  line-height: 1;
  transition: color 0.2s, border-color 0.2s, background 0.2s;
  flex-shrink: 0;
}
.tooltip-icon:hover {
  color: var(--accent);
  border-color: var(--accent);
  background: var(--accent-soft);
}

/* Модификатор: тултип снизу */
[data-tooltip].tooltip-bottom::after {
  bottom: auto;
  top: calc(100% + 6px);
}
[data-tooltip].tooltip-bottom::before {
  bottom: auto;
  top: calc(100% + 1px);
  border-top-color: transparent;
  border-bottom-color: #e5e7eb;
}

/* Модификатор: тултип по левому краю (без центрирования) */
[data-tooltip].tooltip-left::after {
  left: 0;
  transform: none;
}
[data-tooltip].tooltip-left::before {
  left: 12px;
  transform: none;
}

/* ===== Подтверждение данных обогащения ===== */
/* Карточка «тот ли это товар»: собирается в web/confirmation.py и живёт в
   #result-container вместо результатов, пока пользователь не ответит. */
.confirm-section {
  border-left: 3px solid var(--warning);
}
.confirm-lead {
  color: var(--text-muted);
  font-size: 0.9rem;
  margin: 0 0 var(--sp-4);
}
.confirm-subhead {
  font-weight: 600;
  font-size: 0.85rem;
  text-transform: uppercase;
  letter-spacing: 0.03em;
  color: var(--text-muted);
  margin-bottom: var(--sp-2);
}
.confirm-user-input {
  background: var(--bg-muted);
  border-radius: var(--radius);
  padding: var(--sp-3);
  margin-bottom: var(--sp-4);
}
.confirm-field { margin-bottom: var(--sp-3); }
.confirm-field label {
  display: block;
  font-size: 0.9rem;
  font-weight: 600;
  margin-bottom: var(--sp-1);
}
.confirm-field input,
.confirm-field textarea {
  width: 100%;
  padding: 8px 10px;
  font: inherit;
  font-size: 0.9rem;
  color: var(--text);
  background: var(--bg-card);
  border: 1px solid var(--border-input);
  border-radius: var(--radius-sm);
  box-sizing: border-box;
}
.confirm-field textarea { resize: vertical; line-height: 1.45; }
.confirm-field input:focus,
.confirm-field textarea:focus {
  outline: none;
  border-color: var(--accent);
  box-shadow: 0 0 0 3px var(--accent-soft);
}
.confirm-sources { margin-top: var(--sp-3); }
.confirm-sources-list {
  font-size: 0.85rem;
  color: var(--text-muted);
  margin-top: var(--sp-1);
}
.confirm-actions {
  display: flex;
  flex-wrap: wrap;
  gap: var(--sp-3);
  margin-top: var(--sp-4);
}
.confirm-actions button { margin-top: 0; }
.confirm-yes { background: var(--success); }
.confirm-yes:hover:not(:disabled) { background: #15803d; }
.confirm-no {
  background: transparent;
  color: var(--text-muted);
  border: 1px solid var(--border-input);
}
.confirm-no:hover:not(:disabled) {
  background: var(--bg-muted);
  color: var(--text);
}
.confirm-note {
  font-size: 0.82rem;
  color: var(--text-muted);
  margin: var(--sp-3) 0 0;
}
.confirm-cancel {
  background: transparent;
  color: var(--text-muted);
  border: 1px solid transparent;
  text-decoration: underline;
}
.confirm-cancel:hover:not(:disabled) {
  background: transparent;
  color: var(--error);
}

/* Метка «из кэша» с датой записи: показывается в карточке подтверждения и
   в секции «Обогащение» итогов — без неё свежий поиск и запись годовалой
   давности выглядят одинаково. */
.cache-badge {
  display: inline-block;
  font-size: 0.72rem;
  font-weight: 600;
  letter-spacing: 0.01em;
  padding: 2px 8px;
  border-radius: 10px;
  vertical-align: middle;
  text-transform: none;
  color: var(--warning);
  background: var(--warning-soft);
  border: 1px solid var(--warning-border);
  cursor: help;
}
h2 .cache-badge { margin-left: var(--sp-2); }

/* Блок повторного поиска обогащения внутри карточки подтверждения. */
.confirm-regen {
  margin-top: var(--sp-4);
  padding-top: var(--sp-4);
  border-top: 1px solid var(--border);
}
.confirm-regen-note {
  font-size: 0.85rem;
  color: var(--text-muted);
  margin: 0 0 var(--sp-2);
}
.regen-hint {
  width: 100%;
  padding: 8px 10px;
  font: inherit;
  font-size: 0.9rem;
  color: var(--text);
  background: var(--bg-card);
  border: 1px solid var(--border-input);
  border-radius: var(--radius-sm);
  resize: vertical;
  line-height: 1.45;
  box-sizing: border-box;
}
.regen-hint:focus {
  outline: none;
  border-color: var(--accent);
  box-shadow: 0 0 0 3px var(--accent-soft);
}
.confirm-regen-btn {
  margin-top: var(--sp-2);
  background: transparent;
  color: var(--accent);
  border: 1px solid var(--accent);
}
.confirm-regen-btn:hover:not(:disabled) {
  background: var(--accent-soft);
  color: var(--accent-dark);
}
.confirm-regen-error {
  margin: var(--sp-2) 0 0;
  font-size: 0.85rem;
  color: var(--error);
}

/* Выбор контрольных списков в карточке подтверждения. Полные названия
   занимают до 400 символов, поэтому это вертикальные строки-переключатели
   в сворачиваемом блоке, а не чипсы в строку. */
.lists-block {
  margin-top: var(--sp-4);
  padding-top: var(--sp-4);
  border-top: 1px solid var(--border);
}
.lists-summary {
  display: flex;
  align-items: center;
  gap: var(--sp-2);
  cursor: pointer;
  font-weight: 600;
  font-size: 0.85rem;
  text-transform: uppercase;
  letter-spacing: 0.03em;
  color: var(--text-muted);
}
.lists-summary::-webkit-details-marker { color: var(--text-muted); }
.lists-state {
  margin-left: auto;
  font-weight: 500;
  font-size: 0.78rem;
  text-transform: none;
  letter-spacing: 0;
  color: var(--accent);
}
.lists-note {
  font-size: 0.85rem;
  color: var(--text-muted);
  margin: var(--sp-2) 0;
}
.lists-options {
  display: flex;
  flex-direction: column;
  gap: var(--sp-1);
  max-height: 320px;
  overflow-y: auto;
}
.list-option, .list-group-toggle {
  display: flex;
  align-items: flex-start;
  gap: var(--sp-2);
  width: 100%;
  margin-top: 0;
  padding: 8px 10px;
  text-align: left;
  font-size: 0.85rem;
  font-weight: 400;
  line-height: 1.4;
  color: var(--text);
  background: var(--bg-card);
  border: 1px solid var(--border-input);
  border-radius: var(--radius-sm);
}
.list-option:hover, .list-group-toggle:hover { background: var(--bg-muted); }
/* Переключатель «все разделы» — групповое действие, а не ещё один список:
   приглушённый фон и полужирная подпись отличают его от членов группы. */
.list-group-toggle { background: var(--bg-muted); }
.list-group-toggle .list-option-name { font-weight: 600; }
.list-group-toggle[aria-pressed="true"] { background: var(--accent-soft); }
.list-option-mark {
  flex-shrink: 0;
  width: 14px;
  height: 14px;
  margin-top: 2px;
  border: 1px solid var(--border-input);
  border-radius: 3px;
  background: var(--bg-card);
}
.list-option[aria-pressed="true"],
.list-group-toggle[aria-pressed="true"] {
  border-color: var(--accent);
  background: var(--accent-soft);
}
.list-option[aria-pressed="true"] .list-option-mark,
.list-group-toggle[aria-pressed="true"] .list-option-mark {
  border-color: var(--accent);
  background: var(--accent);
  position: relative;
}
.list-option[aria-pressed="true"] .list-option-mark::after,
.list-group-toggle[aria-pressed="true"] .list-option-mark::after {
  content: "✓";
  position: absolute;
  inset: 0;
  color: #fff;
  font-size: 0.62rem;
  line-height: 12px;
  text-align: center;
}
.lists-reset {
  margin-top: var(--sp-2);
  padding: 4px 0;
  background: transparent;
  color: var(--text-muted);
  border: none;
  font-size: 0.82rem;
  font-weight: 400;
  text-decoration: underline;
}
.lists-reset:hover { background: transparent; color: var(--accent); }

/* Кнопка формы в режиме отмены: пока задача идёт, «Классифицировать»
   превращается в «Отменить» — прогресс пользователь видит в логах. */
#submit-btn.cancel-mode,
#submit-btn.cancel-mode:hover:not(:disabled) {
  background: var(--error);
  transform: none;
}
#submit-btn.cancel-mode:hover:not(:disabled) { background: #b91c1c; }
.cancelled-msg { color: var(--text-muted); }

/* ===== Печать в PDF =====
   Кнопка «PDF» в шапке (exportPdf в app.js) зовёт window.print(), файл
   сохраняется через «Сохранить как PDF» в диалоге. Печатается ровно то,
   что сейчас на странице: свёрнутые <details> и позиции не раскрываем.
   Здесь только убираем служебный интерфейс и чиним разрывы страниц. */
@page { margin: 12mm; }

@media print {
  html { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
  body { background: #fff; padding: 0; max-width: none; }

  /* Кнопки на бумаге не работают — прячем все; остальное в списке —
     служебный интерфейс вокруг результата. */
  button,
  .graph-link, .info-panel,
  #classify-form, .progress-container, .analyze-panel,
  .analyze-check, .tooltip-icon,
  .chat-input-row, .chat-mention-suggest, .skeleton-section {
    display: none !important;
  }
  body.analyze-panel-open { padding-bottom: 0; }

  .layout { display: block; }
  .result-container { display: block !important; animation: none; }
  .section { box-shadow: none; }
  .analysis-item, .candidate, .chat-msg, tr { break-inside: avoid; }

  /* Экранный display:block со скроллом в печати обрезал бы широкие
     таблицы заключений — возвращаем табличную раскладку и повторяем
     шапку на разрывах страниц. */
  .analysis-text table { display: table; width: 100%; overflow: visible; }
  .analysis-text thead { display: table-header-group; }

  /* Внутренний скролл истории чата — не «свёрнутость»: в PDF сообщения
     должны попасть целиком, а не обрезанными по 62vh. */
  .chat-history { max-height: none; overflow: visible; }

  a { color: inherit; text-decoration: none; }
}
