<?php
use EasyChat\View\HtmxFragmentRenderer;
use EasyChat\View\IntegrationFragments;

$easychat_proxy_badge = static function ($profile) use ($proxy_route_states) {
    $state = is_array($proxy_route_states[$profile] ?? null) ? $proxy_route_states[$profile] : [];
    $class = (string)($state['class'] ?? 'bg-light text-secondary border');
    $icon = (string)($state['icon'] ?? 'fa-random');
    $label = (string)($state['label'] ?? 'Напрямую');
    return '<span class="badge ' . htmlspecialchars($class, ENT_QUOTES, 'UTF-8') . ' px-2 py-1" style="font-size: 11px;">' .
        '<i class="fa ' . htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') . ' me-1"></i>' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') .
        '</span>';
};

$easychat_channel_profile_url = static function ($provider, $username = '', $user_id = '', $profile_url = '') {
    $provider = strtolower(trim((string)$provider));
    $username = ltrim(trim((string)$username), '@');
    $user_id = trim((string)$user_id);
    $profile_url = trim((string)$profile_url);

    if ($provider === 'max' || $provider === 'max-bot') {
        return preg_match('/^[A-Za-z0-9_.-]{1,64}$/', $username) ? 'https://max.ru/u/' . $username : '';
    }
    if ($provider === 'telegram') {
        return preg_match('/^[A-Za-z0-9_]{5,32}$/', $username) ? 'https://t.me/' . $username : '';
    }
    if ($provider === 'vk') {
        if (preg_match('/^[A-Za-z0-9_.]{3,64}$/', $username)) {
            return 'https://vk.com/' . $username;
        }
        return preg_match('/^\d+$/', $user_id) ? 'https://vk.com/club' . $user_id : '';
    }
    if ($provider === 'avito' && $profile_url !== '') {
        $parts = parse_url($profile_url);
        $host = is_array($parts) ? strtolower((string)($parts['host'] ?? '')) : '';
        $scheme = is_array($parts) ? strtolower((string)($parts['scheme'] ?? '')) : '';
        return ($scheme === 'https' && in_array($host, ['avito.ru', 'www.avito.ru'], true)) ? $profile_url : '';
    }

    return '';
};

$easychat_channel_identity = static function ($provider, $label, $username = '', $user_id = '', $profile_url = '') use ($easychat_channel_profile_url) {
    $label = trim((string)$label);
    if ($label === '') {
        return '';
    }

    $safe_label = htmlspecialchars($label, ENT_QUOTES, 'UTF-8');
    $url = $easychat_channel_profile_url($provider, $username, $user_id, $profile_url);
    if ($url === '') {
        return $safe_label;
    }

    return '<a class="easychat-channel-link" href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer" title="Открыть канал в новой вкладке">' .
        $safe_label . '<i class="fa fa-external-link ms-1" aria-hidden="true"></i></a>';
};
?>
<?php echo easychat_style_tag('css/views/marketplace.css'); ?>
<?php echo easychat_style_tag('css/views/integration.css'); ?>
<?php echo easychat_style_tag('css/views/email_integration.css'); ?>
<?php echo easychat_style_tag('css/views/moysklad_integration.css'); ?>
<?php echo easychat_style_tag('css/views/delivery_integration.css'); ?>
<div class="card border-0 shadow-sm rounded-4 p-4 easychat-integration-card">
    
    <div class="mb-4 border-bottom pb-3">
        <div>
            <h4 class="fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;"><i class="fa fa-plug me-2 text-primary"></i> Интеграции</h4>
            <p class="text-muted small mb-0">Подключайте внешние каналы мессенджеров для приема сообщений и ответов операторов</p>
        </div>
    </div>

    <!-- Alert Notifications -->
    <div id="integration-alert" class="alert d-none mb-4 p-3 animate__animated animate__fadeIn" style="border-radius: 10px; font-size: 14px;"></div>

    <!-- Bootstrap Nav Tabs -->
    <?php include __DIR__ . '/partials/integration_tabs.php'; ?>

    <!-- Integrations Form -->
    <form id="integration-form" autocomplete="off">
        <input type="hidden" id="easychat-settings-nonce" name="settings_nonce" value="<?php echo htmlspecialchars($easychat_settings_nonce ?? ''); ?>">
        <div class="tab-content" id="integrationTabContent">
            
            <!-- PANEL: Telegram -->
            <div class="tab-pane fade<?php echo $integration_tab_active('telegram') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="telegram-panel" role="tabpanel" aria-labelledby="telegram-tab">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-4">
                    <div>
                        <h5 class="fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;">Telegram</h5>
                        <div class="text-muted small">Интеграция с Telegram. Получайте сообщения от бота и отвечайте клиентам прямо из EasyChat.</div>
                        <div class="mt-2"><?php echo $easychat_proxy_badge('messenger_telegram'); ?></div>
                    </div>
                    <div class="form-check form-switch">
                        <input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_telegram_status" value="1" id="telegram-status" <?php echo (($chat_telegram_status ?? '0') == '1') ? 'checked' : ''; ?>>
                    </div>
                </div>

                <?php
                    $chat_telegram_connection = is_array($chat_telegram_connection ?? null) ? $chat_telegram_connection : [];
                    $chat_telegram_connection_title = (string)($chat_telegram_connection['title'] ?? 'Токен не добавлен');
                    $chat_telegram_connection_detail = (string)($chat_telegram_connection['detail'] ?? 'Вставьте токен Telegram бота, сохраните настройки и выполните проверку подключения.');
                    $chat_telegram_connection_class = (string)($chat_telegram_connection['badge_class'] ?? 'bg-light text-secondary border');
                    $chat_telegram_connection_icon = (string)($chat_telegram_connection['icon'] ?? 'fa-circle-o');
                ?>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="mb-3">
                            <label class="form-label text-muted small fw-semibold">Токен Telegram-бота (Bot Token)</label>
                            <input type="password" class="form-control easychat-rounded-field" name="chat_telegram_bot_token" value="" placeholder="<?php echo !empty($chat_telegram_bot_token_mask) ? 'Сохранен: ' . htmlspecialchars($chat_telegram_bot_token_mask) : 'Введите токен из BotFather'; ?>" autocomplete="new-password">
                            <div class="form-text small text-muted">Оставьте пустым, чтобы не менять сохраненный токен.</div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label text-muted small fw-semibold">Состояние подключения</label>
                        <div class="border bg-light-subtle p-3 easychat-status-panel">
                            <div class="d-flex align-items-center justify-content-between gap-2 mb-2">
                                <span id="telegram-connection-badge" class="badge <?php echo htmlspecialchars($chat_telegram_connection_class); ?> px-2 py-1">
                                    <i class="fa <?php echo htmlspecialchars($chat_telegram_connection_icon); ?> me-1"></i>
                                    <span id="telegram-connection-title"><?php echo htmlspecialchars($chat_telegram_connection_title); ?></span>
                                </span>
                                <?php if (!empty($chat_telegram_webhook_synced_at)) { ?>
                                    <span id="telegram-connection-time" class="text-muted small"><?php echo htmlspecialchars($chat_telegram_webhook_synced_at); ?></span>
                                <?php } else { ?>
                                    <span id="telegram-connection-time" class="text-muted small" style="display:none;"></span>
                                <?php } ?>
                            </div>
                            <div id="telegram-connection-detail" class="text-muted small mb-2"><?php echo htmlspecialchars($chat_telegram_connection_detail); ?></div>
                            <div id="telegram-connection-bot" class="text-secondary small" style="<?php echo !empty($chat_telegram_bot_name) ? '' : 'display:none;'; ?>">
                                <i class="fa fa-user-circle-o me-1"></i>
                                <span class="easychat-channel-identity"><?php echo $easychat_channel_identity('telegram', trim(($chat_telegram_bot_name ?? '') . ' ' . (!empty($chat_telegram_bot_username) ? '@' . ltrim((string)$chat_telegram_bot_username, '@') : '')), $chat_telegram_bot_username ?? '', $chat_telegram_bot_user_id ?? ''); ?></span>
                            </div>
                        </div>
                        <div class="form-text small text-muted">Webhook настраивается автоматически при успешной синхронизации.</div>
                    </div>
                </div>

                <div class="d-flex flex-wrap align-items-center gap-2 mb-4">
                    <button type="button" class="btn btn-primary btn-sm px-3 easychat-btn-rounded" id="btn-telegram-sync">
                        <i class="fa fa-plug me-1"></i> Проверить и подключить
                    </button>
                    <?php if (!empty($chat_telegram_last_error)) { ?>
                        <span id="telegram-connection-error" class="text-danger small">Ошибка: <?php echo htmlspecialchars($chat_telegram_last_error); ?></span>
                    <?php } else { ?>
                        <span id="telegram-connection-error" class="text-danger small" style="display:none;"></span>
                    <?php } ?>
                </div>

                <div class="border-top pt-3">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <div class="fw-semibold text-dark small">Диагностика Telegram</div>
                            <div class="text-muted small">Без токенов, raw payload и текста сообщений. Файл: <code>log/telegram.log</code>.</div>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input easychat-switch-md" type="checkbox" name="chat_telegram_logging" value="1" id="telegram-logging" <?php echo (($chat_telegram_logging ?? '0') == '1') ? 'checked' : ''; ?>>
                        </div>
                    </div>

                    <div id="telegram-logging-console-block" style="<?php echo (($chat_telegram_logging ?? '0') == '1') ? '' : 'display:none;'; ?>">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-secondary small fw-bold">Последние записи Telegram:</span>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary py-1 px-2 me-2 easychat-log-action" id="btn-refresh-telegram-logs"><i class="fa fa-refresh me-1"></i> Обновить</button>
                                <button type="button" class="btn btn-sm btn-outline-danger py-1 px-2 easychat-log-action" id="btn-clear-telegram-logs"><i class="fa fa-trash me-1"></i> Очистить</button>
                            </div>
                        </div>
                        <pre id="telegram-logs-console" class="text-white p-3 mb-0 easychat-log-console">Загрузка логов...</pre>
                    </div>
                </div>
            </div>

            <!-- PANEL: VK -->
            <div class="tab-pane fade<?php echo $integration_tab_active('vk') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="vk-panel" role="tabpanel" aria-labelledby="vk-tab">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-4">
                    <div>
                        <h5 class="fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;">ВКонтакте (VK)</h5>
                        <div class="text-muted small">Интеграция с группами ВКонтакте. Получайте сообщения сообщества и отвечайте клиентам прямо из EasyChat.</div>
                        <div class="mt-2"><?php echo $easychat_proxy_badge('messenger_vk'); ?></div>
                    </div>
                    <div class="form-check form-switch">
                        <input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_vk_status" value="1" id="vk-status" <?php echo (($chat_vk_status ?? '0') == '1') ? 'checked' : ''; ?>>
                    </div>
                </div>

                <?php
                    $chat_vk_connection = is_array($chat_vk_connection ?? null) ? $chat_vk_connection : [];
                    $chat_vk_connection_title = (string)($chat_vk_connection['title'] ?? 'Интеграция не настроена');
                    $chat_vk_connection_detail = (string)($chat_vk_connection['detail'] ?? 'Вставьте токен сообщества VK: EasyChat сам сохранит его и запустит проверку.');
                    $chat_vk_connection_class = (string)($chat_vk_connection['badge_class'] ?? 'bg-light text-secondary border');
                    $chat_vk_connection_icon = (string)($chat_vk_connection['icon'] ?? 'fa-circle-o');
                    $chat_vk_setup_steps = is_array($chat_vk_setup_steps ?? null) ? $chat_vk_setup_steps : [];
                    $vk_step_meta = [
                        'done' => ['icon' => 'fa-check-circle', 'class' => 'text-success', 'text_class' => 'text-success'],
                        'current' => ['icon' => 'fa-clock-o', 'class' => 'text-warning', 'text_class' => 'text-warning'],
                        'waiting' => ['icon' => 'fa-circle-o', 'class' => 'text-muted', 'text_class' => 'text-muted'],
                    ];
                ?>

                <div class="row">
                    <div class="col-md-5 mb-3">
                        <div class="mb-3">
                            <label class="form-label text-muted small fw-semibold">Токен сообщества VK (Group Access Token)</label>
                            <input type="password" class="form-control easychat-rounded-field" name="chat_vk_token" id="vk-token-input" value="" placeholder="<?php echo !empty($chat_vk_token_mask) ? 'Сохранен: ' . htmlspecialchars($chat_vk_token_mask) : 'Введите токен группы'; ?>" autocomplete="new-password">
                            <div class="form-text small text-muted">После вставки токена EasyChat сам сохранит его и запустит проверку подключения.</div>
                        </div>
                    </div>
                    <div class="col-md-7 mb-3">
                        <label class="form-label text-muted small fw-semibold">Состояние подключения</label>
                        <div class="border bg-light-subtle p-3 mb-3 easychat-status-panel">
                            <div class="d-flex align-items-center justify-content-between gap-2 mb-2">
                                <span id="vk-connection-badge" class="badge <?php echo htmlspecialchars($chat_vk_connection_class); ?> px-2 py-1">
                                    <i class="fa <?php echo htmlspecialchars($chat_vk_connection_icon); ?> me-1"></i>
                                    <span id="vk-connection-title"><?php echo htmlspecialchars($chat_vk_connection_title); ?></span>
                                </span>
                                <?php if (!empty($chat_vk_webhook_synced_at)) { ?>
                                    <span id="vk-connection-time" class="text-muted small"><?php echo htmlspecialchars($chat_vk_webhook_synced_at); ?></span>
                                <?php } else { ?>
                                    <span id="vk-connection-time" class="text-muted small" style="display:none;"></span>
                                <?php } ?>
                            </div>
                            <div id="vk-connection-detail" class="text-muted small mb-2"><?php echo htmlspecialchars($chat_vk_connection_detail); ?></div>
                            <div id="vk-connection-bot" class="text-secondary small" style="<?php echo !empty($chat_vk_bot_name) ? '' : 'display:none;'; ?>">
                                <i class="fa fa-user-circle-o me-1"></i>
                                <span class="easychat-channel-identity"><?php echo $easychat_channel_identity('vk', $chat_vk_bot_name ?? '', $chat_vk_bot_username ?? '', $chat_vk_bot_user_id ?? ''); ?></span>
                            </div>
                            <div id="vk-setup-checklist" class="small mt-3">
                                <?php foreach ($chat_vk_setup_steps as $step) {
                                    $step_status = (string)($step['status'] ?? 'waiting');
                                    $step_meta = $vk_step_meta[$step_status] ?? $vk_step_meta['waiting'];
                                ?>
                                    <div class="d-flex align-items-center gap-2 mb-1" data-vk-step="<?php echo htmlspecialchars((string)($step['key'] ?? '')); ?>" data-vk-step-status="<?php echo htmlspecialchars($step_status); ?>">
                                        <i class="fa <?php echo htmlspecialchars($step_meta['icon'] . ' ' . $step_meta['class']); ?>" aria-hidden="true"></i>
                                        <span><?php echo htmlspecialchars((string)($step['label'] ?? '')); ?></span>
                                        <span class="ms-auto <?php echo htmlspecialchars($step_meta['text_class']); ?>"><?php echo htmlspecialchars((string)($step['status_text'] ?? '')); ?></span>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>
                        <details class="small text-muted">
                            <summary class="fw-semibold" style="cursor:pointer;">Технические детали</summary>
                            <div class="input-group input-group-sm mt-2">
                                <input type="text" id="vk-webhook-url-input" class="form-control bg-white" readonly value="<?php echo htmlspecialchars($chat_vk_webhook_url ?? ''); ?>" style="border-radius: 8px 0 0 8px;">
                                <button class="btn btn-outline-secondary" type="button" id="btn-copy-vk-webhook" style="border-radius: 0 8px 8px 0;" title="Скопировать Webhook URL"><i class="fa fa-copy"></i></button>
                            </div>
                            <div class="form-text small text-muted mt-2">EasyChat сам получает Confirmation Code, создает Secret Key и включает в VK входящие сообщения и ответы сообщества.</div>
                        </details>
                    </div>
                </div>

                <div class="d-flex flex-wrap align-items-center gap-2">
                    <button type="button" class="btn btn-primary btn-sm px-3 easychat-btn-rounded" id="btn-vk-sync">
                        <i class="fa fa-plug me-1"></i> Проверить и подключить
                    </button>
                    <span id="vk-connection-error" class="text-danger small" style="display:none;"></span>
                </div>
            </div>

            <!-- PANEL: Avito -->
            <div class="tab-pane fade<?php echo $integration_tab_active('avito') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="avito-panel" role="tabpanel" aria-labelledby="avito-tab">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-4">
                    <div>
                        <h5 class="fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;">Авито</h5>
                        <div class="text-muted small">Интеграция с Авито. Получайте сообщения клиентов из мессенджера Авито и отвечайте прямо из EasyChat.</div>
                        <div class="mt-2"><?php echo $easychat_proxy_badge('messenger_avito'); ?></div>
                    </div>
                    <div class="form-check form-switch">
                        <input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_avito_status" value="1" id="avito-status" <?php echo (($chat_avito_status ?? '0') == '1') ? 'checked' : ''; ?>>
                    </div>
                </div>

                <?php
                    $avito_access = is_array($chat_avito_access_incident ?? null) ? $chat_avito_access_incident : [];
                    $avito_access_items = is_array($avito_access['items'] ?? null) ? $avito_access['items'] : [];
                ?>
                <section id="avito-access-incident" class="easychat-avito-incident mb-4" <?php echo empty($avito_access['active']) ? 'hidden' : ''; ?> aria-labelledby="avito-access-incident-title" aria-live="polite">
                    <div class="easychat-avito-incident__mark" aria-hidden="true"><img src="assets/channels/avito.svg" alt=""></div>
                    <div class="easychat-avito-incident__body">
                        <div class="d-flex flex-wrap align-items-start justify-content-between gap-3">
                            <div>
                                <div class="easychat-avito-incident__eyebrow">Требуется действие</div>
                                <h6 id="avito-access-incident-title" class="mb-1">Avito ограничил Messenger API тарифом</h6>
                                <p class="mb-0">Не синхронизируются диалоги: <strong data-avito-incident-count><?php echo (int)($avito_access['count'] ?? 0); ?></strong>. Подключение и webhook могут выглядеть исправными, но сообщения в этих чатах недоступны.</p>
                            </div>
                            <span class="easychat-avito-incident__status"><i class="fa fa-exclamation-circle" aria-hidden="true"></i> HTTP 402</span>
                        </div>
                        <div class="easychat-avito-incident__dialogs" data-avito-incident-dialogs>
                            <?php foreach ($avito_access_items as $item) { ?>
                                <a href="index.php?route=index&chat_id=<?php echo (int)($item['chat_id'] ?? 0); ?>" class="easychat-avito-incident__dialog">
                                    <span class="text-truncate"><?php echo htmlspecialchars((string)($item['display_name'] ?? 'Диалог Avito'), ENT_QUOTES, 'UTF-8'); ?></span>
                                    <small><?php echo htmlspecialchars((string)($item['last_seen_at'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></small>
                                </a>
                            <?php } ?>
                        </div>
                        <div class="easychat-avito-incident__actions">
                            <button type="button" class="btn btn-dark btn-sm easychat-btn-rounded" id="btn-avito-copy-support" data-support-message="<?php echo htmlspecialchars((string)($avito_access['support_message'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"><i class="fa fa-copy me-1" aria-hidden="true"></i> Скопировать обращение</button>
                            <button type="button" class="btn btn-outline-dark btn-sm easychat-btn-rounded" id="btn-avito-recheck-access"><i class="fa fa-refresh me-1" aria-hidden="true"></i> Проверить снова</button>
                            <a href="https://avito.akamaized.net/business/tools/messenger" class="easychat-avito-incident__link" target="_blank" rel="noopener noreferrer">Тарифы с Messenger API <i class="fa fa-external-link" aria-hidden="true"></i></a>
                        </div>
                    </div>
                </section>

                <?php
                    $chat_avito_connection = is_array($chat_avito_connection ?? null) ? $chat_avito_connection : [];
                    $chat_avito_connection_title = (string)($chat_avito_connection['title'] ?? 'Интеграция не настроена');
                    $chat_avito_connection_detail = (string)($chat_avito_connection['detail'] ?? 'Введите Client ID и Client Secret из кабинета Авито: EasyChat сам сохранит их и подключит webhook.');
                    $chat_avito_connection_class = (string)($chat_avito_connection['badge_class'] ?? 'bg-light text-secondary border');
                    $chat_avito_connection_icon = (string)($chat_avito_connection['icon'] ?? 'fa-circle-o');
                ?>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="mb-3">
                            <label class="form-label text-muted small fw-semibold" for="avito-client-id">Client ID Авито</label>
                            <input type="text" class="form-control easychat-rounded-field" id="avito-client-id" name="chat_avito_client_id" value="" data-has-secret="<?php echo !empty($chat_avito_client_id_mask) ? '1' : '0'; ?>" placeholder="<?php echo !empty($chat_avito_client_id_mask) ? 'Сохранен: ' . htmlspecialchars($chat_avito_client_id_mask) : 'Введите Client ID'; ?>" autocomplete="off" autocapitalize="none" autocorrect="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-bwignore>
                        </div>
                        <div class="mb-3">
                            <label class="form-label text-muted small fw-semibold" for="avito-client-secret">Client Secret Авито</label>
                            <input type="password" class="form-control easychat-rounded-field" id="avito-client-secret" name="chat_avito_client_secret" value="" data-has-secret="<?php echo !empty($chat_avito_client_secret_mask) ? '1' : '0'; ?>" placeholder="<?php echo !empty($chat_avito_client_secret_mask) ? 'Сохранен: ' . htmlspecialchars($chat_avito_client_secret_mask) : 'Введите Client Secret'; ?>" autocomplete="new-password" autocapitalize="none" autocorrect="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-bwignore>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label text-muted small fw-semibold">Состояние подключения</label>
                        <div class="border bg-light-subtle p-3 easychat-status-panel">
                            <div class="d-flex align-items-center justify-content-between gap-2 mb-2">
                                <span id="avito-connection-badge" class="badge <?php echo htmlspecialchars($chat_avito_connection_class); ?> px-2 py-1">
                                    <i class="fa <?php echo htmlspecialchars($chat_avito_connection_icon); ?> me-1"></i>
                                    <span id="avito-connection-title"><?php echo htmlspecialchars($chat_avito_connection_title); ?></span>
                                </span>
                                <?php if (!empty($chat_avito_webhook_synced_at)) { ?>
                                    <span id="avito-connection-time" class="text-muted small"><?php echo htmlspecialchars($chat_avito_webhook_synced_at); ?></span>
                                <?php } else { ?>
                                    <span id="avito-connection-time" class="text-muted small" style="display:none;"></span>
                                <?php } ?>
                            </div>
                            <div id="avito-connection-detail" class="text-muted small mb-2"><?php echo htmlspecialchars($chat_avito_connection_detail); ?></div>
                            <div id="avito-connection-bot" class="text-secondary small" style="<?php echo !empty($chat_avito_bot_name) ? '' : 'display:none;'; ?>">
                                <i class="fa fa-user-circle-o me-1"></i>
                                <span class="easychat-channel-identity"><?php echo $easychat_channel_identity('avito', $chat_avito_bot_name ?? '', $chat_avito_bot_username ?? '', $chat_avito_bot_user_id ?? ''); ?></span>
                            </div>
                        </div>
                        <div class="form-text small text-muted">Отдельно сохранять страницу не нужно: после ввода второго поля EasyChat сам проверит доступ и подключит webhook V3.</div>
                    </div>
                </div>

                <div class="d-flex flex-wrap align-items-center gap-2 mb-4">
                    <button type="button" class="btn btn-primary btn-sm px-3 easychat-btn-rounded" id="btn-avito-sync">
                        <i class="fa fa-plug me-1"></i> Проверить и подключить
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm px-3 easychat-btn-rounded" id="btn-avito-health"
                        data-htmx-managed="1"
                        hx-post="index.php?route=integration/avitoHealth"
                        hx-include="#easychat-settings-nonce"
                        hx-target="#avito-health-result"
                        hx-swap="<?php echo htmlspecialchars(HtmxFragmentRenderer::integrationDiagnosticsSwap(), ENT_QUOTES, 'UTF-8'); ?>"
                        hx-sync="this:replace"
                        hx-indicator="#btn-avito-health">
                        <i class="fa fa-heartbeat me-1"></i> Avito Health
                    </button>
                    <span id="avito-connection-error" class="text-danger small" style="display:none;"></span>
                </div>
                <?php echo IntegrationFragments::avitoHealthResult(); ?>

                <div class="border-top pt-3">
                    <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                        <div>
                            <div class="fw-semibold text-dark small">Контекст объявлений для ИИ</div>
                            <div class="text-muted small">ИИ будет видеть карточку товара Авито в ответах и подсказках. Если клиент написал из общего чата без товара, EasyChat передаст ИИ, что объявление не выбрано.</div>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input easychat-switch-md" type="checkbox" name="chat_ai_avito_item_context_status" value="1" id="ai-avito-item-context-status" <?php echo (($chat_ai_avito_item_context_status ?? '1') == '1') ? 'checked' : ''; ?>>
                        </div>
                    </div>
                    <div id="ai-avito-context-hint" class="mt-2 alert alert-info py-2 px-3 small mb-3 easychat-alert-rounded" style="display:none;">
                        <i class="fa fa-info-circle me-1"></i>
                        Сначала укажите API key на вкладке «ИИ-консультант» в основных настройках.
                        <a href="index.php?route=setting#ai-panel" class="btn btn-outline-primary btn-sm ms-2 easychat-btn-rounded" id="btn-open-ai-settings">
                            <i class="fa fa-magic me-1"></i> Открыть настройки ИИ
                        </a>
                    </div>
                    <div id="ai-avito-policy-options" class="mt-3">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label text-muted small fw-semibold">RAG в Avito</label>
                                <select class="form-select form-select-sm easychat-rounded-field" name="chat_ai_avito_rag_mode" id="ai-avito-rag-mode">
                                    <option value="auto" <?php echo (($chat_ai_avito_rag_mode ?? 'auto') === 'auto') ? 'selected' : ''; ?>>Авто</option>
                                    <option value="general_chats" <?php echo (($chat_ai_avito_rag_mode ?? 'auto') === 'general_chats') ? 'selected' : ''; ?>>Только общие чаты</option>
                                    <option value="always" <?php echo (($chat_ai_avito_rag_mode ?? 'auto') === 'always') ? 'selected' : ''; ?>>Всегда</option>
                                    <option value="off" <?php echo (($chat_ai_avito_rag_mode ?? 'auto') === 'off') ? 'selected' : ''; ?>>Выключить</option>
                                </select>
                                <div class="form-text small text-muted">В режиме «Авто» карточка главная для товара, а база знаний помогает с доставкой, оплатой и гарантией.</div>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label text-muted small fw-semibold">Поиск по сайту в Avito</label>
                                <select class="form-select form-select-sm easychat-rounded-field" name="chat_ai_avito_tools_mode" id="ai-avito-tools-mode">
                                    <option value="auto" <?php echo (($chat_ai_avito_tools_mode ?? 'auto') === 'auto') ? 'selected' : ''; ?>>Авто</option>
                                    <option value="pages_only" <?php echo (($chat_ai_avito_tools_mode ?? 'auto') === 'pages_only') ? 'selected' : ''; ?>>Только страницы</option>
                                    <option value="products_pages" <?php echo (($chat_ai_avito_tools_mode ?? 'auto') === 'products_pages') ? 'selected' : ''; ?>>Товары и страницы</option>
                                    <option value="off" <?php echo (($chat_ai_avito_tools_mode ?? 'auto') === 'off') ? 'selected' : ''; ?>>Выключить</option>
                                </select>
                                <div class="form-text small text-muted">Tools вызываются только когда это уместно по вопросу клиента и общему режиму поиска ИИ.</div>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label text-muted small fw-semibold">Альтернативные товары</label>
                                <select class="form-select form-select-sm easychat-rounded-field" name="chat_ai_avito_alternatives_mode" id="ai-avito-alternatives-mode">
                                    <option value="on_request" <?php echo (($chat_ai_avito_alternatives_mode ?? 'on_request') === 'on_request') ? 'selected' : ''; ?>>Только по просьбе</option>
                                    <option value="soft" <?php echo (($chat_ai_avito_alternatives_mode ?? 'on_request') === 'soft') ? 'selected' : ''; ?>>Мягко предлагать</option>
                                    <option value="off" <?php echo (($chat_ai_avito_alternatives_mode ?? 'on_request') === 'off') ? 'selected' : ''; ?>>Не предлагать</option>
                                </select>
                                <div class="form-text small text-muted">По умолчанию ИИ не отвлекает от объявления и предлагает замену только если покупатель попросил.</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="border-top pt-3 mt-3">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <div class="fw-semibold text-dark small">Диагностика Avito</div>
                            <div class="text-muted small">Без токенов, raw payload, полного webhook URL и текста сообщений. Файл: <code>log/avito.log</code>.</div>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input easychat-switch-md" type="checkbox" name="chat_avito_logging" value="1" id="avito-logging" <?php echo (($chat_avito_logging ?? '0') == '1') ? 'checked' : ''; ?>>
                        </div>
                    </div>

                    <div id="avito-logging-console-block" style="<?php echo (($chat_avito_logging ?? '0') == '1') ? '' : 'display:none;'; ?>">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-secondary small fw-bold">Последние записи Avito:</span>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary py-1 px-2 me-2 easychat-log-action" id="btn-refresh-avito-logs"><i class="fa fa-refresh me-1"></i> Обновить</button>
                                <button type="button" class="btn btn-sm btn-outline-danger py-1 px-2 easychat-log-action" id="btn-clear-avito-logs"><i class="fa fa-trash me-1"></i> Очистить</button>
                            </div>
                        </div>
                        <pre id="avito-logs-console" class="text-white p-3 mb-0 easychat-log-console">Загрузка логов...</pre>
                    </div>
                </div>
            </div>

            <!-- PANEL: Youla -->
            <div class="tab-pane fade<?php echo $integration_tab_active('youla') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="youla-panel" role="tabpanel" aria-labelledby="youla-tab">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-4">
                    <div>
                        <h5 class="fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;">Юла</h5>
                        <div class="text-muted small">Интеграция с Partner API Юлы: входящие сообщения, ответы операторов и контекст карточки для ИИ.</div>
                        <div class="mt-2"><?php echo $easychat_proxy_badge('messenger_youla'); ?></div>
                    </div>
                    <div class="form-check form-switch">
                        <input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_youla_status" value="1" id="youla-status" <?php echo (($chat_youla_status ?? '0') == '1') ? 'checked' : ''; ?>>
                    </div>
                </div>

                <?php
                    $chat_youla_connection = is_array($chat_youla_connection ?? null) ? $chat_youla_connection : [];
                    $chat_youla_connection_title = (string)($chat_youla_connection['title'] ?? 'Интеграция не настроена');
                    $chat_youla_connection_detail = (string)($chat_youla_connection['detail'] ?? 'Вставьте Bearer token Юлы. EasyChat автоматически проверит доступ и подготовит webhook URL.');
                    $chat_youla_connection_class = (string)($chat_youla_connection['badge_class'] ?? 'bg-light text-secondary border');
                    $chat_youla_connection_icon = (string)($chat_youla_connection['icon'] ?? 'fa-circle-o');
                    $chat_youla_support_message = implode("\n", [
                        'Здравствуйте. Пожалуйста, подключите CloudEvents webhook для интеграции нашей системы с Youla Partner API.',
                        '',
                        'Webhook URL:',
                        (string)($chat_youla_webhook_url ?? ''),
                        '',
                        'URL нужно добавить целиком, включая параметры provider и id. id — защитный идентификатор в нашей системе, а не идентификатор продавца в Юле.',
                        '',
                        'Нужные события:',
                        '- message.income',
                        '- product.block',
                        '- product.archive',
                        '- user.block',
                        '- user.unblock',
                    ]);
                ?>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="mb-3">
                            <label class="form-label text-muted small fw-semibold">Bearer token Юлы</label>
                            <input type="password" class="form-control easychat-rounded-field" name="chat_youla_token" value="" data-has-secret="<?php echo !empty($chat_youla_token_mask) ? '1' : '0'; ?>" placeholder="<?php echo !empty($chat_youla_token_mask) ? 'Сохранен: ' . htmlspecialchars($chat_youla_token_mask) : 'Вставьте Bearer token'; ?>" autocomplete="new-password">
                        </div>
                        <label class="form-label text-muted small fw-semibold">Webhook URL</label>
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control easychat-rounded-field" id="youla-webhook-url" value="<?php echo htmlspecialchars($chat_youla_webhook_url ?? ''); ?>" readonly>
                            <button type="button" class="btn btn-outline-secondary" id="btn-copy-youla-webhook"><i class="fa fa-copy me-1"></i> Копировать</button>
                        </div>
                        <textarea id="youla-support-message" class="visually-hidden" readonly><?php echo htmlspecialchars($chat_youla_support_message); ?></textarea>
                        <div class="d-flex flex-wrap align-items-center gap-2 mt-2">
                            <button type="button" class="btn btn-outline-primary btn-sm easychat-btn-rounded" id="btn-copy-youla-support-message">
                                <i class="fa fa-envelope-o me-1"></i> Скопировать текст для Юлы
                            </button>
                            <span class="form-text small text-muted m-0">URL можно добавить в кабинете Юлы или передать менеджеру Юлы. Параметр <code>id</code> нужен как защитный идентификатор канала.</span>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label text-muted small fw-semibold">Состояние подключения</label>
                        <div class="border bg-light-subtle p-3 easychat-status-panel">
                            <div class="d-flex align-items-center justify-content-between gap-2 mb-2">
                                <span id="youla-connection-badge" class="badge <?php echo htmlspecialchars($chat_youla_connection_class); ?> px-2 py-1">
                                    <i class="fa <?php echo htmlspecialchars($chat_youla_connection_icon); ?> me-1"></i>
                                    <span id="youla-connection-title"><?php echo htmlspecialchars($chat_youla_connection_title); ?></span>
                                </span>
                                <?php if (!empty($chat_youla_webhook_synced_at)) { ?>
                                    <span id="youla-connection-time" class="text-muted small"><?php echo htmlspecialchars($chat_youla_webhook_synced_at); ?></span>
                                <?php } else { ?>
                                    <span id="youla-connection-time" class="text-muted small" style="display:none;"></span>
                                <?php } ?>
                            </div>
                            <div id="youla-connection-detail" class="text-muted small mb-2"><?php echo htmlspecialchars($chat_youla_connection_detail); ?></div>
                            <div id="youla-connection-bot" class="text-secondary small" style="<?php echo !empty($chat_youla_bot_name) ? '' : 'display:none;'; ?>">
                                <i class="fa fa-user-circle-o me-1"></i>
                                <span class="easychat-channel-identity"><?php echo $easychat_channel_identity('youla', $chat_youla_bot_name ?? '', $chat_youla_bot_username ?? '', $chat_youla_bot_user_id ?? ''); ?></span>
                            </div>
                            <div id="youla-connection-error" class="text-danger small mt-2" style="display:none;"></div>
                        </div>
                        <div class="form-text small text-muted">Официальный Swagger Юлы не содержит метода автоматической регистрации webhook. После вставки нового Bearer token EasyChat автоматически проверит API-доступ и подготовит URL для ручного подключения.</div>
                    </div>
                </div>

                <div class="border-top mt-3 pt-3">
                    <div class="d-flex justify-content-between align-items-start gap-3">
                        <div>
                            <div class="fw-semibold text-dark small">Контекст карточек Юлы для ИИ</div>
                            <div class="text-muted small">ИИ будет видеть товар Юлы в автоответах и подсказках оператору: ID, название, цену, описание и параметры, если они доступны через Partner API.</div>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input easychat-switch-md" type="checkbox" name="chat_ai_youla_item_context_status" value="1" id="ai-youla-item-context-status" <?php echo (($chat_ai_youla_item_context_status ?? '1') == '1') ? 'checked' : ''; ?>>
                        </div>
                    </div>
                </div>

                <div class="border-top mt-3 pt-3">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <div class="fw-semibold text-dark small">Диагностика Юлы</div>
                            <div class="text-muted small">Без токенов, raw payload, полного webhook URL и текста сообщений. Файл: <code>log/youla.log</code>.</div>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input easychat-switch-md" type="checkbox" name="chat_youla_logging" value="1" id="youla-logging" <?php echo (($chat_youla_logging ?? '0') == '1') ? 'checked' : ''; ?>>
                        </div>
                    </div>

                    <div id="youla-logging-console-block" style="<?php echo (($chat_youla_logging ?? '0') == '1') ? '' : 'display:none;'; ?>">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-secondary small fw-bold">Последние записи Юлы:</span>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary py-1 px-2 me-2 easychat-log-action" id="btn-refresh-youla-logs"><i class="fa fa-refresh me-1"></i> Обновить</button>
                                <button type="button" class="btn btn-sm btn-outline-danger py-1 px-2 easychat-log-action" id="btn-clear-youla-logs"><i class="fa fa-trash me-1"></i> Очистить</button>
                            </div>
                        </div>
                        <pre id="youla-logs-console" class="text-white p-3 mb-0 easychat-log-console">Загрузка логов...</pre>
                    </div>
                </div>
            </div>

            <!-- PANEL: Wildberries -->
            <div class="tab-pane fade<?php echo $integration_tab_active('wildberries') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="wildberries-panel" role="tabpanel" aria-labelledby="wildberries-tab">
                <?php
                $marketplace_provider = 'wildberries';
                $marketplace_provider_definition = is_array($marketplace_providers['wildberries'] ?? null) ? $marketplace_providers['wildberries'] : [];
                $marketplace_provider_accounts = is_array($marketplace_accounts_by_provider['wildberries'] ?? null) ? $marketplace_accounts_by_provider['wildberries'] : [];
                include __DIR__ . '/partials/marketplace_provider_panel.php';
                ?>
            </div>

            <!-- PANEL: Ozon -->
            <div class="tab-pane fade<?php echo $integration_tab_active('ozon') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="ozon-panel" role="tabpanel" aria-labelledby="ozon-tab">
                <?php
                $marketplace_provider = 'ozon';
                $marketplace_provider_definition = is_array($marketplace_providers['ozon'] ?? null) ? $marketplace_providers['ozon'] : [];
                $marketplace_provider_accounts = is_array($marketplace_accounts_by_provider['ozon'] ?? null) ? $marketplace_accounts_by_provider['ozon'] : [];
                include __DIR__ . '/partials/marketplace_provider_panel.php';
                ?>
            </div>

            <!-- PANEL: Яндекс Маркет -->
            <div class="tab-pane fade<?php echo $integration_tab_active('yandex_market') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="yandex-market-panel" role="tabpanel" aria-labelledby="yandex-market-tab">
                <?php
                $marketplace_provider = 'yandex_market';
                $marketplace_provider_definition = is_array($marketplace_providers['yandex_market'] ?? null) ? $marketplace_providers['yandex_market'] : [];
                $marketplace_provider_accounts = is_array($marketplace_accounts_by_provider['yandex_market'] ?? null) ? $marketplace_accounts_by_provider['yandex_market'] : [];
                include __DIR__ . '/partials/marketplace_provider_panel.php';
                ?>
            </div>

            <!-- PANEL: MAX -->
            <div class="tab-pane fade<?php echo $integration_tab_active('max') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="max-panel" role="tabpanel" aria-labelledby="max-tab">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-4">
                    <div>
                        <h5 class="fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;">MAX</h5>
                        <div class="text-muted small">Подключите бота или личный аккаунт MAX — оба варианта могут работать одновременно.</div>
                        <div class="mt-2"><?php echo $easychat_proxy_badge('messenger_max'); ?></div>
                    </div>
                </div>

                <?php
                    $chat_max_bot_connection = is_array($chat_max_bot_connection ?? null) ? $chat_max_bot_connection : [];
                    $chat_max_bot_connection_title = (string)($chat_max_bot_connection['title'] ?? 'Токен не добавлен');
                    $chat_max_bot_connection_detail = (string)($chat_max_bot_connection['detail'] ?? 'Вставьте токен MAX-бота, сохраните настройки и выполните проверку подключения.');
                    $chat_max_bot_connection_class = (string)($chat_max_bot_connection['badge_class'] ?? 'bg-light text-secondary border');
                    $chat_max_bot_connection_icon = (string)($chat_max_bot_connection['icon'] ?? 'fa-circle-o');
                    $chat_max_connection = is_array($chat_max_connection ?? null) ? $chat_max_connection : [];
                    $chat_max_connection_title = (string)($chat_max_connection['title'] ?? 'Нужна авторизация');
                    $chat_max_connection_detail = (string)($chat_max_connection['detail'] ?? 'Выполните вход в личный MAX.');
                    $chat_max_connection_class = (string)($chat_max_connection['badge_class'] ?? 'bg-light text-secondary border');
                    $chat_max_connection_icon = (string)($chat_max_connection['icon'] ?? 'fa-circle-o');
                    $chat_max_health_items = is_array($chat_max_health_items ?? null) ? $chat_max_health_items : [];
                    $chat_max_health_generation = max(1, (int)($chat_max_health['generation'] ?? 1));
                    $chat_max_dedicated_cron_state = is_array($chat_max_dedicated_cron_state ?? null) ? $chat_max_dedicated_cron_state : [];
                    $chat_max_dedicated_cron_title = (string)($chat_max_dedicated_cron_state['title'] ?? 'Добавьте отдельный запуск');
                    $chat_max_dedicated_cron_detail = (string)($chat_max_dedicated_cron_state['detail'] ?? 'Скопируйте команду в планировщик хостинга.');
                    $chat_max_dedicated_cron_class = (string)($chat_max_dedicated_cron_state['badge_class'] ?? 'bg-info-subtle text-info border border-info-subtle');
                    $chat_max_dedicated_cron_icon = (string)($chat_max_dedicated_cron_state['icon'] ?? 'fa-copy');
                    $chat_max_dedicated_cron_modes = is_array($chat_max_dedicated_cron_modes ?? null) ? $chat_max_dedicated_cron_modes : [];
                    $chat_max_dedicated_cron_mode = (string)($chat_max_dedicated_cron_mode ?? 'conservative');
                    $chat_max_personal_inbound_scope = is_array($chat_max_personal_inbound_scope ?? null) ? $chat_max_personal_inbound_scope : ['dialogs', 'channels', 'groups'];
                    $chat_max_auth_state = is_array($chat_max_auth_state ?? null) ? $chat_max_auth_state : [];
                    $chat_max_auth_status = (string)($chat_max_auth_state['status'] ?? 'idle');
                    $chat_max_auth_message = (string)($chat_max_auth_state['message'] ?? '');
                    $chat_max_auth_qr_svg = (string)($chat_max_auth_state['qr_svg'] ?? '');
                    $chat_max_auth_qr_link = (string)($chat_max_auth_state['qr_link'] ?? '');
                    $chat_max_auth_password_hint = (string)($chat_max_auth_state['password_hint'] ?? '');
                    $chat_max_auth_phone_mask = (string)($chat_max_auth_state['phone_mask'] ?? '');
                    $chat_max_sms_visible = in_array($chat_max_auth_status, ['sms_starting', 'sms_pending', 'password_required'], true);
                    $chat_max_reset_visible = in_array($chat_max_auth_status, ['connected', 'qr_starting', 'worker_ready', 'qr_pending', 'qr_wait', 'qr_confirming', 'sms_starting', 'sms_pending', 'password_required'], true);
                    $chat_max_qr_blocked = $chat_max_auth_status === 'error' && (string)($chat_max_auth_state['kind'] ?? '') === 'qr';
                    $chat_max_personal = is_array($chat_max_personal ?? null) ? $chat_max_personal : [];
                    $chat_max_personal_ui_state = (string)($chat_max_personal['ui_state'] ?? 'wizard');
                    $chat_max_personal_step = max(0, (int)($chat_max_personal['step'] ?? 1));
                    $chat_max_personal_account = is_array($chat_max_personal['account'] ?? null) ? $chat_max_personal['account'] : [];
                    $chat_max_personal_cron = is_array($chat_max_personal['cron'] ?? null) ? $chat_max_personal['cron'] : [];
                    $chat_max_personal_attention = is_array($chat_max_personal['attention'] ?? null) ? $chat_max_personal['attention'] : [];
                    $chat_max_personal_attention_visible = !empty($chat_max_personal_attention['visible']);
                    $chat_max_personal_attention_level = (string)($chat_max_personal_attention['level'] ?? 'warning') === 'error' ? 'error' : 'warning';
                    $chat_max_personal_diagnostics = is_array($chat_max_personal['diagnostics'] ?? null) ? $chat_max_personal['diagnostics'] : [];
                    $chat_max_personal_revision = max(0, (int)($chat_max_personal['revision'] ?? 0));
                ?>

                <ul class="nav nav-pills gap-2 mb-3" id="max-channel-tabs" role="tablist">
                    <li class="nav-item" role="presentation"><button class="nav-link active" id="max-bot-subtab" data-bs-toggle="pill" data-bs-target="#max-bot-subpanel" type="button" role="tab">MAX-бот</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" id="max-personal-subtab" data-bs-toggle="pill" data-bs-target="#max-personal-subpanel" type="button" role="tab">Личный MAX<span class="easychat-max-tab-attention is-<?php echo htmlspecialchars($chat_max_personal_attention_level); ?>" id="max-personal-tab-attention"<?php echo $chat_max_personal_attention_visible ? '' : ' hidden'; ?> aria-label="Личный MAX требует внимания"></span></button></li>
                </ul>

                <div class="tab-content mb-4">
                    <div class="tab-pane fade show active" id="max-bot-subpanel" role="tabpanel">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="fw-semibold text-dark">MAX-бот</div>
                            <div class="form-check form-switch"><input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_max_bot_status" value="1" id="max-bot-status" <?php echo (($chat_max_bot_status ?? '0') == '1') ? 'checked' : ''; ?>></div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label text-muted small fw-semibold">Токен MAX-бота</label>
                                <input type="password" class="form-control easychat-rounded-field" name="chat_max_bot_token" value="" placeholder="<?php echo !empty($chat_max_bot_token_mask) ? 'Сохранен: ' . htmlspecialchars($chat_max_bot_token_mask) : 'Вставьте токен бота'; ?>" autocomplete="new-password">
                                <div class="form-text small text-muted">Оставьте пустым, чтобы не менять сохраненный токен.</div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label text-muted small fw-semibold">Состояние webhook</label>
                                <div class="border bg-light-subtle p-3 easychat-status-panel">
                                    <div class="d-flex align-items-center justify-content-between gap-2 mb-2">
                                        <span id="max-connection-badge" class="badge <?php echo htmlspecialchars($chat_max_bot_connection_class); ?> px-2 py-1"><i class="fa <?php echo htmlspecialchars($chat_max_bot_connection_icon); ?> me-1"></i><span id="max-connection-title"><?php echo htmlspecialchars($chat_max_bot_connection_title); ?></span></span>
                                        <span id="max-connection-time" class="text-muted small" style="<?php echo !empty($chat_max_bot_webhook_synced_at) ? '' : 'display:none;'; ?>"><?php echo htmlspecialchars($chat_max_bot_webhook_synced_at ?? ''); ?></span>
                                    </div>
                                    <div id="max-connection-detail" class="text-muted small mb-2"><?php echo htmlspecialchars($chat_max_bot_connection_detail); ?></div>
                                    <div id="max-connection-bot" class="text-secondary small" style="<?php echo (!empty($chat_max_bot_name) || !empty($chat_max_bot_username)) ? '' : 'display:none;'; ?>"><i class="fa fa-user-circle-o me-1"></i><span class="easychat-channel-identity"><?php echo $easychat_channel_identity('max-bot', trim(($chat_max_bot_name ?? '') . ' ' . (!empty($chat_max_bot_username) ? '@' . ltrim((string)$chat_max_bot_username, '@') : '')), $chat_max_bot_username ?? '', $chat_max_bot_user_id ?? ''); ?></span></div>
                                </div>
                            </div>
                        </div>
                        <div class="d-flex flex-wrap align-items-center gap-2">
                            <button type="button" class="btn btn-primary btn-sm px-3 easychat-btn-rounded" id="btn-max-sync"><i class="fa fa-plug me-1"></i> Проверить и подключить</button>
                            <span id="max-connection-error" class="text-danger small" style="<?php echo !empty($chat_max_bot_last_error) ? '' : 'display:none;'; ?>"><?php echo !empty($chat_max_bot_last_error) ? 'Ошибка: ' . htmlspecialchars($chat_max_bot_last_error) : ''; ?></span>
                        </div>
                    </div>
                    <div class="tab-pane fade easychat-max-personal"
                        id="max-personal-subpanel"
                        role="tabpanel"
                        data-ui-state="<?php echo htmlspecialchars($chat_max_personal_ui_state); ?>"
                        data-step="<?php echo $chat_max_personal_step; ?>"
                        data-revision="<?php echo $chat_max_personal_revision; ?>">
                        <div class="easychat-max-personal-intro">
                            <div>
                                <span class="easychat-max-eyebrow">Личный аккаунт</span>
                                <h5>Личный MAX</h5>
                                <p>Получайте обращения из своей учётной записи прямо в EasyChat.</p>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-secondary easychat-icon-button easychat-max-dashboard-only" id="btn-max-health-refresh" title="Проверить сейчас" aria-label="Проверить состояние личного MAX">
                                <i class="fa fa-refresh" aria-hidden="true"></i>
                            </button>
                        </div>

                        <div class="easychat-max-wizard-progress" aria-label="Подключение личного MAX">
                            <div class="easychat-max-wizard-step" data-wizard-step="1">
                                <span>1</span><div><strong>MAX Cron</strong><small>Доставка сообщений</small></div>
                            </div>
                            <i class="fa fa-angle-right" aria-hidden="true"></i>
                            <div class="easychat-max-wizard-step" data-wizard-step="2">
                                <span>2</span><div><strong>Вход</strong><small>QR или телефон</small></div>
                            </div>
                        </div>

                        <section class="easychat-max-account-card easychat-max-dashboard-only">
                            <div class="easychat-max-account-avatar" id="max-account-initials"><?php echo htmlspecialchars((string)($chat_max_personal_account['initials'] ?? 'M')); ?></div>
                            <div class="easychat-max-account-copy">
                                <strong id="max-account-name"><?php echo htmlspecialchars((string)($chat_max_personal_account['display_name'] ?? 'Личный MAX')); ?></strong>
                                <span id="max-account-phone"<?php echo empty($chat_max_personal_account['phone_mask']) ? ' hidden' : ''; ?>><?php echo htmlspecialchars((string)($chat_max_personal_account['phone_mask'] ?? '')); ?></span>
                            </div>
                            <div class="easychat-max-receiving-control">
                                <label for="max-status"><strong>Получение сообщений</strong><small id="max-receiving-caption"><?php echo !empty($chat_max_personal['enabled']) ? 'Включено' : 'На паузе'; ?></small></label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input easychat-switch-lg" type="checkbox" value="1" id="max-status" <?php echo !empty($chat_max_personal['enabled']) ? 'checked' : ''; ?>>
                                </div>
                            </div>
                            <div class="dropdown">
                                <button class="btn btn-sm btn-outline-secondary easychat-icon-button" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Действия с подключением">
                                    <i class="fa fa-ellipsis-v" aria-hidden="true"></i>
                                </button>
                                <ul class="dropdown-menu dropdown-menu-end">
                                    <li><button class="dropdown-item" type="button" id="btn-max-reconnect"><i class="fa fa-qrcode me-2"></i>Войти заново</button></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><button class="dropdown-item text-danger" type="button" id="btn-max-auth-clear"><i class="fa fa-sign-out me-2"></i>Отключить аккаунт</button></li>
                                </ul>
                            </div>
                        </section>
                        <section class="easychat-max-attention easychat-max-dashboard-only is-<?php echo htmlspecialchars($chat_max_personal_attention_level); ?> mb-3" id="max-personal-attention" role="status" aria-live="polite"<?php echo $chat_max_personal_attention_visible ? '' : ' hidden'; ?>>
                            <span class="easychat-max-attention-icon" aria-hidden="true"><i class="fa <?php echo $chat_max_personal_attention_level === 'error' ? 'fa-exclamation-triangle' : 'fa-exclamation-circle'; ?>"></i></span>
                            <span class="easychat-max-attention-copy">
                                <strong id="max-personal-attention-title"><?php echo htmlspecialchars((string)($chat_max_personal_attention['title'] ?? 'Личный MAX требует внимания')); ?></strong>
                                <small id="max-personal-attention-detail"><?php echo htmlspecialchars((string)($chat_max_personal_attention['detail'] ?? '')); ?></small>
                            </span>
                            <div class="easychat-max-attention-actions">
                                <a class="btn btn-sm btn-link" id="max-personal-security-help" href="https://help.max.ru/help/security/chto-delat-esli-moj-profil-vzlomali" target="_blank" rel="noopener noreferrer"<?php echo (($chat_max_personal_attention['action'] ?? '') === 'reconnect') ? '' : ' hidden'; ?>>Проверить безопасность</a>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="btn-max-attention-review" data-action="<?php echo htmlspecialchars((string)($chat_max_personal_attention['action'] ?? 'review')); ?>"><?php echo (($chat_max_personal_attention['action'] ?? '') === 'reconnect') ? 'Войти заново' : 'Проверить'; ?></button>
                            </div>
                        </section>
                        <div class="border rounded-3 p-3 bg-white mb-3 easychat-max-inbound-scope easychat-max-dashboard-only" id="max-personal-scope" aria-busy="false">
                            <div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
                                <div>
                                    <div class="fw-semibold text-dark small">Что получать из личного MAX</div>
                                    <div class="text-muted small">Выберите, какие входящие сообщения попадут в EasyChat.</div>
                                </div>
                                <div class="easychat-max-scope-meta">
                                    <span class="easychat-max-scope-save-status" id="max-personal-save-status" role="status" aria-live="polite" hidden></span>
                                    <span class="badge bg-light text-secondary border px-2 py-1"><i class="fa fa-filter me-1"></i>Входящие</span>
                                </div>
                            </div>
                            <div class="easychat-max-scope-grid">
                                <label class="easychat-max-scope-option">
                                    <input type="checkbox" data-max-scope value="dialogs" <?php echo in_array('dialogs', $chat_max_personal_inbound_scope, true) ? 'checked' : ''; ?>>
                                    <span><i class="fa fa-user-circle-o"></i><strong>Личные сообщения</strong><small>Диалоги клиентов с личной учеткой MAX.</small></span>
                                </label>
                                <label class="easychat-max-scope-option">
                                    <input type="checkbox" data-max-scope value="channels" <?php echo in_array('channels', $chat_max_personal_inbound_scope, true) ? 'checked' : ''; ?>>
                                    <span><i class="fa fa-bullhorn"></i><strong>Публичные каналы</strong><small>Посты каналов попадут в EasyChat только для чтения.</small></span>
                                </label>
                                <label class="easychat-max-scope-option">
                                    <input type="checkbox" data-max-scope value="groups" <?php echo in_array('groups', $chat_max_personal_inbound_scope, true) ? 'checked' : ''; ?>>
                                    <span><i class="fa fa-users"></i><strong>Группы</strong><small>Операторы смогут отвечать; автоответы ИИ отключены.</small></span>
                                </label>
                            </div>
                        </div>
                        <div class="easychat-max-wizard-card easychat-max-wizard-cron mb-3">
                            <div class="easychat-max-cron-heading">
                                <span class="easychat-max-step-kicker">Шаг 1 из 2</span>
                                <h6 class="mb-1">Добавьте отдельный MAX Cron</h6>
                                <p>Основной Cron EasyChat не запускает личный MAX. Создайте вторую задачу типа «Произвольная команда».</p>
                            </div>
                            <div class="easychat-max-cron-schedule" aria-label="Расписание MAX Cron">
                                <span><i class="fa fa-clock-o" aria-hidden="true"></i>Каждую минуту</span>
                                <code>* * * * *</code>
                            </div>
                            <?php $chat_max_wizard_cron_command = (string)(($chat_max_dedicated_cron_command ?? '') ?: ($chat_max_dedicated_cron_simple_command ?? '')); ?>
                            <?php if ($chat_max_wizard_cron_command !== '') : ?>
                                <div class="easychat-max-command-compact easychat-max-wizard-command" role="group" aria-labelledby="max-wizard-cron-title">
                                    <div class="easychat-max-command-toolbar">
                                        <div class="easychat-max-command-title">
                                            <span class="easychat-max-command-icon" aria-hidden="true"><i class="fa fa-terminal"></i></span>
                                            <span><strong id="max-wizard-cron-title">Команда для планировщика</strong><small>Вставьте целиком</small></span>
                                        </div>
                                        <button type="button" class="btn btn-sm easychat-max-command-copy" id="btn-copy-max-dedicated-cron" aria-label="Копировать команду отдельного MAX Cron">
                                            <i class="fa fa-copy me-1" aria-hidden="true"></i><span>Копировать</span>
                                        </button>
                                    </div>
                                    <div class="easychat-max-command-line">
                                        <span class="easychat-max-command-prompt" aria-hidden="true">$</span>
                                        <code id="max-dedicated-cron-code"><?php echo htmlspecialchars($chat_max_wizard_cron_command); ?></code>
                                    </div>
                                </div>
                            <?php else : ?>
                                <div class="alert alert-danger small mb-3" role="alert">
                                    <strong>Команда пока недоступна.</strong>
                                    <span><?php echo htmlspecialchars((string)($chat_max_cli_runtime['message'] ?? $chat_max_protected_chain['message'] ?? 'Не найден совместимый PHP CLI 7.4 или выше.')); ?></span>
                                </div>
                                <code id="max-dedicated-cron-code" hidden></code>
                                <button type="button" id="btn-copy-max-dedicated-cron" disabled hidden></button>
                            <?php endif; ?>

                            <?php $chat_max_cron_feedback_visible = (string)($chat_max_personal_cron['state'] ?? 'missing') !== 'missing'; ?>
                            <div class="easychat-max-cron-feedback" id="max-cron-feedback" data-state="<?php echo htmlspecialchars((string)($chat_max_personal_cron['state'] ?? 'missing')); ?>" role="status" aria-live="polite"<?php echo $chat_max_cron_feedback_visible ? '' : ' hidden'; ?>>
                                <i class="fa fa-clock-o" id="max-cron-feedback-icon" aria-hidden="true"></i>
                                <span><strong id="max-cron-title"><?php echo htmlspecialchars((string)($chat_max_personal_cron['title'] ?? 'Проверяем запуски')); ?></strong><small id="max-cron-detail"><?php echo htmlspecialchars((string)($chat_max_personal_cron['detail'] ?? '')); ?></small></span>
                            </div>

                            <div class="easychat-max-wizard-actions">
                                <div class="easychat-max-run-meter" id="max-cron-run-meter" aria-live="polite"<?php echo max(0, (int)($chat_max_personal_cron['observed_runs'] ?? 0)) > 0 ? '' : ' hidden'; ?>>
                                    Проверено: <span id="max-cron-run-count"><?php echo min(3, max(0, (int)($chat_max_personal_cron['observed_runs'] ?? 0))); ?></span> из 3
                                </div>
                                <button type="button" class="btn btn-primary easychat-admin-primary-action" id="btn-max-cron-verify" <?php echo $chat_max_wizard_cron_command === '' ? 'disabled' : ''; ?>>
                                    <i class="fa fa-refresh me-1"></i> Проверить настройку
                                </button>
                            </div>

                            <details class="easychat-max-cron-help"<?php echo $chat_max_wizard_cron_command === '' ? ' open' : ''; ?>>
                                <summary>Не получилось?</summary>
                                <div class="easychat-max-cron-help-body">
                                    <?php if (empty($chat_max_cli_runtime['success'])) : ?>
                                        <div class="alert alert-warning small mb-3" role="alert"><strong>PHP CLI не удалось проверить автоматически.</strong> <?php echo htmlspecialchars((string)($chat_max_cli_runtime['message'] ?? 'Не найден совместимый PHP CLI 7.4 или выше.')); ?></div>
                                    <?php else : ?>
                                        <div class="easychat-cron-runtime-path mb-3">
                                            <span>Подтверждённый интерпретатор · PHP <?php echo htmlspecialchars((string)($chat_max_cli_runtime['version'] ?? '')); ?></span>
                                            <code><?php echo htmlspecialchars((string)($chat_max_cli_runtime['binary'] ?? '')); ?></code>
                                            <?php if (($chat_max_cli_runtime['resolved_binary'] ?? '') !== '' && ($chat_max_cli_runtime['resolved_binary'] ?? '') !== ($chat_max_cli_runtime['binary'] ?? '')) : ?>
                                                <small class="text-muted d-block mt-1">Системная цель alias: <code><?php echo htmlspecialchars((string)$chat_max_cli_runtime['resolved_binary']); ?></code>.</small>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="easychat-cron-panel-mode mb-3">
                                        <span class="easychat-cron-panel-mode-icon"><i class="fa fa-terminal" aria-hidden="true"></i></span>
                                        <div><strong>Выберите «Произвольная команда»</strong><span>В Beget не выбирайте «PHP-скрипт»: панель добавит второй интерпретатор. <a href="https://beget.com/ru/kb/manual/crontab" target="_blank" rel="noopener noreferrer">Инструкция Beget</a>.</span></div>
                                    </div>
                                    <?php if (($chat_max_dedicated_cron_command ?? '') !== '') : ?>
                                        <div class="text-muted small mb-3"><i class="fa fa-shield text-success me-1" aria-hidden="true"></i>Абсолютные пути <code>flock</code> и PHP CLI проверены вместе.<?php if (!empty($chat_max_protected_chain['conflict_exit_normalized'])) : ?> Пересекающийся запуск будет безопасно пропущен без ложной ошибки Cron.<?php endif; ?></div>
                                    <?php else : ?>
                                        <div class="alert alert-warning small mb-3" role="alert"><strong>Команда с flock не подтверждена.</strong> <?php echo htmlspecialchars((string)($chat_max_protected_chain['message'] ?? $chat_max_flock_runtime['message'] ?? 'Используйте короткий вариант ниже.')); ?></div>
                                    <?php endif; ?>
                                    <?php if (empty($chat_max_protected_chain['conflict_exit_normalized'])) : ?>
                                        <div class="alert alert-warning small mb-3" role="status">Код <code>1</code> при уже работающем процессе может означать безопасный пропуск, а не ошибку PHP.</div>
                                    <?php endif; ?>
                                    <?php if (($chat_max_dedicated_cron_simple_command ?? '') !== '' && ($chat_max_dedicated_cron_simple_command ?? '') !== $chat_max_wizard_cron_command) : ?>
                                        <details class="easychat-cron-alt">
                                            <summary><i class="fa fa-code me-1"></i> Вариант без внешнего flock</summary>
                                            <div class="position-relative mt-2 easychat-cron-command-box easychat-cron-command-box-compact">
                                                <pre class="small mb-0"><code id="max-dedicated-cron-simple-code"><?php echo htmlspecialchars((string)$chat_max_dedicated_cron_simple_command); ?></code></pre>
                                                <button type="button" class="btn btn-outline-light btn-sm position-absolute easychat-cron-command-copy" id="btn-copy-max-dedicated-cron-simple"><i class="fa fa-copy me-1"></i> Копировать</button>
                                            </div>
                                        </details>
                                    <?php else : ?>
                                        <code id="max-dedicated-cron-simple-code" hidden></code>
                                        <button type="button" id="btn-copy-max-dedicated-cron-simple" disabled hidden></button>
                                    <?php endif; ?>
                                </div>
                            </details>
                        </div>
                        <div class="easychat-max-wizard-card easychat-max-wizard-auth max-auth-panel" data-max-auth-status="<?php echo htmlspecialchars($chat_max_auth_status); ?>" data-max-auth-polling-interval="<?php echo (int)($chat_max_auth_state['polling_interval_ms'] ?? 0); ?>">
                            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                                <div>
                                    <span class="easychat-max-step-kicker">Шаг 2 из 2</span>
                                    <h6 class="mb-1">Войдите в MAX</h6>
                                    <div id="max-auth-status" class="text-muted small"><?php echo htmlspecialchars($chat_max_auth_message !== '' ? $chat_max_auth_message : ($chat_max_auth_status === 'connected' ? 'Сессия готова. Планировщик будет забирать новые сообщения.' : 'Войдите по QR или SMS, чтобы EasyChat получил защищенную сессию.')); ?></div>
                                </div>
                                <div class="d-flex flex-wrap gap-2 max-auth-actions">
                                    <button type="button" class="btn btn-primary px-3 easychat-btn-rounded" id="btn-max-qr-start"><i class="fa fa-qrcode me-1"></i> Войти по QR</button>
                                    <button type="button" class="btn btn-link btn-sm text-decoration-none px-2" id="btn-max-sms-reveal" aria-expanded="<?php echo $chat_max_sms_visible ? 'true' : 'false'; ?>" aria-controls="max-sms-block" style="<?php echo $chat_max_sms_visible ? 'display:none;' : ''; ?>"><i class="fa fa-mobile me-1"></i> Войти по телефону</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm px-3 easychat-btn-rounded" id="btn-max-auth-reset" style="<?php echo $chat_max_reset_visible ? '' : 'display:none;'; ?>"><i class="fa fa-times me-1"></i> Начать заново</button>
                                </div>
                            </div>
                            <div id="max-qr-block" class="row align-items-center g-3 mb-3" style="<?php echo ($chat_max_auth_qr_svg !== '' || $chat_max_auth_qr_link !== '') ? '' : 'display:none;'; ?>">
                                <div class="col-auto">
                                    <img id="max-qr-image" class="max-auth-qr" src="<?php echo htmlspecialchars($chat_max_auth_qr_svg); ?>" alt="QR для входа в MAX" style="<?php echo $chat_max_auth_qr_svg !== '' ? '' : 'display:none;'; ?>">
                                </div>
                                <div class="col">
                                    <div class="text-muted small mb-2">Откройте MAX на телефоне: <span class="fw-semibold">Устройства → Войти по QR-коду</span>. Отсканируйте QR и подтвердите вход. EasyChat проверяет статус автоматически.</div>
                                    <a id="max-qr-link" class="small text-muted" href="<?php echo htmlspecialchars($chat_max_auth_qr_link); ?>" target="_blank" rel="noopener noreferrer" style="<?php echo $chat_max_auth_qr_link !== '' ? '' : 'display:none;'; ?>">Служебная QR-ссылка</a>
                                </div>
                            </div>
                            <div id="max-auth-blocked-actions" class="max-auth-blocked-actions mt-3" <?php echo $chat_max_qr_blocked ? '' : 'hidden'; ?>>
                                <button type="button" class="btn btn-outline-primary btn-sm easychat-btn-rounded" id="btn-max-qr-retry"><i class="fa fa-refresh me-1"></i> Проверить снова</button>
                                <button type="button" class="btn btn-link btn-sm text-decoration-none" id="btn-max-sms-fallback"><i class="fa fa-mobile me-1"></i> Войти по телефону</button>
                                <details class="small text-muted mt-2">
                                    <summary>Технические подробности</summary>
                                    <div class="mt-2">Код для поддержки: <code id="max-auth-error-code"><?php echo $chat_max_qr_blocked ? htmlspecialchars((string)($chat_max_auth_state['error_code'] ?? 'qr_worker_unavailable')) : '—'; ?></code></div>
                                </details>
                            </div>
                            <div id="max-sms-block" class="row g-2 align-items-end mt-1" aria-hidden="<?php echo $chat_max_sms_visible ? 'false' : 'true'; ?>" style="<?php echo $chat_max_sms_visible ? '' : 'display:none;'; ?>">
                                <div class="col-md-5">
                                    <label class="form-label text-muted small fw-semibold">Телефон для SMS</label>
                                    <input type="tel" class="form-control easychat-rounded-field" id="max-sms-phone" placeholder="+79991234567" autocomplete="tel">
                                </div>
                                <div class="col-md-3">
                                    <button type="button" class="btn btn-outline-primary w-100 easychat-btn-rounded" id="btn-max-sms-start"><i class="fa fa-mobile me-1"></i> Получить код</button>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label text-muted small fw-semibold">Код SMS<?php echo $chat_max_auth_phone_mask !== '' ? ' для ' . htmlspecialchars($chat_max_auth_phone_mask) : ''; ?></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control easychat-rounded-field" id="max-sms-code" inputmode="numeric" autocomplete="one-time-code" placeholder="123456">
                                        <button type="button" class="btn btn-outline-success" id="btn-max-sms-submit"><i class="fa fa-check"></i></button>
                                    </div>
                                </div>
                            </div>
                            <div id="max-password-block" class="row g-2 align-items-end mt-2" aria-hidden="<?php echo $chat_max_auth_status === 'password_required' ? 'false' : 'true'; ?>" style="<?php echo $chat_max_auth_status === 'password_required' ? '' : 'display:none;'; ?>">
                                <div class="col-md-8">
                                    <label class="form-label text-muted small fw-semibold">Пароль MAX 2FA<?php echo $chat_max_auth_password_hint !== '' ? ' · подсказка: ' . htmlspecialchars($chat_max_auth_password_hint) : ''; ?></label>
                                    <input type="password" class="form-control easychat-rounded-field" id="max-auth-password" autocomplete="current-password">
                                </div>
                                <div class="col-md-4">
                                    <button type="button" class="btn btn-outline-success w-100 easychat-btn-rounded" id="btn-max-password-submit"><i class="fa fa-lock me-1"></i> Подтвердить</button>
                                </div>
                            </div>
                        </div>
                        <details class="easychat-max-technical easychat-max-dashboard-only">
                            <summary><span><i class="fa fa-cog me-2" aria-hidden="true"></i>Технические параметры</span><small>cron, источники и диагностика</small></summary>
                            <div class="easychat-max-technical-body">
                                <div class="easychat-max-technical-grid">
                                    <div class="easychat-max-cron-mode-field">
                                        <label class="form-label small fw-semibold" for="max-cron-mode">Длительность проверки</label>
                                        <select class="form-select easychat-rounded-field" id="max-cron-mode">
                                            <?php foreach ($chat_max_dedicated_cron_modes as $mode_key => $mode_info) : ?>
                                                <option value="<?php echo htmlspecialchars((string)$mode_key); ?>" <?php echo $chat_max_dedicated_cron_mode === (string)$mode_key ? 'selected' : ''; ?>><?php echo htmlspecialchars((string)($mode_info['label'] ?? $mode_key)); ?> · <?php echo (int)($mode_info['seconds'] ?? 20); ?> сек.</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="easychat-max-command-compact" role="group" aria-labelledby="max-dashboard-cron-title">
                                        <div class="easychat-max-command-toolbar">
                                            <div class="easychat-max-command-title">
                                                <span class="easychat-max-command-icon" aria-hidden="true"><i class="fa fa-terminal"></i></span>
                                                <span>
                                                    <strong id="max-dashboard-cron-title">Команда отдельного MAX Cron</strong>
                                                    <small>Вставьте целиком в поле «Произвольная команда»</small>
                                                </span>
                                            </div>
                                            <button type="button" class="btn btn-sm easychat-max-command-copy" id="btn-copy-max-dashboard-cron" aria-label="Копировать команду MAX Cron">
                                                <i class="fa fa-copy me-1" aria-hidden="true"></i><span>Копировать</span>
                                            </button>
                                        </div>
                                        <div class="easychat-max-command-line">
                                            <span class="easychat-max-command-prompt" aria-hidden="true">$</span>
                                            <code id="max-dashboard-cron-code"><?php echo htmlspecialchars((string)($chat_max_dedicated_cron_command ?: $chat_max_dedicated_cron_simple_command)); ?></code>
                                        </div>
                                    </div>
                                    <section class="easychat-max-health" id="max-personal-health" role="status" aria-live="polite" data-generation="<?php echo $chat_max_health_generation; ?>">
                                        <div class="easychat-max-health-head">
                                            <div class="min-w-0">
                                                <span id="max-health-summary-badge" class="badge <?php echo htmlspecialchars($chat_max_connection_class); ?> px-2 py-1">
                                                    <i id="max-health-summary-icon" class="fa <?php echo htmlspecialchars($chat_max_connection_icon); ?> me-1" aria-hidden="true"></i>
                                                    <span id="max-health-summary-title"><?php echo htmlspecialchars($chat_max_connection_title); ?></span>
                                                </span>
                                                <div id="max-health-summary-detail" class="text-muted small mt-2"><?php echo htmlspecialchars($chat_max_connection_detail); ?></div>
                                            </div>
                                        </div>
                                        <div class="easychat-max-session-security">
                                            <i class="fa fa-shield text-success" aria-hidden="true"></i>
                                            <span id="max-session-security-label"><?php echo htmlspecialchars((string)($chat_max_session_security_label ?? 'Сессия еще не создана')); ?></span>
                                        </div>
                                        <div class="easychat-max-health-grid" id="max-health-items">
                                            <?php foreach ($chat_max_health_items as $health_item) :
                                                $health_key = preg_replace('/[^a-z_]/', '', (string)($health_item['key'] ?? ''));
                                                $health_state = (string)($health_item['state'] ?? 'pending');
                                                $health_state = in_array($health_state, ['ok', 'warning', 'error', 'pending', 'disabled'], true) ? $health_state : 'pending';
                                            ?>
                                                <div class="easychat-max-health-row is-<?php echo htmlspecialchars($health_state); ?>" data-max-health-key="<?php echo htmlspecialchars($health_key); ?>" data-state="<?php echo htmlspecialchars($health_state); ?>">
                                                    <span class="easychat-max-health-indicator" aria-hidden="true"><i class="fa <?php echo htmlspecialchars((string)($health_item['icon'] ?? 'fa-clock-o')); ?>" data-max-health-icon></i></span>
                                                    <div class="easychat-max-health-copy">
                                                        <div class="easychat-max-health-label" data-max-health-label><?php echo htmlspecialchars((string)($health_item['label'] ?? '')); ?></div>
                                                        <div class="easychat-max-health-title" data-max-health-title><?php echo htmlspecialchars((string)($health_item['title'] ?? '')); ?></div>
                                                        <div class="easychat-max-health-detail" data-max-health-detail><?php echo htmlspecialchars((string)($health_item['detail'] ?? '')); ?></div>
                                                        <div class="easychat-max-health-time" data-max-health-time <?php echo empty($health_item['time']) ? 'hidden' : ''; ?>><?php echo htmlspecialchars((string)($health_item['time'] ?? '')); ?></div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </section>
                                </div>
                            </div>
                        </details>
                    </div>
                </div>

                <details class="easychat-max-shared-diagnostics mt-3">
                    <summary>
                        <span><i class="fa fa-stethoscope me-2" aria-hidden="true"></i>Диагностика MAX</span>
                        <small>временно, без личных данных</small>
                    </summary>
                    <div class="easychat-max-shared-diagnostics-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <div class="fw-semibold text-dark small">Диагностический журнал</div>
                            <div class="text-muted small">Включается на 15 минут. Токены, номера и текст сообщений в журнал не попадают.</div>
                            <div class="text-primary small mt-1" id="max-diagnostics-countdown"<?php echo empty($chat_max_personal_diagnostics['active']) ? ' hidden' : ''; ?> data-until-ts="<?php echo max(0, (int)($chat_max_personal_diagnostics['until_ts'] ?? 0)); ?>"></div>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input easychat-switch-md" type="checkbox" value="1" id="max-logging" <?php echo !empty($chat_max_personal_diagnostics['active']) ? 'checked' : ''; ?>>
                            <label class="visually-hidden" for="max-logging">Диагностика MAX на 15 минут</label>
                        </div>
                    </div>

                    <div id="max-logging-console-block" style="<?php echo !empty($chat_max_personal_diagnostics['active']) ? '' : 'display:none;'; ?>">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-secondary small fw-bold">Последние записи MAX-бота:</span>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary py-1 px-2 me-2 easychat-log-action" id="btn-refresh-max-bot-logs"><i class="fa fa-refresh me-1"></i> Обновить</button>
                                <button type="button" class="btn btn-sm btn-outline-danger py-1 px-2 easychat-log-action" id="btn-clear-max-bot-logs"><i class="fa fa-trash me-1"></i> Очистить</button>
                            </div>
                        </div>
                        <pre id="max-bot-logs-console" class="text-white p-3 mb-3 easychat-log-console">Загрузка логов...</pre>

                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-secondary small fw-bold">Последние записи личного MAX:</span>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary py-1 px-2 me-2 easychat-log-action" id="btn-refresh-max-logs"><i class="fa fa-refresh me-1"></i> Обновить</button>
                                <button type="button" class="btn btn-sm btn-outline-danger py-1 px-2 easychat-log-action" id="btn-clear-max-logs"><i class="fa fa-trash me-1"></i> Очистить</button>
                            </div>
                        </div>
                        <pre id="max-logs-console" class="text-white p-3 mb-0 easychat-log-console">Загрузка логов...</pre>
                    </div>
                    </div>
                </details>
            </div>

            <?php include __DIR__ . '/partials/whatsapp_personal_panel.php'; ?>

            <!-- PANEL: Parameters and Diagnostics -->
            <div class="tab-pane fade<?php echo $integration_tab_active('params') ? ' show active' : ''; ?> animate__animated animate__fadeIn" id="params-panel" role="tabpanel" aria-labelledby="params-tab">
                <h5 class="fw-bold text-dark mb-3" style="font-family: 'Outfit', sans-serif;">Общие параметры мессенджеров</h5>

                <section class="card border border-light shadow-sm mb-4" id="conversation-start-settings" style="border-radius: 8px; background: #ffffff;">
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                            <div>
                                <h6 class="fw-bold text-dark mb-1">Начало диалога</h6>
                                <div class="text-muted small">MAX-бот, Telegram и VK могут сразу поприветствовать человека после запуска. Служебная команда не появится в переписке и не потратит AI-токены.</div>
                            </div>
                            <div class="form-check form-switch flex-shrink-0">
                                <input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_bot_start_greeting_status" value="1" id="bot-start-greeting-status" <?php echo (($chat_bot_start_greeting_status ?? '0') === '1') ? 'checked' : ''; ?>>
                                <label class="visually-hidden" for="bot-start-greeting-status">Отправлять приветствие при запуске бота</label>
                            </div>
                        </div>
                        <label class="form-label fw-semibold" for="bot-start-message">Общее приветствие</label>
                        <textarea class="form-control" rows="7" maxlength="2000" name="chat_bot_start_message" id="bot-start-message"><?php echo htmlspecialchars((string)($chat_bot_start_message ?? ''), ENT_QUOTES, 'UTF-8'); ?></textarea>
                        <div class="d-flex flex-wrap justify-content-between gap-2 mt-2">
                            <span class="text-muted small">Пишите «отправьте цифру», если сообщение не содержит настоящих кнопок.</span>
                            <button type="button" class="btn btn-outline-secondary btn-sm" id="bot-start-restore"><i class="fa fa-undo me-1"></i> Рекомендуемый вариант</button>
                        </div>

                        <div class="input-group mt-3">
                            <input type="text" class="form-control" maxlength="500" id="bot-start-business" autocomplete="off" placeholder="Например: магазин автозапчастей, проверка заказа и подбор детали">
                            <button type="button" class="btn btn-outline-primary" id="bot-start-ai-suggest"><i class="fa fa-magic me-1"></i> Предложить с AI</button>
                        </div>
                        <div class="form-text" id="bot-start-ai-status">AI только подготовит черновик. Он не включит приветствие и ничего не отправит клиентам.</div>

                        <div class="mt-3 p-3 bg-light" style="border-radius: 8px;">
                            <div class="text-muted small mb-1">Так сообщение увидит клиент</div>
                            <div id="bot-start-preview" class="bg-white border p-3" style="border-radius: 8px; white-space: pre-wrap;"></div>
                        </div>

                        <details class="mt-3">
                            <summary class="fw-semibold" style="cursor:pointer;">Отдельный текст для канала</summary>
                            <div class="row g-3 mt-1">
                                <?php foreach (['max_bot' => 'MAX-бот', 'telegram' => 'Telegram', 'vk' => 'VK'] as $start_key => $start_title) { $value_key = 'chat_bot_start_message_' . $start_key; ?>
                                <div class="col-12 col-lg-4">
                                    <label class="form-label small fw-semibold" for="bot-start-<?php echo $start_key; ?>"><?php echo $start_title; ?></label>
                                    <textarea class="form-control form-control-sm" rows="5" maxlength="2000" name="<?php echo $value_key; ?>" id="bot-start-<?php echo $start_key; ?>" placeholder="Использовать общее приветствие"><?php echo htmlspecialchars((string)($$value_key ?? ''), ENT_QUOTES, 'UTF-8'); ?></textarea>
                                </div>
                                <?php } ?>
                            </div>
                        </details>

                        <div class="form-check form-switch mt-3" id="bot-start-notify-row">
                            <input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_bot_start_notify_status" value="1" id="bot-start-notify-status" <?php echo (($chat_bot_start_notify_status ?? '0') === '1') ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="bot-start-notify-status"><strong>Уведомлять оператора, если приветствие выключено</strong><br><span class="text-muted small">В диалоге появится служебная отметка, и оператор сможет написать первым.</span></label>
                        </div>
                    </div>
                </section>
                
                <div class="card border border-light shadow-sm mb-4" style="border-radius: 14px; background: #ffffff;">
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between align-items-start gap-3">
                            <div class="pe-3">
                                <h6 class="fw-bold text-dark mb-1" style="font-size: 16px;">Аватарки клиентов</h6>
                                <div class="text-muted small" style="line-height: 1.45;">
                                    EasyChat скачивает доступные аватарки из MAX, Avito, VK и Telegram, безопасно сжимает их на сервере и показывает в админке и Android-приложении. Если выключено — используются инициалы.
                                </div>
                            </div>
                            <div class="form-check form-switch flex-shrink-0">
                                <input class="form-check-input easychat-switch-lg" type="checkbox" name="chat_messenger_avatars_status" value="1" id="messenger-avatars-status" <?php echo (($chat_messenger_avatars_status ?? '1') == '1') ? 'checked' : ''; ?>>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card border border-light shadow-sm mb-4" style="border-radius: 14px; background: #ffffff;">
                    <div class="card-body p-4">
                        <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
                            <div>
                                <h6 class="fw-bold text-dark mb-1" style="font-size: 16px;">HTTPS внешних сервисов</h6>
                                <div class="text-muted small">Проверка доверия сертификатам MAX, EasyTokens, VK и EasyChat Gateway.</div>
                            </div>
                            <button type="button" class="btn btn-outline-primary btn-sm px-3" id="btn-tls-diagnostics" style="border-radius: 8px;"
                                data-htmx-managed="1"
                                hx-post="index.php?route=integration/tlsDiagnostics"
                                hx-include="#easychat-settings-nonce"
                                hx-target="#tls-diagnostics-result"
                                hx-swap="<?php echo htmlspecialchars(HtmxFragmentRenderer::integrationDiagnosticsSwap(), ENT_QUOTES, 'UTF-8'); ?>"
                                hx-sync="this:replace"
                                hx-indicator="#btn-tls-diagnostics">
                                <i class="fa fa-shield me-1"></i> Проверить
                            </button>
                        </div>

                        <?php echo IntegrationFragments::tlsDiagnosticsResult(); ?>
                    </div>
                </div>
            </div>

        </div>

        <!-- Submit Button -->
        <div class="d-flex justify-content-end border-top pt-4 mt-4<?php echo in_array($integration_active_tab, ['wildberries', 'ozon', 'yandex_market', 'whatsapp', 'email', 'moysklad', 'delivery'], true) ? ' d-none' : ''; ?>" data-integration-global-save>
            <button type="submit" id="btn-save-integrations" class="btn btn-primary easychat-admin-primary-action px-5 py-2.5">
                <i class="fa fa-check me-2"></i> Сохранить интеграции
            </button>
        </div>
    </form>
    <?php include __DIR__ . '/moysklad_integration.php'; ?>
    <?php include __DIR__ . '/delivery_integration.php'; ?>
    <?php include __DIR__ . '/email_integration.php'; ?>
</div>

<script type="text/javascript">
window.EasyChatIntegrationConfig = {
    recommendedGreeting: <?php echo json_encode("Добро пожаловать!\n\nЯ помогу проверить оформленный заказ или подобрать подходящий товар.\n\n1 — Я уже оформил заказ\n0 — Мне нужна консультация\n\nМожно отправить цифру или просто написать вопрос своими словами.", JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
    i18n: {
        "common.error": "Ошибка",
        "common.ready": "Готово",
        "common.warning": "Предупреждение",
        "settings.session_expired": "Сессия настроек устарела. Обновите страницу."
    }
};
</script>
<?php echo easychat_script_tag('js/views/integration.js'); ?>
<?php echo easychat_script_tag('js/views/marketplace.js'); ?>
<?php echo easychat_script_tag('js/views/email_integration.js'); ?>
<?php echo easychat_script_tag('js/views/moysklad_integration.js'); ?>
<?php echo easychat_script_tag('js/views/delivery_integration.js'); ?>
