<?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-бота по токену и принимайте обращения в EasyChat.</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');
                ?>

                <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' : ''; ?>>
                        <label class="visually-hidden" for="max-bot-status">Включить MAX-бота</label>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label text-muted small fw-semibold" for="max-bot-token">Токен MAX-бота</label>
                        <input type="password" class="form-control easychat-rounded-field" id="max-bot-token" 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">
                        <div class="form-label text-muted small fw-semibold">Состояние webhook</div>
                        <div class="border bg-light-subtle p-3 easychat-status-panel" role="status" aria-live="polite">
                            <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" aria-hidden="true"></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" aria-hidden="true"></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" aria-hidden="true"></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>

            <?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'); ?>
