:root {
  --bg: #0f1117;
  --bg-panel: #171a23;
  --bg-hover: #1f2330;
  --bg-active: #2a2f42;
  --bg-input: #1c2029;
  --border: #262b3a;
  --text: #e8eaf0;
  --text-dim: #8a91a5;
  --accent: #6c7bff;
  --accent-hover: #5a68e8;
  --bubble-in: #232837;
  --bubble-out: #3d4a8f;
  --online: #3ecf6a;
  --danger: #e05555;
  --msg-meta: rgba(255, 255, 255, .55);
  --tick-read: #8fd8ff;
}

/* Светлая тема (переключается в настройках, хранится в localStorage) */
:root[data-theme="light"] {
  --bg: #eef1f7;
  --bg-panel: #ffffff;
  --bg-hover: #f0f2f8;
  --bg-active: #e4e8f4;
  --bg-input: #f1f3f9;
  --border: #dfe4ef;
  --text: #1b2233;
  --text-dim: #7a819a;
  --accent: #5b6af0;
  --accent-hover: #4757e0;
  --bubble-in: #ffffff;
  --bubble-out: #d5ddff;
  --online: #2fae5c;
  --danger: #d64545;
  --msg-meta: rgba(27, 34, 51, .45);
  --tick-read: #2f7fd6;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  -webkit-tap-highlight-color: transparent;
}

[hidden] { display: none !important; }

/* Плавное появление нового сообщения (отправка / приход в реальном времени) */
@keyframes msg-pop {
  from { opacity: 0; transform: translateY(10px) scale(.98); }
  to   { opacity: 1; transform: none; }
}
.msg-enter { animation: msg-pop .22s cubic-bezier(.22, 1, .36, 1); }
@media (prefers-reduced-motion: reduce) { .msg-enter { animation: none; } }

/* Круговое раскрытие новой темы поверх старой (View Transitions) — включается
   ТОЛЬКО классом .theme-wave (ставим его на время перехода там, где волна идёт
   плавно, т.е. на iOS). Без этого класса работает штатный кроссфейд браузера:
   он делается на композиторе, поэтому не дёргается на Android и ПК. */
html.theme-wave::view-transition-old(root),
html.theme-wave::view-transition-new(root) { animation: none; mix-blend-mode: normal; }
html.theme-wave::view-transition-new(root) { z-index: 1; }
html.theme-wave::view-transition-old(root) { z-index: 0; }

/* Фон «холста» страницы. body спозиционирован fixed и на iPhone может не
   доставать под home-indicator — тогда снизу проступал фон body (--bg, серый).
   Красим холст в цвет нижних панелей (--bg-panel), чтобы любой такой зазор в
   зоне safe-area был неотличим от панели, а не серой полосой. */
html { background: var(--bg-panel); }

body {
  font-family: "Segoe UI", system-ui, sans-serif;
  background: var(--bg);
  color: var(--text);
  /* position: fixed + inset:0 заполняет весь экран, включая нижнюю safe-area
     iPhone, и служит системой координат для экранов приложения. */
  position: fixed;
  inset: 0;
  overflow: hidden;
}

/* select забыли в этом правиле, из-за чего выпадающие списки рисовались мелким
   браузерным шрифтом на фоне остальных полей */
input, button, select, textarea { font: inherit; color: inherit; }

/* Настройки «Звук и камера»: один размер шрифта на весь раздел, иначе там
   соседствовали 13px (заголовки), 14px (подсказки/бинды) и 16px (кнопки, списки) */
[data-panel="audio"] { font-size: 15px; }
[data-panel="audio"] .section-title,
[data-panel="audio"] .bind-btn,
[data-panel="audio"] .hint,
[data-panel="audio"] .modal-input,
[data-panel="audio"] .btn-secondary { font-size: inherit; }

/* iOS Safari масштабирует страницу при фокусе на поле с font-size < 16px */
input, textarea { font-size: 16px; }

/* ---------- Авторизация ---------- */

#auth-screen {
  /* inset:0 + height:auto = растянут до самого низа экрана БЕЗ участия JS
     (при переопределённых top/bottom и height браузер игнорирует bottom, поэтому
     когда JS задаёт --app-h под клавиатуру — работает высота, иначе низ). */
  position: absolute;
  inset: 0;
  height: var(--app-h, auto);
  display: flex;
  overflow-y: auto;
}

.auth-card {
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 16px;
  padding: 36px 32px;
  width: 380px;
  max-width: calc(100vw - 32px);
  /* margin:auto центрирует карточку по обеим осям, но у высокой формы
     регистрации (выше экрана) не обрезает верх и даёт прокрутку — поэтому
     вёрстка не «прыгает» при перерисовке (смене темы). */
  margin: auto;
}

/* Переключатель темы в левом верхнем углу экрана входа */
#auth-theme-btn {
  position: absolute;
  top: calc(14px + env(safe-area-inset-top, 0px));
  left: 16px;
  color: var(--text-dim);
}
#auth-theme-btn svg[data-t="moon"] { display: none; }
:root[data-theme="light"] #auth-theme-btn svg[data-t="sun"] { display: none; }
:root[data-theme="light"] #auth-theme-btn svg[data-t="moon"] { display: block; }

.auth-logo {
  width: 76px;
  height: 76px;
  border-radius: 18px;
  display: block;
  margin: 0 auto 12px;
}

.auth-card h1 { text-align: center; font-size: 28px; }
.auth-subtitle { text-align: center; color: var(--text-dim); margin: 4px 0 20px; }

.tabs { display: flex; gap: 8px; margin-bottom: 20px; }

.tab {
  flex: 1;
  padding: 8px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  cursor: pointer;
  color: var(--text-dim);
}

.tab.active { background: var(--accent); border-color: var(--accent); color: #fff; }

.auth-form { display: flex; flex-direction: column; gap: 12px; }

/* Чекбокс согласия при регистрации (152-ФЗ) */
.consent-row {
  display: flex;
  gap: 9px;
  align-items: flex-start;
  font-size: 13px;
  line-height: 1.45;
  color: var(--text-dim);
  cursor: pointer;
}
.consent-row input { width: 18px; height: 18px; margin-top: 1px; flex-shrink: 0; accent-color: var(--accent); }
.consent-row a { color: var(--accent); text-decoration: none; }
.consent-row a:hover { text-decoration: underline; }

/* Ссылки на правовые документы под карточкой входа */
.auth-legal { text-align: center; font-size: 12px; color: var(--text-dim); margin: 16px 0 0; }
.auth-legal a { color: var(--text-dim); text-decoration: none; }
.auth-legal a:hover { text-decoration: underline; color: var(--accent); }

/* ---------- Правка своего сообщения ---------- */

/* Полоса режима правки — оформлением повторяет полосу ответа */
#edit-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background: var(--bg-panel);
  border-top: 1px solid var(--border);
  font-size: 13px;
  color: var(--text-dim);
}
#edit-bar[hidden] { display: none; }
#edit-bar .edit-preview { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#edit-bar b { color: var(--accent); }

/* Пометка у времени, что сообщение правили */
.edited-mark { opacity: .75; font-style: italic; }

/* Крестики на плитках альбома видны только в режиме правки */
.album-rm { display: none; }
body.album-editing .msg.album.editing .album-rm {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  background: rgba(0, 0, 0, .62);
  color: #fff;
  font-size: 18px;
  line-height: 1;
  cursor: pointer;
  z-index: 3;
}
.album-cell { position: relative; }
body.album-editing .msg.album.editing { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 12px; }

/* Точка «никто, кроме автора, ещё не прослушал» у голосовых и кружков.
   Гаснет, когда сообщение прослушал кто-то другой (см. WS-событие played). */
.played-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--accent);
  flex-shrink: 0;
  pointer-events: none;
}
.voice-msg, .circle-wrap { position: relative; }

/* Диалог удаления: два равнозначных варианта в столбик */
.delete-options { display: flex; flex-direction: column; gap: 8px; margin: 14px 0 4px; }
.delete-options button { width: 100%; }
.delete-options button[hidden] { display: none; }

/* Просмотр видео: элемент и панель управления */
#lightbox-video {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  max-width: 96vw;
  max-height: 82vh;
  border-radius: 8px;
  background: #000;
}
#lightbox-video[hidden] { display: none; }

#lb-controls {
  position: absolute;
  left: 12px;
  right: 12px;
  bottom: calc(14px + env(safe-area-inset-bottom, 0px));
  z-index: 5;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 16px;
  background: rgba(20, 20, 24, .82);
  color: #fff;
  backdrop-filter: blur(8px);
}
#lb-controls[hidden] { display: none; }
#lb-controls .icon-btn { color: #fff; flex-shrink: 0; }
.lbv-time { font-size: 12px; font-variant-numeric: tabular-nums; flex-shrink: 0; opacity: .85; }
/* Кнопка показывает противоположное текущему состоянию */
#lb-controls .lbv-play { display: none; }
#lb-controls.paused .lbv-play { display: block; }
#lb-controls.paused .lbv-pause { display: none; }

.lbv-range {
  flex: 1;
  min-width: 0;
  height: 4px;
  appearance: none;
  border-radius: 2px;
  background: rgba(255, 255, 255, .3);
  cursor: pointer;
}
.lbv-range::-webkit-slider-thumb {
  appearance: none;
  width: 13px;
  height: 13px;
  border-radius: 50%;
  background: #fff;
}
.lbv-range::-moz-range-thumb { width: 13px; height: 13px; border: none; border-radius: 50%; background: #fff; }
/* Громкость занимает фиксированную долю, чтобы перемотка оставалась длинной */
.lbv-vol { flex: 0 0 68px; }

.lbv-speed {
  flex-shrink: 0;
  min-width: 38px;
  padding: 3px 8px;
  border: 1px solid rgba(255, 255, 255, .3);
  border-radius: 9px;
  background: none;
  color: #fff;
  font-size: 12px;
  font-variant-numeric: tabular-nums;
  cursor: pointer;
}

/* На узком экране прячем громкость: там ей управляют кнопками устройства */
@media (max-width: 560px) {
  #lb-controls .lbv-vol { display: none; }
}

/* Поиск по сообщениям внутри чата */
#msg-search {
  border-bottom: 1px solid var(--border);
  background: var(--bg-panel);
  max-height: 46vh;
  display: flex;
  flex-direction: column;
}
#msg-search[hidden] { display: none; }
.msg-search-row { display: flex; align-items: center; gap: 8px; padding: 8px 12px; }
/* Размер иконке задаём здесь: класс .pin-icon получает его только внутри
   #reply-bar и #pinned-bar, а без размеров SVG растягивается на всю строку */
.msg-search-row .pin-icon { width: 18px; height: 18px; color: var(--text-dim); flex-shrink: 0; }
.msg-search-row .icon-btn { flex-shrink: 0; }
#msg-search-input {
  flex: 1;
  min-width: 0;
  padding: 8px 12px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 10px;
  outline: none;
  color: var(--text);
}
#msg-search-input:focus { border-color: var(--accent); }
#msg-search-results { overflow-y: auto; }

.msg-search-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
  width: 100%;
  padding: 9px 14px;
  border: none;
  background: none;
  color: var(--text);
  text-align: left;
  cursor: pointer;
  border-top: 1px solid var(--border);
}
.msg-search-item:active { background: var(--bg-hover); }
@media (hover: hover) { .msg-search-item:hover { background: var(--bg-hover); } }
.msg-search-item .ms-head { font-size: 12px; color: var(--text-dim); }
.msg-search-item .ms-text {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/* Совпадение подсвечиваем, а не выделяем жёлтым по умолчанию браузера */
.msg-search-item mark { background: transparent; color: var(--accent); font-weight: 600; }

/* Своё оформление видео: кадр, кнопка и длительность вместо системного плеера */
.video-wrap {
  position: relative;
  display: block;
  max-width: min(360px, 78vw);
  border-radius: 12px;
  overflow: hidden;
  background: #000;
  cursor: pointer;
}
.video-wrap video { display: block; width: 100%; height: 100%; object-fit: cover; }
/* Полоска прогресса под видео в ленте */
.video-bar {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 3px;
  background: rgba(255, 255, 255, .25);
  pointer-events: none;
}
.video-bar-fill { display: block; height: 100%; width: 0; background: #fff; }

.video-dur {
  position: absolute;
  left: 8px;
  top: 8px;
  padding: 2px 8px;
  border-radius: 10px;
  background: rgba(0, 0, 0, .55);
  color: #fff;
  font-size: 12px;
  font-variant-numeric: tabular-nums;
  pointer-events: none;
}
/* Видео без подписи живёт без пузыря — как кружок */
/* То же скругление, что у фото: видео не должно выделяться формой */
.msg.bare .video-wrap { border-radius: 5px; }

/* Пачка документов: список внутри одного блока вместо отдельных сообщений */
.msg.album.file-album .album-grid { display: flex; flex-direction: column; gap: 2px; }
.album-file {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 10px;
  border-radius: 10px;
  color: inherit;
  text-decoration: none;
  background: rgba(127, 127, 127, .12);
}
.album-file svg { width: 20px; height: 20px; flex-shrink: 0; color: var(--accent); }
.album-file .file-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.album-file .file-size { font-size: 12px; color: var(--msg-meta); flex-shrink: 0; }

/* Сворачивание раздела Медиа/Ссылки/Файлы свайпом вниз */
@keyframes shared-collapse {
  from { max-height: 38vh; opacity: 1; transform: translateY(0); }
  to   { max-height: 0; opacity: 0; transform: translateY(12px); }
}
#shared-panel.collapsing {
  overflow: hidden;
  animation: shared-collapse .24s ease-in forwards;
}
@media (prefers-reduced-motion: reduce) {
  #shared-panel.collapsing { animation-duration: .01s; }
}

/* Кольца громкости вокруг кнопки записи: два слоя, внешний инертнее.
   --lvl и --lvl-slow обновляет JS из анализатора звука (см. startLevelRings). */
#send-form.recording #send-btn::before,
#send-form.recording #send-btn::after {
  content: "";
  position: absolute;
  left: 50%;
  top: 50%;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: var(--accent);
  transform: translate(-50%, -50%) scale(calc(1 + var(--lvl, 0) * 0.55));
  opacity: calc(.28 - var(--lvl, 0) * .1);
  pointer-events: none;
  z-index: -1;
}
#send-form.recording #send-btn::after {
  transform: translate(-50%, -50%) scale(calc(1 + var(--lvl-slow, 0) * 0.95));
  opacity: calc(.16 - var(--lvl-slow, 0) * .05);
}
/* Кнопка — точка отсчёта для колец, а сами кольца уходят под неё */
#send-btn { position: relative; isolation: isolate; }

/* Панель управления прослушиванием — висит под шапкой чата */
#play-bar {
  position: absolute;
  left: 10px;
  right: 10px;
  top: calc(10px + env(safe-area-inset-top, 0px));
  z-index: 60;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 7px 10px;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 22px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, .3);
}
#play-bar[hidden] { display: none; }
#play-bar .pb-info { flex: 1; min-width: 0; display: flex; flex-direction: column; line-height: 1.25; }
#play-bar #pb-title {
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
#play-bar .pb-time { font-size: 11px; color: var(--text-dim); font-variant-numeric: tabular-nums; }
/* Кнопка показывает либо паузу, либо продолжение — смотря что идёт сейчас */
#play-bar .pb-play { display: none; }
#play-bar.paused .pb-play { display: block; }
#play-bar.paused .pb-pause { display: none; }
#play-bar #pb-toggle { color: var(--accent); }

.pb-speed {
  flex-shrink: 0;
  min-width: 40px;
  padding: 4px 8px;
  border: 1px solid var(--border);
  border-radius: 10px;
  background: var(--bg-input);
  color: var(--text);
  font-size: 12px;
  font-variant-numeric: tabular-nums;
  cursor: pointer;
}

/* Переворот камеры в кружке: поворот вокруг вертикальной оси.
   Пока идёт поворот, JS подставляет на canvas размытый последний кадр —
   иначе на Android секунду видна чернота от переключения камеры. */
/* Полуоборот, а не полный круг: камера буквально показывает другую сторону.
   scaleX(-1) в конце компенсирует зеркальность разворота — итоговый кадр
   выглядит как обычный, поэтому после снятия класса нет рывка обратно. */
@keyframes circle-flip {
  from { transform: perspective(700px) rotateY(0deg); }
  to   { transform: perspective(700px) rotateY(180deg) scaleX(-1); }
}
#circle-overlay.flipping canvas {
  animation: circle-flip .42s cubic-bezier(.4, 0, .2, 1);
}
@media (prefers-reduced-motion: reduce) {
  #circle-overlay.flipping canvas { animation: none; }
}

/* ---------- Настройки оформления: акцент и фон чата ---------- */

.swatches { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 4px; }

.swatch {
  width: 34px;
  height: 34px;
  border-radius: 50%;
  border: 2px solid transparent;
  cursor: pointer;
  padding: 0;
  position: relative;
}
/* Выбранный обводим кольцом цвета фона + внешним контуром самого цвета */
.swatch.active {
  border-color: var(--bg-panel);
  box-shadow: 0 0 0 2px currentColor;
  color: var(--text-dim);
}

.wallpapers {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(84px, 1fr));
  gap: 10px;
}

.wp {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  padding: 0;
  background: none;
  border: none;
  color: var(--text-dim);
  font-size: 12px;
  cursor: pointer;
}
.wp-preview {
  width: 100%;
  aspect-ratio: 3 / 4;
  border-radius: 10px;
  border: 2px solid var(--border);
  background: var(--bg);
  background-size: cover;
  background-position: center;
}
.wp.active .wp-preview { border-color: var(--accent); }
.wp.active .wp-name { color: var(--accent); }

/* Картиночные фоны (лапки, кролики): повторяются плиткой, поэтому размер задаём
   фиксированный — иначе на широком экране рисунок растянется и станет мыльным.
   Сам URL подставляет JS, так как у каждого фона две версии: тёмная и светлая. */
#messages[data-wallpaper="paws"],
#messages[data-wallpaper="rabbits"] {
  background-repeat: repeat;
  background-size: 420px;
}
.wp-preview[data-wp-preview="paws"],
.wp-preview[data-wp-preview="rabbits"] {
  background-repeat: repeat;
  background-size: 120px;
}

/* Фоны чата. Узор и градиент нарисованы средствами CSS — они не зависят от
   загрузки картинок и одинаково выглядят на любом экране. */
#messages[data-wallpaper="pattern"],
.wp-preview[data-wp-preview="pattern"] {
  background-image:
    radial-gradient(circle at 25% 25%, color-mix(in srgb, var(--accent) 14%, transparent) 0 2px, transparent 2px),
    radial-gradient(circle at 75% 75%, color-mix(in srgb, var(--accent) 10%, transparent) 0 2px, transparent 2px);
  background-size: 26px 26px;
}
#messages[data-wallpaper="gradient"],
.wp-preview[data-wp-preview="gradient"] {
  background-image: linear-gradient(160deg,
    color-mix(in srgb, var(--accent) 16%, transparent),
    transparent 55%,
    color-mix(in srgb, var(--accent) 10%, transparent));
  background-attachment: local;
}

/* «Избранное»: вместо своей аватарки — закладка на фирменном фоне */
.avatar .saved-icon {
  width: 22px;
  height: 22px;
  color: #fff;
}
.chat-item.saved .avatar,
#chat-avatar:has(.saved-icon) {
  background: var(--accent);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Длительность и точка «не прослушано» стоят рядом */
.voice-meta { display: flex; align-items: center; gap: 6px; }

/* Время отправки и галочки у голосового — к правому краю пузыря.
   Селектор с .msg обязателен: правило `.msg .msg-time` ниже по файлу имеет тот
   же вес и иначе возвращает display:inline-block, из-за чего время липнет влево. */
.msg .voice-msg + .msg-time {
  display: block;
  text-align: right;
  margin-left: 0;
}

/* Плашка кружка: длительность и точка непрослушанного, как в телеграме */
.circle-meta {
  position: absolute;
  left: 10px;
  bottom: 10px;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 3px 9px;
  border-radius: 12px;
  background: rgba(0, 0, 0, .45);
  color: #fff;
  font-size: 12px;
  font-variant-numeric: tabular-nums;
  pointer-events: none;
  z-index: 2;
}
/* На тёмной плашке точка должна читаться и в светлой теме */
.circle-meta .played-dot { background: #fff; }

/* Объявление о переезде на новый домен (поверх всего, сверху экрана) */
#moved-notice {
  position: fixed;
  left: 12px;
  right: 12px;
  top: calc(12px + env(safe-area-inset-top, 0px));
  z-index: 300;
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px 16px;
  background: var(--bg-panel);
  border: 1px solid var(--accent);
  border-radius: 14px;
  box-shadow: 0 12px 34px rgba(0, 0, 0, .32);
}
#moved-notice[hidden] { display: none; }
#moved-notice .moved-text { flex: 1; min-width: 0; }
#moved-notice b { font-size: 15px; }
#moved-notice p { margin-top: 4px; font-size: 13px; line-height: 1.45; color: var(--text-dim); }
#moved-notice .moved-actions { display: flex; flex-direction: column; gap: 8px; flex-shrink: 0; }
#moved-notice .moved-go { text-align: center; text-decoration: none; }

@media (max-width: 560px) {
  #moved-notice { flex-direction: column; align-items: stretch; }
  #moved-notice .moved-actions { flex-direction: row; }
  #moved-notice .moved-actions > * { flex: 1; }
}

/* Уведомление об используемом локальном хранилище (внизу экрана) */
#storage-notice {
  position: fixed;
  left: 12px;
  right: 12px;
  bottom: calc(12px + env(safe-area-inset-bottom, 0px));
  z-index: 200;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 14px;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 14px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, .28);
}
#storage-notice[hidden] { display: none; }
#storage-notice p { font-size: 13px; line-height: 1.45; color: var(--text-dim); }
#storage-notice a { color: var(--accent); }
#storage-notice button { flex-shrink: 0; align-self: flex-end; }

@media (max-width: 520px) {
  #storage-notice { flex-direction: column; align-items: stretch; }
  #storage-notice button { align-self: stretch; }
}

.settings-docs { text-align: center; font-size: 12px; color: var(--text-dim); margin: 4px 0 12px; }
.settings-docs a { color: var(--text-dim); text-decoration: none; }
.settings-docs a:hover { text-decoration: underline; color: var(--accent); }

.auth-form input, #profile-form input {
  padding: 11px 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  outline: none;
}

.auth-form input:focus, #profile-form input:focus { border-color: var(--accent); }

.hint { color: var(--text-dim); font-size: 14px; text-align: center; line-height: 1.5; }

.error {
  margin-top: 12px;
  padding: 10px;
  background: rgba(224, 85, 85, .12);
  border: 1px solid var(--danger);
  border-radius: 8px;
  color: #ff9b9b;
  font-size: 14px;
  text-align: center;
}

/* ---------- Кнопки ---------- */

.btn-primary {
  padding: 11px 18px;
  background: var(--accent);
  border: none;
  border-radius: 8px;
  color: #fff;
  cursor: pointer;
}

.btn-primary:hover { background: var(--accent-hover); }

.btn-secondary {
  padding: 10px 16px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  cursor: pointer;
  text-align: center;
}

.btn-secondary:hover { background: var(--bg-hover); }

.btn-danger {
  padding: 10px 16px;
  background: transparent;
  border: 1px solid var(--danger);
  border-radius: 8px;
  color: var(--danger);
  cursor: pointer;
}

.icon-btn {
  background: none;
  border: none;
  color: var(--text-dim);
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-btn:hover { background: var(--bg-hover); color: var(--text); }

.icon-btn svg { width: 20px; height: 20px; display: block; }

/* Кнопка с бейджем-счётчиком (заявки в друзья) */
.badge-btn { position: relative; }

.nav-badge {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 18px;
  height: 18px;
  padding: 0 5px;
  border-radius: 9px;
  background: var(--danger);
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid var(--bg-panel);
}

.nav-badge[hidden] { display: none; }

/* ---------- Основной экран ---------- */

/* Как и #auth-screen: inset:0 + height:auto растягивает до низа экрана без JS;
   --app-h (клавиатура) при наличии перебивает и работает как высота. */
#main-screen {
  display: flex;
  position: absolute;
  inset: 0;
  height: var(--app-h, auto);
}
#main-screen[hidden] { display: none; }

#sidebar {
  width: 320px;
  min-width: 320px;
  background: var(--bg-panel);
  border-right: 1px solid var(--border);
  display: flex;
  flex-direction: column;
}

/* Шапка приложения: название и статус соединения.
   По тапу на лупу плавно превращается в поисковую строку */
#app-header {
  position: relative;
  padding: calc(10px + env(safe-area-inset-top, 0px)) 12px 10px;
  border-bottom: 1px solid var(--border);
}

.header-main {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 40px;
  position: relative;
  transition: opacity .22s ease, transform .22s ease;
}

#app-status {
  font-weight: 700;
  font-size: 17px;
  letter-spacing: .2px;
}

#search-open {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

/* Поисковая пилюля поверх шапки; появляется с лёгким выездом сверху */
.header-search {
  position: absolute;
  left: 12px;
  right: 12px;
  top: calc(10px + env(safe-area-inset-top, 0px));
  height: 40px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 4px 0 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 20px;
  opacity: 0;
  transform: translateY(-10px) scale(.97);
  pointer-events: none;
  transition: opacity .22s ease, transform .22s ease;
}

#app-header.searching .header-search {
  opacity: 1;
  transform: translateY(0) scale(1);
  pointer-events: auto;
}

#app-header.searching .header-main {
  opacity: 0;
  transform: translateY(8px);
  pointer-events: none;
}

.hs-icon {
  width: 18px;
  height: 18px;
  color: var(--text-dim);
  flex-shrink: 0;
}

.header-search input {
  flex: 1;
  min-width: 0;
  background: none;
  border: none;
  outline: none;
  font-size: 16px;
  color: var(--text);
}

/* Табы разделов: Чаты | Каналы */
#nav-tabs {
  display: flex;
  border-top: 1px solid var(--border);
}

#nav-tabs button {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 3px;
  padding: 8px 0 6px;
  background: none;
  border: none;
  color: var(--text-dim);
  cursor: pointer;
  font-size: 12px;
}

#nav-tabs button svg { width: 21px; height: 21px; }
#nav-tabs button.active { color: var(--accent); }

#channel-list { flex: 1; overflow-y: auto; }
#channel-list[hidden] { display: none; }
#chat-list[hidden] { display: none; }

.channel-id-badge {
  font-size: 12px;
  color: var(--text-dim);
  background: var(--bg-input);
  border-radius: 8px;
  padding: 2px 8px;
}

/* Экран канала */
#channel-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

#channel-view[hidden] { display: none; }

#channel-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: calc(10px + env(safe-area-inset-top, 0px)) 16px 10px;
  background: var(--bg-panel);
  border-bottom: 1px solid var(--border);
}

#channel-back { display: none; }

#room-list { flex: 1; overflow-y: auto; padding: 10px 12px; }

.room-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  border-radius: 10px;
  cursor: pointer;
}

@media (hover: hover) {
  .room-item:hover { background: var(--bg-hover); }
}

.room-item:active { background: var(--bg-hover); }
.room-item svg { width: 18px; height: 18px; color: var(--text-dim); flex-shrink: 0; }
.room-item .name { flex: 1; font-weight: 500; }
.room-item .btn-mini { flex-shrink: 0; }

/* Гость видит комнаты, но они заблокированы (замок) */
.room-item.locked { opacity: .55; }
.room-item.locked:active { background: transparent; }
.room-item .room-lock { width: 16px; height: 16px; color: var(--text-dim); flex-shrink: 0; }
#channel-join-btn.nudge { animation: nudge .45s ease; }
@keyframes nudge {
  0%, 100% { transform: none; }
  30% { transform: scale(1.05); }
  60% { transform: scale(.98); }
}

.room-users {
  /* верхний отступ, чтобы кольцо речи вокруг аватарки не наезжало на подсветку комнаты */
  padding: 4px 12px 6px 40px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.room-user {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--text-dim);
}

.room-user .avatar {
  width: 26px;
  height: 26px;
  min-width: 26px;
  font-size: 11px;
  box-shadow: 0 0 0 0 rgba(62, 207, 106, 0);
  transition: box-shadow .12s;
}

/* Зелёное кольцо, когда участник говорит */
.room-user.speaking .avatar { box-shadow: 0 0 0 2px var(--online); }

.room-user .mic-off {
  width: 15px;
  height: 15px;
  color: var(--danger);
  flex-shrink: 0;
}

.channel-actions {
  display: flex;
  gap: 10px;
  padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px));
  border-top: 1px solid var(--border);
  background: var(--bg-panel);
}

.channel-actions button { flex: 1; }

/* Плавающая панель голосового подключения */
#voice-bar {
  position: fixed;
  left: 50%;
  bottom: calc(90px + env(safe-area-inset-bottom, 0px));
  transform: translateX(-50%) translateY(16px);
  z-index: 80;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 10px 8px 16px;
  background: var(--bg-panel);
  border: 1px solid var(--accent);
  border-radius: 26px;
  box-shadow: 0 8px 28px rgba(0, 0, 0, .35);
  max-width: calc(100vw - 24px);
  /* Плашка видна только когда открыт канал своей голосовой; иначе плавно
     сворачивается в иконку в шапке (см. .voice-mini) */
  opacity: 0;
  pointer-events: none;
  transition: opacity .22s ease, transform .22s ease;
}

body.in-voice:not(.voice-collapsed) #voice-bar {
  opacity: 1;
  pointer-events: auto;
  transform: translateX(-50%) translateY(0);
}

.vb-icon { width: 18px; height: 18px; color: var(--online); flex-shrink: 0; }

/* Свёрнутая голосовая: маленькая иконка в шапке */
.voice-mini {
  display: none;
  align-items: center;
  gap: 5px;
  padding: 4px 9px 4px 7px;
  border: 1px solid var(--accent);
  border-radius: 16px;
  background: color-mix(in srgb, var(--accent) 16%, transparent);
  color: var(--accent);
  cursor: pointer;
  animation: vm-in .22s ease;
}
.voice-mini svg { width: 17px; height: 17px; }
.vm-dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: var(--online);
  animation: vm-pulse 1.4s ease-in-out infinite;
}
@keyframes vm-in { from { opacity: 0; transform: scale(.7); } to { opacity: 1; transform: scale(1); } }
@keyframes vm-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }

/* Иконка в шапке-сайдбаре: слева, «LapChat» остаётся по центру */
#voice-mini { position: absolute; left: 0; top: 50%; transform: translateY(-50%); }
body.voice-collapsed #voice-mini { display: inline-flex; }

/* Иконки в шапках чата/канала — только на телефоне (в сайдбар не видно) */
.vm-hdr { flex-shrink: 0; }
@media (max-width: 700px) {
  body.voice-collapsed .vm-hdr { display: inline-flex; }
}

#voice-bar-label {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 40vw;
}

#voice-bar .icon-btn.danger { color: var(--danger); }
#voice-mute-btn.muted { color: var(--danger); }
#voice-mute-btn svg[data-v="off"] { display: none; }
#voice-mute-btn.muted svg[data-v="off"] { display: block; }
#voice-mute-btn.muted svg[data-v="on"] { display: none; }
#voice-deafen-btn.muted { color: var(--danger); }
#voice-deafen-btn svg[data-v="off"] { display: none; }
#voice-deafen-btn.muted svg[data-v="off"] { display: block; }
#voice-deafen-btn.muted svg[data-v="on"] { display: none; }
#voice-screen-btn.active,
#voice-cam-btn.active { color: var(--online); }
/* Кнопку камеры на телефоне НЕ прячем (в отличие от демонстрации экрана):
   камера там как раз есть, и это основной сценарий */

/* ---------- Демонстрация экрана ---------- */
/* Боковая панель на компьютере */
#screen-view {
  position: fixed;
  top: calc(64px + env(safe-area-inset-top, 0px));
  right: 12px;
  z-index: 79;
  width: min(360px, 32vw);
  max-height: calc(100vh - 180px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 12px;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 16px;
  box-shadow: 0 12px 34px rgba(0, 0, 0, .5);
}
#screen-view[hidden] { display: none; }

.screen-panel-head {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  font-weight: 700;
  color: var(--text-muted);
}
.screen-panel-head svg { width: 16px; height: 16px; color: var(--online); }

.screen-tile {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  background: #000;
  border: 1px solid var(--border);
}
.screen-tile video {
  display: block;
  width: 100%;
  height: auto;
  max-height: 40vh;
  object-fit: contain;
  background: #000;
}
.screen-label {
  position: absolute;
  left: 0;
  bottom: 0;
  max-width: 70%;
  padding: 9px 12px 5px;
  font-size: 12px;
  font-weight: 600;
  color: #fff;
  background: linear-gradient(transparent, rgba(0, 0, 0, .7));
  pointer-events: none;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.screen-acts {
  position: absolute;
  top: 6px;
  right: 6px;
  display: flex;
  gap: 6px;
}
.screen-acts .icon-btn {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: rgba(0, 0, 0, .55);
  color: #fff;
}
.screen-acts .icon-btn.danger { color: var(--danger); }
.screen-acts .icon-btn svg { width: 16px; height: 16px; }

/* Иконка демонстрации у участника в списке голосовой */
.room-screen {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  margin-left: auto;
  border-radius: 8px;
  color: var(--online);
  background: color-mix(in srgb, var(--online) 18%, transparent);
}
.room-screen svg { width: 16px; height: 16px; }

/* Полноэкранный просмотр демонстрации */
#screen-fs {
  position: fixed;
  inset: 0;
  z-index: 250;
  background: rgba(0, 0, 0, .94);
  display: flex;
  align-items: center;
  justify-content: center;
}
#screen-fs[hidden] { display: none; }
#screen-fs video {
  max-width: 100vw;
  max-height: 100vh;
  width: auto;
  height: auto;
  object-fit: contain;
}
.screen-fs-label {
  position: absolute;
  top: calc(12px + env(safe-area-inset-top, 0px));
  left: 16px;
  font-size: 14px;
  font-weight: 700;
  color: #fff;
  text-shadow: 0 1px 4px rgba(0, 0, 0, .8);
}
.screen-fs-close {
  position: absolute;
  top: calc(12px + env(safe-area-inset-top, 0px));
  right: 16px;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 9px 16px;
  border-radius: 22px;
  background: rgba(255, 255, 255, .14);
  color: #fff;
  font-size: 14px;
  font-weight: 600;
}
.screen-fs-close svg { width: 18px; height: 18px; }

.screen-sound.on { color: var(--online); }
.screen-fs-sound {
  position: absolute;
  bottom: calc(22px + env(safe-area-inset-bottom, 0px));
  left: 50%;
  transform: translateX(-50%);
  width: auto;
  height: auto;
  padding: 11px 20px;
  border-radius: 24px;
  background: rgba(255, 255, 255, .16);
  color: #fff;
  display: flex;
  align-items: center;
  gap: 8px;
}
.screen-fs-sound.on { color: #fff; background: var(--accent); }
.screen-fs-sound svg { width: 20px; height: 20px; }

.modal-input {
  width: 100%;
  padding: 11px 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  outline: none;
  color: var(--text);
  margin-bottom: 12px;
}

.modal-input:focus { border-color: var(--accent); }

/* Панель профиля и действий — прижата к низу сайдбара */
#me-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px calc(10px + env(safe-area-inset-bottom, 0px));
  border-top: 1px solid var(--border);
  background: var(--bg-panel);
}

.me-info { flex: 1; min-width: 0; }

/* Кликабельная плашка пользователя (в сайдбаре и шапке чата) */
.user-chip {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
  cursor: pointer;
  border-radius: 10px;
  padding: 4px 6px;
  margin: -4px 0 -4px -6px;
}

.user-chip:hover { background: var(--bg-hover); }
/* Шапка «Избранного» никуда не ведёт — не притворяемся кнопкой */
.user-chip.chip-inert { cursor: default; }
.user-chip.chip-inert:hover { background: none; }
.name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.nickname { color: var(--text-dim); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

/* Полоска «обновление готово» — как приглашение включить уведомления,
   но зелёная: это не просьба разрешить, а хорошая новость */
#update-bar {
  margin: 10px 12px 0;
  padding: 10px;
  background: var(--bg-input);
  border: 1px solid var(--online);
  border-radius: 8px;
  color: var(--online);
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
#update-bar svg { width: 16px; height: 16px; flex-shrink: 0; }

#notify-bar {
  margin: 10px 12px 0;
  padding: 10px;
  background: var(--bg-input);
  border: 1px solid var(--accent);
  border-radius: 8px;
  color: var(--accent);
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

#notify-bar[hidden] { display: none; }

#notify-bar svg { width: 18px; height: 18px; flex-shrink: 0; }

#notify-bar:hover { background: var(--bg-hover); }

/* Список найденных может быть длиннее экрана — он должен прокручиваться сам.
   Без своей прокрутки он просто упирался в низ сайдбара и обрезался. */
/* Поиск ищет по нику среди всех людей, а не среди открытых чатов, поэтому
   на время поиска списки убираем: иначе под результатами тянется длинный
   список, к запросу отношения не имеющий. */
#search-results:not([hidden]) ~ #chat-list,
#search-results:not([hidden]) ~ #channel-list { display: none; }

#search-results {
  border-bottom: 1px solid var(--border);
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  overscroll-behavior: contain;
}

/* Кнопки в профиле: «Написать» ведущая, остальные рядом и не жмутся */
/* Кнопки профиля: ведущая во всю ширину, остальные делят строку поровну.
   Оба класса в селекторе намеренно: правило .modal-buttons объявлено ниже и
   с одиночным классом перебивало бы эту раскладку обратно на flex. */
.modal-buttons.peer-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-top: 16px;
}
.modal-buttons.peer-buttons button { width: 100%; }
.modal-buttons.peer-buttons #peer-write-btn { grid-column: 1 / -1; }

.search-title { padding: 6px 14px; font-size: 12px; color: var(--text-dim); text-transform: uppercase; }

#chat-list { flex: 1; overflow-y: auto; }

.chat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  cursor: pointer;
}

.chat-item:hover { background: var(--bg-hover); }
.chat-item.active { background: var(--bg-active); }

.chat-item .preview { color: var(--text-dim); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.chat-item-right { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; }
.chat-time { font-size: 12px; color: var(--text-dim); }

.unread-badge {
  background: var(--accent);
  color: #fff;
  font-size: 12px;
  min-width: 20px;
  height: 20px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6px;
}

/* ---------- Аватарки ---------- */

.avatar {
  width: 42px;
  height: 42px;
  min-width: 42px;
  border-radius: 50%;
  background: var(--accent);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 18px;
  color: #fff;
  position: relative;
}

.avatar img { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; display: block; }

.avatar-big { width: 80px; height: 80px; min-width: 80px; font-size: 32px; }

.avatar .online-dot {
  position: absolute;
  bottom: 1px;
  right: 1px;
  width: 11px;
  height: 11px;
  border-radius: 50%;
  background: var(--online);
  border: 2px solid var(--bg-panel);
}

/* ---------- Окно чата ---------- */

#chat-area { flex: 1; display: flex; flex-direction: column; min-width: 0; }

#chat-empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: var(--text-dim);
}

#chat-empty[hidden], #chat-view[hidden] { display: none; }

.empty-icon { width: 56px; height: 56px; color: var(--text-dim); }

/* position: relative — якорь для панели воспроизведения, висящей поверх ленты */
#chat-view { flex: 1; display: flex; flex-direction: column; min-height: 0; position: relative; }

#chat-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: calc(10px + env(safe-area-inset-top, 0px)) 16px 10px;
  background: var(--bg-panel);
  border-bottom: 1px solid var(--border);
}

#back-btn { display: none; }
/* В комнате канала стрелка «назад к комнатам» видна и на десктопе */
#chat-view.show-back #back-btn { display: flex; }

/* ---------- Режим выделения сообщений ---------- */
#selection-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: calc(10px + env(safe-area-inset-top, 0px)) 12px 10px;
  background: var(--bg-panel);
  border-bottom: 1px solid var(--border);
}
#selection-bar[hidden] { display: none; }
#sel-count { flex: 1; font-weight: 600; font-size: 15px; }
.sel-tools { display: flex; gap: 4px; }

#selection-actions {
  display: flex;
  gap: 10px;
  padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px));
  background: var(--bg-panel);
  border-top: 1px solid var(--border);
}
#selection-actions[hidden] { display: none; }
#selection-actions .btn-secondary {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
#selection-actions svg { width: 18px; height: 18px; }

/* В режиме выделения прячем обычную шапку/поле ввода/историю */
body.selecting #chat-header,
body.selecting #send-form,
body.selecting #shared-bar,
body.selecting #reply-bar,
body.selecting #pinned-bar { display: none; }

/* Выделенное сообщение */
/* Выделение: обводку прочерчивает SVG (см. addSelectOutline), поэтому рамкой
   пузырь не обводим — иначе линия задваивалась бы. */
.msg.selected { position: relative; }

.sel-outline {
  position: absolute;
  left: 0;
  top: 0;
  pointer-events: none;
  overflow: visible;
  /* Ниже содержимого пузыря: иначе линия перекрывала плашку с длительностью
     кружка. Значение 0 всё ещё поднимает её над самим видео. */
  z-index: 0;
}
.sel-outline path {
  fill: none;
  stroke: var(--accent);
  stroke-width: 2;
  stroke-linecap: round;
  /* dash 100 + gap 100 при pathLength=100: смещение 100 прячет линию целиком,
     50 — открывает ровно половину пути, то есть каждый путь чертит свою сторону */
  stroke-dasharray: 100;
  stroke-dashoffset: 100;
  animation: sel-draw .34s ease-out forwards;
}
@keyframes sel-draw { to { stroke-dashoffset: 50; } }

@media (prefers-reduced-motion: reduce) {
  .sel-outline path { animation: none; stroke-dashoffset: 50; }
}
body.selecting #messages .msg { cursor: pointer; }
body.selecting .msg-row.selected,
body.selecting #messages .msg.selected { }

#chat-status.online { color: var(--online); }

#messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  overscroll-behavior: contain;      /* скролл чата не дёргает страницу */
  -webkit-overflow-scrolling: touch; /* плавная инерция на iOS */
}

/* Отступы между сообщениями: обычный — 6px, между подряд идущими
   от одного отправителя — вдвое меньше */
#messages > .msg,
#messages > .msg-row { margin-top: 6px; }

#messages > .msg.compact,
#messages > .msg-row.compact { margin-top: 3px; }

/* Распорка сверху: пока сообщений мало, они прижаты к низу, как в Telegram */
#messages::before {
  content: "";
  flex: 1 0 0;
}

.msg {
  max-width: 65%;
  padding: 8px 12px;
  border-radius: 14px;
  line-height: 1.4;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.msg.in { background: var(--bubble-in); align-self: flex-start; border-bottom-left-radius: 4px; }
.msg.out { background: var(--bubble-out); align-self: flex-end; border-bottom-right-radius: 4px; }

/* Кликабельные ссылки в сообщениях */
.msg-link { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; word-break: break-all; }
.msg.out .msg-link { color: #fff; }

.friend-row.clickable { cursor: pointer; }

/* Раздел приватности */
.priv-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}
.priv-row > span { font-size: 14px; flex: 1; min-width: 0; }
.priv-dd {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 10px 8px 12px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  color: var(--text);
  font: inherit;
  font-size: 14px;
  cursor: pointer;
}
.priv-dd:active { background: var(--bg-hover); }
.priv-dd > svg { width: 14px; height: 14px; color: var(--text-dim); transform: rotate(-90deg); }

#priv-menu {
  position: fixed;
  margin: 0;
  padding: 5px;
  width: auto;
  min-width: 190px;
  max-width: 220px;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, .4);
}
#priv-menu::backdrop { background: transparent; }
#priv-menu button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  width: 100%;
  padding: 10px 12px;
  background: none;
  border: none;
  border-radius: 8px;
  color: var(--text);
  font-size: 15px;
  text-align: left;
  cursor: pointer;
}
#priv-menu button:hover { background: var(--bg-hover); }
#priv-menu button.sel { color: var(--accent); }
#priv-menu .pm-check { width: 16px; height: 16px; color: var(--accent); }

/* Кнопка «Пригласить в канал» в настройках канала */
/* Кнопки в настройках канала и беседы: одиночные — во всю ширину, парные —
   поровну пополам. Прижатые вправо кнопки разной ширины выглядели случайными. */
#channel-settings-modal .modal-buttons,
#group-info-modal .modal-buttons {
  display: flex;
  gap: 10px;
  margin-top: 12px;
  margin-bottom: 12px;
}
#channel-settings-modal .modal-buttons > button,
#group-info-modal .modal-buttons > button {
  flex: 1;              /* поровну между собой */
  margin-right: 0;      /* сбрасываем прижатие .btn-danger влево */
}
/* Скрытая кнопка не должна забирать половину ширины у видимой */
#channel-settings-modal .modal-buttons > button[hidden],
#group-info-modal .modal-buttons > button[hidden] { display: none; }

.cs-invite-btn { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; margin-bottom: 16px; }
.cs-invite-btn svg { width: 18px; height: 18px; }

/* Карточка-приглашение в канал */
.msg.invite-card {
  background: var(--bubble-in);
  color: var(--text);
  max-width: min(320px, 82%);
  display: flex;
  flex-direction: column;
  gap: 9px;
}
.msg.invite-card.out { align-self: flex-end; }
.msg.invite-card.in { align-self: flex-start; }
.invite-head { display: flex; align-items: center; gap: 10px; }
.invite-av { width: 44px; height: 44px; min-width: 44px; font-size: 18px; }
.invite-meta { min-width: 0; }
.invite-label { font-size: 12px; color: var(--text-dim); }
.invite-name { font-weight: 600; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.invite-count { font-size: 12px; color: var(--text-dim); }
.invite-join { width: 100%; padding: 9px; }
.invite-joined {
  text-align: center;
  padding: 9px;
  font-size: 14px;
  color: var(--text-dim);
  background: var(--bg-input);
  border-radius: 8px;
}
.invite-card .msg-time { align-self: flex-end; }

.msg .msg-time {
  display: inline-block;
  font-size: 11px;
  color: var(--msg-meta);
  margin-left: 8px;
  vertical-align: bottom;
}

/* Галочки прочтения на своих сообщениях */
.msg-time svg.tick {
  width: 15px;
  height: 15px;
  margin-left: 3px;
  vertical-align: -4px;
  color: var(--msg-meta);
}

svg.tick[data-read="1"] { color: var(--tick-read); }

#send-form {
  display: flex;
  gap: 10px;
  padding: 12px 16px;
  background: var(--bg-panel);
  border-top: 1px solid var(--border);
  position: relative; /* якорь для центрирования «Отмены» при записи */
}
/* Композер — нижняя панель только когда вкладок Медиа/Ссылки/Файлы нет
   (комнаты канала). Тогда он сам закрывает нижнюю safe-area iPhone. */
#send-form:has(~ #shared-bar[hidden]) {
  padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px));
}

/* Вкладки истории отправленного (под полем ввода). */
#shared-bar {
  display: flex;
  background: var(--bg-panel);
  border-top: 1px solid var(--border);
  padding: 0 8px;
}
/* Когда панель под вкладками закрыта — вкладки становятся нижней панелью и сами
   продлевают фон в зону home-indicator. Когда открыта — safe-area у панели,
   а тут его быть не должно (иначе пустая полоса между вкладками и панелью). */
#shared-bar:has(~ #shared-panel[hidden]) {
  padding-bottom: env(safe-area-inset-bottom, 0px);
}
#shared-bar[hidden] { display: none; }

/* На телефоне при открытой клавиатуре прячем вкладки, чтобы не мешали */
@media (max-width: 700px) {
  body.kb-open #shared-bar,
  body.kb-open #shared-panel { display: none; }
}

/* Во время записи голосового/кружка вкладки недоступны */
#send-form.recording ~ #shared-bar { opacity: .4; pointer-events: none; }

.shared-tab {
  flex: 1;
  background: none;
  border: none;
  border-top: 2px solid transparent;
  color: var(--text-dim);
  padding: 9px 6px;
  cursor: pointer;
  font-size: 13px;
}

.shared-tab:hover { color: var(--text); }
.shared-tab.active { color: var(--accent); border-top-color: var(--accent); }

#shared-panel {
  max-height: 38vh;
  overflow-y: auto;
  background: var(--bg-panel);
  border-top: 1px solid var(--border);
  padding: 10px 12px calc(10px + env(safe-area-inset-bottom, 0px));
}

#shared-panel[hidden] { display: none; }

/* Подвкладки внутри «Медиа»: Фото / Видео */
.media-subtabs {
  display: flex;
  gap: 4px;
  margin-bottom: 10px;
  border-bottom: 1px solid var(--border);
}

.media-subtab {
  flex: 1;
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  color: var(--text-dim);
  padding: 8px 6px;
  margin-bottom: -1px;
  cursor: pointer;
  font-size: 14px;
}

.media-subtab:hover { color: var(--text); }
.media-subtab.active { color: var(--accent); border-bottom-color: var(--accent); }

.shared-media-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));
  gap: 4px;
}

.shared-media-grid img,
.shared-media-grid video {
  width: 100%;
  aspect-ratio: 1;
  object-fit: cover;
  border-radius: 6px;
  display: block;
}

.shared-link {
  display: block;
  padding: 9px 4px;
  color: var(--accent);
  text-decoration: none;
  border-bottom: 1px solid var(--border);
  word-break: break-all;
  font-size: 14px;
}

.shared-link:last-child { border-bottom: none; }
.shared-link:hover { text-decoration: underline; }

.shared-empty {
  color: var(--text-dim);
  text-align: center;
  padding: 18px;
  font-size: 14px;
}

#msg-input {
  flex: 1;
  padding: 11px 16px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 22px;
  outline: none;
  font-size: 16px; /* iOS не зумит поля с 16px+ */
  line-height: 1.35;
  min-height: 44px;
  max-height: 120px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
}

#msg-input:empty::before {
  content: attr(data-placeholder);
  color: var(--text-dim);
  pointer-events: none;
}

#msg-input:focus { border-color: var(--accent); }

#send-form .btn-primary {
  border-radius: 50%;
  width: 44px;
  height: 44px;
  min-width: 44px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Иконки кнопки лежат стопкой по центру; активная всплывает с поворотом */
#send-btn { touch-action: none; position: relative; } /* свайп вверх не должен скроллить */

#send-btn svg {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 20px;
  height: 20px;
  margin: -10px 0 0 -10px;
  opacity: 0;
  transform: scale(.3) rotate(-100deg);
  transition: transform .2s ease, opacity .2s ease;
  pointer-events: none;
}

#send-btn svg.active {
  opacity: 1;
  transform: scale(1) rotate(0deg);
}

/* «Хлопок» кнопки в момент старта записи */
@keyframes recpop {
  0% { transform: scale(1); }
  45% { transform: scale(1.35); }
  100% { transform: scale(1); }
}

#send-btn.rec-pop { animation: recpop .32s ease; }

.attach-btn { align-self: center; }

/* Панель записи голосового/кружка */
#send-form.recording .attach-btn,
#send-form.recording #msg-input { display: none; }

#record-bar {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 0 6px;
  min-width: 0;
}

#record-bar[hidden] { display: none; }

/* Панель записи плавно выезжает при появлении */
@keyframes rec-slidein {
  from { opacity: 0; transform: translateY(8px); }
  to { opacity: 1; transform: translateY(0); }
}

#record-bar:not([hidden]) { animation: rec-slidein .22s ease; }

/* «Отмена» по центру всей строки ввода (якорь — #send-form),
   а не панели записи, которую справа поджимают кнопки */
#record-bar .link-btn {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
}

.rec-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: var(--danger);
  flex-shrink: 0;
  animation: recblink 1s infinite;
}

@keyframes recblink { 50% { opacity: .15; } }

#record-time {
  min-width: 44px;
  font-variant-numeric: tabular-nums;
}

#record-bar .link-btn { font-size: 15px; }

/* Живое превью кружка при записи — крупно и по центру экрана */
#circle-overlay {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 60;
}

#circle-overlay[hidden] { display: none; }

/* Превью кружка «выпрыгивает» при старте записи */
@keyframes circle-popin {
  from { transform: translate(-50%, -50%) scale(.45); opacity: 0; }
  to { transform: translate(-50%, -50%) scale(1); opacity: 1; }
}

#circle-overlay:not([hidden]) { animation: circle-popin .28s cubic-bezier(.2, 1.4, .4, 1); }

#circle-canvas {
  width: min(320px, 78vw);
  height: auto;
  aspect-ratio: 1 / 1;
  border-radius: 50%;
  background: #000;
  box-shadow: 0 8px 40px rgba(0, 0, 0, .45);
}

/* Вложения в сообщениях */
.msg-media {
  display: block;
  max-width: 100%;
  max-height: 340px;
  border-radius: 5px;
  margin: 2px 0 4px;
}

/* Альбом: несколько медиа одной пачки — мозаикой (как в Telegram) */
.msg.album { padding: 3px; width: min(360px, 78vw); max-width: 78vw; }
.msg.album .msg-author { padding: 5px 9px 3px; display: block; }
.album-grid {
  display: flex;
  flex-direction: column;
  gap: 3px;
  border-radius: 12px;
  overflow: hidden;
}
.album-row { display: flex; gap: 3px; }
.album-cell {
  position: relative;
  flex-grow: 1;
  flex-basis: 0;
  overflow: hidden;
  background: var(--bg-input);
}
.album-media {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  cursor: pointer;
}
.album-play {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
}
.album-play svg { width: 42px; height: 42px; color: #fff; filter: drop-shadow(0 1px 5px rgba(0, 0, 0, .6)); }
.album-caption { display: block; padding: 6px 9px 2px; }
.msg.album .msg-time { padding: 0 9px 4px; }

/* Обёртка фото с известными размерами: место резервируется сразу,
   пока грузится — фон и спиннер, потом картинка плавно проявляется */
.msg-media-wrap {
  position: relative;
  display: block;
  max-width: 100%;
  background: rgba(127, 127, 127, .15);
  border-radius: 5px;
  overflow: hidden;
  margin: 2px 0 4px;
}

.msg-media-wrap .msg-media {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  max-height: none;
  object-fit: cover;
  margin: 0;
  opacity: 0;
  transition: opacity .25s;
}

.msg-media-wrap.loaded .msg-media { opacity: 1; }
.msg-media-wrap.loaded .media-spinner { display: none; }

.media-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 34px;
  height: 34px;
  margin: -17px 0 0 -17px;
  color: var(--text-dim);
  animation: spin 1s linear infinite;
}

@keyframes spin { to { transform: rotate(360deg); } }

/* Голосовое сообщение — свой плеер в стиле мессенджера */
.voice-msg {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 210px;
  padding: 4px 2px;
}

.voice-play {
  width: 38px;
  height: 38px;
  min-width: 38px;
  border-radius: 50%;
  border: none;
  background: var(--accent);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.voice-play:hover { background: var(--accent-hover); }
.voice-play svg { width: 15px; height: 15px; margin-left: 1px; }
.voice-msg .vp-pause { display: none; margin-left: 0; }
.voice-msg.playing .vp-pause { display: block; }
.voice-msg.playing .vp-play { display: none; }

.voice-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 0;
}

/* Волна громкости как в Telegram: столбики, прокрашиваются по мере прослушивания */
.voice-wave {
  display: flex;
  align-items: center;
  gap: 2px;
  height: 24px;
  min-width: 130px;
  cursor: pointer;
}

.voice-wave span {
  flex: 1;
  min-width: 2px;
  height: 25%;
  border-radius: 2px;
  background: rgba(127, 127, 127, .45);
  transition: background .1s;
}

.voice-wave span.played { background: var(--accent); }

.voice-time {
  font-size: 12px;
  color: var(--msg-meta);
  font-variant-numeric: tabular-nums;
}

/* Видеокружок: без фона-квадрата, звук по тапу с увеличением.
   Увеличиваем реальные размеры (не transform) — раскладка сама
   раздвигает соседние сообщения, наложений нет */
.circle-wrap {
  position: relative;
  display: block;
  width: 210px;
  height: 210px;
  margin: 2px 0 4px;
  transition: width .22s, height .22s;
}

/* Размер в режиме звука задаёт JS: почти во всю ширину переписки */

/* Пауза внутри просмотра: полупрозрачный треугольник по центру */
.circle-wrap.paused::after {
  content: "";
  position: absolute;
  left: 50%;
  top: 50%;
  width: 0;
  height: 0;
  transform: translate(-38%, -50%);
  border-style: solid;
  border-width: 24px 0 24px 40px;
  border-color: transparent transparent transparent rgba(255, 255, 255, .85);
  pointer-events: none;
  filter: drop-shadow(0 2px 10px rgba(0, 0, 0, .45));
}

.msg-circle {
  display: block;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  cursor: pointer;
  background: #000;
}

/* Кольцо прогресса просмотра: видно только при включённом звуке */
.circle-ring {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  transform: rotate(-90deg); /* старт сверху */
  opacity: 0;
  transition: opacity .25s;
}

.circle-wrap.sound-on .circle-ring { opacity: 1; }

/* Кольцо загрузки кружка (пока грузится на сервер) */
.circle-wrap.uploading video { filter: brightness(.65); }
.upload-ring {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  transform: rotate(-90deg);
  pointer-events: none;
}
.upload-track { fill: none; stroke: rgba(255, 255, 255, .3); stroke-width: 2.5; }
.upload-bar {
  fill: none;
  stroke: #fff;
  stroke-width: 2.5;
  stroke-linecap: round;
  transition: stroke-dashoffset .15s linear;
}

.circle-ring circle {
  fill: none;
  stroke: rgba(255, 255, 255, .95);
  stroke-width: 2;
  stroke-linecap: round;
  stroke-dasharray: 301.6;   /* 2·π·48 */
  stroke-dashoffset: 301.6;  /* 0% прогресса */
  transition: stroke-dashoffset .3s linear; /* плавное заполнение между тиками */
}

/* Сообщение-кружок без пузыря на фоне; ширина не ограничена,
   чтобы кружок мог развернуться почти во всю переписку */
.msg.bare {
  background: transparent;
  padding: 0;
  overflow: visible;
  max-width: none;
}

.msg.bare .msg-time {
  display: block;
  text-align: right;
  padding: 2px 8px 0 0;
}

.msg-file {
  display: flex;
  align-items: center;
  gap: 10px;
  color: inherit;
  text-decoration: none;
  padding: 4px 2px;
}

.msg-file svg { width: 28px; height: 28px; flex-shrink: 0; }

.msg-file:hover .file-name { text-decoration: underline; }

.msg-file .file-name {
  max-width: 260px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.msg-file .file-size { color: var(--msg-meta); font-size: 12px; }

/* ---------- Модалка профиля ---------- */

dialog {
  margin: auto;
  background: var(--bg-panel);
  color: var(--text);
  border: 1px solid var(--border);
  border-radius: 16px;
  padding: 28px;
  width: 400px;
  max-width: calc(100vw - 32px);
  /* Не залезаем под козырёк iPhone: высокие модалки скроллятся внутри,
     а расчёт учитывает безопасные зоны сверху и снизу */
  max-height: calc(100vh - 32px);
  max-height: calc(100dvh - 32px - 2 * max(env(safe-area-inset-top, 0px), env(safe-area-inset-bottom, 0px)));
  overflow-y: auto;
}

dialog::backdrop { background: rgba(0, 0, 0, .6); }

dialog h2 { margin-bottom: 20px; }

.profile-avatar-row { display: flex; align-items: center; gap: 16px; margin-bottom: 20px; }

.profile-meta { display: flex; flex-direction: column; gap: 10px; align-items: flex-start; }

/* Настройки */
.settings-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 16px;
}

.settings-dialog { width: 440px; }

/* Уровень 1: список разделов в столбик */
.settings-list {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-bottom: 8px;
}

.sitem {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 13px 12px;
  border: none;
  border-radius: 12px;
  background: transparent;
  color: var(--text);
  font-size: 15px;
  font-weight: 500;
  text-align: left;
  cursor: pointer;
}
.sitem > svg { width: 20px; height: 20px; color: var(--text-dim); flex-shrink: 0; }
.sitem span { flex: 1; }
.sitem .chev { width: 16px; height: 16px; transform: rotate(180deg); color: var(--text-dim); }
@media (hover: hover) { .sitem:hover { background: var(--bg-hover); } }
.sitem:active { background: var(--bg-hover); }
/* Диалог сам держит фокус при открытии — рамку у него не рисуем.
   Пунктам списка даём аккуратную рамку по форме элемента, но только при
   навигации с клавиатуры (:focus-visible), а не при открытии тапом. */
dialog:focus { outline: none; }
.sitem:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }

/* Уровень 2: шапка раздела с кнопкой назад */
.settings-head {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 18px;
}
.settings-head h2 { margin: 0; font-size: 19px; }
.settings-head .icon-btn { margin-left: -6px; }

/* Карточка профиля: всё по центру */
.profile-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}
.profile-card .nickname { color: var(--text-dim); }

/* Поля формы профиля */
#profile-form label {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 14px;
  font-size: 13px;
  font-weight: 600;
  color: var(--text-dim);
}

#profile-form textarea {
  padding: 11px 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  color: var(--text);
  font: inherit;
  font-size: 16px;
  resize: vertical;
  min-height: 70px;
}
#profile-form textarea:focus { outline: none; border-color: var(--accent); }

/* Звук: выбор устройств и проверка микрофона */
#mic-select, #spk-select { margin-bottom: 10px; cursor: pointer; }

.mic-test-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
}
.mic-test-row .btn-secondary { flex-shrink: 0; width: auto; }
#mic-test-btn.testing { color: var(--online); border-color: var(--online); }

.level-meter {
  flex: 1;
  height: 10px;
  border-radius: 5px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  overflow: hidden;
}
#mic-level {
  height: 100%;
  width: 0;
  border-radius: 5px;
  background: linear-gradient(90deg, var(--online), #d7e35b 70%, var(--danger));
  transition: width .06s linear;
}

/* Кнопки записи горячих клавиш */
.bind-btn {
  min-width: 150px;
  padding: 8px 14px;
  border-radius: 10px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  color: var(--text);
  font-size: 14px;
  cursor: pointer;
}
.bind-btn.recording { border-color: var(--accent); color: var(--accent); }

/* Горячие клавиши — только для компьютеров с клавиатурой */
@media (pointer: coarse) {
  #binds-block { display: none; }
}

.hint-left { text-align: left; }

/* Зелёное «Сохранено» — перекрашиваем и фон с рамкой, не только текст */
.error.ok {
  color: var(--online);
  background: rgba(62, 207, 106, .12);
  border-color: var(--online);
}

/* Дата рождения и телефон в профиле собеседника */
.peer-fields {
  margin-top: 12px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.peer-field {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 9px 14px;
  background: var(--bg-input);
  border-radius: 10px;
  font-size: 14px;
}
.peer-field-label { color: var(--text-dim); }
.peer-field a { color: var(--accent); text-decoration: none; }

/* «О себе» в профиле собеседника */
.peer-about {
  margin-top: 10px;
  padding: 10px 14px;
  background: var(--bg-input);
  border-radius: 10px;
  font-size: 14px;
  color: var(--text);
  white-space: pre-wrap;
  overflow-wrap: break-word;
  text-align: left;
  max-width: 100%;
}

.theme-tabs { flex: 1; max-width: 220px; }

/* Широкие кнопки — только «установить приложение» и «разрешить доступ» */
#install-btn, #audio-perm-btn { width: 100%; margin-bottom: 12px; }

/* Профиль собеседника */
.peer-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  padding: 8px 0 16px;
  text-align: center;
}

.peer-name { font-size: 20px; font-weight: 600; margin-top: 8px; }

.peer-status { font-size: 14px; color: var(--text-dim); }
.peer-status.online { color: var(--online); }

/* ---------- Пароль: показать/скрыть ---------- */

.pw-field { position: relative; display: flex; }
.pw-field input { flex: 1; padding-right: 44px !important; }

.pw-toggle {
  position: absolute;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: var(--text-dim);
  cursor: pointer;
  padding: 8px;
  display: flex;
}

.pw-toggle svg { width: 20px; height: 20px; }

.link-btn {
  background: none;
  border: none;
  color: var(--accent);
  cursor: pointer;
  font-size: 14px;
  padding: 4px;
}

.link-btn:hover { text-decoration: underline; }

.field-label { display: flex; flex-direction: column; gap: 6px; color: var(--text-dim); font-size: 14px; margin-bottom: 14px; }
.field-label input {
  padding: 11px 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  outline: none;
  color: var(--text);
}
.field-label input:focus { border-color: var(--accent); }

/* ---------- Друзья / списки выбора ---------- */

.friends-block { margin-top: 18px; border-top: 1px solid var(--border); padding-top: 12px; }

/* ---------- Пароль и безопасность ---------- */

/* Строка-переход внутри раздела: слева название, справа текущее состояние */
.snav { padding: 12px 0; gap: 10px; }
.snav > span:first-child { flex: 1; }
.snav .snav-val { flex: 0 0 auto; color: var(--text-dim); font-weight: 400; }
.snav .snav-on { color: var(--accent); }
@media (hover: hover) { .snav:hover { background: none; color: var(--accent); } }
.snav:active { background: none; }

/* Действия с аккаунтом — столбиком, по центру, одной ширины: они разного веса,
   и в ряд читались как равнозначные, а «Удалить» точно не равно «Выйти» */
.account-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-top: 12px;
}
.account-actions button { width: 100%; max-width: 280px; }

/* Раздел второй проверки. Один шаг отступа на весь раздел: кнопки отбиты от
   текста и друг от друга одинаково, поэтому ничего не «слипается». */
.mfa-panel { --mfa-gap: 16px; }

.mfa-hero {
  padding: 20px 18px;
  border: 1px solid var(--border);
  border-radius: 14px;
  background: var(--bg-input);
  text-align: center;
}
.mfa-hero-icon {
  width: 30px;
  height: 30px;
  color: var(--accent);
}
.mfa-hero h3 { margin: 8px 0 6px; font-size: 17px; }
.mfa-hero p { color: var(--text-dim); font-size: 14px; line-height: 1.5; }
.mfa-hero-on .mfa-hero-icon { color: var(--online); }
.mfa-hero-on { border-color: var(--online); }

/* Пронумерованная инструкция: цифры рисуем сами, чтобы совпасть по стилю */
.mfa-steps {
  list-style: none;
  margin: var(--mfa-gap) 0 0;
  padding: 0;
  counter-reset: mfa;
}
.mfa-steps li {
  position: relative;
  counter-increment: mfa;
  padding: 0 0 14px 40px;
}
.mfa-steps li:last-child { padding-bottom: 0; }
.mfa-steps li::before {
  content: counter(mfa);
  position: absolute;
  left: 0;
  top: 0;
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background: var(--accent);
  color: #fff;
  font-size: 13px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
}
/* Линия между кружками — видно, что шаги идут подряд */
.mfa-steps li:not(:last-child)::after {
  content: "";
  position: absolute;
  left: 12.5px;
  top: 30px;
  bottom: 8px;
  width: 1px;
  background: var(--border);
}
.mfa-steps b { display: block; font-size: 15px; margin-bottom: 2px; }
.mfa-steps span { color: var(--text-dim); font-size: 14px; line-height: 1.45; }

/* Шаги самой настройки — те же кружки, но с содержимым внутри */
.mfa-step {
  display: flex;
  gap: 14px;
  margin-top: var(--mfa-gap);
  padding-top: var(--mfa-gap);
  border-top: 1px solid var(--border);
}
.mfa-num {
  flex: 0 0 26px;
  height: 26px;
  border-radius: 50%;
  background: var(--accent);
  color: #fff;
  font-size: 13px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
}
.mfa-step-body { flex: 1; min-width: 0; }
.mfa-step-title { display: block; font-size: 15px; margin-bottom: 10px; }
.mfa-note { color: var(--text-dim); font-size: 13px; line-height: 1.45; margin: 10px 0 6px; }

/* Поле формы в модалках. Без этого браузер рисует поля своими стилями — белый
   фон и чёрная рамка посреди тёмного окна. */
.form-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 12px;
  font-size: 13px;
  font-weight: 600;
  color: var(--text-dim);
}
.form-field input {
  padding: 11px 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  color: var(--text);
  font-size: 15px;
  font-weight: 400;
  outline: none;
  width: 100%;
}
.form-field input:focus { border-color: var(--accent); }

/* Автозаполнение Chrome закрашивает поле своим светлым фоном, и никакой
   background его не перебивает. Единственный способ — залить фон толстой
   внутренней тенью и перекрасить текст через -webkit-text-fill-color. */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus {
  -webkit-box-shadow: 0 0 0 1000px var(--bg-input) inset;
  -webkit-text-fill-color: var(--text);
  caret-color: var(--text);
  transition: background-color 9999s ease-in-out 0s;
}

/* Поле кода — крупно и вразрядку: шесть цифр читаются с одного взгляда */
#mfa-enable-code, #mfa-code-input, #mfa-off-code, #mfa-code {
  font-family: ui-monospace, "SF Mono", Consolas, monospace;
  font-size: 20px;
  letter-spacing: 4px;
  text-align: center;
}
/* Сюда вводят и резервный код с дефисом — он длиннее, разрядку убавляем */
#mfa-off-code, #mfa-code { letter-spacing: 2px; }

/* Кнопки по центру, отбитые от текста и друг от друга одинаково */
.mfa-actions {
  display: flex;
  justify-content: center;
  gap: var(--mfa-gap);
  margin-top: var(--mfa-gap);
}
.mfa-actions .btn-primary,
.mfa-actions .btn-secondary,
.mfa-actions .btn-danger { min-width: 190px; }
.mfa-actions-col { flex-direction: column; align-items: center; }
.mfa-actions-col button { width: 100%; max-width: 280px; }
.mfa-open { display: inline-block; text-decoration: none; color: var(--text); }

/* Счётчик резервных кодов */
.mfa-backup {
  margin-top: var(--mfa-gap);
  padding: 14px 16px;
  border: 1px solid var(--border);
  border-radius: 14px;
}
.mfa-backup-count { display: flex; align-items: baseline; gap: 8px; }
.mfa-backup-count b { font-size: 24px; color: var(--accent); }
.mfa-backup-count span { color: var(--text-dim); font-size: 14px; }
.mfa-backup p { margin-top: 6px; color: var(--text-dim); font-size: 13px; line-height: 1.45; }

@media (max-width: 480px) {
  .mfa-actions { flex-direction: column; align-items: center; }
  .mfa-actions button, .mfa-actions .mfa-open { width: 100%; max-width: 280px; }
}

.mfa-qr {
  display: flex;
  justify-content: center;
  margin: 4px 0 2px;
}
/* QR приходит как SVG: белая подложка нужна и в тёмной теме, иначе чёрные
   модули сольются с фоном и код не прочитается */
.mfa-qr svg {
  width: 190px;
  height: 190px;
  background: #fff;
  padding: 8px;
  border-radius: 10px;
}
.mfa-qr svg path { fill: #000; }

.mfa-secret {
  display: block;
  width: 100%;
  margin: 6px 0 4px;
  padding: 10px;
  border: 1px dashed var(--border);
  border-radius: 8px;
  background: var(--bg-input);
  color: var(--text);
  font-family: ui-monospace, "SF Mono", Consolas, monospace;
  font-size: 15px;
  letter-spacing: 1px;
  text-align: center;
  cursor: pointer;
}
.backup-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin: 14px 0 4px;
}
.backup-list code {
  padding: 8px;
  border-radius: 8px;
  background: var(--bg-input);
  font-family: ui-monospace, "SF Mono", Consolas, monospace;
  font-size: 14px;
  text-align: center;
  letter-spacing: .5px;
}

.session-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 0;
}
.session-icon { width: 22px; height: 22px; color: var(--text-dim); flex-shrink: 0; }
.session-info { flex: 1; min-width: 0; }
.session-name { font-weight: 600; font-size: 15px; }
.session-meta { color: var(--text-dim); font-size: 13px; margin-top: 2px; }
.session-kill svg { width: 18px; height: 18px; }

/* Короткое подтверждение действия поверх всего, включая модалки */
#toast {
  position: fixed;
  left: 50%;
  bottom: calc(28px + env(safe-area-inset-bottom, 0px));
  z-index: 100;
  padding: 11px 18px;
  border-radius: 10px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  box-shadow: 0 6px 24px rgba(0, 0, 0, .3);
  color: var(--text);
  font-size: 14px;
  transform: translate(-50%, 12px);
  opacity: 0;
  pointer-events: none;
  transition: opacity .2s ease, transform .2s ease;
}
#toast.show { opacity: 1; transform: translate(-50%, 0); }

/* На телефоне долгое нажатие по сообщению — наш жест выделения. Системный
   webview на то же нажатие норовит открыть своё меню («сохранить картинку»)
   или начать выделять текст, и наш жест до срабатывания не доживает.
   Только для касаний: на компьютере текст по-прежнему выделяется мышью. */
@media (pointer: coarse) {
  #messages .msg {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    user-select: none;
  }
}

/* ---------- Участники канала ---------- */

/* На компьютере панель встаёт колонкой справа: область чата становится рядом,
   а не под ней, поэтому переключаем направление только когда панель открыта */
.members-open #chat-area { flex-direction: row; }
/* Панель всегда справа, независимо от того, что открыто. В разметке она
   лежит между экраном канала и чатом, поэтому в комнате без явного порядка
   оказывалась слева от переписки. */
.members-open #chat-view,
.members-open #channel-view,
.members-open #chat-empty { flex: 1; min-width: 0; order: 1; }
.members-open #members-panel { order: 2; }

#members-panel {
  flex: 0 0 240px;
  display: flex;
  flex-direction: column;
  min-height: 0;
  background: var(--bg-panel);
  border-left: 1px solid var(--border);
}
#members-panel[hidden] { display: none; }

.mp-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: calc(12px + env(safe-area-inset-top, 0px)) 12px 10px 16px;
  border-bottom: 1px solid var(--border);
  font-size: 13px;
  font-weight: 600;
  text-transform: uppercase;
  color: var(--text-dim);
}
/* Крестик нужен только шторке на телефоне: на компьютере панель закрывают
   той же кнопкой в шапке, которой открыли */
.mp-head .icon-btn { display: none; }

#members-list { flex: 1; overflow-y: auto; padding: 8px 0 12px; }

.mp-group {
  padding: 12px 16px 6px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  color: var(--text-dim);
}

.member-row {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 6px 16px;
  border: none;
  background: none;
  color: var(--text);
  text-align: left;
  cursor: pointer;
}
@media (hover: hover) { .member-row:hover { background: var(--bg-hover); } }
.member-row:active { background: var(--bg-hover); }
/* Не в сети — приглушены целиком, вместе с аватаркой: так список читается
   одним взглядом, без вчитывания в подписи */
.member-row.offline { opacity: .45; }

/* min-width обязателен: у базового .avatar он 42px, и без переопределения
   аватарка расплывалась в овал 42×32 — width слушался, а min-width нет */
.member-avatar { width: 32px; height: 32px; min-width: 32px; flex-shrink: 0; }
.member-info { min-width: 0; display: flex; flex-direction: column; line-height: 1.25; }
.member-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.member-role {
  flex-shrink: 0;
  padding: 1px 6px;
  border-radius: 6px;
  background: var(--bg-active);
  color: var(--accent);
  font-size: 10px;
  font-weight: 700;
  text-transform: uppercase;
}
.member-nick {
  font-size: 12px;
  color: var(--text-dim);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* На телефоне места для второй колонки нет — панель выезжает поверх справа */
@media (max-width: 700px) {
  .members-open #chat-area { flex-direction: column; }
  #members-panel {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 70;
    width: min(280px, 82vw);
    box-shadow: -8px 0 24px rgba(0, 0, 0, .4);
    padding-bottom: env(safe-area-inset-bottom, 0px);
  }
  .mp-head .icon-btn { display: flex; }
}

/* ---------- Реакции ---------- */

/* Ряд под пузырём. display:flex сбрасывает pre-wrap родителя — иначе переносы
   в разметке превратились бы в пустые строки внутри сообщения. */
.msg-reactions {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-top: 6px;
  white-space: normal;
}

.reaction {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px 2px 6px;
  border: 1px solid var(--border);
  border-radius: 12px;
  background: var(--bg-input);
  color: var(--text);
  font-size: 14px;
  line-height: 1.4;
  cursor: pointer;
}
.reaction span { font-size: 12px; color: var(--text-dim); }
/* Своя реакция подсвечена: видно, где ты уже отметился */
.reaction.mine { border-color: var(--accent); background: var(--bubble-out, var(--bg-active)); }
.reaction.mine span { color: var(--accent); }
@media (hover: hover) { .reaction:hover { border-color: var(--accent); } }

/* Ряд эмодзи в меню сообщения */
.msg-reactions-row {
  display: flex;
  gap: 2px;
  padding: 4px 4px 8px;
  margin-bottom: 4px;
  border-bottom: 1px solid var(--border);
}
.msg-reactions-row button {
  flex: 1;
  padding: 6px 0;
  border: none;
  border-radius: 8px;
  background: none;
  font-size: 20px;
  line-height: 1;
  cursor: pointer;
}
@media (hover: hover) { .msg-reactions-row button:hover { background: var(--bg-hover); } }
.msg-reactions-row button:active { background: var(--bg-hover); }

/* ---------- Черта с датой и «непрочитанные» ---------- */

.chat-divider {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 14px 4px 10px;
  color: var(--text-dim);
  font-size: 12px;
  font-weight: 600;
  /* Черта не сообщение: выделять и тащить её незачем */
  user-select: none;
}
/* Линии по бокам рисуем самим блоком, чтобы не плодить пустых элементов */
.chat-divider::before,
.chat-divider::after {
  content: "";
  flex: 1;
  height: 1px;
  background: var(--border);
}
.chat-divider span { white-space: nowrap; }

/* Дата липнет к верху ленты: прокручивая длинную переписку, всегда видно,
   какой сейчас день */
.divider-day {
  position: sticky;
  top: 4px;
  z-index: 2;
}
.divider-day span {
  padding: 3px 10px;
  border-radius: 10px;
  background: var(--bg-panel);
  border: 1px solid var(--border);
}

/* Плашка «Загружаем…» над лентой, пока тянем следующую порцию истории */
.divider-loading { opacity: .7; }
.divider-loading::before,
.divider-loading::after { opacity: .4; }

.divider-unread { color: var(--accent); }
.divider-unread::before,
.divider-unread::after { background: var(--accent); opacity: .5; }

/* Пометка о недописанном в списке чатов */
.draft-mark { color: var(--danger, #e05555); font-weight: 600; }

/* ---------- Полосы прокрутки ---------- */

/* По умолчанию Windows рисует широкую серую полосу со стрелками — посреди
   тёмного окна она выглядит вставкой из другой программы. Красим сами.
   Firefox понимает scrollbar-*, остальные — псевдоэлементы. */
* {
  scrollbar-width: thin;
  scrollbar-color: var(--border) transparent;
}
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 6px;
  /* Прозрачная рамка внутрь: ползунок кажется тоньше дорожки и не липнет к краю */
  border: 3px solid transparent;
  background-clip: content-box;
}
::-webkit-scrollbar-thumb:hover { background: var(--text-dim); background-clip: content-box; }
/* Уголок между вертикальной и горизонтальной полосами и кнопки-стрелки */
::-webkit-scrollbar-corner { background: transparent; }
::-webkit-scrollbar-button { display: none; }

/* ---------- Полоса заголовка в программе для Windows ---------- */

/* В браузере её нет вовсе — там заголовок рисует сам браузер */
#titlebar { display: none; }

.has-titlebar #titlebar {
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: var(--titlebar-h);
  z-index: 60;
  background: var(--bg-panel);
  border-bottom: 1px solid var(--border);
  /* Тащим окно за пустую полосу — своих кнопок здесь нет, их рисует Windows
     справа поверх этой же полосы */
  -webkit-app-region: drag;
}

/* Приложение начинается под полосой. Высоту не задаём: у экранов
   inset:0 с height:auto, и смещения верха достаточно, чтобы низ остался на
   месте. */
.has-titlebar { --titlebar-h: 32px; }
.has-titlebar #main-screen,
.has-titlebar #auth-screen { top: var(--titlebar-h); }

/* Кнопка скачивания программы для Windows */
.win-install {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-top: 18px;
  text-decoration: none;
  color: var(--text);
}
.win-install svg { width: 18px; height: 18px; flex-shrink: 0; }

/* Бинд, который оболочка вывела за пределы окна */
.bind-btn.bind-global { border-color: var(--accent); color: var(--accent); }

.section-title {
  font-size: 13px;
  text-transform: uppercase;
  color: var(--text-dim);
  margin: 14px 0 8px;
  font-weight: 600;
}

.friend-row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 0;
}

.friend-row .me-info { flex: 1; min-width: 0; }
.friend-row .avatar { width: 38px; height: 38px; min-width: 38px; font-size: 16px; }

.friend-row .row-actions { display: flex; gap: 6px; }

.btn-mini {
  padding: 6px 12px;
  border-radius: 8px;
  border: 1px solid var(--border);
  background: var(--bg-input);
  color: var(--text);
  cursor: pointer;
  font-size: 13px;
}
.btn-mini:hover { background: var(--bg-hover); }
.btn-mini.accent { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn-mini.accent:hover { background: var(--accent-hover); }

.pick-list { max-height: 34vh; overflow-y: auto; }

.pick-row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 4px;
  cursor: pointer;
  border-radius: 8px;
}
.pick-row:hover { background: var(--bg-hover); }
.pick-row .avatar { width: 38px; height: 38px; min-width: 38px; font-size: 16px; }
.pick-row .me-info { flex: 1; min-width: 0; }

/* Кастомный чекбокс в стиле мессенджера */
.pick-row input[type="checkbox"],
.check-row input[type="checkbox"] {
  appearance: none;
  -webkit-appearance: none;
  width: 22px;
  height: 22px;
  flex-shrink: 0;
  border: 2px solid var(--border);
  border-radius: 6px;
  background: var(--bg-input);
  cursor: pointer;
  position: relative;
  transition: background .12s, border-color .12s;
}

.pick-row input[type="checkbox"]:checked,
.check-row input[type="checkbox"]:checked {
  background: var(--accent);
  border-color: var(--accent);
}

.pick-row input[type="checkbox"]:checked::after,
.check-row input[type="checkbox"]:checked::after {
  content: "";
  position: absolute;
  left: 6px;
  top: 2px;
  width: 6px;
  height: 11px;
  border: solid #fff;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

/* Название беседы и другие одиночные поля в модалках */
#group-create-name {
  width: 100%;
  padding: 11px 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  outline: none;
  color: var(--text);
  margin-bottom: 6px;
}

#group-create-name:focus { border-color: var(--accent); }

/* Отключение уведомлений */
.mute-control { margin-top: 10px; border-top: 1px solid var(--border); padding-top: 14px; }
.mute-row { display: flex; align-items: center; justify-content: space-between; }
.mute-title { font-weight: 600; }
.mute-state { color: var(--text-dim); font-size: 13px; margin-top: 4px; min-height: 16px; }

/* Свитч в стиле мессенджера */
.switch { position: relative; display: inline-block; width: 46px; height: 26px; flex-shrink: 0; }
.switch input { opacity: 0; width: 0; height: 0; }
.switch .slider {
  position: absolute;
  inset: 0;
  cursor: pointer;
  background: var(--bg-active);
  border-radius: 26px;
  transition: background .18s;
}
.switch .slider::before {
  content: "";
  position: absolute;
  height: 20px;
  width: 20px;
  left: 3px;
  top: 3px;
  background: #fff;
  border-radius: 50%;
  transition: transform .18s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
}
.switch input:checked + .slider { background: var(--accent); }
.switch input:checked + .slider::before { transform: translateX(20px); }

/* Колесо выбора времени (как в будильнике) */
.mute-picker { margin-top: 12px; }
.mute-picker .hint { text-align: left; margin-bottom: 6px; }

.wheel {
  position: relative;
  height: 160px;
  overflow-y: auto;
  scroll-snap-type: y mandatory;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  border-radius: 12px;
  background: var(--bg-input);
  -webkit-mask-image: linear-gradient(transparent, #000 34%, #000 66%, transparent);
          mask-image: linear-gradient(transparent, #000 34%, #000 66%, transparent);
}
.wheel::-webkit-scrollbar { display: none; }

.wheel-list { padding: 60px 0; }

.wheel-item {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  scroll-snap-align: center;
  font-size: 16px;
  color: var(--text-dim);
  transition: color .12s, font-size .12s;
}
.wheel-item.selected { color: var(--text); font-weight: 700; font-size: 19px; }

/* Полоса-указатель по центру */
.wheel-band {
  position: absolute;
  left: 0;
  right: 0;
  top: 60px;
  height: 40px;
  border-top: 1px solid var(--border);
  border-bottom: 1px solid var(--border);
  pointer-events: none;
}

.mute-apply { width: 100%; margin-top: 12px; }

/* Ряд «аватарка + сообщение» для чужих сообщений в беседе */
.msg-row {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  max-width: 78%;
  align-self: flex-start;
}

.msg-row .msg {
  max-width: 100%;
  align-self: auto;
}

.msg-avatar {
  width: 30px;
  height: 30px;
  min-width: 30px;
  font-size: 13px;
}

/* Имя отправителя над сообщением в групповом чате */
.msg .msg-author {
  display: block;
  font-size: 12px;
  font-weight: 600;
  color: var(--accent);
  margin-bottom: 2px;
}

/* Пометка «переслано» и цитата ответа */
.msg .fwd-label {
  display: block;
  font-size: 12px;
  color: var(--text-dim);
  font-style: italic;
  margin-bottom: 2px;
}

.msg .reply-quote {
  display: block;
  border-left: 3px solid var(--accent);
  padding: 4px 8px;
  margin-bottom: 4px;
  font-size: 13px;
  line-height: 1.3;
  white-space: normal; /* .msg — pre-wrap, здесь возвращаем обычный перенос */
  background: rgba(127, 127, 127, .12);
  border-radius: 4px;
  cursor: pointer;
}

.msg .reply-quote .rq-author { font-weight: 600; color: var(--accent); display: block; }
.msg .reply-quote .rq-text { color: var(--text-dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; }

/* Галочка последнего сообщения в списке чатов */
.preview-tick { width: 15px; height: 15px; vertical-align: -3px; margin-right: 2px; color: var(--text-dim); }
.preview-tick[data-read="1"] { color: var(--tick-read); }

/* Закреплённое сообщение */
#pinned-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: var(--bg-panel);
  border-bottom: 1px solid var(--border);
}
#pinned-bar[hidden] { display: none; }
#pinned-bar .pin-icon { width: 18px; height: 18px; color: var(--accent); flex-shrink: 0; }
.pinned-text { flex: 1; min-width: 0; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pinned-text b { color: var(--accent); font-weight: 600; }

/* Строка ответа над полем ввода */
#reply-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: var(--bg-panel);
  border-top: 1px solid var(--border);
}
#reply-bar[hidden] { display: none; }
#reply-bar .pin-icon { width: 18px; height: 18px; color: var(--accent); flex-shrink: 0; }
.reply-preview { flex: 1; min-width: 0; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.reply-preview b { color: var(--accent); }

.confirm-text {
  color: var(--text-dim);
  font-size: 15px;
  line-height: 1.5;
  margin-bottom: 6px;
}

/* Меню действий над участником канала (троеточие); dialog в верхнем слое */
#member-menu {
  position: fixed;
  margin: 0;
  width: auto;
  max-width: 220px;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 10px;
  padding: 4px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, .3);
  min-width: 190px;
}
#member-menu::backdrop { background: transparent; }
#member-menu button {
  display: block;
  width: 100%;
  background: none;
  border: none;
  color: var(--text);
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  text-align: left;
}
#member-menu button:hover { background: var(--bg-hover); }
#member-menu button.danger { color: var(--danger); }

.member-dots { flex-shrink: 0; }

/* Меню действий над сообщением */
#msg-menu {
  position: fixed;
  z-index: 120;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 10px;
  padding: 4px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, .3);
  min-width: 160px;
}
#msg-menu[hidden] { display: none; }
#msg-menu button {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  background: none;
  border: none;
  color: var(--text);
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  text-align: left;
}
#msg-menu button:hover { background: var(--bg-hover); }
#msg-menu button svg { width: 18px; height: 18px; color: var(--text-dim); }

.msg { cursor: default; position: relative; }
.msg.actionable { cursor: pointer; }

/* Стрелка «ответить» проявляется при свайпе сообщения влево */
.msg.swiping::after {
  content: "";
  position: absolute;
  right: -38px;
  top: 50%;
  width: 26px;
  height: 26px;
  margin-top: -13px;
  border-radius: 50%;
  background-color: var(--accent);
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2.4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='9 17 4 12 9 7'/%3E%3Cpath d='M20 18v-2a4 4 0 0 0-4-4H4'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 14px;
  opacity: var(--swipe-hint, 0);
  transform: scale(calc(.6 + .4 * var(--swipe-hint, 0)));
}

#profile-form { display: flex; flex-direction: column; gap: 14px; }
#profile-form label { display: flex; flex-direction: column; gap: 6px; color: var(--text-dim); font-size: 14px; }

/* «Сохранить» в одну ширину с кнопками аккаунта — раздел читается как целое */
#profile-form .modal-buttons { justify-content: center; }
#profile-form .modal-buttons .btn-primary { width: 100%; max-width: 280px; }

.modal-buttons { display: flex; justify-content: flex-end; gap: 10px; margin-top: 8px; }
.modal-buttons .btn-danger { margin-right: auto; }

/* ---------- Лайтбокс (просмотр фото) ---------- */

#lightbox {
  position: fixed;
  border: none;
  border-radius: 0;
  padding: 0;
  margin: 0;
  inset: 0;
  width: 100vw;
  height: 100vh;
  max-width: 100vw;
  max-height: 100vh;
  background: rgba(0, 0, 0, .92);
  overflow: hidden;
  cursor: zoom-out;
}

/* Фон затемнения даёт сам #lightbox (его анимируем), backdrop прозрачный —
   иначе сплошной чёрный перекрыл бы плавное появление и жест «потянуть вниз» */
#lightbox::backdrop { background: transparent; }

/* Абсолютное центрирование надёжнее flex: <img> не схлопывается в 0 внутри dialog */
#lightbox img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 94vw;
  max-height: 92vh;
  border-radius: 4px;
}

/* Верхняя панель лайтбокса: счётчик слева, действия справа */
.lb-top {
  position: fixed;
  top: calc(10px + env(safe-area-inset-top, 0px));
  left: 0;
  right: 0;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  pointer-events: none;
}
.lb-top > * { pointer-events: auto; }

/* В программе для Windows кнопки окна рисует система, и рисует их ПОВЕРХ всего,
   включая просмотр фото. Увести их назад нельзя — можно только не лезть под
   них: опускаем свою полоску на высоту заголовка. Полоса при этом остаётся
   местом, за которое окно таскают, что в полноэкранном просмотре тоже кстати. */
.has-titlebar .lb-top { top: calc(10px + var(--titlebar-h)); }
#lightbox-counter {
  color: #fff;
  font-size: 15px;
  font-weight: 600;
  text-shadow: 0 1px 4px rgba(0, 0, 0, .7);
  padding-left: 6px;
}
.lb-actions { display: flex; gap: 4px; }
.lb-actions .icon-btn { color: #fff; }
.lb-actions .icon-btn:hover { background: rgba(255, 255, 255, .15); color: #fff; }

/* Стрелки листания по бокам (десктоп) */
.lb-nav {
  position: fixed;
  top: 50%;
  transform: translateY(-50%);
  z-index: 2;
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 50%;
  background: rgba(0, 0, 0, .4);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.lb-nav svg { width: 24px; height: 24px; }
#lb-prev { left: 12px; }
.lb-next { right: 12px; }
.lb-next svg { transform: rotate(180deg); }
@media (hover: none) { .lb-nav { display: none; } } /* на телефоне — только свайпы */

/* Меню-троеточие лайтбокса */
#lightbox-menu {
  position: fixed;
  top: calc(54px + env(safe-area-inset-top, 0px));
  right: 12px;
  z-index: 3;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 5px;
  min-width: 210px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, .5);
  cursor: default;
}
#lightbox-menu[hidden] { display: none; }
#lightbox-menu button {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 11px 12px;
  background: none;
  border: none;
  border-radius: 8px;
  color: var(--text);
  font-size: 15px;
  cursor: pointer;
  text-align: left;
}
#lightbox-menu button:hover { background: var(--bg-hover); }
#lightbox-menu button.danger { color: var(--danger); }
#lightbox-menu button svg { width: 18px; height: 18px; color: var(--text-dim); }
#lightbox-menu button.danger svg { color: var(--danger); }

.avatar.clickable { cursor: zoom-in; }

.avatar.clickable { cursor: zoom-in; }

/* ---------- Кадрирование аватарки ---------- */

.crop-hint { margin: -8px 0 14px; }

#crop-area { display: flex; justify-content: center; margin-bottom: 14px; }

#crop-canvas {
  border-radius: 12px;
  background: #000;
  touch-action: none; /* перетаскивание пальцем вместо скролла страницы */
  cursor: grab;
}

#crop-zoom {
  display: block;
  width: 100%;
  margin-bottom: 14px;
  accent-color: var(--accent);
}

/* ---------- Превью перед отправкой ---------- */

.preview-media {
  display: block;
  max-width: 100%;
  max-height: 50vh;
  border-radius: 10px;
  margin: 0 auto 14px;
}

#send-preview-body .msg-file { margin-bottom: 14px; }

#send-caption {
  width: 100%;
  padding: 11px 14px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 8px;
  outline: none;
  margin-bottom: 4px;
}

#send-caption:focus { border-color: var(--accent); }

/* ---------- Меню «что прикрепить» ---------- */
#attach-menu {
  width: 340px;
  padding: 12px;
}

.attach-opt {
  display: flex;
  align-items: center;
  gap: 14px;
  width: 100%;
  padding: 10px 12px;
  border: none;
  border-radius: 12px;
  background: transparent;
  color: var(--text);
  text-align: left;
  cursor: pointer;
}
@media (hover: hover) { .attach-opt:hover { background: var(--bg-hover); } }
.attach-opt:active { background: var(--bg-hover); }

.attach-ico {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44px;
  height: 44px;
  min-width: 44px;
  border-radius: 50%;
  color: #fff;
}
.attach-ico.media { background: var(--accent); }
.attach-ico.file { background: #3aa76d; }
.attach-ico svg { width: 22px; height: 22px; }

.attach-txt { display: flex; flex-direction: column; gap: 2px; }
.attach-txt b { font-size: 15px; font-weight: 600; }
.attach-txt small { font-size: 13px; color: var(--text-dim); }

/* На телефоне меню выезжает шторкой снизу */
@media (max-width: 700px) {
  #attach-menu {
    margin: auto 0 0;
    width: 100%;
    max-width: 100%;
    border-radius: 18px 18px 0 0;
    border-bottom: none;
    padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px));
  }
}

/* ---------- Сетка предпросмотра нескольких файлов ---------- */
.preview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 14px;
  max-height: 46vh;
  overflow-y: auto;
}

.preview-cell {
  position: relative;
  aspect-ratio: 1;
  border-radius: 10px;
  overflow: hidden;
  background: var(--bg-input);
}
.preview-cell img, .preview-cell video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
.preview-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 6px;
  height: 100%;
  padding: 8px;
}
.preview-file svg { width: 24px; height: 24px; color: var(--text-dim); }
.preview-file span {
  font-size: 11px;
  color: var(--text-dim);
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.preview-remove {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  background: rgba(0, 0, 0, .55);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.preview-remove svg { width: 13px; height: 13px; }

/* ---------- Зона переноса файлов (компьютер) ---------- */
#drop-overlay {
  position: fixed;
  inset: 0;
  z-index: 300;
  background: rgba(0, 0, 0, .55);
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none; /* события drag ловит документ */
}
#drop-overlay[hidden] { display: none; }

.drop-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 40px 60px;
  border: 2px dashed var(--accent);
  border-radius: 20px;
  background: var(--bg-panel);
  color: var(--text);
  font-size: 16px;
  font-weight: 600;
}
.drop-box svg { width: 40px; height: 40px; color: var(--accent); }

/* На десктопе голос-панель центрируем по области чата (без сайдбара 320px) */
@media (min-width: 701px) {
  #voice-bar {
    left: calc((100vw + 320px) / 2);
    bottom: 84px; /* выше панели действий канала */
  }
}

/* Секция рекомендованных каналов в поиске/списке */
.channel-suggest-title {
  padding: 12px 14px 6px;
  font-size: 12px;
  color: var(--text-dim);
  text-transform: uppercase;
  font-weight: 600;
}

/* ---------- Тач-устройства: hover не «залипает» ----------
   На iOS первый тап применяет :hover-стиль вместо клика — чаты
   открывались только со второго нажатия. На тач-экранах hover-подсветку
   отключаем и заменяем мгновенным :active */
@media (hover: none) {
  .chat-item:not(.active):hover,
  .user-chip:hover,
  .pick-row:hover,
  .friend-row:hover,
  .icon-btn:hover,
  .btn-mini:hover,
  .shared-tab:hover,
  .media-subtab:hover { background: transparent; }

  .icon-btn:hover { color: var(--text-dim); }

  .chat-item:active,
  .user-chip:active,
  .pick-row:active { background: var(--bg-hover); }
}

/* ---------- Мобильная версия ---------- */

@media (max-width: 700px) {
  #sidebar { width: 100%; min-width: 0; }
  #chat-area { display: none; }
  #main-screen.chat-open #sidebar { display: none; }
  #main-screen.chat-open #chat-area { display: flex; }
  #back-btn { display: flex; }
  #channel-back { display: flex; }
  .msg { max-width: 85%; }

  /* Во время свайпа «назад» показываем список позади уезжающего экрана */
  body.back-swiping #main-screen.chat-open #sidebar {
    display: flex;
    position: absolute;
    inset: 0;
    z-index: 0;
  }
  body.back-swiping #main-screen.chat-open #chat-area {
    position: relative;
    z-index: 1;
    background: var(--bg);
  }
}


/* ---------- Блокировка пользователя ---------- */

/* Кнопка блокировки — отдельной строкой под остальными: это не рядовое
   действие, и ставить её в один ряд с «Закрыть» значит приглашать промах. */
.modal-buttons.peer-buttons #peer-block-btn {
  grid-column: 1 / -1;
  margin-right: 0;         /* сбрасываем прижатие .btn-danger влево */
  margin-top: 2px;
}

/* Не перебиваем общий для окон предел по ширине экрана: с голым 420px
   окно вылезало за край телефона */
#block-modal { max-width: min(420px, calc(100vw - 32px)); }
#block-modal h2 { margin-bottom: 8px; }
#block-modal .hint { line-height: 1.45; }

.check-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 16px 0 4px;
  padding: 12px;
  border: 1px solid var(--border);
  border-radius: 12px;
  background: var(--bg-input);
}

.check-row {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  font-size: 14px;
}

/* Вложенный выбор — он уточняет верхний, а не спорит с ним */
.check-row.check-sub { margin-left: 32px; }
.check-row.check-sub.disabled { opacity: .45; pointer-events: none; }

.check-hint { margin: 2px 0 0 32px; font-size: 12px; }

/* Столбиком, а не в ряд: в два столбца «Заблокировать» не влезало по ширине
   на телефоне и кнопки получались разной длины. */
.modal-buttons.block-buttons {
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
  margin-top: 18px;
}
.modal-buttons.block-buttons button { width: 100%; margin: 0; }

/* Список заблокированных в настройках */
.blocked-row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0;
}
.blocked-row .avatar { width: 38px; height: 38px; min-width: 38px; font-size: 16px; }
.blocked-row .blocked-name { flex: 1; min-width: 0; }
.blocked-row .blocked-name b { display: block; font-size: 14px; }
.blocked-row .blocked-name span { font-size: 12px; color: var(--text-dim); }


/* ---------- Активность в списке участников ---------- */

/* Игра встаёт на место ника: две строки на человека и так предел, а «во что
   играет» полезнее адреса, который и так виден в профиле. */
.member-act {
  font-size: 12px;
  color: var(--accent);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* Когда игра не найдена, это не новость, а спокойное состояние — не кричим
   акцентом, иначе отсутствие игры выглядит как ошибка */
.activity-now.act-idle { color: var(--text-dim); }

.activity-now {
  margin: 12px 0 0;
  padding: 10px 12px;
  border-radius: 10px;
  background: var(--bg-input);
  font-size: 13px;
  color: var(--accent);
}

/* Напоминание, что без программы для Windows тут нечему работать */
.act-note {
  display: flex;
  gap: 12px;
  margin: 14px 0 0;
  padding: 12px 14px;
  border: 1px solid var(--border);
  border-radius: 12px;
  background: var(--bg-input);
  font-size: 13px;
  line-height: 1.5;
  color: var(--text-dim);
  text-align: left;
}
.act-note svg { width: 20px; height: 20px; flex-shrink: 0; margin-top: 2px; stroke: var(--text-dim); fill: none; }
.act-note b { display: block; color: var(--text); font-weight: 600; }
.act-note a { display: inline-block; margin-top: 6px; color: var(--accent); }

/* Список игр длинный — держим его в своей прокрутке, чтобы кнопки раздела
   не уезжали за край экрана */
.act-games {
  max-height: 320px;
  overflow-y: auto;
  text-align: left;
}


/* ---------- Меню чата и закрепление ---------- */

/* Оформление то же, что у меню участника: это одно и то же по смыслу окно,
   и разводить их внешне значило бы делать вид, что они разные */
#chat-menu {
  position: fixed;
  margin: 0;
  padding: 5px;
  width: auto;
  min-width: 200px;
  max-width: 260px;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, .4);
}
#chat-menu::backdrop { background: transparent; }
#chat-menu button {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 10px 12px;
  background: none;
  border: none;
  border-radius: 8px;
  color: var(--text);
  font-size: 15px;
  text-align: left;
  cursor: pointer;
}
#chat-menu button:hover { background: var(--bg-hover); }
#chat-menu button svg { width: 17px; height: 17px; stroke: currentColor; fill: none; flex-shrink: 0; }

/* Значок закрепления в строке чата — там же, где время и счётчик */
.chat-pin {
  width: 14px;
  height: 14px;
  stroke: var(--text-dim);
  fill: none;
  transform: rotate(45deg);
}
