<?php
if (!headers_sent()) {
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Pragma: no-cache');
    header('X-Robots-Tag: noindex, nofollow');
}
$easychat_route_base_url = defined('EASYCHAT_ROUTE_BASE_URL') ? EASYCHAT_ROUTE_BASE_URL : 'index.php?route=';
$active_route = isset($this->controller) ? $this->controller : 'index';
$easychat_page_layout = 'standard';
if ($active_route === 'index') {
    $easychat_page_layout = 'workspace';
} elseif (in_array($active_route, array('update', 'onboarding'), true)) {
    $easychat_page_layout = 'focused';
}
$easychat_mobile_gutter = $easychat_page_layout === 'workspace' ? '0px' : '16px';
$easychat_admin_help_flag = strtolower(\EasyChat\Library\Support\OfficialSupportRuntimeConfig::value('EASYCHAT_ADMIN_HELP_ENABLED'));
$easychat_admin_help_enabled = $easychat_admin_help_flag !== ''
    ? in_array($easychat_admin_help_flag, array('1', 'true', 'yes', 'on'), true)
    : (string)($chat_admin_help_status ?? '0') === '1';
$easychat_admin_help_locale = (string)($easychat_locale ?? 'ru') === 'en' ? 'en' : 'ru';
$easychat_admin_help_copy_all = array(
    'ru' => array(
        'nav' => 'Спросить EasyChat', 'eyebrow' => 'ПОМОЩНИК ПО EASYCHAT', 'title' => 'Спросить EasyChat',
        'new_chat' => 'Начать новый вопрос', 'new_chat_short' => 'Новый', 'new_chat_title' => 'Новый разговор', 'close' => 'Закрыть',
        'intro_title' => 'Помогу разобраться с EasyChat', 'intro_text' => 'Найду ответ в актуальной документации и учту этот раздел.',
        'gift_title' => 'Подключим помощь одним действием', 'gift_text' => 'Используем ваш подарок EasyTokens и сразу продолжим вопрос.',
        'email' => 'Email для получения токенов', 'gift_action' => 'Получить и продолжить', 'diagnose' => 'Проверить установку',
        'disclosure' => 'Передадим только:', 'privacy' => 'Без переписки, паролей, ключей и необработанных логов.',
        'diagnose_action' => 'Начать проверку', 'question_label' => 'Вопрос по EasyChat', 'placeholder' => 'Что хотите настроить?',
        'send_label' => 'Отправить вопрос', 'send_title' => 'Отправить',
        'preparing' => 'Готовлю справку…', 'open_failed' => 'Не удалось открыть помощника. Проверьте соединение и повторите.',
        'docs' => 'Документация EasyChat', 'docs_line' => 'Источники', 'open_section' => 'Открыть раздел',
        'open_source' => 'Открыть источник {id}', 'handoff_text' => 'Здесь лучше подключить специалиста. Не отправляйте пароли и API-ключи.',
        'telegram' => 'Написать в Telegram', 'max' => 'Написать в MAX', 'searching' => 'Ищу в документации…',
        'diagnosing' => 'Проверяю безопасные параметры…', 'connecting' => 'Подключаю EasyTokens…',
        'connected' => 'Готово. Продолжаю ваш вопрос…', 'email_required' => 'Укажите рабочий email.',
        'gift_failed' => 'Подарок сейчас недоступен. Можно обратиться в поддержку.',
        'diagnostic_question' => 'Проверь безопасные параметры этой установки и подскажи, что требует внимания.',
        'error_rate_limited' => 'Слишком много вопросов подряд. Подождите минуту.',
        'error_knowledge_unavailable' => 'Документация временно недоступна. Можно повторить или написать специалисту.',
        'error_support_unavailable' => 'Помощник временно не отвечает. Вопрос сохранён в этой вкладке.',
        'error_offline' => 'Нет соединения. Вопрос сохранён в этой вкладке и отправится после восстановления сети.',
        'error_easytokens_key_required' => 'Сначала подключим подарочные EasyTokens.',
        'error_csrf_validation_failed' => 'Сессия защиты устарела. Обновите страницу.',
        'error_question_too_long' => 'Сократите вопрос до 2000 знаков.',
        'error_stream_interrupted' => 'Ответ прервался. Продолжим безопасно тем же запросом.',
        'feedback_prompt' => 'Ответ помог?', 'feedback_yes' => 'Да, помог', 'feedback_no' => 'Нет, нужна помощь',
        'feedback_thanks' => 'Спасибо', 'feedback_failed' => 'Не удалось сохранить оценку.',
        'error_default' => 'Не удалось получить ответ. Повторите попытку.',
    ),
    'en' => array(
        'nav' => 'Ask EasyChat', 'eyebrow' => 'EASYCHAT ASSISTANT', 'title' => 'Ask EasyChat',
        'new_chat' => 'Start a new question', 'new_chat_short' => 'New', 'new_chat_title' => 'New conversation', 'close' => 'Close',
        'intro_title' => 'I can help with EasyChat', 'intro_text' => 'I’ll check the current documentation and use the context of this section.',
        'gift_title' => 'Enable help in one step', 'gift_text' => 'We’ll use your EasyTokens gift and continue your question automatically.',
        'email' => 'Email for gift tokens', 'gift_action' => 'Get tokens and continue', 'diagnose' => 'Check this installation',
        'disclosure' => 'Only these details will be sent:', 'privacy' => 'No conversations, passwords, keys, or raw logs.',
        'diagnose_action' => 'Start the check', 'question_label' => 'Question about EasyChat', 'placeholder' => 'What would you like to configure?',
        'send_label' => 'Send question', 'send_title' => 'Send',
        'preparing' => 'Preparing help…', 'open_failed' => 'Could not open the assistant. Check your connection and try again.',
        'docs' => 'EasyChat documentation', 'docs_line' => 'Sources', 'open_section' => 'Open section',
        'open_source' => 'Open source {id}', 'handoff_text' => 'A specialist can help with this. Do not send passwords or API keys.',
        'telegram' => 'Message on Telegram', 'max' => 'Message on MAX', 'searching' => 'Searching the documentation…',
        'diagnosing' => 'Checking safe setup details…', 'connecting' => 'Connecting EasyTokens…',
        'connected' => 'Ready. Continuing your question…', 'email_required' => 'Enter a valid work email.',
        'gift_failed' => 'Gift tokens are unavailable right now. You can contact support.',
        'diagnostic_question' => 'Check the safe details of this installation and tell me what needs attention.',
        'error_rate_limited' => 'Too many questions in a short time. Try again in a minute.',
        'error_knowledge_unavailable' => 'Documentation is temporarily unavailable. Try again or contact support.',
        'error_support_unavailable' => 'The assistant is temporarily unavailable. Your question is kept in this tab.',
        'error_offline' => 'You are offline. The question is kept in this tab and will be sent when the connection returns.',
        'error_easytokens_key_required' => 'Let’s connect your EasyTokens gift first.',
        'error_csrf_validation_failed' => 'Your security session expired. Reload the page.',
        'error_question_too_long' => 'Shorten the question to 2,000 characters.',
        'error_stream_interrupted' => 'The response was interrupted. We’ll safely retry the same request.',
        'feedback_prompt' => 'Was this helpful?', 'feedback_yes' => 'Yes, it helped', 'feedback_no' => 'No, I need help',
        'feedback_thanks' => 'Thank you', 'feedback_failed' => 'Could not save your feedback.',
        'error_default' => 'Could not get an answer. Please try again.',
    ),
);
$easychat_admin_help_copy = $easychat_admin_help_copy_all[$easychat_admin_help_locale];
$easychat_help_text = static function ($key) use ($easychat_admin_help_copy) {
    return htmlspecialchars((string)($easychat_admin_help_copy[$key] ?? $key), ENT_QUOTES, 'UTF-8');
};
$manager_role = isset(\EasyChat\Library\RequestContext::session()['manager_role']) ? \EasyChat\Library\RequestContext::session()['manager_role'] : 'manager';
$easychat_sound_tones = array(
    'classic' => array(
        'label' => 'Классический',
        'hint' => 'Прежний мягкий сигнал',
        'file' => 'sound/notification_classic.mp3',
    ),
    'clear' => array(
        'label' => 'Звонкий',
        'hint' => 'Короткий и заметный',
        'file' => 'sound/send_message.mp3',
    ),
    'calm' => array(
        'label' => 'Спокойный',
        'hint' => 'Мягкое системное звучание',
        'file' => 'sound/new_message_tone_2.mp3',
    ),
    'melodic' => array(
        'label' => 'Мелодичный',
        'hint' => 'Более длинный сигнал',
        'file' => 'sound/new_message_tone.mp3',
    ),
);
$easychat_sound_tone_config = array();
foreach ($easychat_sound_tones as $easychat_sound_tone_key => $easychat_sound_tone) {
    $easychat_sound_tone_config[$easychat_sound_tone_key] = array(
        'label' => $easychat_sound_tone['label'],
        'url' => easychat_asset_versioned_url($easychat_sound_tone['file']),
    );
}
$easychat_render_sound_control = static function () use ($easychat_sound_tones) {
    ?>
    <div class="easychat-sound-control-wrap" data-easychat-sound-control>
        <button type="button" class="btn btn-link text-muted-custom sidebar-icon-action easychat-sound-trigger" aria-expanded="false" data-easychat-sound-trigger title="Звук уведомлений" aria-label="Настройки звука уведомлений">
            <i class="fa fa-volume-up fa-lg" data-easychat-sound-icon style="vertical-align: middle;"></i>
        </button>
        <div class="easychat-sound-menu" role="group" aria-label="Настройки звука уведомлений">
            <div class="easychat-sound-primary-controls">
                <button type="button" class="easychat-sound-mini-btn easychat-sound-test" data-easychat-sound-test title="Проверить звук" aria-label="Проверить звук">
                    <i class="fa fa-play" aria-hidden="true"></i>
                </button>
                <div class="easychat-sound-volume-track">
                    <input type="range" class="easychat-sound-volume" min="0" max="100" step="5" orient="vertical" data-easychat-sound-volume aria-label="Громкость уведомлений">
                </div>
                <button type="button" class="easychat-sound-mini-btn easychat-sound-mute" data-easychat-sound-mute-toggle aria-pressed="false" title="Выключить звук" aria-label="Выключить звук">
                    <i class="fa fa-volume-off" data-easychat-sound-mute-icon aria-hidden="true"></i>
                </button>
                <details class="easychat-sound-tone-picker" data-easychat-sound-tone-picker>
                    <summary class="easychat-sound-mini-btn easychat-sound-tone-summary" data-easychat-sound-tone-summary title="Выбрать сигнал" aria-label="Выбрать сигнал уведомления" aria-expanded="false">
                        <i class="fa fa-music" aria-hidden="true"></i>
                    </summary>
                    <div class="easychat-sound-tone-panel" role="radiogroup" aria-label="Сигнал нового сообщения">
                        <div class="easychat-sound-tone-heading">Сигнал сообщения</div>
                        <?php foreach ($easychat_sound_tones as $easychat_sound_tone_key => $easychat_sound_tone) { ?>
                            <button type="button" class="easychat-sound-tone-option" data-easychat-sound-tone="<?php echo htmlspecialchars($easychat_sound_tone_key, ENT_QUOTES, 'UTF-8'); ?>" role="radio" aria-checked="false">
                                <span class="easychat-sound-tone-copy">
                                    <strong><?php echo htmlspecialchars($easychat_sound_tone['label'], ENT_QUOTES, 'UTF-8'); ?></strong>
                                    <small><?php echo htmlspecialchars($easychat_sound_tone['hint'], ENT_QUOTES, 'UTF-8'); ?></small>
                                </span>
                                <i class="fa fa-check" aria-hidden="true"></i>
                            </button>
                        <?php } ?>
                        <div class="easychat-sound-tone-note">Сохраняется только в этом браузере</div>
                    </div>
                </details>
                <span class="easychat-sound-volume-label" data-easychat-sound-volume-label>100%</span>
                <div class="easychat-sound-status visually-hidden" data-easychat-sound-status aria-live="polite"></div>
            </div>
        </div>
    </div>
    <?php
};
$easychat_render_brand_link = static function ($variant = 'desktop', $label_id = '') {
    $allowed_variants = array('desktop', 'mobile-top', 'mobile-sidebar');
    $variant = in_array($variant, $allowed_variants, true) ? $variant : 'desktop';
    $label_id = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)$label_id);
    ?>
    <a href="https://easychat24.ru"
       target="_blank"
       rel="noopener noreferrer"
       class="easychat-brand-link easychat-brand-link--<?php echo htmlspecialchars($variant, ENT_QUOTES, 'UTF-8'); ?>"
       title="Открыть сайт EasyChat в новой вкладке"
       aria-label="Открыть официальный сайт EasyChat в новой вкладке">
        <span class="easychat-brand-mark" aria-hidden="true">
            <svg viewBox="0 0 24 24" focusable="false">
                <path fill-rule="evenodd" d="M 12 3.5 C 7.3 3.5, 3.5 7.3, 3.5 12 c 0 1.88, 0.61 3.61, 1.64 5.03 L 4.35 19.65 l 2.69 -0.79 C 8.44 19.42, 10.16 19.74, 12 19.74 c 4.69,0 8.5 -3.81,8.5 -8.5 S 16.69,3.5 12,3.5 Z M 9.1,8.5 A 0.9,0.9 0 0 1 10,7.6 H 14.2 A 0.9,0.9 0 0 1 14.2,9.4 H 10.9 V 10.6 H 13 A 0.9,0.9 0 0 1 13,12.4 H 10.9 V 13.6 H 14.2 A 0.9,0.9 0 0 1 14.2,15.4 H 10 A 0.9,0.9 0 0 1 9.1,14.5 Z"></path>
            </svg>
        </span>
        <span class="easychat-brand-name"<?php echo $label_id !== '' ? ' id="' . htmlspecialchars($label_id, ENT_QUOTES, 'UTF-8') . '"' : ''; ?>>EasyChat</span>
    </a>
    <?php
};
?>
<!DOCTYPE html>
<html dir="ltr" lang="<?php echo htmlspecialchars((string)($easychat_locale ?? 'ru'), ENT_QUOTES, 'UTF-8'); ?>">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex,nofollow">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo isset($title) ? $title : 'EasyChat'; ?></title>
    <base href="<?php echo HTTP_SERVER; ?>" />
    <meta name="theme-color" content="#6366f1">
    <link rel="icon" href="<?php echo easychat_asset_url('images/icon.png'); ?>" type="image/png">
    <link rel="apple-touch-icon" href="<?php echo easychat_asset_url('images/icon-192.png'); ?>">
    <link rel="manifest" href="index.php?route=webpush/manifest">
    <?php echo easychat_preload_tag('css/fonts/Inter-Regular.woff2', 'font', array('type' => 'font/woff2', 'crossorigin' => 'anonymous')); ?>
    <?php echo easychat_preload_tag('css/fonts/Outfit-Medium.woff2', 'font', array('type' => 'font/woff2', 'crossorigin' => 'anonymous')); ?>
    
    <!-- FontAwesome -->
    <?php echo easychat_style_tag('js/font-awesome/css/font-awesome.min.css', array('type' => 'text/css')); ?>
    
    <!-- Bootstrap & Custom Stylesheet -->
    <?php echo easychat_style_tag('js/bootstrap/css/bootstrap.min.css', array('media' => 'screen')); ?>
    <?php echo easychat_style_tag('css/stylesheet.css'); ?>
    <?php echo easychat_style_tag('css/components/android_update_notice.css'); ?>
    <?php echo easychat_style_tag('css/components/operator_profile.css'); ?>
    <?php if ($easychat_admin_help_enabled) { echo easychat_style_tag('css/components/admin_help.css'); } ?>
    <style>
        :root {
            --easychat-accent: <?php echo htmlspecialchars(isset($chat_widget_color) ? $chat_widget_color : '#6366f1', ENT_QUOTES, 'UTF-8'); ?>;
            --easychat-on-accent: <?php echo htmlspecialchars(isset($chat_on_accent_color) ? $chat_on_accent_color : '#ffffff', ENT_QUOTES, 'UTF-8'); ?>;
            --easychat-surface: #ffffff;
            --easychat-on-surface: #111827;
        }
    </style>

    <!-- Core Scripts -->
    <script type="text/javascript">
        window.EasyChatRouteBase = <?php echo json_encode((string)$easychat_route_base_url, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
        window.EasyChatCsrfToken = <?php echo json_encode((string)($easychat_csrf_token ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
        window.EasyChatManagerRole = <?php echo json_encode((string)$manager_role, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
        window.EasyChatAdminHelpI18n = <?php echo json_encode($easychat_admin_help_copy, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
        window.EasyChatLazyAssetUrls = {
            qrcode: <?php echo json_encode(easychat_asset_versioned_url('js/qrcode-generator.js'), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            mobileConnect: <?php echo json_encode(easychat_asset_versioned_url('js/mobile_connect.js'), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            passkeys: <?php echo json_encode(easychat_asset_versioned_url('js/passkeys.js'), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            webpushSubscribe: <?php echo json_encode(easychat_asset_versioned_url('js/webpush_subscribe.js'), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            chart: <?php echo json_encode(easychat_asset_versioned_url('js/chart.js'), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>
        };

        window.EasyChatPolling = window.EasyChatPolling || (function() {
            var tabIdKey = 'easychat_admin_tab_id';
            var lockPrefix = 'easychat_admin_poll_lock:';
            var activeWindowMs = 5 * 60 * 1000;
            var lastInteractionAt = Date.now();
            var tabId = '';
            var suspendedReasons = Object.create(null);

            try {
                tabId = sessionStorage.getItem(tabIdKey) || '';
                if (!tabId) {
                    tabId = 'tab_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2);
                    sessionStorage.setItem(tabIdKey, tabId);
                }
            } catch (e) {
                tabId = 'tab_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2);
            }

            function recordInteraction() {
                lastInteractionAt = Date.now();
            }

            function isVisible() {
                return document.visibilityState === 'visible';
            }

            function isActive() {
                return isVisible() && document.hasFocus() && Date.now() - lastInteractionAt <= activeWindowMs;
            }

            function suspend(reason) {
                reason = String(reason || 'manual');
                suspendedReasons[reason] = true;
            }

            function resume(reason) {
                reason = String(reason || 'manual');
                delete suspendedReasons[reason];
            }

            function isSuspended() {
                return Object.keys(suspendedReasons).length > 0;
            }

            function claim(scope, leaseMs, allowHidden) {
                if (!allowHidden && !isVisible()) {
                    return false;
                }
                leaseMs = leaseMs || 12000;
                var key = lockPrefix + scope;
                var now = Date.now();

                try {
                    var current = JSON.parse(localStorage.getItem(key) || 'null');
                    if (current && current.id && current.id !== tabId && current.expires && current.expires > now) {
                        return false;
                    }
                    localStorage.setItem(key, JSON.stringify({ id: tabId, expires: now + leaseMs }));
                    return true;
                } catch (e) {
                    return true;
                }
            }

            ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll'].forEach(function(eventName) {
                document.addEventListener(eventName, recordInteraction, { passive: true });
            });
            window.addEventListener('focus', recordInteraction);
            document.addEventListener('visibilitychange', function() {
                if (isVisible()) {
                    recordInteraction();
                }
            });

            return {
                isVisible: isVisible,
                isActive: isActive,
                recordInteraction: recordInteraction,
                suspend: suspend,
                resume: resume,
                isSuspended: isSuspended,
                canPoll: function(scope, options) {
                    options = options || {};
                    if (isSuspended()) {
                        return false;
                    }
                    if (!options.allowIdle && !isActive()) {
                        return false;
                    }
                    return claim(scope || 'default', options.leaseMs || 12000, !!options.allowHidden);
                }
            };
        })();
    </script>
    <?php echo easychat_script_tag('js/bootstrap/js/bootstrap.bundle.min.js'); ?>
    <?php echo easychat_script_tag('js/htmx/htmx-4.0.0-beta5.min.js'); ?>
    <?php echo easychat_script_tag('js/htmx-admin.js'); ?>
    <?php echo easychat_script_tag('js/common.js'); ?>
    <?php echo easychat_script_tag('js/admin_shell.js'); ?>
    <?php echo easychat_script_tag('js/admin_instant.js'); ?>
    <?php echo easychat_script_tag('js/admin_chat_prefetch.js'); ?>
    <script>
        window.EasyChatSoundConfig = {
            defaultNotificationTone: 'classic',
            notificationTones: <?php echo json_encode($easychat_sound_tone_config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            notificationUrl: <?php echo json_encode($easychat_sound_tone_config['classic']['url'], JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            sendUrl: <?php echo json_encode(easychat_asset_versioned_url('sound/send_message.mp3'), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>
        };
    </script>
    <?php echo easychat_script_tag('js/sound_manager.js'); ?>
    <?php echo easychat_script_tag('js/admin_lazy_assets.js'); ?>
    <?php echo easychat_script_tag('js/webpush.js'); ?>
    <?php echo easychat_script_tag('js/notification_health.js'); ?>
    <?php echo easychat_script_tag('js/android_update_notice.js'); ?>
    <?php echo easychat_script_tag('js/operator_profile.js'); ?>
    <?php if ($easychat_admin_help_enabled) { echo easychat_script_tag('js/admin_help.js'); } ?>
</head>
<body class="bg-light" data-easychat-manager-role="<?php echo htmlspecialchars((string)$manager_role, ENT_QUOTES, 'UTF-8'); ?>">

    <?php
    $manager_name = isset(\EasyChat\Library\RequestContext::session()['manager_name']) ? (string)\EasyChat\Library\RequestContext::session()['manager_name'] : 'Оператор';
    $manager_role = isset(\EasyChat\Library\RequestContext::session()['manager_role']) ? \EasyChat\Library\RequestContext::session()['manager_role'] : 'manager';
    $manager_avatar_file = basename((string)(\EasyChat\Library\RequestContext::session()['manager_img'] ?? ''));
    $manager_avatar = $manager_avatar_file !== '' ? HTTP_AVATARS . rawurlencode($manager_avatar_file) : '';
    $manager_name_html = htmlspecialchars($manager_name, ENT_QUOTES, 'UTF-8');
    $manager_avatar_html = htmlspecialchars($manager_avatar, ENT_QUOTES, 'UTF-8');
    $manager_name_parts = preg_split('/\s+/u', trim($manager_name), -1, PREG_SPLIT_NO_EMPTY);
    $manager_initials = '';
    foreach (array_slice((array)$manager_name_parts, 0, 2) as $manager_name_part) {
        $manager_initials .= mb_substr((string)$manager_name_part, 0, 1, 'UTF-8');
    }
    $manager_initials = mb_strtoupper($manager_initials !== '' ? $manager_initials : 'ОП', 'UTF-8');
    $manager_initials_html = htmlspecialchars($manager_initials, ENT_QUOTES, 'UTF-8');
    if (isset(\EasyChat\Library\RequestContext::get()['dismiss_password_notice'])) {
        unset(\EasyChat\Library\RequestContext::session()['suggest_password_change']);
    }
    $show_password_change_notice = !empty(\EasyChat\Library\RequestContext::session()['suggest_password_change']) && $manager_role === 'admin';
    if (empty(\EasyChat\Library\RequestContext::session()['easychat_mobile_connect_nonce'])) {
        \EasyChat\Library\RequestContext::session()['easychat_mobile_connect_nonce'] = bin2hex(random_bytes(16));
    }
    $mobile_connect_nonce = \EasyChat\Library\RequestContext::session()['easychat_mobile_connect_nonce'];
    $easychat_current_version = defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '1.0.0';
    $easychat_release_notes_url = function ($version) {
        $version = trim((string)$version);
        if (preg_match('/^(\d+)\.(\d+)\.(\d+)/', $version, $matches)) {
            return 'https://docs.easychat24.ru/docs/releases/' . $matches[1] . '-' . $matches[2] . '-' . $matches[3] . '/';
        }
        return 'https://docs.easychat24.ru/docs/whats-new/';
    };
    $easychat_current_release_notes_url = $easychat_release_notes_url($easychat_current_version);
    ?>

    <div class="d-flex min-vh-100 flex-column flex-xl-row main-wrapper">
        
        <!-- MOBILE TOP BAR -->
        <header class="d-xl-none bg-dark text-white d-flex align-items-center justify-content-between p-3" style="background: #0f172a !important; border-bottom: 1px solid rgba(255,255,255,0.05); height: 60px; z-index: 1010; position: sticky; top: 0; flex-shrink: 0; width: 100%;">
            <div class="d-flex align-items-center">
                <!-- Hamburger Menu Button -->
                <button class="btn btn-link text-white p-0 me-3" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileSidebar" aria-controls="mobileSidebar" style="font-size: 20px; outline: none; box-shadow: none; line-height: 1;">
                    <i class="fa fa-bars"></i>
                </button>
                
                <?php $easychat_render_brand_link('mobile-top'); ?>
            </div>

            <div class="d-flex align-items-center gap-2">
                <?php if ($manager_role == 'admin') { ?>
                    <a href="index.php?route=notification_health" class="easychat-mobile-notification-chip text-decoration-none" data-notification-health-chip data-state="gateway_unavailable" title="Уведомления">
                        <i class="fa fa-bell-o"></i>
                        <span data-notification-health-badge>—</span>
                    </a>
                <?php } ?>
                <!-- Unread badge -->
                <span id="mobile-unread-badge" class="badge bg-danger rounded-pill px-2 py-1 <?php echo ($total_unread > 0) ? '' : 'd-none'; ?>" style="font-size: 10px;">
                    <?php echo $total_unread; ?>
                </span>
                <!-- Operator profile -->
                <button type="button" class="btn p-0 border-0 rounded-circle" data-easychat-profile-open title="Мой профиль" aria-label="Открыть мой профиль">
                    <span data-easychat-shell-avatar class="position-relative d-grid rounded-circle" style="width: 32px; height: 32px;">
                        <img src="<?php echo $manager_avatar_html; ?>" alt="" data-easychat-shell-avatar-image class="rounded-circle border border-secondary" style="width: 32px; height: 32px; object-fit: cover;"<?php echo $manager_avatar === '' ? ' hidden' : ''; ?>>
                        <span data-easychat-shell-avatar-initials class="easychat-shell-avatar-initials rounded-circle align-items-center justify-content-center bg-secondary fw-semibold text-white border border-secondary" style="width: 32px; height: 32px; font-size: 11px;"<?php echo $manager_avatar !== '' ? ' hidden' : ''; ?>>
                            <?php echo $manager_initials_html; ?>
                        </span>
                    </span>
                </button>
            </div>
        </header>

        <!-- SIDEBAR PANEL (DESKTOP) -->
        <aside class="sidebar bg-dark text-white d-none d-xl-flex flex-column justify-content-between p-4 flex-shrink-0">
            <div>
                <!-- Sidebar Header -->
                <div class="easychat-brand-block mb-4 mt-2">
                    <?php $easychat_render_brand_link('desktop'); ?>
                    <div class="easychat-brand-release d-flex align-items-center flex-wrap">
                        <a href="<?php echo htmlspecialchars($easychat_current_release_notes_url, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener noreferrer" class="easychat-release-notes-link" title="Что нового в версии <?php echo htmlspecialchars($easychat_current_version, ENT_QUOTES, 'UTF-8'); ?>" aria-label="Что нового в версии EasyChat <?php echo htmlspecialchars($easychat_current_version, ENT_QUOTES, 'UTF-8'); ?>">
                            <span class="easychat-release-notes-label">Self-Hosted v.<?php echo htmlspecialchars($easychat_current_version, ENT_QUOTES, 'UTF-8'); ?></span>
                            <i class="fa fa-info-circle" aria-hidden="true"></i>
                            <span class="visually-hidden">Что нового в этой версии</span>
                        </a>
                    </div>
                </div>

                <div id="sidebar-update-banner" class="d-none mb-4 p-3 rounded-3" style="background: rgba(99, 102, 241, 0.1); border: 1px solid rgba(99, 102, 241, 0.2);">
                    <div class="d-flex align-items-center mb-2">
                        <i class="fa fa-arrow-circle-up me-2" style="color: #818cf8;"></i>
                        <span class="fw-bold text-white" style="font-size: 13px;">Доступно обновление</span>
                    </div>
                    <div class="small text-muted-custom mb-2" style="font-size: 11px;">
                        Версия <span id="sidebar-update-version" class="text-white fw-bold"></span>
                    </div>
                    <div class="d-grid gap-2 mt-1">
                        <a id="sidebar-update-link" href="index.php?route=update" class="btn btn-sm fw-medium" style="background: #6366f1; color: white; border: none; font-size: 12px; border-radius: 6px;">Обновить</a>
                        <a id="sidebar-update-notes-link" href="https://docs.easychat24.ru/docs/whats-new/" target="_blank" rel="noopener noreferrer" class="easychat-update-notes-link">
                            <i class="fa fa-file-text-o me-1" aria-hidden="true"></i>Что нового
                        </a>
                    </div>
                </div>

                <!-- Navigation List -->
                <nav class="nav flex-column mb-auto easychat-admin-nav"
                     data-easychat-admin-shell-nav="desktop"
                     hx-boost:inherited="true"
                     hx-target:inherited="#easychat-main-shell"
                     hx-select:inherited="#easychat-main-shell"
                     hx-swap:inherited="outerHTML transition:true settle:80ms"
                     hx-push-url:inherited="true"
                     hx-sync:inherited="#easychat-main-shell:replace"
                     hx-indicator:inherited="#easychat-admin-shell-indicator">
                    <!-- Chats Link -->
                    <a href="index.php?route=index" data-easychat-shell-route="index" class="nav-link d-flex align-items-center justify-content-between py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'index') ? 'active-link' : 'text-muted-custom'; ?>">
                        <span><i class="fa fa-commenting-o me-3 fa-fw"></i> Диалоги</span>
                        <span id="sidebar-unread-badge" class="badge bg-danger rounded-pill px-2 py-1 <?php echo ($total_unread > 0) ? '' : 'd-none'; ?>" style="font-size: 11px;">
                            <?php echo $total_unread; ?>
                        </span>
                    </a>

                    <!-- Templates Link -->
                    <a href="index.php?route=quickreply" data-easychat-shell-route="quickreply" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'quickreply') ? 'active-link' : 'text-muted-custom'; ?>">
                        <i class="fa fa-bolt me-3 fa-fw"></i> Шаблоны
                    </a>

                    <!-- Operators Link (Admin Only) -->
                    <?php if ($manager_role == 'admin') { ?>
                        <a href="index.php?route=operator" data-easychat-shell-route="operator" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'operator') ? 'active-link' : 'text-muted-custom'; ?>">
                            <i class="fa fa-users me-3 fa-fw"></i> Операторы
                        </a>
                    <?php } ?>

                    <!-- Analytics Link -->
					<a href="index.php?route=analytics" data-easychat-shell-route="analytics" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'analytics') ? 'active-link' : 'text-muted-custom'; ?>">
						<i class="fa fa-bar-chart me-3 fa-fw"></i> Аналитика
					</a>

                    <!-- Notification Health Link (Admin Only) -->
                    <?php if ($manager_role == 'admin') { ?>
                        <a href="index.php?route=notification_health" data-easychat-shell-route="notification_health" class="nav-link d-flex align-items-center justify-content-between py-2.5 px-3 mb-2 rounded-3 easychat-notification-health-chip <?php echo ($active_route == 'notification_health') ? 'active-link' : 'text-muted-custom'; ?>" data-notification-health-chip data-state="gateway_unavailable">
                            <span><i class="fa fa-bell-o me-3 fa-fw"></i> Уведомления</span>
                            <span class="badge rounded-pill px-2 py-1" data-notification-health-badge style="font-size: 11px;">—</span>
                        </a>
                    <?php } ?>

                    <!-- Knowledge Storage Link (Admin + configured AI provider only) -->
                    <?php if ($manager_role == 'admin' && ($chat_ai_tools_available ?? '0') === '1') { ?>
                        <a href="index.php?route=knowledge_storage" data-easychat-shell-route="knowledge_storage" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'knowledge_storage') ? 'active-link' : 'text-muted-custom'; ?>">
                            <i class="fa fa-database me-3 fa-fw"></i> База знаний ИИ
                        </a>
                    <?php } ?>

                    <!-- Integrations Link (Admin Only) -->
                    <?php if ($manager_role == 'admin') { ?>
                        <a href="index.php?route=integration" data-provider-alert-link data-easychat-shell-route="integration" data-easychat-shell-routes="integration marketplace" class="nav-link d-flex align-items-center justify-content-between py-2.5 px-3 mb-2 rounded-3 <?php echo (in_array($active_route, ['integration', 'marketplace'], true)) ? 'active-link' : 'text-muted-custom'; ?>">
                            <span><i class="fa fa-plug me-3 fa-fw"></i> Интеграции</span><span class="badge rounded-pill bg-warning text-dark d-none" data-provider-alert-badge>0</span>
                        </a>
                        <a href="index.php?route=crm_integration" data-easychat-shell-route="crm_integration" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route === 'crm_integration') ? 'active-link' : 'text-muted-custom'; ?>">
                            <i class="fa fa-address-card-o me-3 fa-fw"></i> CRM
                        </a>
                    <?php } ?>

                    <!-- Settings Link (Admin Only) -->
                    <?php if ($manager_role == 'admin') { ?>
                        <a href="index.php?route=setting" data-easychat-shell-route="setting" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'setting') ? 'active-link' : 'text-muted-custom'; ?>">
                            <i class="fa fa-sliders me-3 fa-fw"></i> Настройки
                        </a>
                    <?php } ?>
                    
                    <?php if ($easychat_admin_help_enabled) { ?>
                    <button type="button" class="nav-link easychat-admin-help-trigger d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 text-muted-custom" data-bs-toggle="offcanvas" data-bs-target="#easychatAdminHelp" aria-controls="easychatAdminHelp">
                        <i class="fa fa-magic me-3 fa-fw" aria-hidden="true"></i> <?php echo $easychat_help_text('nav'); ?>
                    </button>
                    <?php } else { ?>
                    <!-- Telegram Support Link -->
                    <a href="https://t.me/easychat24_support" target="_blank" hx-boost="false" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 text-muted-custom" style="color: #24a1de !important;">
                        <i class="fa fa-paper-plane me-3 fa-fw"></i> Поддержка в Telegram
                    </a>
                    
                    <!-- Max Support Link -->
                    <a href="https://max.ru/join/k50gnE1X8NVzvuE2pAY4DThceZg00BVITThogZBntyk" target="_blank" hx-boost="false" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 text-muted-custom" style="color: #e0466e !important;">
                        <span class="me-3 fa-fw d-inline-flex align-items-center justify-content-center" style="width: 1.28571429em; height: 1.28571429em;">
                            <svg xmlns="http://www.w3.org/2000/svg" style="width: 14px; height: 14px; fill: currentColor;" viewBox="0 0 720 720"><path d="M350.4,9.6C141.8,20.5,4.1,184.1,12.8,390.4c3.8,90.3,40.1,168,48.7,253.7,2.2,22.2-4.2,49.6,21.4,59.3,31.5,11.9,79.8-8.1,106.2-26.4,9-6.1,17.6-13.2,24.2-22,27.3,18.1,53.2,35.6,85.7,43.4,143.1,34.3,299.9-44.2,369.6-170.3C799.6,291.2,622.5-4.6,350.4,9.6h0ZM269.4,504c-11.3,8.8-22.2,20.8-34.7,27.7-18.1,9.7-23.7-.4-30.5-16.4-21.4-50.9-24-137.6-11.5-190.9,16.8-72.5,72.9-136.3,150-143.1,78-6.9,150.4,32.7,183.1,104.2,72.4,159.1-112.9,316.2-256.4,218.6h0Z"></path></svg>
                        </span> Поддержка в МАКС
                    </a>
                    <?php } ?>
                </nav>
            </div>

            <!-- Profile & Sign-out Block -->
            <div class="pt-4" style="border-top: 1px solid rgba(255,255,255,0.08);">
                <!-- RuStore App Download Block -->
                <div class="android-update-notice-slot" data-android-update-notice hidden></div>
                <div class="mb-4 text-center">
                    <a href="javascript:void(0);" class="btn-rustore-badge-trigger d-flex flex-row align-items-center justify-content-center p-3 rounded-3 text-decoration-none" data-bs-toggle="modal" data-bs-target="#rustoreAppModal">
                        <!-- RuStore SVG Logo -->
						<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" version="1.1" viewBox="0 0 88 88">
						 <path d="m42.2 88c-19.9 0-29.9 0-36.1-6.19-6.19-6.19-6.19-16.1-6.19-36.1l-1.6e-7 -3.52c-8.7e-7 -19.9-1.32e-6 -29.9 6.19-36.1 6.19-6.19 16.1-6.19 36.1-6.19h1e-4l3.52-1.5e-7c19.9-8.7e-7 29.9-1.29e-6 36.1 6.19 6.19 6.19 6.19 16.1 6.19 36.1v3.52c0 19.9 0 29.9-6.19 36.1s-16.1 6.19-36.1 6.19z" clip-rule="evenodd" fill="#07f" fill-rule="evenodd"/>
						 <path d="m51.2 16.1c-2.3-0.0226-4.3 1.83-4.3 4.25v5.17l-10.8-2.69c-0.336-0.0838-0.671-0.126-1-0.129-2.3-0.0226-4.3 1.83-4.3 4.25v5.15l-10.7-2.67c-2.69-0.67-5.3 1.36-5.3 4.12v28.7c0 2.44 1.66 4.56 4.03 5.15l17.1 4.26c2.69 0.67 5.3-1.36 5.3-4.12v-28.7c0-1.75-0.857-3.33-2.21-4.3-0.0216-0.0707-0.0167-0.149 0.0273-0.213 0.075-0.109 0.21-0.161 0.336-0.123 2.25 0.68 4.39 2.98 4.61 5.88l0.742 21.9c0.0191 0.734 0.509 1.36 1.2 1.59l6 1.49c2.69 0.67 5.3-1.36 5.3-4.12 0.0708-9.47 0.0504-19.1 0.0528-28.6 0-1.29-0.436-2.28-0.926-3-0.0794-0.12-0.163-0.238-0.252-0.352-0.107-0.136-0.224-0.265-0.344-0.391-0.179-0.188-0.37-0.367-0.576-0.527-0.0014-0.0011-0.0025-0.0028-0.0039-0.0039-0.0848-0.0852-0.109-0.218-0.0391-0.318 0.075-0.109 0.21-0.161 0.336-0.123 2.25 0.68 4.4 2.98 4.61 5.88l0.742 21.9c0.019 0.728 0.504 1.35 1.19 1.57l6.01 1.5c2.69 0.67 5.3-1.36 5.3-4.12v-28.7c0-2.44-1.66-4.56-4.03-5.15l-17.1-4.26c-0.336-0.0838-0.671-0.126-1-0.129z" fill="#fff"/>
						</svg>
                        <span class="text-white fw-semibold" style="font-family: 'Outfit', sans-serif; font-size: 13px; letter-spacing: 0.3px;">Установить приложение</span>
                    </a>
                </div>

                <div class="sidebar-profile-row d-flex align-items-center">
                    <button type="button" class="sidebar-profile-main easychat-profile-trigger d-flex align-items-start" data-easychat-profile-open aria-label="Открыть мой профиль">
                        <span data-easychat-shell-avatar class="position-relative d-grid rounded-circle me-2 flex-shrink-0" style="width: 44px; height: 44px;">
                            <img src="<?php echo $manager_avatar_html; ?>" alt="" data-easychat-shell-avatar-image class="rounded-circle border border-secondary" style="width: 44px; height: 44px; object-fit: cover;"<?php echo $manager_avatar === '' ? ' hidden' : ''; ?>>
                            <span data-easychat-shell-avatar-initials class="easychat-shell-avatar-initials rounded-circle align-items-center justify-content-center bg-secondary fw-semibold text-white border border-secondary" style="width: 44px; height: 44px; font-size: 14px;"<?php echo $manager_avatar !== '' ? ' hidden' : ''; ?>>
                                <?php echo $manager_initials_html; ?>
                            </span>
                        </span>
                        <div class="sidebar-profile-text">
                            <h6 class="mb-0 text-white small fw-bold text-truncate"><?php echo $manager_name_html; ?></h6>
                            <span class="text-muted small" style="font-size: 11px;"><?php echo ($manager_role == 'admin') ? 'Администратор' : 'Оператор'; ?></span>
                        </div>
                    </button>
                </div>
                <div class="sidebar-buttons-row d-flex align-items-center justify-content-end">
                    <div class="sidebar-buttons-main d-flex align-items-end">
                        <div class="sidebar-buttons-text">
                            <div class="sidebar-buttons-actions d-flex align-items-center" role="group" aria-label="Быстрые действия профиля">
                                <button type="button" id="easychat-webpush-toggle" class="btn btn-link text-muted-custom sidebar-icon-action" title="Включить браузерные уведомления" aria-label="Включить браузерные уведомления">
                                    <i class="fa fa-bell-o fa-lg" style="vertical-align: middle;"></i>
                                </button>
                                <?php $easychat_render_sound_control(); ?>
                                <button type="button" id="easychat-mobile-connect-toggle" class="btn btn-link text-muted-custom sidebar-icon-action sidebar-mobile-connect-action" data-mobile-connect-nonce="<?php echo htmlspecialchars($mobile_connect_nonce, ENT_QUOTES, 'UTF-8'); ?>" title="Подключить приложение" aria-label="Подключить приложение">
                                    <i class="fa fa-mobile fa-lg" style="vertical-align: middle;"></i>
                                    <span class="mobile-connect-plus" aria-hidden="true">+</span>
                                </button>
                                <button type="button" class="btn btn-link text-muted-custom sidebar-icon-action easychat-passkey-action d-none" data-bs-toggle="modal" data-bs-target="#easychatPasskeyModal" title="Быстрый вход на этом устройстве" aria-label="Быстрый вход на этом устройстве">
                                    <i class="fa fa-key fa-lg" style="vertical-align: middle;"></i>
                                </button>
                                <a href="index.php?route=auth/logout" class="btn btn-link text-danger sidebar-icon-action" title="Выйти" aria-label="Выйти">
                                    <i class="fa fa-sign-out fa-lg"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </aside>

        <!-- MOBILE OFFCANVAS SIDEBAR -->
        <div class="offcanvas offcanvas-start bg-dark text-white d-xl-none" tabindex="-1" id="mobileSidebar" aria-labelledby="mobileSidebarLabel" style="background: #0f172a !important; width: 280px; border-right: 1px solid rgba(255,255,255,0.05);">
            <div class="offcanvas-header border-bottom border-secondary-subtle p-4">
                <div class="easychat-brand-block easychat-brand-block--mobile-sidebar">
                    <?php $easychat_render_brand_link('mobile-sidebar', 'mobileSidebarLabel'); ?>
                    <div class="easychat-brand-release d-flex align-items-center flex-wrap">
                        <a href="<?php echo htmlspecialchars($easychat_current_release_notes_url, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener noreferrer" class="easychat-release-notes-link" title="Что нового в версии <?php echo htmlspecialchars($easychat_current_version, ENT_QUOTES, 'UTF-8'); ?>" aria-label="Что нового в версии EasyChat <?php echo htmlspecialchars($easychat_current_version, ENT_QUOTES, 'UTF-8'); ?>">
                            <span class="easychat-release-notes-label">v.<?php echo htmlspecialchars($easychat_current_version, ENT_QUOTES, 'UTF-8'); ?></span>
                            <i class="fa fa-info-circle" aria-hidden="true"></i>
                            <span class="visually-hidden">Что нового в этой версии</span>
                        </a>
                    </div>
                </div>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close" style="box-shadow: none; outline: none;"></button>
            </div>
            <div class="offcanvas-body d-flex flex-column justify-content-between p-4" style="overflow-y: auto;">
                <div>
                    <div id="mobile-sidebar-update-banner" class="d-none mb-4 p-3 rounded-3" style="background: rgba(99, 102, 241, 0.1); border: 1px solid rgba(99, 102, 241, 0.2);">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fa fa-arrow-circle-up me-2" style="color: #818cf8;"></i>
                            <span class="fw-bold text-white" style="font-size: 13px;">Доступно обновление</span>
                        </div>
                        <div class="small text-muted-custom mb-2" style="font-size: 11px;">
                            Версия <span id="mobile-sidebar-update-version" class="text-white fw-bold"></span>
                        </div>
                        <div class="d-grid gap-2 mt-1">
                            <a id="mobile-sidebar-update-link" href="index.php?route=update" class="btn btn-sm fw-medium" style="background: #6366f1; color: white; border: none; font-size: 12px; border-radius: 6px;">Обновить</a>
                            <a id="mobile-sidebar-update-notes-link" href="https://docs.easychat24.ru/docs/whats-new/" target="_blank" rel="noopener noreferrer" class="easychat-update-notes-link">
                                <i class="fa fa-file-text-o me-1" aria-hidden="true"></i>Что нового
                            </a>
                        </div>
                    </div>

                    <!-- Navigation List -->
                    <nav class="nav flex-column mb-auto easychat-admin-nav"
                         data-easychat-admin-shell-nav="mobile"
                         hx-boost:inherited="true"
                         hx-target:inherited="#easychat-main-shell"
                         hx-select:inherited="#easychat-main-shell"
                         hx-swap:inherited="outerHTML transition:true settle:80ms"
                         hx-push-url:inherited="true"
                         hx-sync:inherited="#easychat-main-shell:replace"
                         hx-indicator:inherited="#easychat-admin-shell-indicator">
                        <!-- Chats Link -->
                        <a href="index.php?route=index" data-easychat-shell-route="index" class="nav-link d-flex align-items-center justify-content-between py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'index') ? 'active-link' : 'text-muted-custom'; ?>">
                            <span><i class="fa fa-commenting-o me-3 fa-fw"></i> Диалоги</span>
                            <span id="offcanvas-unread-badge" class="badge bg-danger rounded-pill px-2 py-1 <?php echo ($total_unread > 0) ? '' : 'd-none'; ?>" style="font-size: 11px;">
                                <?php echo $total_unread; ?>
                            </span>
                        </a>

                        <!-- Templates Link -->
                        <a href="index.php?route=quickreply" data-easychat-shell-route="quickreply" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'quickreply') ? 'active-link' : 'text-muted-custom'; ?>">
                            <i class="fa fa-bolt me-3 fa-fw"></i> Шаблоны
                        </a>

                        <!-- Operators Link (Admin Only) -->
                        <?php if ($manager_role == 'admin') { ?>
                            <a href="index.php?route=operator" data-easychat-shell-route="operator" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'operator') ? 'active-link' : 'text-muted-custom'; ?>">
                                <i class="fa fa-users me-3 fa-fw"></i> Операторы
                            </a>
                        <?php } ?>

                        <!-- Analytics Link -->
                        <a href="index.php?route=analytics" data-easychat-shell-route="analytics" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'analytics') ? 'active-link' : 'text-muted-custom'; ?>">
                            <i class="fa fa-bar-chart me-3 fa-fw"></i> Аналитика
                        </a>

                        <!-- Notification Health Link (Admin Only) -->
                        <?php if ($manager_role == 'admin') { ?>
                            <a href="index.php?route=notification_health" data-easychat-shell-route="notification_health" class="nav-link d-flex align-items-center justify-content-between py-2.5 px-3 mb-2 rounded-3 easychat-notification-health-chip <?php echo ($active_route == 'notification_health') ? 'active-link' : 'text-muted-custom'; ?>" data-notification-health-chip data-state="gateway_unavailable">
                                <span><i class="fa fa-bell-o me-3 fa-fw"></i> Уведомления</span>
                                <span class="badge rounded-pill px-2 py-1" data-notification-health-badge style="font-size: 11px;">—</span>
                            </a>
                        <?php } ?>

                        <!-- Knowledge Storage Link (Admin + configured AI provider only) -->
                        <?php if ($manager_role == 'admin' && ($chat_ai_tools_available ?? '0') === '1') { ?>
                            <a href="index.php?route=knowledge_storage" data-easychat-shell-route="knowledge_storage" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'knowledge_storage') ? 'active-link' : 'text-muted-custom'; ?>">
                                <i class="fa fa-database me-3 fa-fw"></i> База знаний ИИ
                            </a>
                        <?php } ?>

                        <!-- Integrations Link (Admin Only) -->
                        <?php if ($manager_role == 'admin') { ?>
                            <a href="index.php?route=integration" data-provider-alert-link data-easychat-shell-route="integration" data-easychat-shell-routes="integration marketplace" class="nav-link d-flex align-items-center justify-content-between py-2.5 px-3 mb-2 rounded-3 <?php echo (in_array($active_route, ['integration', 'marketplace'], true)) ? 'active-link' : 'text-muted-custom'; ?>">
                                <span><i class="fa fa-plug me-3 fa-fw"></i> Интеграции</span><span class="badge rounded-pill bg-warning text-dark d-none" data-provider-alert-badge>0</span>
                            </a>
                            <a href="index.php?route=crm_integration" data-easychat-shell-route="crm_integration" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route === 'crm_integration') ? 'active-link' : 'text-muted-custom'; ?>">
                                <i class="fa fa-address-card-o me-3 fa-fw"></i> CRM
                            </a>
                        <?php } ?>

                        <!-- Settings Link (Admin Only) -->
                        <?php if ($manager_role == 'admin') { ?>
                            <a href="index.php?route=setting" data-easychat-shell-route="setting" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 <?php echo ($active_route == 'setting') ? 'active-link' : 'text-muted-custom'; ?>">
                                <i class="fa fa-sliders me-3 fa-fw"></i> Настройки
                            </a>
                        <?php } ?>
                        
                        <?php if ($easychat_admin_help_enabled) { ?>
                        <button type="button" class="nav-link easychat-admin-help-trigger d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 text-muted-custom" data-bs-toggle="offcanvas" data-bs-target="#easychatAdminHelp" aria-controls="easychatAdminHelp">
                            <i class="fa fa-magic me-3 fa-fw" aria-hidden="true"></i> <?php echo $easychat_help_text('nav'); ?>
                        </button>
                        <?php } else { ?>
                        <!-- Telegram Support Link -->
                        <a href="https://t.me/easychat24_support" target="_blank" hx-boost="false" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 text-muted-custom" style="color: #24a1de !important;">
                            <i class="fa fa-paper-plane me-3 fa-fw"></i> Поддержка в Telegram
                        </a>
                        
                        <!-- Max Support Link -->
                        <a href="https://max.ru/join/k50gnE1X8NVzvuE2pAY4DThceZg00BVITThogZBntyk" target="_blank" hx-boost="false" class="nav-link d-flex align-items-center py-2.5 px-3 mb-2 rounded-3 text-muted-custom" style="color: #e0466e !important;">
                            <span class="me-3 fa-fw d-inline-flex align-items-center justify-content-center" style="width: 1.28571429em; height: 1.28571429em;">
                                <svg xmlns="http://www.w3.org/2000/svg" style="width: 14px; height: 14px; fill: currentColor;" viewBox="0 0 720 720"><path d="M350.4,9.6C141.8,20.5,4.1,184.1,12.8,390.4c3.8,90.3,40.1,168,48.7,253.7,2.2,22.2-4.2,49.6,21.4,59.3,31.5,11.9,79.8-8.1,106.2-26.4,9-6.1,17.6-13.2,24.2-22,27.3,18.1,53.2,35.6,85.7,43.4,143.1,34.3,299.9-44.2,369.6-170.3C799.6,291.2,622.5-4.6,350.4,9.6h0ZM269.4,504c-11.3,8.8-22.2,20.8-34.7,27.7-18.1,9.7-23.7-.4-30.5-16.4-21.4-50.9-24-137.6-11.5-190.9,16.8-72.5,72.9-136.3,150-143.1,78-6.9,150.4,32.7,183.1,104.2,72.4,159.1-112.9,316.2-256.4,218.6h0Z"></path></svg>
                            </span> Поддержка в МАКС
                        </a>
                        <?php } ?>
                    </nav>
                </div>

                <!-- Profile & Sign-out Block -->
                <div class="pt-4" style="border-top: 1px solid rgba(255,255,255,0.08);">
                    <!-- RuStore App Download Block -->
                    <div class="android-update-notice-slot" data-android-update-notice hidden></div>
                    <div class="mb-4 text-center">
                        <a href="javascript:void(0);" class="btn-rustore-badge-trigger d-flex flex-row align-items-center justify-content-center p-3 rounded-3 text-decoration-none" data-bs-toggle="modal" data-bs-target="#rustoreAppModal">
                            <!-- RuStore SVG Logo -->
                            <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" version="1.1" viewBox="0 0 88 88">
                             <path d="m42.2 88c-19.9 0-29.9 0-36.1-6.19-6.19-6.19-6.19-16.1-6.19-36.1l-1.6e-7 -3.52c-8.7e-7 -19.9-1.32e-6 -29.9 6.19-36.1 6.19-6.19 16.1-6.19 36.1-6.19h1e-4l3.52-1.5e-7c19.9-8.7e-7 29.9-1.29e-6 36.1 6.19 6.19 6.19 6.19 16.1 6.19 36.1v3.52c0 19.9 0 29.9-6.19 36.1s-16.1 6.19-36.1 6.19z" clip-rule="evenodd" fill="#07f" fill-rule="evenodd"/>
                             <path d="m51.2 16.1c-2.3-0.0226-4.3 1.83-4.3 4.25v5.17l-10.8-2.69c-0.336-0.0838-0.671-0.126-1-0.129-2.3-0.0226-4.3 1.83-4.3 4.25v5.15l-10.7-2.67c-2.69-0.67-5.3 1.36-5.3 4.12v28.7c0 2.44 1.66 4.56 4.03 5.15l17.1 4.26c2.69 0.67 5.3-1.36 5.3-4.12v-28.7c0-1.75-0.857-3.33-2.21-4.3-0.0216-0.0707-0.0167-0.149 0.0273-0.213 0.075-0.109 0.21-0.161 0.336-0.123 2.25 0.68 4.39 2.98 4.61 5.88l0.742 21.9c0.0191 0.734 0.509 1.36 1.2 1.59l6 1.49c2.69 0.67 5.3-1.36 5.3-4.12 0.0708-9.47 0.0504-19.1 0.0528-28.6 0-1.29-0.436-2.28-0.926-3-0.0794-0.12-0.163-0.238-0.252-0.352-0.107-0.136-0.224-0.265-0.344-0.391-0.179-0.188-0.37-0.367-0.576-0.527-0.0014-0.0011-0.0025-0.0028-0.0039-0.0039-0.0848-0.0852-0.109-0.218-0.0391-0.318 0.075-0.109 0.21-0.161 0.336-0.123 2.25 0.68 4.4 2.98 4.61 5.88l0.742 21.9c0.019 0.728 0.504 1.35 1.19 1.57l6.01 1.5c2.69 0.67 5.3-1.36 5.3-4.12v-28.7c0-2.44-1.66-4.56-4.03-5.15l-17.1-4.26c-0.336-0.0838-0.671-0.126-1-0.129z" fill="#fff"/>
                            </svg>
                            <span class="text-white fw-semibold" style="font-family: 'Outfit', sans-serif; font-size: 13px; letter-spacing: 0.3px;">Установить приложение</span>
                        </a>
                    </div>

                    <div class="sidebar-profile-row d-flex align-items-center mb-0">
                        <button type="button" class="sidebar-profile-main easychat-profile-trigger d-flex align-items-start" data-easychat-profile-open aria-label="Открыть мой профиль">
                            <span data-easychat-shell-avatar class="position-relative d-grid rounded-circle me-2 flex-shrink-0" style="width: 44px; height: 44px;">
                                <img src="<?php echo $manager_avatar_html; ?>" alt="" data-easychat-shell-avatar-image class="rounded-circle border border-secondary" style="width: 44px; height: 44px; object-fit: cover;"<?php echo $manager_avatar === '' ? ' hidden' : ''; ?>>
                                <span data-easychat-shell-avatar-initials class="easychat-shell-avatar-initials rounded-circle align-items-center justify-content-center bg-secondary fw-semibold text-white border border-secondary" style="width: 44px; height: 44px; font-size: 14px;"<?php echo $manager_avatar !== '' ? ' hidden' : ''; ?>>
                                    <?php echo $manager_initials_html; ?>
                                </span>
                            </span>
                            <div class="sidebar-profile-text">
                                <h6 class="mb-0 text-white small fw-bold text-truncate" style="color: #ffffff !important;"><?php echo $manager_name_html; ?></h6>
                                <span class="text-muted small" style="font-size: 11px; color: #94a3b8 !important;"><?php echo ($manager_role == 'admin') ? 'Администратор' : 'Оператор'; ?></span>
                            </div>
                        </button>
                    </div>
                    <div class="sidebar-buttons-row d-flex align-items-center justify-content-end mb-0">
                        <div class="sidebar-buttons-main d-flex align-items-start">
                            <div class="sidebar-buttons-text">
                                <div class="sidebar-buttons-actions d-flex align-items-center" role="group" aria-label="Быстрые действия профиля на мобильном">
                                    <button type="button" class="btn btn-link text-muted-custom sidebar-icon-action mobile-webpush-trigger" title="Включить браузерные уведомления" aria-label="Включить браузерные уведомления">
                                        <i class="fa fa-bell-o fa-lg" style="vertical-align: middle;"></i>
                                    </button>
                                    <?php $easychat_render_sound_control(); ?>
                                    <button type="button" class="btn btn-link text-muted-custom sidebar-icon-action sidebar-mobile-connect-action mobile-mobile-connect-trigger" title="Подключить приложение" aria-label="Подключить приложение">
                                        <i class="fa fa-mobile fa-lg" style="vertical-align: middle;"></i>
                                        <span class="mobile-connect-plus" aria-hidden="true">+</span>
                                    </button>
                                    <button type="button" class="btn btn-link text-muted-custom sidebar-icon-action easychat-passkey-action d-none" data-bs-toggle="modal" data-bs-target="#easychatPasskeyModal" title="Быстрый вход на этом устройстве" aria-label="Быстрый вход на этом устройстве">
                                        <i class="fa fa-key fa-lg" style="vertical-align: middle;"></i>
                                    </button>
                                    <a href="index.php?route=auth/logout" class="btn btn-link text-danger sidebar-icon-action" title="Выйти" aria-label="Выйти">
                                        <i class="fa fa-sign-out fa-lg"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- MAIN WORKSPACE -->
        <main class="flex-grow-1 bg-light overflow-auto content-main" style="min-height: 100vh;" data-easychat-admin-shell-main>
            <div id="easychat-admin-shell-indicator" class="easychat-admin-shell-indicator htmx-indicator" role="status" aria-live="polite" aria-label="Загружаем раздел">
                <span class="easychat-admin-shell-progress" aria-hidden="true"></span>
                <span class="visually-hidden">Загружаем раздел EasyChat</span>
            </div>
            <div id="easychat-main-shell" class="container-fluid p-0 easychat-main-shell easychat-main-shell--<?php echo htmlspecialchars($easychat_page_layout, ENT_QUOTES, 'UTF-8'); ?>" data-easychat-active-route="<?php echo htmlspecialchars((string)$active_route, ENT_QUOTES, 'UTF-8'); ?>" data-easychat-page-layout="<?php echo htmlspecialchars($easychat_page_layout, ENT_QUOTES, 'UTF-8'); ?>" hx-history-elt>
                <?php if ($show_password_change_notice) { ?>
                    <div class="alert border-0 shadow-sm mb-4 d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3" style="border-radius: 14px; background: #fff7ed; color: #7c2d12;">
                        <div>
                            <strong>Смените начальный пароль администратора EasyChat</strong>
                            <div class="small mt-1">Вы вошли из админки CMS с паролем, созданным при установке. Для безопасности задайте свой постоянный пароль.</div>
                        </div>
                        <div class="d-flex gap-2 flex-shrink-0">
                            <a class="btn btn-sm btn-primary" href="index.php?route=operator&focus_admin_password=1" style="border-radius: 8px; background: linear-gradient(135deg, #6366f1, #a855f7); border: none;">Сменить пароль</a>
                            <a class="btn btn-sm btn-outline-secondary" href="index.php?route=<?php echo urlencode($active_route); ?>&dismiss_password_notice=1" style="border-radius: 8px;">Позже</a>
                        </div>
                    </div>
                <?php } ?>
                <?php include ($contentPage); ?>
            </div>
        </main>
    </div>

    <?php if ($easychat_admin_help_enabled) { ?>
    <aside class="offcanvas offcanvas-end easychat-admin-help" tabindex="-1" id="easychatAdminHelp" aria-labelledby="easychatAdminHelpTitle" data-easychat-admin-help data-manager-role="<?php echo htmlspecialchars((string)$manager_role, ENT_QUOTES, 'UTF-8'); ?>">
        <div class="offcanvas-header easychat-admin-help__header">
            <div class="easychat-admin-help__identity">
                <span class="easychat-admin-help__mark" aria-hidden="true"><i class="fa fa-magic"></i></span>
                <div>
                    <div class="easychat-admin-help__eyebrow"><?php echo $easychat_help_text('eyebrow'); ?></div>
                    <h2 class="offcanvas-title" id="easychatAdminHelpTitle"><?php echo $easychat_help_text('title'); ?></h2>
                </div>
            </div>
            <div class="easychat-admin-help__header-actions">
                <button type="button" class="easychat-admin-help__header-button easychat-admin-help__header-button--reset" data-admin-help-reset aria-label="<?php echo $easychat_help_text('new_chat'); ?>" title="<?php echo $easychat_help_text('new_chat_title'); ?>">
                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                    <span><?php echo $easychat_help_text('new_chat_short'); ?></span>
                </button>
                <button type="button" class="easychat-admin-help__header-button easychat-admin-help__header-button--close" data-bs-dismiss="offcanvas" aria-label="<?php echo $easychat_help_text('close'); ?>" title="<?php echo $easychat_help_text('close'); ?>">
                    <i class="fa fa-times" aria-hidden="true"></i>
                </button>
            </div>
        </div>
        <div class="offcanvas-body easychat-admin-help__body">
            <div class="easychat-admin-help__intro" data-admin-help-intro>
                <strong><?php echo $easychat_help_text('intro_title'); ?></strong>
                <span><?php echo $easychat_help_text('intro_text'); ?></span>
            </div>
            <div class="easychat-admin-help__messages" data-admin-help-messages role="log" aria-live="polite" aria-relevant="additions"></div>
            <div class="easychat-admin-help__status" data-admin-help-status role="status" aria-live="polite" hidden></div>
            <section class="easychat-admin-help__gift" data-admin-help-gift hidden>
                <span class="easychat-admin-help__gift-icon" aria-hidden="true"><i class="fa fa-gift"></i></span>
                <div>
                    <strong><?php echo $easychat_help_text('gift_title'); ?></strong>
                    <p><?php echo $easychat_help_text('gift_text'); ?></p>
                    <label class="easychat-admin-help__email" data-admin-help-email-wrap hidden>
                        <span><?php echo $easychat_help_text('email'); ?></span>
                        <input type="email" inputmode="email" autocomplete="email" data-admin-help-email maxlength="190" placeholder="name@example.ru">
                    </label>
                    <button type="button" class="easychat-admin-help__primary" data-admin-help-gift-action><?php echo $easychat_help_text('gift_action'); ?></button>
                </div>
            </section>
            <details class="easychat-admin-help__diagnostic" data-admin-help-diagnostic hidden>
                <summary><i class="fa fa-stethoscope" aria-hidden="true"></i><span><?php echo $easychat_help_text('diagnose'); ?></span></summary>
                <div class="easychat-admin-help__diagnostic-body">
                    <p><?php echo $easychat_help_text('disclosure'); ?></p>
                    <ul data-admin-help-diagnostic-list></ul>
                    <p class="easychat-admin-help__privacy"><i class="fa fa-shield" aria-hidden="true"></i> <?php echo $easychat_help_text('privacy'); ?></p>
                    <button type="button" class="easychat-admin-help__secondary" data-admin-help-diagnose><?php echo $easychat_help_text('diagnose_action'); ?></button>
                </div>
            </details>
        </div>
        <form class="easychat-admin-help__composer" data-admin-help-form>
            <label class="visually-hidden" for="easychatAdminHelpQuestion"><?php echo $easychat_help_text('question_label'); ?></label>
            <textarea id="easychatAdminHelpQuestion" data-admin-help-question rows="1" maxlength="2000" placeholder="<?php echo $easychat_help_text('placeholder'); ?>"></textarea>
            <button type="submit" class="easychat-admin-help__send" aria-label="<?php echo $easychat_help_text('send_label'); ?>" title="<?php echo $easychat_help_text('send_title'); ?>"><i class="fa fa-arrow-up" aria-hidden="true"></i></button>
        </form>
    </aside>
    <?php } ?>

    <!-- Custom CSS Variables and Highlights -->
    <style id="easychat-route-layout-vars">
:root {
    --layout-overflow: <?php echo ($active_route === 'index') ? 'hidden' : 'auto'; ?>;
    --layout-height: <?php echo ($active_route === 'index') ? '100%' : 'auto'; ?>;
    --layout-mobile-gutter: <?php echo $easychat_mobile_gutter; ?>;
}
</style>

    <!-- Global foreground presence and unread tab notifications -->
    <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        function easychatAll(selector) {
            return Array.prototype.slice.call(document.querySelectorAll(selector));
        }

        function easychatJson(url, options) {
            options = options || {};
            if (window.EasyChatRequest && typeof window.EasyChatRequest.json === 'function') {
                return window.EasyChatRequest.json(url, options);
            }
            function routeUrl(value) {
                if (typeof window.EasyChatRouteUrl === 'function') {
                    return window.EasyChatRouteUrl(value);
                }
                var raw = String(value || '');
                var marker = 'index.php?route=';
                var base = String(window.EasyChatRouteBase || '');
                if (base && raw.indexOf(marker) === 0) {
                    return base + raw.substring(marker.length);
                }
                return raw;
            }
            var method = String(options.method || 'GET').toUpperCase();
            var headers = new Headers(options.headers || {});
            var requestUrl = routeUrl(url);
            var body = null;
            headers.set('Accept', 'application/json');
            if (options.data && method === 'GET') {
                requestUrl += (requestUrl.indexOf('?') === -1 ? '?' : '&') + new URLSearchParams(options.data).toString();
            } else if (options.data) {
                headers.set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
                body = new URLSearchParams(options.data);
            }
            return fetch(requestUrl, {
                method: method,
                headers: headers,
                body: method === 'GET' || method === 'HEAD' ? null : body,
                credentials: 'same-origin'
            }).then(function(response) {
                return response.text().then(function(raw) {
                    return raw ? JSON.parse(raw) : {};
                });
            });
        }

        function easychatPost(url, data) {
            if (window.EasyChatRequest && typeof window.EasyChatRequest.post === 'function') {
                return window.EasyChatRequest.post(url, data || {});
            }
            return easychatJson(url, { method: 'POST', data: data || {} });
        }

        (function initEasyChatPresence() {
            var heartbeatIntervalMs = 30000;
            var minGapMs = 25000;
            var activeWindowMs = 5 * 60 * 1000;
            var lastInteractionAt = Date.now();
            var lastSentAt = 0;
            var pending = false;

            function isForeground() {
                return document.visibilityState === 'visible'
                    && document.hasFocus()
                    && Date.now() - lastInteractionAt <= activeWindowMs;
            }

            function recordInteraction() {
                lastInteractionAt = Date.now();
            }

            function sendPresence(force) {
                var now = Date.now();
                if (!isForeground() || pending) {
                    return;
                }
                if (!force && now - lastSentAt < minGapMs) {
                    return;
                }

                pending = true;
                lastSentAt = now;
                easychatPost('index.php?route=index/presence', {
                        visibility: document.visibilityState,
                        has_focus: document.hasFocus() ? '1' : '0',
                        csrf_token: window.EasyChatCsrfToken || ''
                    })
                    .catch(function() {})
                    .then(function() {
                        pending = false;
                    });
            }

            sendPresence(true);
            window.setInterval(function() {
                sendPresence(false);
            }, heartbeatIntervalMs);
            window.addEventListener('focus', function() {
                recordInteraction();
                sendPresence(true);
            });
            document.addEventListener('visibilitychange', function() {
                if (document.visibilityState === 'visible') {
                    recordInteraction();
                    sendPresence(true);
                }
            });
            window.addEventListener('pagehide', function() {
                pending = false;
            });
            ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll'].forEach(function(eventName) {
                document.addEventListener(eventName, recordInteraction, { passive: true });
            });
        })();

        window.EasyChatUnreadNotifier = (function initEasyChatUnreadNotifier() {
            var baseTitle = document.title.replace(/^\(\d+\)\s+/, '');
            var unreadCount = <?php echo (int)$total_unread; ?>;
            var lastUnreadCount = unreadCount;
            var visibleIntervalMs = 15000;
            var hiddenIntervalMs = 60000;
            var titleBlinkIntervalMs = 1400;
            var pollTimer = null;
            var titleBlinkTimer = null;
            var titleBlinkState = false;
            var pending = false;
            var providerAlertKey = (function() {
                try { return String(window.sessionStorage.getItem('easychat-provider-alert-key') || ''); }
                catch (e) { return ''; }
            })();

            function normalizeCount(value) {
                var count = parseInt(value, 10);
                if (isNaN(count) || count < 0) {
                    return 0;
                }
                return count;
            }

            function formatTitle(count) {
                return count > 0 ? '(' + count + ') ' + baseTitle : baseTitle;
            }

            function setBaseTitle(nextTitle) {
                nextTitle = String(nextTitle || '').replace(/^\(\d+\)\s+/, '').trim();
                if (!nextTitle) {
                    return;
                }
                baseTitle = nextTitle;
                if (document.visibilityState === 'visible' || !titleBlinkTimer) {
                    document.title = formatTitle(unreadCount);
                }
            }

            function updateBadge(count) {
                var badges = easychatAll('#sidebar-unread-badge, #mobile-unread-badge, #offcanvas-unread-badge');
                if (!badges.length) {
                    return;
                }
                badges.forEach(function(badge) {
                    if (count > 0) {
                        badge.textContent = count;
                        badge.classList.remove('d-none');
                    } else {
                        badge.classList.add('d-none');
                    }
                });
            }

            function updateProviderAlert(alert) {
                alert = alert || {};
                var count = normalizeCount(alert.count);
                easychatAll('[data-provider-alert-badge]').forEach(function(badge) {
                    badge.textContent = count > 99 ? '99+' : count;
                    badge.classList.toggle('d-none', count === 0);
                });
                easychatAll('[data-provider-alert-link]').forEach(function(link) {
                    link.setAttribute('href', count > 0 && alert.route ? String(alert.route) : 'index.php?route=integration');
                });
                var key = String(alert.key || '');
                if (count > 0 && key && key !== providerAlertKey && window.EasyChatNotify) {
                    window.EasyChatNotify.warning(String(alert.detail || 'Одна из интеграций требует внимания.'), {
                        title: String(alert.title || 'Интеграция требует внимания'),
                        delay: 12000,
                        dedupeKey: 'provider-incident-' + key
                    });
                }
                providerAlertKey = key;
                try { window.sessionStorage.setItem('easychat-provider-alert-key', key); }
                catch (e) {}
            }

            function stopTitleAlert() {
                if (titleBlinkTimer) {
                    window.clearInterval(titleBlinkTimer);
                    titleBlinkTimer = null;
                }
                titleBlinkState = false;
            }

            function startTitleAlert(count) {
                if (document.visibilityState === 'visible' || titleBlinkTimer) {
                    return;
                }
                var alertTitle = count > 1 ? 'Новые сообщения' : 'Новое сообщение';
                titleBlinkTimer = window.setInterval(function() {
                    titleBlinkState = !titleBlinkState;
                    document.title = titleBlinkState ? alertTitle : formatTitle(unreadCount);
                }, titleBlinkIntervalMs);
            }

            function playUnreadSound() {
                if (document.visibilityState !== 'visible') {
                    return;
                }
                if (window.EasyChatSound) {
                    window.EasyChatSound.play('notification');
                }
            }

            function setUnread(count, options) {
                options = options || {};
                count = normalizeCount(count);

                var increased = count > lastUnreadCount;
                unreadCount = count;
                updateBadge(count);

                if (increased && options.prefetch !== false && window.EasyChatUnreadPrefetch) {
                    window.EasyChatUnreadPrefetch.warm(count);
                }

                if (count === 0) {
                    stopTitleAlert();
                    document.title = baseTitle;
                    lastUnreadCount = count;
                    return;
                }

                if (document.visibilityState === 'visible') {
                    stopTitleAlert();
                    document.title = formatTitle(count);
                    if (increased && options.playSound !== false) {
                        playUnreadSound();
                    }
                } else {
                    document.title = formatTitle(count);
                    if (increased) {
                        startTitleAlert(count);
                    }
                }

                lastUnreadCount = count;
            }

            function scheduleNextCheck() {
                if (pollTimer) {
                    window.clearTimeout(pollTimer);
                }
                pollTimer = window.setTimeout(checkUnread, document.visibilityState === 'visible' ? visibleIntervalMs : hiddenIntervalMs);
            }

            function checkUnread() {
                if (pending) {
                    scheduleNextCheck();
                    return;
                }
                if (window.EasyChatPolling && !window.EasyChatPolling.canPoll('unread', {
                    allowIdle: true,
                    allowHidden: document.visibilityState !== 'visible',
                    leaseMs: document.visibilityState === 'visible' ? 12000 : 55000
                })) {
                    scheduleNextCheck();
                    return;
                }
                pending = true;
                easychatJson('index.php?route=index/getUnreadCount')
                    .then(function(json) {
                        if (json && typeof json.unread !== 'undefined') {
                            setUnread(json.unread);
                            updateProviderAlert(json.provider_alert);
                        }
                    })
                    .catch(function() {})
                    .then(function() {
                        pending = false;
                        scheduleNextCheck();
                    });
            }

            document.addEventListener('visibilitychange', function() {
                if (document.visibilityState === 'visible') {
                    stopTitleAlert();
                    document.title = formatTitle(unreadCount);
                    checkUnread();
                } else {
                    scheduleNextCheck();
                }
            });

            setUnread(unreadCount, { playSound: false });
            scheduleNextCheck();

            return {
                setUnread: setUnread,
                checkNow: checkUnread,
                setBaseTitle: setBaseTitle
            };
        })();

        // Проксирование кликов для мобильных действий из Offcanvas
        document.addEventListener('click', function(e) {
            var trigger = e.target.closest('.mobile-webpush-trigger');
            if (!trigger) {
                return;
            }
            e.preventDefault();
            var toggle = document.getElementById('easychat-webpush-toggle');
            if (toggle) {
                toggle.click();
            }
        });

        document.addEventListener('click', function(e) {
            var trigger = e.target.closest('.mobile-mobile-connect-trigger');
            if (!trigger) {
                return;
            }
            e.preventDefault();
            if (window.EasyChatMobileConnect) {
                // Закрываем offcanvas перед открытием модального окна
                var offcanvasEl = document.getElementById('mobileSidebar');
                if (offcanvasEl && typeof bootstrap !== 'undefined' && bootstrap.Offcanvas) {
                    var instance = bootstrap.Offcanvas.getInstance(offcanvasEl);
                    if (instance) instance.hide();
                }
                window.EasyChatMobileConnect.open();
            } else {
                var toggle = document.getElementById('easychat-mobile-connect-toggle');
                if (toggle) {
                    toggle.click();
                }
            }
        });

        // Синхронизация состояния кнопок WebPush через MutationObserver
        var webpushTarget = document.getElementById('easychat-webpush-toggle');
        if (webpushTarget) {
            var webpushObserver = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'attributes') {
                        var isSubscribed = webpushTarget.classList.contains('text-success');
                        var isWarning = webpushTarget.classList.contains('text-warning');
                        var title = webpushTarget.title;
                        
                        easychatAll('.mobile-webpush-trigger').forEach(function(item) {
                            item.title = title;
                            item.classList.toggle('text-success', isSubscribed);
                            item.classList.toggle('text-warning', isWarning);
                            item.classList.toggle('text-muted-custom', !isSubscribed && !isWarning);
                            
                            var icon = item.querySelector('i');
                            if (icon) {
                                icon.className = isSubscribed ? 'fa fa-bell fa-lg' : 'fa fa-bell-o fa-lg';
                            }
                        });
                    }
                });
            });
            webpushObserver.observe(webpushTarget, {
                attributes: true,
                attributeFilter: ['class', 'title']
            });
            // Первоначальный вызов для установки корректного состояния
            var isSubscribed = webpushTarget.classList.contains('text-success');
            var isWarning = webpushTarget.classList.contains('text-warning');
            easychatAll('.mobile-webpush-trigger').forEach(function(item) {
                item.title = webpushTarget.title;
                item.classList.toggle('text-success', isSubscribed);
                item.classList.toggle('text-warning', isWarning);
                item.classList.toggle('text-muted-custom', !isSubscribed && !isWarning);
                var icon = item.querySelector('i');
                if (icon) {
                    icon.className = isSubscribed ? 'fa fa-bell fa-lg' : 'fa fa-bell-o fa-lg';
                }
            });
        }

        // Проверка наличия новой версии
        <?php if ($manager_role === 'admin') { ?>
        function easychatReleaseNotesUrl(version) {
            var match = String(version || '').trim().match(/^(\d+)\.(\d+)\.(\d+)/);
            if (!match) {
                return 'https://docs.easychat24.ru/docs/whats-new/';
            }
            return 'https://docs.easychat24.ru/docs/releases/' + match[1] + '-' + match[2] + '-' + match[3] + '/';
        }

        setTimeout(function() {
            easychatPost('index.php?route=index/checkUpdate', {
                    csrf_token: window.EasyChatCsrfToken || ''
                })
                .then(function(json) {
                    if (json && json.success && json.has_update) {
                        var releaseNotesUrl = String(json.release_notes_url || easychatReleaseNotesUrl(json.latest_version));
                        easychatAll('#sidebar-update-version, #mobile-sidebar-update-version').forEach(function(item) {
                            item.textContent = json.latest_version;
                        });
                        easychatAll('#sidebar-update-link, #mobile-sidebar-update-link').forEach(function(item) {
                            item.setAttribute('href', 'index.php?route=update');
                        });
                        easychatAll('#sidebar-update-notes-link, #mobile-sidebar-update-notes-link').forEach(function(item) {
                            item.setAttribute('href', releaseNotesUrl);
                        });
                        easychatAll('#sidebar-update-banner, #mobile-sidebar-update-banner').forEach(function(item) {
                            item.classList.remove('d-none');
                            item.classList.add('d-block');
                        });
                    }
                })
                .catch(function() {});
        }, 3000);
        <?php } ?>
    });
    </script>

    <!-- MOBILE APP CONNECT MODAL -->
    <div class="modal fade easychat-profile-modal" id="easychatOperatorProfileModal" tabindex="-1" aria-labelledby="easychatOperatorProfileTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" style="max-width: 590px;">
            <div class="modal-content">
                <div class="easychat-profile-hero">
                    <div class="easychat-profile-avatar" aria-hidden="true">
                        <img data-profile-avatar-image src="" alt="" hidden>
                        <span data-profile-avatar-initials>ОП</span>
                    </div>
                    <div>
                        <div class="d-flex align-items-start justify-content-between gap-3">
                            <div>
                                <h4 class="mb-1 fw-bold text-white" id="easychatOperatorProfileTitle" data-profile-name>Мой профиль</h4>
                                <div class="small text-white-50" data-profile-login></div>
                                <span class="easychat-profile-role"><i class="fa fa-shield" aria-hidden="true"></i><span data-profile-role>Оператор</span></span>
                            </div>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Закрыть"></button>
                        </div>
                    </div>
                </div>
                <div class="easychat-profile-body">
                    <h6 class="fw-bold mb-2">Фотография</h6>
                    <p class="small text-muted mb-3">Помогает клиентам и коллегам узнавать вас в диалоге.</p>
                    <div class="easychat-profile-photo-actions">
                        <label class="btn btn-outline-primary mb-0" for="easychatProfileAvatarInput">
                            <i class="fa fa-camera me-2" aria-hidden="true"></i>Выбрать фото
                        </label>
                        <input id="easychatProfileAvatarInput" data-profile-avatar-input class="visually-hidden" type="file" accept="image/jpeg,image/png,image/gif">
                        <button type="button" class="btn btn-outline-danger" data-profile-remove-avatar hidden>
                            <i class="fa fa-trash-o me-2" aria-hidden="true"></i>Удалить
                        </button>
                    </div>

                    <section class="easychat-profile-section">
                        <h6 class="fw-bold mb-2">Сменить пароль</h6>
                        <p class="small text-muted mb-3">Используйте длинную парольную фразу. После смены другие web- и Android-сессии завершатся.</p>
                        <form data-profile-password-form autocomplete="off">
                            <div class="easychat-profile-form-grid">
                                <div class="easychat-profile-field">
                                    <label class="form-label small fw-semibold" for="easychatCurrentPassword">Текущий пароль</label>
                                    <input class="form-control" id="easychatCurrentPassword" name="current_password" type="password" required autocomplete="current-password" maxlength="128">
                                    <button class="easychat-password-toggle" type="button" data-password-toggle="easychatCurrentPassword" aria-label="Показать текущий пароль" aria-pressed="false"><i class="fa fa-eye"></i></button>
                                </div>
                                <div class="easychat-profile-field">
                                    <label class="form-label small fw-semibold" for="easychatNewPassword">Новый пароль</label>
                                    <input class="form-control" id="easychatNewPassword" name="new_password" type="password" required autocomplete="new-password" minlength="15" maxlength="128">
                                    <button class="easychat-password-toggle" type="button" data-password-toggle="easychatNewPassword" aria-label="Показать новый пароль" aria-pressed="false"><i class="fa fa-eye"></i></button>
                                </div>
                                <div class="easychat-profile-field">
                                    <label class="form-label small fw-semibold" for="easychatConfirmPassword">Повторите новый пароль</label>
                                    <input class="form-control" id="easychatConfirmPassword" name="password_confirmation" type="password" required autocomplete="new-password" minlength="15" maxlength="128">
                                    <button class="easychat-password-toggle" type="button" data-password-toggle="easychatConfirmPassword" aria-label="Показать повтор пароля" aria-pressed="false"><i class="fa fa-eye"></i></button>
                                </div>
                                <button type="submit" class="btn easychat-profile-save fw-semibold" data-profile-save>
                                    <i class="fa fa-lock me-2" aria-hidden="true"></i>Сохранить новый пароль
                                </button>
                            </div>
                        </form>
                    </section>
                    <div class="easychat-profile-feedback text-muted" data-profile-feedback role="status" aria-live="polite"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade mobile-connect-modal" id="mobileConnectModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered mobile-connect-dialog">
            <div class="modal-content border-0 shadow-lg bg-white">
                <div style="height: 4px; background: linear-gradient(90deg, #6366f1, #a855f7);"></div>
                <div class="modal-header border-0 bg-light p-4">
                    <h5 class="modal-title fw-bold text-dark" style="font-family: 'Outfit', sans-serif;"><i class="fa fa-mobile me-2" style="color: #6366f1;"></i>Подключить приложение</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <div id="mobile-connect-status" class="alert alert-light border small mb-3">
                        Подготовим одноразовую ссылку для входа в Android-приложение.
                    </div>

                    <div id="mobile-connect-android-view">
                        <div class="row g-4 align-items-center">
                            <div class="col-sm-5 text-center">
                                <div class="mobile-connect-qr-frame border bg-white shadow-sm">
                                    <img id="mobile-connect-qr-img" src="" alt="QR Code">
                                </div>
                            </div>
                            <div class="col-sm-7">
                                <h6 class="fw-bold text-dark mb-2">Android</h6>
                                <ol class="mobile-connect-steps small text-muted">
                                    <li>Откройте EasyChat на телефоне или наведите камеру на QR.</li>
                                    <li>Подтвердите подключение к сайту <span id="mobile-connect-site-url" class="text-dark fw-semibold"></span>.</li>
                                    <li>После входа разрешите уведомления в Android, чтобы сообщения приходили в шторку.</li>
                                </ol>
                                <div class="d-flex flex-wrap gap-2 mt-3">
                                    <button type="button" id="mobile-connect-open-app" class="btn btn-sm btn-primary d-none"><i class="fa fa-mobile me-1"></i>Открыть приложение</button>
                                    <button type="button" id="mobile-connect-copy-link" class="btn btn-sm btn-outline-primary"><i class="fa fa-link me-1"></i>Скопировать ссылку</button>
                                    <a id="mobile-connect-rustore-link" href="https://www.rustore.ru/catalog/app/ru.liveopencart.easychat" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="fa fa-external-link me-1"></i>RuStore</a>
                                </div>
                                <div class="mobile-connect-copy-feedback small text-success mt-2" id="mobile-connect-copy-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div id="mobile-connect-ios-view" class="mt-4 p-3 rounded-3 border" style="background: #f8fafc;">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fa fa-apple me-2" style="color: #111827;"></i>
                            <h6 class="fw-bold mb-0 text-dark">У вас iPhone?</h6>
                        </div>
                        <p class="small text-muted mb-2">На iPhone уведомления работают через веб-приложение EasyChat на домашнем экране.</p>
                        <ol class="mobile-connect-steps small text-muted">
                            <li>Откройте эту панель в Safari.</li>
                            <li>Нажмите «Поделиться» и выберите «На экран Домой».</li>
                            <li>Откройте EasyChat с домашнего экрана и нажмите колокольчик, чтобы разрешить уведомления.</li>
                        </ol>
                        <button type="button" id="mobile-connect-ios-qr" class="btn btn-sm btn-outline-dark mt-2"><i class="fa fa-qrcode me-1"></i>Показать QR этой панели</button>
                        <div id="mobile-connect-ios-qr-wrap" class="text-center mt-3 d-none">
                            <img id="mobile-connect-ios-qr-img" src="" alt="QR Code iPhone" class="img-fluid border rounded-3 bg-white p-2" style="width: 180px; height: 180px;">
                        </div>
                    </div>

                    <div class="small text-muted mt-3"><i class="fa fa-clock-o me-1"></i>Ссылка действует 10 минут и только один раз.</div>
                    <button type="button" class="btn btn-light w-100 mt-3" data-bs-dismiss="modal" style="border-radius: 8px;">Закрыть</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="easychatPasskeyModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" style="max-width: 460px;">
            <div class="modal-content border-0 shadow-lg" style="border-radius: 16px; overflow: hidden; background: #ffffff;">
                <div style="height: 4px; background: linear-gradient(90deg, #6366f1, #a855f7);"></div>
                <div class="modal-header border-0 bg-light p-4">
                    <div>
                        <h5 class="modal-title fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;"><i class="fa fa-key me-2 text-primary"></i>Passkey для входа</h5>
                        <div id="easychat-passkey-modal-hint" class="small text-muted">Подтвердите вход способом, который поддерживает это устройство.</div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <div id="easychat-passkey-status" class="alert d-none mb-3" style="border-radius: 10px;"></div>
                    <div class="d-grid gap-2 mb-3">
                        <button type="button" id="easychat-passkey-register" class="btn btn-primary fw-semibold" style="border-radius: 10px; background: linear-gradient(135deg, #6366f1, #a855f7); border: none;">
                            <i class="fa fa-plus-circle me-2"></i>Привязать это устройство
                        </button>
                    </div>
                    <div class="small text-muted mb-3">После привязки пароль останется резервным способом входа. Passkey можно удалить в любой момент.</div>
                    <div id="easychat-passkey-list" class="list-group list-group-flush border rounded-3 overflow-hidden"></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- QR CODE MODAL FOR RUSTORE APP DOWNLOAD (SIDEBAR) -->
    <div class="modal fade" id="rustoreAppModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" style="max-width: 380px;">
            <div class="modal-content border-0 shadow-lg" style="border-radius: 16px; overflow: hidden; background: #ffffff;">
                <div style="height: 4px; background: linear-gradient(90deg, #0077FF, #0037C4);"></div>
                <div class="modal-header border-0 bg-light p-4">
                    <h5 class="modal-title fw-bold text-dark" style="font-family: 'Outfit', sans-serif;">
                        <svg width="20" height="20" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" class="me-2" style="vertical-align: middle;">
                            <!-- Левая плашка -->
                            <path d="m8.5735,14.7891l10.4885,2.5746c2.5091.6532,2.9967,2.2925,2.9583,4.2269l.0384,17.484c-.0384,2.0539-1.5578,2.9981-3.5346,2.4593l-10.4885-2.5361c-1.9084-.4575-2.4588-1.4268-2.5357-3.6121l.0768-17.3687c.1271-2.5862,1.3038-3.4815,2.9967-3.2278Z" fill="#0077FF"/>
                            <!-- Средняя плашка -->
                            <path d="m15.7665,16.5547l.1068-3.6485c-.1068-1.5531,1.1806-2.5879,2.6509-2.3056l10.9879,2.6514c2.0092.3604,2.6128,1.3819,2.6509,3.3431l.1921,18.3293c.005,1.6497-.5651,2.9715-2.4973,2.4977l-7.7991-1.6392" fill="#0059FC"/>
                            <!-- Правая плашка -->
                            <path d="m25.879,12.3753l-.0168-3.1965c.0168-2.4238,1.3456-3.1458,3.0351-2.7667l10.2195,2.4209c1.9732.5535,3.4479,1.5237,3.3809,3.8042v18.0219c0,1.1518-.8375,2.9942-3.7651,2.4593l-6.4088-1.171" fill="#0037C4"/>
                        </svg>Установка приложения
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4 text-center">
                    <p class="text-muted small mb-3">Сканируйте QR-код камерой вашего телефона, чтобы перейти к установке приложения EasyChat из RuStore:</p>
                    <div class="d-inline-block p-3 border rounded-4 bg-white shadow-sm mb-3">
                        <img src="index.php?route=index/qr&data=https%3A%2F%2Fwww.rustore.ru%2Fcatalog%2Fapp%2Fru.liveopencart.easychat" alt="QR Code RuStore" class="img-fluid" style="width: 220px; height: 220px; display: block; border-radius: 4px;">
                    </div>
                    <div class="mb-3">
                        <a href="https://www.rustore.ru/catalog/app/ru.liveopencart.easychat" target="_blank" class="btn btn-primary w-100" style="border-radius: 8px; background: #0077FF; border: none; font-family: 'Outfit', sans-serif; font-size: 14px; font-weight: 500;">
                            <i class="fa fa-external-link me-1.5"></i> Перейти в RuStore
                        </a>
                    </div>
                    <button type="button" class="btn btn-light w-100" data-bs-dismiss="modal" style="border-radius: 8px;">Закрыть</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
