/* ============================================
   АДАПТИВНЫЕ СТИЛИ ДЛЯ РАЗДЕЛА РАССЫЛОК
   ============================================ */

/* ИСПРАВЛЕНИЕ: Модальные окна на мобильных устройствах */
@media screen and (max-width: 768px) {

    /* Основной контейнер модального окна */
    .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        z-index: 9999;
    }

    /* Контент модального окна */
    .modal-content {
        margin: 20px auto;
        padding: 20px;
        width: 95%;
        max-width: 500px;
        max-height: calc(100vh - 40px);
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        position: relative;
        background: rgba(30, 30, 30, 0.98);
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
    }

    /* Внутренний контейнер для текста */
    .modal-content > div {
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }

    /* Telegram предпросмотр в модальном окне */
    .tg-preview-shell {
        max-height: 60vh;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }

    /* Текст в модальном окне - предотвращаем overflow */
    .modal-content p,
    .modal-content div {
        word-wrap: break-word;
        overflow-wrap: break-word;
        word-break: break-word;
    }

    /* Текстовые блоки с длинным текстом */
    .tg-text-bubble,
    .tg-caption-bubble {
        max-height: none;
        overflow-y: visible;
        word-wrap: break-word;
        overflow-wrap: break-word;
        word-break: break-word;
    }

    /* Кнопка закрытия модального окна */
    .modal-content .close {
        position: sticky;
        top: 0;
        right: 0;
        z-index: 10;
        background: rgba(30, 30, 30, 0.9);
        border-radius: 50%;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
        line-height: 1;
        padding: 0;
        margin-left: auto;
        margin-bottom: 10px;
    }

    /* Двухколоночная сетка редактора -> одна колонка */
    #mailing .card > div[style*="grid-template-columns: 1fr 1fr"] {
        display: block !important;
    }

    /* Карточки редактора и предпросмотра */
    #mailing .card + .card {
        margin-top: 15px;
    }

    /* Форма редактирования */
    .text-editor-toolbar {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 10px;
    }

    .format-btn {
        min-width: 44px;
        min-height: 44px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 8px;
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .format-btn:active {
        background: rgba(255, 255, 255, 0.2);
        transform: scale(0.95);
    }

    /* Textarea для текста */
    #mailingText {
        min-height: 200px;
        font-size: 16px; /* Важно: предотвращает zoom на iOS */
        padding: 12px;
        line-height: 1.5;
    }

    /* Селекторы и инпуты */
    #mailing select,
    #mailing input[type="text"],
    #mailing input[type="url"],
    #mailing textarea {
        font-size: 16px !important; /* Предотвращает zoom */
        padding: 12px;
        min-height: 44px;
    }

    /* Шаблонные кнопки */
    .template-buttons-container {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .template-btn {
        width: 100%;
        min-height: 44px;
        padding: 12px;
        text-align: left;
        background: rgba(33, 150, 243, 0.1);
        border: 1px solid rgba(33, 150, 243, 0.3);
        border-radius: 8px;
        color: #64b5f6;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .template-btn:active {
        background: rgba(33, 150, 243, 0.2);
        transform: scale(0.98);
    }

    /* Список кнопок для редактирования */
    .button-editor {
        display: flex;
        flex-direction: column;
        gap: 8px;
        padding: 12px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 8px;
        margin-bottom: 10px;
    }

    .button-editor input {
        width: 100%;
        font-size: 14px;
        padding: 10px;
    }

    .button-editor button {
        align-self: flex-start;
        min-height: 40px;
        padding: 8px 16px;
        font-size: 24px;
    }

    /* Предпросмотр Telegram — оболочка */
    .tg-preview-shell {
        max-width: 100%;
        margin: 0 auto;
        border-radius: 10px;
        overflow: hidden;
    }

    .tg-ps-header {
        padding: 8px 12px;
        gap: 8px;
    }

    .tg-ps-avatar {
        width: 30px;
        height: 30px;
        font-size: 13px;
        flex-shrink: 0;
    }

    .tg-ps-name {
        font-size: 13px;
    }

    .tg-ps-sub {
        font-size: 11px;
    }

    .tg-ps-body {
        padding: 10px 8px 12px;
        max-height: 70vh;
    }

    /* Блок сообщения */
    .tg-msg-block {
        max-width: 90%;
    }

    /* Текстовый пузырь */
    .tg-text-bubble {
        padding: 8px 10px 22px;
        font-size: 14px;
        line-height: 1.45;
        border-radius: 12px 12px 12px 3px;
    }

    /* Подпись под медиа */
    .tg-caption-bubble {
        padding: 6px 10px 20px;
        font-size: 14px;
        line-height: 1.45;
    }

    /* Временна́я метка */
    .tg-ts {
        font-size: 10px;
        bottom: 5px;
        right: 8px;
    }

    .tg-ts-photo {
        font-size: 10px;
        bottom: 6px;
        right: 6px;
        padding: 1px 5px;
    }

    /* Альбом: адаптивные высоты строк */
    .tg-album-row {
        gap: 2px;
    }

    .tg-album-cell img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
    }

    /* Масштабируем высоты альбомных строк под мобильный экран (×0.7) */
    .tg-media-area .tg-album-row:first-child .tg-album-cell,
    .tg-media-area .tg-album-row .tg-album-cell {
        /* высоты задаются inline-стилем; clip через overflow:hidden на .tg-media-area */
    }

    .tg-media-area {
        max-width: 100%;
    }

    /* Кнопки в предпросмотре */
    .tg-kbd {
        gap: 4px;
        margin-top: 4px;
    }

    .tg-kbd-btn {
        padding: 9px 10px;
        font-size: 13px;
        min-height: 38px;
        border-radius: 6px;
    }

    /* Прогресс рассылки */
    .progress-container {
        padding: 15px;
        max-height: calc(100vh - 100px);
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }

    .progress-stats {
        display: flex;
        flex-direction: column;
        gap: 12px;
        margin-bottom: 20px;
    }

    .stat-item {
        display: flex;
        justify-content: space-between;
        padding: 12px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 8px;
    }

    .stat-label {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.7);
    }

    .stat-value {
        font-size: 20px;
        font-weight: bold;
    }

    /* Кнопки управления */
    #mailing .btn {
        width: 100%;
        min-height: 50px;
        font-size: 16px;
        margin-bottom: 10px;
    }

    #mailing .btn-edit {
        width: 100%;
        min-height: 50px;
        margin-bottom: 10px;
    }

    /* Группа кнопок */
    #mailing > .card > div[style*="justify-content: flex-end"] {
        flex-direction: column !important;
        gap: 10px !important;
    }

    /* ============================================
       ИСПРАВЛЕНИЕ: История рассылок - таблица
       ============================================ */

    #mailingHistory {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        margin-top: 20px;
    }

    /* Таблица истории */
    #mailingHistory table {
        width: 100%;
        min-width: 800px; /* Увеличено для предотвращения сжатия */
        border-collapse: collapse;
        font-size: 12px;
        table-layout: fixed; /* Фиксированная ширина колонок */
    }

    /* Заголовки таблицы */
    #mailingHistory thead {
        background: rgba(33, 150, 243, 0.1);
        position: sticky;
        top: 0;
        z-index: 1;
    }

    #mailingHistory th {
        padding: 10px 8px;
        text-align: left;
        font-weight: 600;
        color: rgba(255, 255, 255, 0.9);
        white-space: nowrap;
        border-bottom: 2px solid rgba(255, 255, 255, 0.1);
    }

    /* Ширина колонок */
    #mailingHistory th:nth-child(1), /* Дата */
    #mailingHistory td:nth-child(1) {
        width: 140px;
        min-width: 140px;
    }

    #mailingHistory th:nth-child(2), /* Отправитель */
    #mailingHistory td:nth-child(2) {
        width: 120px;
        min-width: 120px;
    }

    #mailingHistory th:nth-child(3), /* Сегмент */
    #mailingHistory td:nth-child(3) {
        width: 180px;
        min-width: 180px;
    }

    #mailingHistory th:nth-child(4), /* Успешно */
    #mailingHistory td:nth-child(4) {
        width: 80px;
        min-width: 80px;
        text-align: center;
    }

    #mailingHistory th:nth-child(5), /* Ошибок */
    #mailingHistory td:nth-child(5) {
        width: 80px;
        min-width: 80px;
        text-align: center;
    }

    #mailingHistory th:nth-child(6), /* Пропущено */
    #mailingHistory td:nth-child(6) {
        width: 80px;
        min-width: 80px;
        text-align: center;
    }

    #mailingHistory th:nth-child(7), /* Всего */
    #mailingHistory td:nth-child(7) {
        width: 80px;
        min-width: 80px;
        text-align: center;
    }

    /* Ячейки таблицы */
    #mailingHistory td {
        padding: 10px 8px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        color: rgba(255, 255, 255, 0.85);
    }

    /* Строки таблицы */
    #mailingHistory tbody tr {
        transition: background 0.2s;
    }

    #mailingHistory tbody tr:hover {
        background: rgba(255, 255, 255, 0.02);
    }

    /* Альтернативный вариант: карточки вместо таблицы */
    @media screen and (max-width: 480px) {
        /* Скрываем таблицу на очень маленьких экранах */
        #mailingHistory table {
            display: none;
        }

        /* Показываем карточки */
        #mailingHistory {
            display: block;
        }

        /* Стили для карточек (если нужно переделать в будущем) */
        #mailingHistory .history-card {
            background: rgba(255, 255, 255, 0.05);
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 10px;
            border-left: 4px solid #2196f3;
        }

        #mailingHistory .history-card .date {
            font-weight: bold;
            margin-bottom: 8px;
            color: #64b5f6;
        }

        #mailingHistory .history-card .info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            font-size: 12px;
        }

        #mailingHistory .history-card .stat {
            display: flex;
            justify-content: space-between;
        }
    }

    /* Карточка информации о сегменте */
    .stat-card {
        margin-top: 15px;
    }

    /* Селектор сегмента */
    #customIdsInput textarea {
        min-height: 120px;
        font-size: 14px;
        line-height: 1.5;
    }

    /* Мультизагрузка изображений */
    #multiImageGroup {
        padding: 10px;
    }

    #multiImageThumbnails {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
    }

    #multiImageThumbnails .thumb-item {
        width: 64px;
        height: 64px;
    }

    #multiImageThumbnails .thumb-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 6px;
    }

    #multiImageThumbnails .thumb-item button {
        width: 20px;
        height: 20px;
        font-size: 11px;
        top: -4px;
        right: -4px;
    }

    /* Радиокнопки выбора источника медиа */
    #mediaUrlGroup label {
        font-size: 15px;
        padding: 10px;
    }

    #mediaUrlGroup input[type="radio"] {
        width: 20px;
        height: 20px;
    }

    /* Загрузка файла */
    #mailingMediaFile {
        width: 100%;
        padding: 12px;
        font-size: 14px;
    }

    /* Прогресс загрузки */
    #uploadProgress {
        margin-top: 15px;
    }

    .progress-bar {
        height: 8px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 4px;
        overflow: hidden;
        margin-bottom: 8px;
    }

    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #4caf50 0%, #66bb6a 100%);
        transition: width 0.3s ease;
    }

    #uploadStatus {
        font-size: 13px;
        line-height: 1.4;
    }

    /* Заголовки форм */
    #mailing h2 {
        font-size: 20px;
        margin-bottom: 15px;
    }

    #mailing h3 {
        font-size: 18px;
        margin-bottom: 12px;
    }

    /* Инструкции и подсказки */
    #mailing p,
    #mailing small {
        font-size: 14px;
        line-height: 1.5;
    }

    #mailing ul {
        padding-left: 20px;
    }

    #mailing li {
        margin-bottom: 8px;
        font-size: 13px;
    }

    /* Код-блоки */
    #mailing code {
        padding: 2px 6px;
        font-size: 12px;
        word-break: break-all;
    }
}

/* Очень маленькие экраны (до 480px) */
@media screen and (max-width: 480px) {

    /* Модальное окно на очень маленьких экранах */
    .modal-content {
        margin: 10px auto;
        padding: 15px;
        width: 98%;
        max-height: calc(100vh - 20px);
    }

    /* Уменьшаем отступы */
    #mailing .card {
        padding: 15px;
    }

    /* Ещё меньше шрифты */
    #mailing h2 {
        font-size: 18px;
    }

    #mailing h3 {
        font-size: 16px;
    }

    /* Кнопки форматирования */
    .format-btn {
        min-width: 40px;
        min-height: 40px;
        padding: 6px;
    }

    /* Статистика */
    .stat-value {
        font-size: 18px;
    }

    /* Прогресс */
    #progressPercent {
        font-size: 18px !important;
    }

    /* Telegram предпросмотр */
    .tg-text-bubble,
    .tg-caption-bubble {
        font-size: 13px;
        padding: 7px 9px 20px;
    }

    .tg-ps-body {
        max-height: 65vh;
        padding: 8px 6px 10px;
    }

    .tg-msg-block {
        max-width: 95%;
    }

    .tg-kbd-btn {
        font-size: 12px;
        padding: 8px;
        min-height: 34px;
    }

    /* Ограничиваем высоту ячеек альбома на маленьких экранах */
    .tg-album-cell {
        max-height: 120px !important;
    }

    /* История - показываем таблицу со скроллом */
    #mailingHistory {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    #mailingHistory table {
        display: table; /* Показываем таблицу */
        min-width: 700px;
        font-size: 11px;
    }

    #mailingHistory th,
    #mailingHistory td {
        padding: 6px 4px;
    }
}

/* Ландшафтная ориентация на планшетах */
@media screen and (min-width: 769px) and (max-width: 1024px) and (orientation: landscape) {

    /* Восстанавливаем двухколоночную сетку */
    #mailing .card > div[style*="grid-template-columns: 1fr 1fr"] {
        display: grid !important;
        grid-template-columns: 1fr 1fr !important;
        gap: 15px;
    }

    /* Модальное окно в ландшафте */
    .modal-content {
        max-height: calc(100vh - 40px);
        overflow-y: auto;
    }
}

/* Улучшение touch-взаимодействия */
@media (hover: none) and (pointer: coarse) {

    /* Все интерактивные элементы должны быть минимум 44x44px */
    #mailing button,
    #mailing select,
    #mailing input,
    #mailing textarea {
        min-height: 44px;
    }

    /* Увеличиваем область клика */
    #mailing .close {
        padding: 15px;
        font-size: 32px;
    }

    /* Улучшаем видимость активного состояния */
    #mailing button:active,
    #mailing .btn:active {
        opacity: 0.7;
        transform: scale(0.98);
    }

    /* Скрываем tooltip на touch-устройствах */
    #mailing [title]:hover::after {
        display: none;
    }
}

/* Темная тема - дополнительные улучшения для мобильных */
@media screen and (max-width: 768px) and (prefers-color-scheme: dark) {

    #mailing .card {
        background: rgba(30, 30, 30, 0.95);
    }

    #mailing input,
    #mailing select,
    #mailing textarea {
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .tg-preview-shell {
        background: #0e1621;
    }

    .tg-ps-header {
        background: #17212b;
    }

    .tg-ps-body {
        background: #17212b;
    }

    .tg-text-bubble,
    .tg-caption-bubble {
        background: #1f2d3a;
    }

    .modal-content {
        background: rgba(30, 30, 30, 0.98);
    }

    #mailingHistory thead {
        background: rgba(33, 150, 243, 0.15);
    }
}

/* ДОПОЛНИТЕЛЬНЫЕ ИСПРАВЛЕНИЯ ДЛЯ SAFARI iOS */
@supports (-webkit-touch-callout: none) {

    /* Исправление для Safari iOS */
    .modal {
        position: fixed !important;
        top: 0 !important;
        bottom: 0 !important;
        left: 0 !important;
        right: 0 !important;
        overflow-y: scroll !important;
        -webkit-overflow-scrolling: touch !important;
    }

    .modal-content {
        min-height: min-content;
        margin-bottom: 50px; /* Дополнительный отступ снизу */
    }

    /* Предотвращение bounce эффекта */
    body.modal-open {
        position: fixed;
        width: 100%;
        overflow: hidden;
    }
}