/* ══════════════════════════════════════════════════════════════
   mobile-responsive.css — мобильная адаптация основных блоков
   Яндекс.Директ · Фотосайт · Рассылки · Аналитика нейросетей
   ══════════════════════════════════════════════════════════════ */

/* ── Общие утилиты ─────────────────────────────────────────────────────── */
.scroll-x {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

/* ══════════════════════════════════════════════════════════════
   1. ЯНДЕКС.ДИРЕКТ
   ══════════════════════════════════════════════════════════════ */

/* Дата-фильтры в хедере — wrap на мобилке */
#yadirect-header-btns {
    flex-wrap: wrap;
}

/* Кампанийный блок: два графика → один столбец на мобилке */
@media (max-width: 640px) {
    #yadirect-stats-panel > div[style*="grid-template-columns"] {
        grid-template-columns: 1fr !important;
    }

    /* Минимальная высота контейнера графика */
    #yadirect-stats-panel .chart-container {
        height: 280px;
    }

    /* KPI-плитки — мельче минимальный размер */
    #yadirect-kpis {
        grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)) !important;
        gap: 8px !important;
    }

    /* Контролы графика: кнопки метрик — перенос */
    #yd-chart-controls > div > div:first-child {
        flex-wrap: wrap !important;
        gap: 4px !important;
    }
    #yd-chart-controls select {
        max-width: 100% !important;
        width: 100%;
    }

    /* Таблица кампаний — горизонтальный скролл */
    #yadirect-camp-table .overflow-x-wrap {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    /* Кнопки подключения — на всю ширину */
    #yadirect-connect-panel .btn {
        width: 100%;
    }

    /* Buyer stats tiles — в одну строку без лишних столбцов */
    #yadirect-buyer-stats .ai-summary-tile {
        padding: 10px 12px;
    }
}

/* ══════════════════════════════════════════════════════════════
   2. АНАЛИТИКА ФОТОСАЙТА — ТОП-100 ПОЛЬЗОВАТЕЛЕЙ
   ══════════════════════════════════════════════════════════════ */

/* Таблица топ-пользователей — контейнер со скроллом */
#psTopUsersTable {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

/* Таблица внутри должна не сжиматься */
#psTopUsersTable table {
    min-width: 580px;
}

@media (max-width: 640px) {
    /* Строки диаграмм — один столбец */
    .ps-row-2, .ps-row-3 {
        grid-template-columns: 1fr !important;
    }

    /* Панель с пончиками — на мобилке вертикально */
    .ps-donut-wrap {
        flex-direction: column;
        align-items: center;
    }

    /* Дата-хедер фотосайта — перенос */
    .ps-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .ps-date-range {
        flex-wrap: wrap;
    }

    .ps-refresh-btn {
        margin-left: 0;
    }

    /* Карточки фотосайта — меньший минимум */
    .ps-cards {
        grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
        gap: 10px;
    }
}

/* ══════════════════════════════════════════════════════════════
   3. РАССЫЛКИ — ИСТОРИЯ И КОНВЕРСИИ
   ══════════════════════════════════════════════════════════════ */

/* Обёртка таблицы истории со скроллом */
.mailing-history-scroll {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    margin-bottom: 4px;
}

/* Сама таблица истории */
.mailing-history-scroll table,
#mailingHistory > div > table {
    min-width: 860px;
    width: 100%;
}

@media (max-width: 768px) {
    /* Ячейка конверсий — перенос текста */
    #mailingHistory td:last-child,
    #mailingHistory td .conv-cell {
        white-space: normal !important;
        word-break: break-word;
    }

    /* Статус-бейдж — чуть меньше */
    #mailingHistory span[style*="border-radius:4px"] {
        font-size: 10px !important;
        padding: 2px 6px !important;
    }

    /* Пагинация — по центру */
    .utm-pagination {
        flex-wrap: wrap;
        justify-content: center;
        gap: 6px;
    }
}

@media (max-width: 480px) {
    /* Кнопки управления рассылкой — на всю ширину */
    #mailing .send-btn-row {
        flex-direction: column;
    }
}

/* ══════════════════════════════════════════════════════════════
   4. АНАЛИТИКА НЕЙРОСЕТЕЙ
   ══════════════════════════════════════════════════════════════ */

/* Высота canvas для графиков окупаемости и заработка */
#aiROIChart {
    min-height: 300px;
}
#aiEptChart {
    min-height: 360px;
}
#aiTokenSpendingChart {
    min-height: 220px;
}

/* min-width на таблицах — гарантирует горизонтальный скролл,
   не даёт ячейкам сжиматься ниже читаемого размера */
#aiRequestsChartContainer table,
#aiProviderChartContainer table {
    min-width: 480px;
}

@media (max-width: 768px) {
    /* Хедер раздела аналитики нейросетей: кнопки + даты → перенос */
    #analytics-ai > .card > div[style*="justify-content:space-between"],
    #analytics-ai > .card > div[style*="justify-content: space-between"] {
        flex-direction: column !important;
        align-items: flex-start !important;
        gap: 10px !important;
    }

    /* Группы кнопок периода/группировки — перенос */
    #analytics-ai > .card > div > div[style*="gap:8px"] {
        flex-wrap: wrap !important;
    }

    /* Кнопки «По дням» / «По месяцам» и «Провайдер» / «Нейросеть» / «Итого» */
    #analytics-ai > .card > div > div[style*="gap:8px"] > div {
        flex-wrap: wrap !important;
    }

    /* Дата-инпуты в хедере аналитики — сжимаем */
    #analytics-ai .ai-date-input {
        max-width: 130px;
        font-size: 12px;
    }

    /* Блок «Расход токенов» — сетка плиток 1 столбец */
    #aiTokenSummaryTiles {
        grid-template-columns: 1fr 1fr !important;
        gap: 6px !important;
    }

    /* Контролы периода токенов — перенос */
    #analytics-ai .card > div[style*="gap:4px"] {
        flex-wrap: wrap !important;
    }

    /* Карточки «Окупаемость» — stat tiles в столбец */
    #aiROINetworkStats {
        flex-wrap: wrap !important;
        gap: 8px !important;
    }
    #aiROINetworkStats .ai-roi-stat-tile {
        min-width: calc(50% - 8px);
        flex: 1 1 calc(50% - 8px);
    }

    /* Карточки провайдеров в строку с переносом */
    #aiProviderChartContainer > div:first-child {
        display: flex !important;
        flex-wrap: wrap !important;
        gap: 8px !important;
    }
    #aiProviderChartContainer > div:first-child > div {
        min-width: 140px !important;
        flex: 1 1 140px !important;
    }

    /* Таблица провайдеров — скролл */
    #aiProviderChartContainer > div[style*="overflow-x"] {
        -webkit-overflow-scrolling: touch;
    }

    /* Таблица запросов — touch scroll */
    #aiRequestsChartContainer > div[style*="overflow-x"] {
        -webkit-overflow-scrolling: touch;
    }

    /* Карточки «Динамики запросов» — перенос по аналогии с провайдерами */
    #aiRequestsChartContainer > div:first-child {
        display: flex !important;
        flex-wrap: wrap !important;
        gap: 8px !important;
    }
    #aiRequestsChartContainer > div:first-child > div {
        min-width: 120px !important;
        flex: 1 1 120px !important;
    }

    /* Блок «Эталонная стоимость токена» — карточки с переносом */
    #refTokenCostBlock > div {
        flex-wrap: wrap !important;
        gap: 8px !important;
    }
    #refTokenCostBlock > div > div {
        flex: 1 1 160px !important;
        min-width: 0 !important;
    }

    /* Легенда ROI */
    #aiROILegend {
        flex-wrap: wrap;
        gap: 6px;
    }

    /* Кнопки периода ROI */
    #aiROIPeriodBtns {
        flex-wrap: wrap !important;
    }

    /* Выбор нейросети ROI */
    #aiROINetworkSelect {
        max-width: 100%;
        width: 100%;
    }

    /* Карточка с заголовком + контролами ROI/EPT → столбец */
    #analytics-ai .card > div[style*="align-items:flex-end"] {
        flex-direction: column !important;
        align-items: flex-start !important;
        gap: 10px !important;
    }

    /* Дата-фильтры + кнопки в блоках ROI/токенов → перенос */
    #analytics-ai .card > div > div[style*="flex-wrap:wrap"] {
        gap: 6px !important;
    }
}

@media (max-width: 480px) {
    /* Плитки токенов — 1 столбец */
    #aiTokenSummaryTiles {
        grid-template-columns: 1fr !important;
    }

    /* Stat-tiles окупаемости — 1 столбец */
    #aiROINetworkStats .ai-roi-stat-tile {
        min-width: 100%;
        flex: 1 1 100%;
    }

    /* Графики — минимальная высота меньше */
    #aiROIChart {
        min-height: 260px;
    }
    #aiEptChart {
        min-height: 300px;
    }

    /* Эталонная стоимость — вертикальная стопка */
    #refTokenCostBlock > div {
        flex-direction: column !important;
    }
    #refTokenCostBlock > div > div {
        flex: none !important;
        width: 100% !important;
        box-sizing: border-box !important;
    }

    /* Таблицы запросов/провайдеров — компактные ячейки */
    #aiRequestsChartContainer td,
    #aiRequestsChartContainer th,
    #aiProviderChartContainer td,
    #aiProviderChartContainer th {
        padding: 6px !important;
        font-size: 11px !important;
    }
}

/* ══════════════════════════════════════════════════════════════
   5. ОБЩИЕ ИСПРАВЛЕНИЯ ДЛЯ ТАБЛИЦ
   ══════════════════════════════════════════════════════════════ */
@media (max-width: 640px) {
    .card > div[style*="overflow-x:auto"],
    .card > div[style*="overflow-x: auto"] {
        -webkit-overflow-scrolling: touch;
    }
}

/* ══════════════════════════════════════════════════════════════
   6. SEO-ИНСТРУМЕНТ
   ══════════════════════════════════════════════════════════════ */

@media (max-width: 768px) {
    /* Двухколоночный сплит → 1 столбец, форма сверху */
    .st-split {
        grid-template-columns: 1fr !important;
    }

    /* Кнопки режима → перенос */
    .st-mode-switch {
        display: flex !important;
        flex-wrap: wrap;
    }

    /* Таблицы в результате → горизонтальный скролл */
    .st-result-body table {
        display: block;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        white-space: nowrap;
    }
    .st-result-body td,
    .st-result-body th {
        white-space: normal;
        min-width: 80px;
    }

    /* Кнопки действий справа в хедере результата → на новую строку */
    .st-result-tabs {
        flex-wrap: wrap;
        height: auto !important;
    }
    .st-result-tabs .st-tab-right {
        margin-left: 0;
        width: 100%;
        border-top: 1px solid rgba(255,255,255,.06);
        padding-top: 8px;
        padding-bottom: 8px;
        flex-wrap: wrap;
        gap: 6px;
    }

    /* Полноэкранный режим — паддинг уменьшить */
    .st-fs-body {
        padding: 20px 16px;
    }
}

@media (max-width: 480px) {
    /* Кнопки "Сгенерировать" + "Промпт" → вертикально */
    .st-submit-row {
        flex-direction: column;
    }
    .st-btn-primary,
    .st-submit-row .st-btn-sec {
        width: 100%;
        text-align: center;
        justify-content: center;
    }

    /* Кнопки подсказок → переносим */
    #seo-tool [style*="display:flex"][style*="gap:8px"] {
        flex-wrap: wrap;
    }

    /* Уменьшаем горизонтальный паддинг секции SEO */
    #seo-tool {
        padding-left: 12px !important;
        padding-right: 12px !important;
    }
}

/* ══════════════════════════════════════════════════════════════
   7. УПРАВЛЕНИЕ / СПРАВОЧНИКИ AI
   ══════════════════════════════════════════════════════════════ */

@media (max-width: 640px) {
    /* Инпуты справочника — убираем min-width */
    .ai-mgmt-input {
        min-width: 0 !important;
        width: 100%;
        box-sizing: border-box;
    }

    /* Кнопки вкладок справочника → перенос */
    #aiMgmtTabBtns {
        flex-wrap: wrap !important;
    }

    /* Секция "Курс RUB/USD" — 2 колонки → 1 */
    #aiMgmtRate > div {
        grid-template-columns: 1fr !important;
    }

    /* Провайдеры — таблица с горизонтальным скроллом */
    #aiProvidersList {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
    #aiProvidersList table {
        min-width: 360px;
    }
}

/* ══════════════════════════════════════════════════════════════
   8. РАСХОДЫ
   ══════════════════════════════════════════════════════════════ */

@media (max-width: 640px) {
    /* Форма добавления расхода: категория + кнопка → перенос */
    #expenseForm div[style*="display: flex"][style*="gap: 10px"] {
        flex-wrap: wrap;
    }
    #expenseForm div[style*="display: flex"][style*="gap: 10px"] > button {
        width: 100%;
    }

    /* Фильтр периода — убираем min-width у form-group */
    #expenses .filter-row .form-group {
        min-width: 0 !important;
        flex: 1 1 100%;
    }

    /* Таблица расходов — min-width для скролла */
    #expenses .table-container table {
        min-width: 580px;
    }

    /* Динамика расходов — уменьшаем высоту контейнера */
    #expenses .chart-container {
        height: 260px !important;
        padding: 12px !important;
        margin-top: 12px !important;
    }

    /* Блок AI Транзакций: 2-колоночная сетка → 1 столбец */
    #aiTransactionsBlock div[style*="grid-template-columns:1fr 1fr"] {
        grid-template-columns: 1fr !important;
    }

    /* Таблица AI транзакций — min-width */
    #aiTxTable {
        min-width: 700px;
    }

    /* Модалка AI Tx: 2 поля рядом → 1 столбец */
    #aiTxSingleMode > div[style*="grid-template-columns:1fr 1fr"] {
        grid-template-columns: 1fr !important;
    }
}

/* ══════════════════════════════════════════════════════════════
   9. ИСТОРИЯ РАССЫЛОК — СТОЛБЕЦ КОНВЕРСИЙ
   ══════════════════════════════════════════════════════════════ */

/* Разрешаем перенос текста внутри ячейки конверсий */
.conv-td {
    min-width: 110px;
}
.conv-td > div {
    white-space: normal !important;
    word-break: break-word;
    line-height: 1.5;
}

/* ── Дашборд: 2-колоночные сетки графиков → 1 колонка на мобильном ──
   Иначе графики (Доходы по сервисам / Расходы по категориям) сжимаются
   и выходят за ширину экрана. .stats-grid уже сворачивается отдельно. */
@media (max-width: 768px) {
    #dashboard div[style*="grid-template-columns: repeat(2"] {
        grid-template-columns: 1fr !important;
    }
    /* Chart.js канвасы не должны вылезать за карточку */
    #dashboard canvas {
        max-width: 100% !important;
    }
}
