/* ngsMobile.css — мобильный слой представления, v2 (дизайн: docs/MOBILE_PLAN.md).
   ПРАВИЛА СЛОЯ (не нарушать):
   - каждый селектор заскоуплен на html.ngs-mobile — класс ставит ранний инлайн-скрипт в ngs.php
     по фичефлагу localStorage.ngs_mobile_beta (?mobile=1 включает, ?mobile=0 выключает);
     без флага и на десктопе этот файл не применяется вовсе;
   - десктопные правила NGSapp.css из-за мобильных нужд НЕ редактируются — только добавления здесь;
   - раскладка — внутри @media (max-width:960px), порог един с гейтом заглушки (NGSapp.css:7678);
   - высоты — только var(--ngs-m-vh) (dvh), кромки — через --ngs-m-safe-top/bottom. */

html.ngs-mobile{
  --ngs-m-vh: 100vh;
  --ngs-m-safe-top: 0px;
  --ngs-m-safe-bottom: 0px;
  --ngs-m-header-h: 46px;
  --ngs-m-nav-h: 50px; /* компактнее (паттерн Instagram/Telegram — фидбэк владельца) */
}
@supports (height: 100dvh){
  html.ngs-mobile{
    --ngs-m-vh: 100dvh;
  }
}
@supports (padding: env(safe-area-inset-top)){
  html.ngs-mobile{
    --ngs-m-safe-top: env(safe-area-inset-top);
    --ngs-m-safe-bottom: env(safe-area-inset-bottom);
  }
}

/* Вне мобильной ширины (планшет повернули в landscape >960px) каркас — десктопный;
   мобильные элементы, созданные ранее, прячутся. */
html.ngs-mobile #ngsMobileNav,
html.ngs-mobile #ngsMobileHeader,
html.ngs-mobile #ngsMobileMorePanel{
  display: none;
}

@media screen and (max-width:960px){

  /* ==== Гейт: под флагом гасим заглушку и показываем приложение. ==== */
  html.ngs-mobile #mobile{
    display: none !important;
  }
  html.ngs-mobile #desktop{
    display: block !important;
    height: var(--ngs-m-vh);
    overflow: hidden;
  }

  /* ==== Запирание документа: iOS скроллит ОКНО при фокусе инпутов (клавиатура) и оставляет
     его съехавшим — «дыры» снизу/сверху. position:fixed на body исключает страничный скролл;
     JS-guard (ngsMobileNav.js) возвращает окно после клавиатуры. ==== */
  html.ngs-mobile body{
    position: fixed;
    inset: 0;
    width: 100%;
    height: var(--ngs-m-vh);
    overflow: hidden;
  }

  /* Фоновая canvas-анимация psflow на телефоне не видна за контентом и жжёт батарею. */
  html.ngs-mobile #ngs-scene > canvas.ps-flow-bg-canvas{
    display: none !important;
  }

  /* ==== Каркас уровня 1 (ngs.php, table.app-main-table): таблица → вертикальный стек. ==== */
  html.ngs-mobile .app-main-table,
  html.ngs-mobile .app-main-table > tbody{
    display: block;
    width: 100%;
    height: var(--ngs-m-vh);
  }
  html.ngs-mobile .app-main-table > tbody > tr{
    display: block;
    width: 100%;
  }
  /* Строка шапки несёт десктопный класс .app-main-table-statusbars{height:25px} — при
     display:block она оставалась 25px, а td#header (46px) вылезал из неё ПОВЕРХ контента:
     виджеты «заезжали под шапку», снизу оставалась дыра той же величины. */
  html.ngs-mobile .app-main-table > tbody > tr:first-child{
    height: auto;
  }
  /* Нижний статус-бар десктопа заменяет ngsMobileNav. */
  html.ngs-mobile .app-main-table > tbody > tr:last-child{
    display: none;
  }
  /* Шапка: фикс-высота + отступ под вырез. Десктопная начинка скрыта ЦЕЛИКОМ — вместо неё
     JS-собранная мобильная шапка #ngsMobileHeader (ngsMobileNav.js) внутри того же td#header. */
  html.ngs-mobile #header{
    display: block;
    box-sizing: border-box;
    height: calc(var(--ngs-m-header-h) + var(--ngs-m-safe-top));
    padding-top: var(--ngs-m-safe-top);
    overflow: visible; /* дропдаун «⋯» выпадает ниже кромки шапки */
    position: relative;
    z-index: 9100;
    background: rgba(28,30,34,.98);
    border-bottom: 1px solid rgba(255,255,255,.07);
  }
  html.ngs-mobile #header > div:not(#ngsMobileHeader){
    display: none !important;
  }

  /* ==== Мобильная шапка ==== */
  html.ngs-mobile #ngsMobileHeader{
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    height: var(--ngs-m-header-h);
    padding: 0 6px 0 12px;
    box-sizing: border-box;
  }
  html.ngs-mobile .ngs-mhead-brand{
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 0;
    color: var(--LightGray);
    font: 600 14px/1 Inter, ui-sans-serif, system-ui;
  }
  html.ngs-mobile .ngs-mhead-brand img{
    width: 22px;
    height: 22px;
    display: block;
  }
  html.ngs-mobile .ngs-mhead-actions{
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 0 0 auto;
  }
  /* Размеры с !important: глобальные button/a-правила NGSapp.css и override.css иначе
     сплющивают кнопки (пересечение install/support — фидбэк владельца). */
  html.ngs-mobile .ngs-mhead-btn{
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    box-sizing: border-box !important;
    width: 38px !important;
    min-width: 38px !important;
    height: 38px !important;
    border: none !important;
    border-radius: 10px;
    background: none;
    color: var(--LightGray);
    font-size: 16px;
    line-height: 1 !important;
    cursor: pointer;
    padding: 0 !important;
    margin: 0 !important;
    position: relative;
    flex: 0 0 auto;
  }
  html.ngs-mobile .ngs-mhead-btn:active{
    background: rgba(255,255,255,.08);
  }
  html.ngs-mobile .ngs-mhead-btn.ngs-mhead-install{
    color: #c6db4e;
  }
  /* Панель «⋯» — fixed В BODY (шапка сидит в стэкинг-контексте #ngs-scene-content z:2,
     и выпадашка внутри неё была ПОД слоями соцсети/задачи — «меню не вызывалось»). */
  html.ngs-mobile #ngsMobileMorePanel{
    display: none;
    position: fixed;
    top: calc(var(--ngs-m-header-h) + var(--ngs-m-safe-top) + 4px);
    right: 6px;
    z-index: 100100;
    border-radius: 14px;
    min-width: 216px;
    padding: 6px;
    background: rgba(28,30,34,.98);
    border: 1px solid rgba(255,255,255,.09);
    box-shadow: 0 16px 44px rgba(0,0,0,.55);
  }
  html.ngs-mobile #ngsMobileMorePanel.open{
    display: block;
  }
  html.ngs-mobile .ngs-mhead-item{
    display: flex !important;
    align-items: center;
    gap: 12px;
    padding: 13px 12px !important;
    border-radius: 10px;
    color: #e9edf3 !important;
    font: 600 14.5px/1 Inter, ui-sans-serif, system-ui !important;
  }
  html.ngs-mobile .ngs-mhead-item i{
    width: 18px;
    text-align: center;
    font-size: 14px;
    color: var(--LightGreen);
  }
  html.ngs-mobile .ngs-mhead-item:active{
    background: rgba(255,255,255,.08);
  }
  html.ngs-mobile .ngs-mhead-item-out,
  html.ngs-mobile .ngs-mhead-item-out i{
    color: #ff9a9a !important;
  }
  html.ngs-mobile .ngs-mhead-langrow{
    display: flex;
    gap: 8px;
    padding: 8px 10px;
  }
  html.ngs-mobile .ngs-mhead-langrow button{
    flex: 1;
    border: 1px solid rgba(255,255,255,.16);
    border-radius: 10px;
    background: transparent;
    color: var(--LightGray);
    font: 700 13px/1 Inter, ui-sans-serif, system-ui;
    padding: 11px 0;
    cursor: pointer;
  }
  html.ngs-mobile .ngs-mhead-langrow button.active{
    background: rgba(198,219,78,.18);
    border-color: rgba(198,219,78,.55);
    color: #e7f6a0;
  }

  /* Контентная строка: всё, что осталось от высоты экрана. */
  html.ngs-mobile .app-main-table > tbody > tr:nth-child(2){
    height: calc(var(--ngs-m-vh) - var(--ngs-m-header-h) - var(--ngs-m-safe-top)
                 - var(--ngs-m-nav-h) - var(--ngs-m-safe-bottom));
  }
  html.ngs-mobile .app-main-table-pading-l,
  html.ngs-mobile .app-main-table-pading-r{
    display: none;
  }
  html.ngs-mobile .app-main-table-content{
    display: block;
    width: 100%;
    height: 100%;
  }

  /* ==== Каркас уровня 2 (main.php): сайдбар/правая панель/панель задачи скрыты (задачи — Ф3),
     контент на всю ширину. ==== */
  html.ngs-mobile .app-l-panel-table,
  html.ngs-mobile .app-l-panel-table > tbody{
    display: block;
    width: 100%;
    height: 100%;
  }
  html.ngs-mobile .app-l-panel-table > tbody > tr{
    display: block;
    width: 100%;
    height: 100%;
  }
  html.ngs-mobile .app-l-panel,
  html.ngs-mobile .app-r-panel,
  html.ngs-mobile .app-task-table{
    display: none !important;
  }
  html.ngs-mobile .app-project-table{
    display: block;
    width: 100%;
    height: 100%;
  }
  html.ngs-mobile .app-project-table > .app-ScrollBox{
    width: 100%;
    height: 100%;
  }
  /* Окна с raw-iframe (чат/почта/облако/доски/стримы/home): iOS разращивает iframe до высоты
     его контента, контейнер начинает скроллиться → контент «заезжает под шапку», снизу дыра.
     Фиксация: контейнер не скроллится, iframe — абсолютом ровно в его габариты. */
  html.ngs-mobile .app-project-table > .app-ScrollBox:has(> iframe){
    overflow: hidden;
    position: relative;
  }
  html.ngs-mobile .app-project-table > .app-ScrollBox > iframe{
    position: absolute;
    inset: 0;
    width: 100% !important;
    height: 100% !important;
    border: 0;
    background-color: transparent;
  }
  /* Почта: рамку и гуттер даёт СВОЯ тема Roundcube (NGSmail.css: #layout-* margin+radius) —
     снаружи ничего не добавляем, иначе отступ двоится (смок 2026-08-29). */

  /* ==== Нижний тулбар (src/ngsMobileNav.js): скролл пальцем, safe-area снизу. ==== */
  html.ngs-mobile #ngsMobileNav{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9000;
    display: flex;
    align-items: stretch;
    height: calc(var(--ngs-m-nav-h) + var(--ngs-m-safe-bottom));
    padding-bottom: var(--ngs-m-safe-bottom);
    box-sizing: border-box;
    overflow-x: auto;
    overflow-y: hidden;
    background: rgba(28,30,34,.98);
    border-top: 1px solid rgba(255,255,255,.08);
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }
  html.ngs-mobile #ngsMobileNav::-webkit-scrollbar{
    display: none;
  }
  html.ngs-mobile .ngs-mnav-btn{
    position: relative;
    flex: 1 1 0; /* 6 кнопок умещаются без скролла на 390px; при большем числе бар скроллится */
    min-width: 64px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 3px;
    border: none;
    background: none;
    padding: 5px 4px 3px;
    color: var(--MidGray);
    font: 500 9.5px/1 Inter, ui-sans-serif, system-ui;
    cursor: pointer;
  }
  html.ngs-mobile .ngs-mnav-btn i{
    font-size: 20px;
  }
  /* Счётчики — бейджем в правом верхнем углу иконки (штатный ngsSignalBadge позиционирован
     bottom:-14px и на тонком баре оказывался ПОД ним — фидбэк владельца). */
  html.ngs-mobile .ngs-mnav-btn .ngsSignalBadge{
    left: auto !important;
    bottom: auto !important;
    transform: none !important;
    top: 0 !important;
    right: calc(50% - 22px) !important;
  }
  html.ngs-mobile .ngs-mnav-btn.active{
    color: var(--LightGreen);
  }
  html.ngs-mobile .ngs-mnav-lbl{
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /* ==== Детали задачи: на мобильном 4-я колонка каркаса становится полноэкранным слоем
     между шапкой и нижним баром. Класс ngs-m-task-open ставит обёртка openTaskDetails
     (ngsMobileNav.js) — она перехватывает ВСЕ пути открытия (чат/поиск/хом/уведомления:
     все идут через showTaskDetails → boot виджета → openTaskDetails). Инлайновые
     min/maxWidth:40vw из openTaskDetails перебиваются !important. Слой ВЫШЕ соц-экрана
     (8600 > 8500): задача, открытая из соцсети, видна поверх. ==== */
  html.ngs-mobile.ngs-m-task-open .app-task-table{
    display: block !important;
    position: fixed;
    left: 0;
    right: 0;
    top: calc(var(--ngs-m-header-h) + var(--ngs-m-safe-top));
    bottom: calc(var(--ngs-m-nav-h) + var(--ngs-m-safe-bottom));
    width: auto !important;
    max-width: none !important;
    min-width: 0 !important;
    /* NGSapp.css:2119 даёт .app-task-table{height:100%} — у fixed-элемента с top высота
       побеждает bottom, и низ уезжал под тулбар. bottom главнее: */
    height: auto !important;
    z-index: 8600;
    background: rgb(35, 35, 40); /* фон приложения (.back-color-gray) — слой не темнее чата/хома */
    overflow: hidden;
  }
  html.ngs-mobile.ngs-m-task-open .app-task-details{
    height: 100%;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    border-left: none !important;
  }
  /* Страховка от горизонтального распирания контента карточки на 390px. */
  html.ngs-mobile.ngs-m-task-open #taskDetails{
    overflow-x: hidden;
  }
  /* Десктопная кнопка-стрелка (►) на мобильном не нужна (мешала контенту — фидбэк владельца):
     закрытие — повторным тапом по пункту «Задача» в тулбаре (ngsMobileNav.js). */
  html.ngs-mobile .app-task-table-btn{
    display: none !important;
  }

  /* ==== Соцсеть: на мобильном это ЭКРАН, а не модалка — занимает место от верха до нижнего
     бара (бар остаётся видимым и рабочим: z-index соц ниже бара), вертикальный рельс вкладок
     становится горизонтальным верхним таб-баром. Стили модалки живут в JS-<style>
     ngsSocialStyle — здесь только оверрайды. ==== */
  html.ngs-mobile #ngsSocialModal{
    padding: 0 !important;
    z-index: 8500 !important;
    top: calc(var(--ngs-m-header-h) + var(--ngs-m-safe-top)) !important;
    bottom: calc(var(--ngs-m-nav-h) + var(--ngs-m-safe-bottom)) !important;
    background: rgb(35, 35, 40) !important; /* фон приложения — единая тёмность экранов */
  }
  html.ngs-mobile .ngs-social-wrap{
    position: relative;
    overflow: hidden;
    flex-direction: column;
    width: 100%;
    max-width: 100vw !important;
    height: 100% !important;
  }
  html.ngs-mobile #ngsSocialRail{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    width: 100% !important;
    flex: 0 0 auto;
    flex-direction: row;
    align-items: center;
    gap: 8px;
    padding: 6px 8px !important;
    box-sizing: border-box;
    background: #111318;
    border-bottom: 1px solid rgba(255,255,255,.08);
    pointer-events: auto !important;
    transform: translate3d(0,0,0);
    will-change: transform;
  }
  html.ngs-mobile #ngsSocialBell,
  html.ngs-mobile #ngsSocialSearch{
    margin: 0 !important;
    width: 36px !important;
    height: 36px !important;
    border-radius: 10px !important;
    box-shadow: none !important;
  }
  html.ngs-mobile #ngsSocialBellDot{
    top: 5px !important;
    right: 5px !important;
  }
  html.ngs-mobile .ngs-rail-tabs{
    flex-direction: row !important;
    align-items: center !important;
    width: auto !important;
    flex: 1 1 auto;
    gap: 6px !important;
    overflow-x: auto;
    scrollbar-width: none;
  }
  html.ngs-mobile .ngs-rail-tabs::-webkit-scrollbar{
    display: none;
  }
  /* Вкладки — иконками (текстовые подписи на русском не влезают и рвут строку):
     Моя страница → user, Подписки → user-friends, Рекомендации → compass.
     Три вкладки делят всю свободную ширину бара поровну (не путаются с кнопками
     колокольчика/поиска, которые остаются компактными слева). */
  html.ngs-mobile .ngs-vtab{
    flex: 1 1 0 !important;
    width: auto !important;
    min-width: 0;
    height: 36px;
    padding: 0 !important;
    border-radius: 10px !important;
    box-shadow: none !important;
    font-size: 15px;
  }
  html.ngs-mobile .ngs-vtab span{
    display: none !important;
  }
  html.ngs-mobile .ngs-vtab::before{
    font-family: "Font Awesome 6 Free", "Font Awesome 5 Free", FontAwesome;
    font-weight: 900;
    content: "\f007";
  }
  html.ngs-mobile .ngs-vtab[data-view="following"]::before{
    content: "\f500";
  }
  html.ngs-mobile .ngs-vtab[data-view="discover"]::before{
    content: "\f14e";
  }
  html.ngs-mobile .ngs-social-card{
    position: absolute !important;
    inset: 0 !important;
    width: 100% !important;
    height: 100% !important;
    min-height: 0;
    border-radius: 0 !important;
    border: none !important;
    box-shadow: none !important;
  }
  /* Крестика на мобильном нет (перекрывал вкладки — фидбэк владельца): закрытие — переходом
     по нижнему бару (Хом/Чат/Почта закрывают соц-экран). */
  html.ngs-mobile #ngsSocialCloseM{
    display: none !important;
  }
  /* Панели уведомлений/поиска — во всю ширину под таб-баром. */
  html.ngs-mobile #ngsSocialNotif,
  html.ngs-mobile #ngsSocialSearchPanel{
    left: 8px !important;
    right: 8px !important;
    width: auto !important;
    top: 54px !important;
    max-height: 60vh !important;
  }

  /* ==== Шторки загрузки. Обе беды от 100vh: на телефоне он больше видимой области
     (адресная строка браузера), поэтому «центр» уезжал вниз. Меряем в dvh. ==== */
  /* В PWA vh-семантика опять врёт (лого сползал ниже центра) — фиксируем шторки строго
     по видимому вьюпорту через inset. Плюс ОПТИЧЕСКАЯ центровка: контент не может лечь под
     статусбар, поэтому геом. центр стекла ниже визуального — поднимаем группу паддингом. */
  html.ngs-mobile .loading-screen,
  html.ngs-mobile #loadingOverlay{
    position: fixed !important;
    inset: 0 !important;
    width: auto !important;
    height: auto !important;
    padding-bottom: 12vh !important;
    box-sizing: border-box !important;
  }
  /* Ротация фраз: position:absolute без координат — текст стоял криво и прыгал при смене
     длины фразы. Фиксированная полоса, выровненная точно по центру видимой области. */
  html.ngs-mobile .fileLoadingMessages{
    position: fixed !important;
    left: 24px !important;
    right: 24px !important;
    top: 50% !important;
    transform: translateY(-50%);
    text-align: center !important;
    font-size: 12px !important;
    letter-spacing: 2px !important;
    line-height: 1.7 !important;
    overflow: visible !important;
  }

  /* ==== Галерея (хостовый вьюер, зовётся комментариями через мост): фулскрин + жесты
     (src/ngsMobileGallery.js — пинч/пан портированы из NGS_Chat, свайп и двойной тап).
     Слайдер зума/±/reset/стрелки заменены жестами; скачивание и закрытие — штатные. ==== */
  /* Как в чате: галерея живёт МЕЖДУ шапкой и нижним баром (консистентность), бар рабочий. */
  html.ngs-mobile .ngsGalleryOverlay{
    top: calc(var(--ngs-m-header-h) + var(--ngs-m-safe-top)) !important;
    bottom: calc(var(--ngs-m-nav-h) + var(--ngs-m-safe-bottom)) !important;
    z-index: 8700 !important;
  }
  /* Бейдж типа и имя файла на телефоне только мешают (фидбэк владельца, как в чате). */
  html.ngs-mobile #ngsGalleryTypeBadge,
  html.ngs-mobile #ngsGalleryCaption{
    display: none !important;
  }
  html.ngs-mobile .ngsGalleryShell{
    width: 100% !important;
    height: 100% !important;
    max-width: none !important;
    max-height: none !important;
    box-sizing: border-box !important; /* база даёт padding:14px — при content-box 100vw
                                          вылезал за экран на 28px (кнопки/фото уезжали) */
    /* КОРЕНЬ «уезда» (замер плашкой: shell w402, ряды w490): колонка грида неявная (auto),
       её минимум раздувается до min-content ПОЛОСЫ ПРЕВЬЮ (6×72px несжимаемых миниатюр
       = 490) — и ВСЕ ряды (топбар/стейдж) торчат за экран. Явная колонка minmax(0,1fr). */
    grid-template-columns: minmax(0, 1fr) !important;
    border-radius: 0 !important;
    border: none !important;
  }
  html.ngs-mobile .ngsGalleryTopbar,
  html.ngs-mobile .ngsGalleryStage,
  html.ngs-mobile .ngsGalleryThumbsWrap{
    min-width: 0 !important;
    max-width: 100% !important;
  }
  html.ngs-mobile .ngsGalleryStage{
    touch-action: none; /* жесты наши: без нативного скролла/зума под пальцами */
  }
  /* Слайдер зума/± и стрелки заменены жестами; кнопка сброса скейла ОСТАЁТСЯ (как в чате). */
  html.ngs-mobile .ngsGalleryZoomBox,
  html.ngs-mobile .ngsGalleryNav{
    display: none !important;
  }
  html.ngs-mobile .ngsGalleryTopbar{
    padding-top: calc(var(--ngs-m-safe-top) + 8px) !important;
  }
  html.ngs-mobile .ngsGalleryBtn{
    width: 40px !important;
    height: 40px !important;
  }
  /* Превью-полоса: явные габариты с !important — все миниатюры видны рядом, скролл пальцем. */
  html.ngs-mobile .ngsGalleryThumbsWrap{
    padding: 6px 8px !important;
  }
  html.ngs-mobile .ngsGalleryThumbs{
    display: flex !important;
    gap: 8px !important;
    overflow-x: auto !important;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }
  html.ngs-mobile .ngsGalleryThumb{
    flex: 0 0 auto !important;
    width: 72px !important;
    height: 54px !important;
  }

  /* Рельс двигает ngsMobileNav пиксель-в-пиксель с нативным скроллом через translate3d.
     Здесь намеренно нет transition/margin/height: геометрия iframe остаётся стабильной,
     поэтому iOS не сбивает инерцию и позицию контента под пальцем. */

  /* ==== Мелочь оболочки: тосты/статус не шире экрана и не под баром. ==== */
  html.ngs-mobile .notification{
    width: min(92vw, 360px) !important;
    right: 10px !important;
    top: calc(var(--ngs-m-header-h) + var(--ngs-m-safe-top) + 6px) !important;
  }
  html.ngs-mobile .ngStatusMsg{
    max-width: 90vw !important;
    bottom: calc(var(--ngs-m-nav-h) + var(--ngs-m-safe-bottom) + 8px) !important;
  }
}
