<?php
$theme_color = isset($widget_color) ? $widget_color : '#6366f1';
$theme_foreground_color = isset($chat_on_accent_color) ? $chat_on_accent_color : (isset($widget_foreground_color) ? $widget_foreground_color : '#ffffff');
$ai_suggestions_can_use = !empty($ai_suggestions_can_use);
$copilot_ghost_enabled = !empty($copilot_ghost_enabled);
$outbound_draft_ai_available = !empty($outbound_draft_ai_available);
$scheduled_timezone_name = isset($scheduled_timezone) ? (string)$scheduled_timezone : 'UTC';
?>
<?php echo easychat_style_tag('css/views/index_outbound_assistant.css'); ?>
<?php echo easychat_style_tag('css/views/index_assignments.css'); ?>
<?php echo easychat_style_tag('css/views/index_copilot.css'); ?>
<svg class="easychat-status-icon-sprite" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">
    <symbol id="icon_status_read" fill="none" viewBox="0 0 24 24"><path fill="currentColor" fill-rule="evenodd" d="M18.089 5.589a.9.9 0 0 1 0 1.272L7.064 17.886a.9.9 0 0 1-1.273 0L1.883 13.98a.9.9 0 0 1 1.273-1.273l3.271 3.271L16.816 5.59a.9.9 0 0 1 1.273 0m5.459-.001a.9.9 0 0 1 0 1.273L12.523 17.887a.9.9 0 0 1-1.272 0l-.73-.73a.9.9 0 0 1 1.273-1.272l.093.092L22.276 5.59a.9.9 0 0 1 1.272 0" clip-rule="evenodd"></path></symbol>
    <symbol id="icon_status_delivered" fill="none" viewBox="0 0 24 24"><path fill="currentColor" fill-rule="evenodd" d="M18.09 5.589a.9.9 0 0 1 0 1.272L7.063 17.886a.9.9 0 0 1-1.273 0L1.884 13.98a.9.9 0 0 1 1.273-1.273l3.27 3.271L16.818 5.59a.9.9 0 0 1 1.272 0" clip-rule="evenodd"></path></symbol>
</svg>
<div class="row g-0 g-md-4 chat-row-layout">
    
    <!-- LEFT PANEL: ACTIVE CHAT LIST -->
    <div class="col-md-5 d-flex flex-column h-100 chat-list-panel">
        <div class="card border-0 flex-grow-1 d-flex flex-column overflow-hidden" style="background: #ffffff;">
            <!-- Panel Header & Search -->
            <div class="p-3 bg-white" style="border: 1px solid #e2e8f0;">
                <div class="d-flex align-items-center justify-content-between mb-3 easychat-chat-list-toolbar">
                    <div class="nav nav-pills easychat-queue-tabs" id="chat-tabs" aria-label="Очередь диалогов">
                        <button class="nav-link active" id="tab-unassigned" data-scope="unassigned" data-archived="0">
                            <span>Ничьи</span><span class="easychat-queue-count" data-queue-count="unassigned">0</span>
                        </button>
                        <button class="nav-link" id="tab-mine" data-scope="mine" data-archived="0">
                            <span>Мои</span><span class="easychat-queue-count" data-queue-count="mine">0</span>
                        </button>
                        <button class="nav-link" id="tab-all" data-scope="all" data-archived="0">
                            <span>Все</span><span class="easychat-queue-count" data-queue-count="all">0</span>
                        </button>
                        <button class="nav-link" id="tab-archive" data-scope="archive" data-archived="1">
                            <span>Архив</span><span class="easychat-queue-count" data-queue-count="archive">0</span>
                        </button>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <button type="button" id="btn-new-outbound-contact" class="btn btn-primary btn-sm d-flex align-items-center gap-1" style="border-radius: 8px; background: <?php echo $theme_color; ?> !important; border: none;">
                            <i class="fa fa-envelope-o easychat-new-dialog-icon" aria-hidden="true"></i> Новый
                        </button>
                        <div class="dropdown easychat-list-actions-menu">
                            <button type="button" id="btn-list-actions-menu" class="btn btn-light btn-sm easychat-list-actions-trigger" aria-haspopup="true" aria-expanded="false" title="Действия со списком" style="border-radius: 8px;">
                                <i class="fa fa-ellipsis-v"></i>
                            </button>
                            <div class="dropdown-menu dropdown-menu-end easychat-list-actions-dropdown" aria-labelledby="btn-list-actions-menu">
                                <button type="button" id="btn-mark-chats-read" class="dropdown-item easychat-chat-action-item" disabled>
                                    <i class="fa fa-check-circle-o me-2"></i><span>Отметить прочитанным</span>
                                </button>
                                <?php if (!empty($can_delete_chats)) { ?>
                                    <div class="dropdown-divider"></div>
                                    <button type="button" id="btn-delete-all-chats" class="dropdown-item text-danger easychat-chat-action-item">
                                        <i class="fa fa-trash-o me-2"></i>Удалить всё
                                    </button>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="input-group easychat-chat-search">
                    <label class="visually-hidden" for="chat-search">Поиск диалогов</label>
                    <span class="input-group-text easychat-chat-search__icon" aria-hidden="true"><i class="fa fa-search"></i></span>
                    <input type="search" id="chat-search" class="form-control easychat-chat-search__input" placeholder="Имя, телефон или тег…" autocomplete="off" enterkeyhint="search" aria-describedby="chat-search-status">
                    <button type="button" id="chat-search-clear" class="easychat-chat-search__clear" aria-label="Очистить поиск" title="Очистить поиск" hidden>
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <span id="chat-search-status" class="visually-hidden" role="status" aria-live="polite" aria-atomic="true"></span>
                <div id="outbound-phone-action" class="d-none mt-2"></div>
                <div id="chat-operator-filter-wrap" class="easychat-operator-filter d-none mt-2">
                    <label for="chat-operator-filter"><i class="fa fa-user-circle-o" aria-hidden="true"></i><span>Оператор</span></label>
                    <select id="chat-operator-filter" class="form-select form-select-sm" aria-label="Фильтр по оператору">
                        <option value="0">Все операторы</option>
                    </select>
                </div>
                <div id="chat-source-filters" class="chat-source-filters mt-3" aria-label="Фильтр диалогов по источнику"></div>
                <div id="chat-marketplace-list-mode" class="chat-marketplace-list-mode mt-2 d-none"></div>
            </div>

            <div id="mobile-open-chat-resume" class="easychat-mobile-open-chat-resume d-none" aria-live="polite">
                <button type="button" id="btn-resume-open-chat" class="easychat-mobile-open-chat-resume__button">
                    <span class="easychat-mobile-open-chat-resume__icon" aria-hidden="true">
                        <i class="fa fa-commenting-o"></i>
                    </span>
                    <span class="easychat-mobile-open-chat-resume__copy">
                        <small>Открытый диалог</small>
                        <strong id="mobile-open-chat-name">Клиент</strong>
                        <span id="mobile-open-chat-source">EasyChat</span>
                    </span>
                    <span class="easychat-mobile-open-chat-resume__action">
                        Продолжить
                        <i class="fa fa-chevron-right" aria-hidden="true"></i>
                    </span>
                </button>
            </div>
            
            <!-- Scrollable Chat List -->
            <div id="chat-list-container" class="flex-grow-1 overflow-auto" style="background: #fafafa;">
                <div class="text-center py-5 text-muted" id="chat-list-loader">
                    <i class="fa fa-circle-o-notch fa-spin fa-2x mb-2 text-primary"></i>
                    <p class="small">Загрузка диалогов...</p>
                </div>
                <div id="chats-wrapper" class="d-none"></div>
                <div id="chat-pagination" class="easychat-pagination pb-2"></div>
            </div>
        </div>
    </div>
    
    <!-- RIGHT PANEL: CHAT CONVERSATION WINDOW -->
    <div class="easychat-chat-splitter d-none d-md-flex" role="separator" aria-orientation="vertical" aria-label="Изменить ширину списка диалогов" tabindex="0"></div>

    <div class="col-md-7 d-none d-md-flex flex-column h-100 chat-conversation-panel">
        <div class="card flex-grow-1 d-flex flex-column overflow-hidden" style="background: #ffffff;">
            
            <!-- Fallback: No chat selected -->
            <div id="chat-placeholder" class="d-flex flex-column justify-content-center align-items-center flex-grow-1 py-5 text-center bg-white">
                <div class="d-flex align-items-center justify-content-center bg-light rounded-circle mb-3 shadow-sm" style="width: 80px; height: 80px; background: <?php echo $theme_color; ?>15 !important; border: 1px solid <?php echo $theme_color; ?>30;">
                    <i class="fa fa-commenting text-primary fa-2x" style="color: <?php echo $theme_color; ?> !important;"></i>
                </div>
                <h5 class="fw-bold text-dark" style="font-family: 'Outfit', sans-serif;">Диалог не выбран</h5>
                <p class="text-muted small px-4" style="max-width: 320px;">Выберите чат из списка слева, чтобы начать общение с клиентом в реальном времени.</p>
            </div>
            
            <!-- Main Chat Workspace -->
            <div id="chat-workspace" class="d-none flex-grow-1 d-flex flex-column h-100">
                <!-- Chat Workspace Header -->
                <div class="p-3 bg-white d-flex flex-wrap align-items-center justify-content-between gap-3 easychat-chat-header" style="border-bottom: 1px solid #f1f5f9;">
                    <div class="d-flex align-items-center easychat-active-customer">
                        <button type="button" id="btn-back-to-list" class="btn btn-link text-muted p-0 me-3 d-md-none" style="font-size: 18px; line-height: 1;" title="Назад к диалогам">
                            <i class="fa fa-arrow-left fa-lg"></i>
                        </button>
                        <div id="active-customer-avatar" class="easychat-avatar-circle rounded-circle me-3 d-flex align-items-center justify-content-center bg-primary text-white fw-bold shadow-sm flex-shrink-0" style="width: 46px; height: 46px; font-size: 16px; background: <?php echo $theme_color; ?> !important;">
                            Г
                        </div>
                        <div class="easychat-active-customer-info">
                            <div class="d-flex align-items-center gap-2 easychat-customer-name-row">
                                <h6 id="active-customer-name" class="fw-bold mb-0 text-dark">Гость</h6>
                                <button type="button" id="btn-edit-customer" class="btn btn-link text-muted p-0 border-0" style="font-size: 13px; line-height: 1; margin-top: 1px;" title="Редактировать профиль клиента">
                                    <i class="fa fa-pencil"></i>
                                </button>
                            </div>
                            <div id="active-customer-channel" class="easychat-active-customer-channel">
                                <span class="badge border easychat-source-badge easychat-source-badge-widget easychat-active-source-badge" title="Источник: Сайт" style="background:#f8f9fa;color:#6c757d;border-color:#dee2e6 !important;font-size:10px;">Сайт</span>
                            </div>
                            <div id="active-chat-list-context" class="easychat-active-list-context d-none" role="status" aria-live="polite">
                                <i class="fa fa-filter" aria-hidden="true"></i>
                                <span>Диалог открыт вне текущего списка</span>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 align-items-center easychat-chat-actions">
                        <button type="button" id="btn-open-customer-panel" class="btn-chat-action btn-customer-panel-action" title="Карточка клиента">
                            <i class="fa fa-id-card-o me-2"></i> Клиент
                        </button>
                        <button type="button" id="btn-open-avito-context" class="btn-chat-action btn-avito-context-action d-none" title="Информация о товаре">
                            <i class="fa fa-shopping-bag me-2"></i> О товаре
                        </button>
                        <span id="active-customer-confirm-wrapper"></span>
                        <div class="dropdown easychat-chat-actions-menu">
                            <button type="button" id="btn-chat-actions-menu" class="btn-chat-action btn-chat-more-action" aria-haspopup="true" aria-expanded="false" aria-label="Действия диалога" title="Действия диалога">
                                <i class="fa fa-ellipsis-v me-2"></i><span>Действия</span>
                            </button>
                            <div class="dropdown-menu dropdown-menu-end easychat-chat-actions-dropdown" aria-labelledby="btn-chat-actions-menu">
                                <button type="button" id="btn-archive-chat" class="dropdown-item easychat-chat-action-item btn-archive-unarchived">
                                    <i class="fa fa-archive"></i><span id="archive-btn-text">В архив</span>
                                </button>
                                <button type="button" id="btn-block-chat" class="dropdown-item easychat-chat-action-item btn-block-unblocked" data-blocked="0">
                                    <i class="fa fa-ban"></i><span id="block-btn-text">Заблокировать</span>
                                </button>
                                <?php if (isset($can_delete_chats) && $can_delete_chats) { ?>
                                    <div class="dropdown-divider"></div>
                                    <button type="button" id="btn-delete-chat" class="dropdown-item easychat-chat-action-item btn-delete-chat-action">
                                        <i class="fa fa-trash-o"></i><span>Удалить диалог</span>
                                    </button>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Chat Messages Scroll Area Wrapper -->
                <div class="flex-grow-1 position-relative overflow-hidden d-flex flex-column">
                    <div id="avito-context-sticky" class="easychat-avito-context-sticky d-none"></div>
                    <div id="site-context-sticky" class="easychat-site-context-sticky d-none"></div>
                    <div id="chat-messages-container" class="flex-grow-1 overflow-auto p-4" style="background: #f8fafc;">
                        <div id="messages-wrapper"></div>
                        <div id="scheduled-messages-tail"></div>
                    </div>
                    
                    <!-- Кнопка прокрутки вниз -->
                    <button type="button" id="btn-scroll-bottom" class="btn btn-white shadow border rounded-circle d-flex align-items-center justify-content-center" style="position: absolute; bottom: 20px; right: 25px; width: 38px; height: 38px; z-index: 99; background: rgba(255,255,255,0.9); backdrop-filter: blur(4px); border-color: rgba(0,0,0,0.08) !important; transition: opacity 0.3s ease, transform 0.3s ease; transform: scale(0.8); opacity: 0; pointer-events: none; outline: none;">
                        <i class="fa fa-chevron-down text-muted" style="font-size: 14px;"></i>
                    </button>

                    <!-- Плашка "Новое сообщение" -->
                    <button type="button" id="btn-new-messages" class="btn btn-primary shadow d-none align-items-center gap-2" style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%) scale(0.8); z-index: 99; border-radius: 20px; font-size: 12px; font-weight: 600; padding: 8px 16px; background: <?php echo $theme_color; ?> !important; border: none; transition: opacity 0.3s ease, transform 0.3s ease; opacity: 0; box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important; outline: none;">
                        <i class="fa fa-chevron-down text-white" style="font-size: 11px; margin-top: 1px;"></i> Новое сообщение
                    </button>
                </div>
                


                <?php if ($ai_suggestions_can_use) { ?>
                    <div id="ai-suggest-nudge" class="d-none px-3 py-2 border-top d-flex align-items-center justify-content-between gap-2" style="background: #f8f7ff; border-color: #ede9fe !important;">
                        <div class="small fw-semibold" style="color: #4c1d95;">
                            <i class="fa fa-magic me-1"></i>AI может предложить ответ
                        </div>
                        <button type="button" class="btn btn-sm btn-primary px-3 py-1.5" id="btn-ai-suggest-nudge" style="border-radius: 8px; font-size: 12px; background: <?php echo $theme_color; ?> !important; border: none;">
                            Предложить
                        </button>
                    </div>
                    <div id="ai-suggest-panel" class="d-none border-top px-3 py-3" style="background: #ffffff;">
                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2">
                            <div class="fw-bold text-dark small"><i class="fa fa-magic text-primary me-1"></i>AI-подсказки</div>
                            <div class="d-flex align-items-center gap-2">
                                <select id="ai-suggest-skill" class="form-select form-select-sm" style="width: 150px; border-radius: 8px; font-size: 12px;">
                                    <option value="support">Поддержка</option>
                                    <option value="sales">Продажи</option>
                                    <option value="clarify">Уточнить</option>
                                </select>
                                <button type="button" id="btn-ai-suggest-refresh" class="btn btn-sm btn-light border" style="border-radius: 8px; font-size: 12px;" title="Сгенерировать заново">
                                    <i class="fa fa-refresh"></i>
                                </button>
                                <button type="button" id="btn-ai-suggest-close" class="btn btn-sm btn-light border" style="border-radius: 8px; font-size: 12px;" title="Скрыть">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>
                        </div>
                        <div id="ai-suggest-status" class="small text-muted mb-2 d-none"></div>
                        <div id="ai-suggest-list" class="d-flex flex-column gap-2"></div>
                    </div>
                <?php } ?>
                
                <!-- Chat Workspace Footer: Textarea & Send -->
                <div id="easychat-readonly-reply-panel" class="easychat-readonly-reply-panel d-none" role="status" aria-live="polite">
                    <span class="easychat-readonly-reply-icon"><i class="fa fa-eye"></i></span>
                    <span class="easychat-readonly-reply-copy">
                        <strong>Публичный канал MAX</strong>
                        <small>EasyChat получает сообщения из этого канала, но ответить в него нельзя.</small>
                    </span>
                </div>
                <section id="easychat-marketplace-action-panel" class="easychat-marketplace-action-panel d-none" aria-labelledby="easychat-marketplace-action-title">
                    <div class="easychat-marketplace-action-head">
                        <span class="easychat-marketplace-action-icon"><i class="fa fa-check-square-o"></i></span>
                        <span class="easychat-marketplace-action-copy">
                            <strong id="easychat-marketplace-action-title">Действие маркетплейса</strong>
                            <small id="easychat-marketplace-action-message">Проверьте ответ перед публикацией.</small>
                        </span>
                    </div>
                    <textarea id="easychat-marketplace-action-text" class="form-control d-none" rows="2" maxlength="5000" placeholder="Введите проверенный ответ покупателю"></textarea>
                    <div id="easychat-marketplace-action-buttons" class="easychat-marketplace-action-buttons"></div>
                    <div id="easychat-marketplace-action-status" class="easychat-marketplace-action-status d-none" role="status" aria-live="polite"></div>
                </section>
                <div class="p-3 bg-white easychat-composer" style="border-top: 1px solid #e2e8f0;">
                    <div id="easychat-next-conversation" class="easychat-next-conversation" hidden>
                        <button type="button" id="btn-next-conversation" class="easychat-next-conversation__button" aria-describedby="easychat-next-conversation-wait">
                            <span class="easychat-next-conversation__icon" aria-hidden="true"><i class="fa fa-arrow-right"></i></span>
                            <span class="easychat-next-conversation__copy">
                                <small id="easychat-next-conversation-kicker">Следующий</small>
                                <strong id="easychat-next-conversation-name">Клиент</strong>
                            </span>
                            <span id="easychat-next-conversation-wait" class="easychat-next-conversation__wait"></span>
                            <i class="fa fa-chevron-right easychat-next-conversation__chevron" aria-hidden="true"></i>
                        </button>
                    </div>
                    <div id="easychat-next-conversation-status" class="visually-hidden" role="status" aria-live="polite"></div>
                    <div id="outbound-delivery-status" class="d-none mb-2 px-3 py-2 small fw-semibold" style="border-radius: 8px; background: #fff7ed; color: #9a3412; border: 1px solid #fed7aa;"></div>
                    <form id="send-msg-form" autocomplete="off">
                        <input type="hidden" name="chat_id" id="active-chat-id" value="0">
                        <input type="file" id="operator-attachment-input" class="d-none" multiple accept=".jpg,.jpeg,.png,.gif,.bmp,.webp,.pdf,.doc,.docx,.odt,.ods,.odp,image/jpeg,image/png,image/gif,image/bmp,image/webp,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation">
                        <div id="operator-attachment-tray" class="easychat-attachment-tray d-none" aria-live="polite" aria-label="Выбранные вложения"></div>
                        <div id="operator-attachment-status" class="easychat-attachment-status visually-hidden" role="status" aria-live="polite" aria-atomic="true"></div>
                        <span id="operator-attachment-paste-hint" class="visually-hidden">Изображение или файл можно вставить из буфера обмена сочетанием Ctrl+V или Command+V.</span>
                        <div class="d-flex flex-column align-items-stretch gap-2">
                            <!-- Input Block: input field and send button (Row 1) -->
                            <div class="d-flex align-items-end flex-grow-1 gap-2 order-1 easychat-composer-input-row">
                                <button type="button" id="btn-mobile-keyboard" class="easychat-mobile-keyboard-toggle" title="Открыть клавиатуру" aria-label="Открыть клавиатуру" hidden>
                                    <i class="fa fa-keyboard-o" aria-hidden="true"></i>
                                </button>
                                <div class="easychat-copilot-composer-field flex-grow-1">
                                    <div id="easychat-copilot-ghost" class="easychat-copilot-ghost" aria-hidden="true"><span></span><mark></mark></div>
                                    <textarea name="text" id="msg-input" class="form-control border-0 flex-grow-1" placeholder="Ваше сообщение" rows="1" aria-describedby="operator-attachment-paste-hint easychat-copilot-status" aria-keyshortcuts="Control+V Meta+V Control+K Meta+K Tab Escape" style="border-radius: 8px; font-size: 14px; resize: none; min-height: 38px; max-height: 120px; padding: 8px 12px; line-height: 1.4;"></textarea>
                                    <?php if ($ai_suggestions_can_use) { ?>
                                        <div id="easychat-copilot-palette" class="easychat-copilot-palette" role="dialog" aria-label="Команды Copilot" hidden>
                                            <div class="easychat-copilot-palette__head">
                                                <span><i class="fa fa-magic" aria-hidden="true"></i>EasyChat Copilot</span>
                                                <kbd>Esc</kbd>
                                            </div>
                                            <div id="easychat-copilot-command-list" class="easychat-copilot-command-list" role="listbox" aria-label="Команды обработки текста"></div>
                                            <div class="easychat-copilot-palette__hint">Введите <kbd>/</kbd> или нажмите <kbd>Ctrl K</kbd></div>
                                        </div>
                                    <?php } ?>
                                </div>
                                <span class="easychat-composer-delivery-actions">
                                    <button type="submit" id="btn-send" class="btn btn-primary d-flex align-items-center justify-content-center flex-shrink-0" style="border-radius: 8px; background: <?php echo $theme_color; ?> !important; border: none; width: 38px; height: 38px;" title="Отправить сообщение" aria-label="Отправить сообщение">
                                        <i class="fa fa-paper-plane text-white"></i>
                                    </button>
                                    <button type="button" id="btn-schedule-message" class="btn easychat-schedule-trigger d-flex align-items-center justify-content-center flex-shrink-0" style="border-radius: 8px; width: 38px; height: 38px;" title="Отложить отправку" aria-label="Отложить отправку" aria-haspopup="dialog" aria-controls="scheduled-message-popover" aria-expanded="false" disabled>
                                        <i class="fa fa-clock-o" aria-hidden="true"></i>
                                    </button>
                                </span>
                            </div>
                            
                            <!-- Actions Block: attachment, emoji and AI buttons (Row 2, always below) -->
                            <div class="d-flex align-items-center gap-2 order-2 flex-shrink-0">
                                <button type="button" id="btn-attach-file" class="btn btn-light d-flex align-items-center justify-content-center" style="border-radius: 8px; width: 38px; height: 38px;" title="Прикрепить файл" aria-label="Прикрепить файл">
                                    <i class="fa fa-paperclip text-muted"></i>
                                </button>
                                <button type="button" id="btn-emoji" class="btn btn-light d-flex align-items-center justify-content-center" style="border-radius: 8px; width: 38px; height: 38px;" title="Добавить emoji" aria-label="Добавить emoji">
                                    <i class="fa fa-smile-o text-muted"></i>
                                </button>
                                <?php if (!empty($quick_replies)) { ?>
                                    <button type="button" id="btn-quick-replies" class="btn btn-light d-flex align-items-center justify-content-center" style="border-radius: 8px; width: 38px; height: 38px;" title="Быстрые ответы" aria-label="Быстрые ответы" data-bs-toggle="modal" data-bs-target="#modal-quick-replies">
                                        <i class="fa fa-bolt text-muted"></i>
                                    </button>
                                <?php } ?>
                                <?php if ($ai_suggestions_can_use) { ?>
                                    <button type="button" id="btn-ai-suggest" class="btn btn-light d-flex align-items-center justify-content-center" style="border-radius: 8px; width: 38px; height: 38px;" title="AI-подсказки ответов" aria-label="AI-подсказки ответов">
                                        <i class="fa fa-magic text-muted"></i>
                                    </button>
                                    <button type="button" id="btn-copilot-commands" class="btn btn-light d-flex align-items-center justify-content-center easychat-copilot-trigger" title="Команды Copilot (Ctrl+K)" aria-label="Открыть команды Copilot" aria-haspopup="dialog" aria-controls="easychat-copilot-palette" aria-expanded="false">
                                        <i class="fa fa-terminal text-muted" aria-hidden="true"></i>
                                    </button>
                                <?php } ?>
                            </div>
                        </div>
                        <div id="mobile-emoji-panel" class="easychat-mobile-emoji-panel" hidden></div>
                        <div id="easychat-draft-status" class="easychat-draft-status" role="status" aria-live="polite" hidden>
                            <i class="fa fa-check-circle" aria-hidden="true"></i>
                            <span></span>
                            <button type="button" id="easychat-draft-conflict-open" class="easychat-draft-conflict-open" hidden>Сравнить версии</button>
                        </div>
                        <?php if ($ai_suggestions_can_use) { ?>
                            <div id="easychat-copilot-status" class="easychat-copilot-status" role="status" aria-live="polite" aria-atomic="true" hidden>
                                <span></span>
                                <button type="button" id="easychat-copilot-undo" hidden>Вернуть</button>
                            </div>
                        <?php } ?>
                    </form>
                </div>
            </div>
            
        </div>
    </div>

    <div class="easychat-customer-splitter easychat-customer-desktop-only d-none" role="separator" aria-orientation="vertical" aria-label="Изменить ширину карточки клиента" tabindex="0"></div>

    <aside class="customer-insight-panel easychat-customer-desktop-only d-none flex-column h-100">
        <div class="card border-0 flex-grow-1 d-flex flex-column overflow-hidden bg-white">
            <div id="customer-panel-desktop-body" class="easychat-customer-panel-body"></div>
        </div>
    </aside>
</div>

<div class="modal fade" id="modal-operator-draft-conflict" tabindex="-1" aria-labelledby="operator-draft-conflict-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg easychat-draft-conflict-modal">
            <div class="modal-header border-0 pb-0">
                <div>
                    <span class="easychat-draft-conflict-kicker">Черновик с другого устройства</span>
                    <h5 class="modal-title" id="operator-draft-conflict-title">Какую версию продолжить?</h5>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                <div class="easychat-draft-compare-grid">
                    <section aria-labelledby="operator-draft-local-label">
                        <strong id="operator-draft-local-label">На этом устройстве</strong>
                        <p id="operator-draft-local-text"></p>
                    </section>
                    <section aria-labelledby="operator-draft-remote-label">
                        <strong id="operator-draft-remote-label">Сохранено последним</strong>
                        <p id="operator-draft-remote-text"></p>
                    </section>
                </div>
                <p class="easychat-draft-conflict-help">Ни одна версия не потеряется, пока вы не выберете.</p>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" id="operator-draft-use-remote" class="btn btn-light">Продолжить сохранённую</button>
                <button type="button" id="operator-draft-keep-local" class="btn btn-primary easychat-admin-primary-action">Оставить мою</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modal-marketplace-action-confirm" tabindex="-1" aria-labelledby="modal-marketplace-action-confirm-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg easychat-marketplace-confirm-modal">
            <div class="modal-header border-0">
                <h5 class="modal-title" id="modal-marketplace-action-confirm-title">Подтвердите действие</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body pt-0">
                <p id="modal-marketplace-action-confirm-copy" class="mb-0 text-muted"></p>
                <details id="marketplace-return-options" class="easychat-marketplace-return-options d-none mt-3">
                    <summary>Дополнительные условия Ozon</summary>
                    <div class="easychat-marketplace-return-options-body">
                        <label class="form-label" for="marketplace-return-rejection-reason">Причина отклонения</label>
                        <select id="marketplace-return-rejection-reason" class="form-select" autocomplete="off">
                            <option value="">Не требуется для этого действия</option>
                        </select>
                        <small id="marketplace-return-rejection-hint" class="text-muted d-block mt-1"></small>
                        <div class="row g-2 mt-1">
                            <div class="col-sm-6">
                                <label class="form-label" for="marketplace-return-compensation">Компенсация, ₽</label>
                                <input id="marketplace-return-compensation" class="form-control" type="number" min="0" max="100000000" step="0.01" inputmode="decimal" autocomplete="off" placeholder="Не требуется">
                            </div>
                            <div class="col-sm-6">
                                <label class="form-label" for="marketplace-return-back-way">Обратная доставка, ₽</label>
                                <input id="marketplace-return-back-way" class="form-control" type="number" min="0" max="100000000" step="0.01" inputmode="decimal" autocomplete="off" placeholder="Не требуется">
                            </div>
                        </div>
                    </div>
                </details>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Отмена</button>
                <button type="button" id="btn-marketplace-action-confirm" class="btn btn-primary">
                    <i class="fa fa-check me-1"></i> Подтвердить
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal: New outbound contact -->
<div class="modal fade" id="modal-outbound-contact" tabindex="-1" aria-labelledby="modal-outbound-contact-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 14px; overflow: hidden;">
            <div class="modal-header border-0 bg-white px-4 pt-4 pb-2">
                <h5 class="modal-title fw-bold text-dark" id="modal-outbound-contact-title">Новый диалог</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body px-4 pb-4">
                <div id="outbound-contact-alert" class="alert alert-danger d-none small" role="alert"></div>
                <form id="outbound-contact-form" autocomplete="off">
                    <div class="d-flex gap-2 mb-3" role="group" aria-label="Канал">
                        <input type="radio" class="btn-check" name="channel" id="outbound-channel-sms" value="sms" checked>
                        <label class="btn btn-outline-primary flex-fill" for="outbound-channel-sms" style="border-radius: 8px;">SMS</label>
                        <?php if (!empty($ozon_outbound_accounts)) { ?>
                            <input type="radio" class="btn-check" name="channel" id="outbound-channel-ozon" value="ozon">
                            <label class="btn btn-outline-primary flex-fill" for="outbound-channel-ozon" style="border-radius: 8px;">Ozon</label>
                        <?php } ?>
                        <?php if (!empty($yandex_market_outbound_accounts)) { ?>
                            <input type="radio" class="btn-check" name="channel" id="outbound-channel-yandex-market" value="yandex_market">
                            <label class="btn btn-outline-primary flex-fill easychat-outbound-yandex-market" for="outbound-channel-yandex-market" style="border-radius: 8px;">
                                <img src="assets/marketplace/yandex-market.svg" width="82" height="12" alt="Яндекс Маркет">
                            </label>
                        <?php } ?>
                    </div>
                    <div data-outbound-fields="phone">
                        <div class="mb-3">
                            <label class="form-label small fw-semibold text-muted" for="outbound-phone">Телефон клиента</label>
                            <input type="tel" id="outbound-phone" name="phone" class="form-control" autocomplete="tel" placeholder="+79991234567" style="border-radius: 8px;">
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-semibold text-muted" for="outbound-customer-name">Имя клиента</label>
                            <input type="text" id="outbound-customer-name" name="customer_name" class="form-control" autocomplete="off" placeholder="Можно оставить пустым" style="border-radius: 8px;">
                        </div>
                    </div>
                    <div data-outbound-fields="ozon" class="d-none">
                        <div class="mb-3">
                            <label class="form-label small fw-semibold text-muted" for="outbound-ozon-account">Кабинет Ozon</label>
                            <select id="outbound-ozon-account" name="ozon_channel_id" class="form-select" style="border-radius: 8px;">
                                <?php foreach (($ozon_outbound_accounts ?? []) as $ozon_account) { ?>
                                    <option value="<?php echo (int)($ozon_account['channel_id'] ?? 0); ?>">
                                        <?php echo htmlspecialchars((string)($ozon_account['title'] ?? 'Ozon'), ENT_QUOTES, 'UTF-8'); ?> · ID <?php echo htmlspecialchars((string)($ozon_account['external_account_id'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>
                                    </option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-semibold text-muted" for="outbound-ozon-posting">Номер отправления</label>
                            <input type="text" id="outbound-ozon-posting" name="posting_number" class="form-control" autocomplete="off" spellcheck="false" placeholder="Например, 12345678-0001-1" style="border-radius: 8px;">
                            <div class="form-text">Ozon разрешает начать чат только по отправлению из этого кабинета.</div>
                        </div>
                    </div>
                    <div data-outbound-fields="yandex_market" class="d-none">
                        <div class="mb-3">
                            <label class="form-label small fw-semibold text-muted" for="outbound-yandex-account">Кабинет Яндекс Маркета</label>
                            <select id="outbound-yandex-account" name="yandex_market_channel_id" class="form-select" style="border-radius: 8px;">
                                <?php foreach (($yandex_market_outbound_accounts ?? []) as $yandex_account) { ?>
                                    <option value="<?php echo (int)($yandex_account['channel_id'] ?? 0); ?>">
                                        <?php echo htmlspecialchars((string)($yandex_account['title'] ?? 'Яндекс Маркет'), ENT_QUOTES, 'UTF-8'); ?> · Business ID <?php echo htmlspecialchars((string)($yandex_account['external_account_id'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>
                                    </option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-sm-5">
                                <label class="form-label small fw-semibold text-muted" for="outbound-yandex-context-type">Контекст</label>
                                <select id="outbound-yandex-context-type" class="form-select" style="border-radius: 8px;">
                                    <option value="ORDER">Заказ</option>
                                    <option value="RETURN">Возврат</option>
                                </select>
                            </div>
                            <div class="col-sm-7">
                                <label class="form-label small fw-semibold text-muted" for="outbound-yandex-context-id">ID заказа или возврата</label>
                                <input type="text" inputmode="numeric" pattern="[0-9]*" id="outbound-yandex-context-id" class="form-control" autocomplete="off" spellcheck="false" placeholder="Например, 123456789" style="border-radius: 8px;">
                            </div>
                        </div>
                        <div class="form-text mb-3">Маркет разрешает начать чат только по заказу или возврату этого кабинета.</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-semibold text-muted" for="outbound-text">Сообщение</label>
                        <textarea id="outbound-text" name="text" class="form-control" rows="4" maxlength="4000" placeholder="Введите сообщение..." style="border-radius: 8px;"></textarea>
                        <div id="outbound-sms-metrics" class="form-text d-none" aria-live="polite"></div>
                    </div>
                    <section id="outbound-delivery-mode" class="easychat-delivery-mode mb-3" aria-labelledby="outbound-delivery-mode-title">
                        <div class="easychat-delivery-mode__head">
                            <span class="easychat-delivery-mode__icon"><i class="fa fa-clock-o" aria-hidden="true"></i></span>
                            <span>
                                <strong id="outbound-delivery-mode-title">Когда отправить</strong>
                                <small>Можно отправить сейчас или выбрать точное время.</small>
                            </span>
                        </div>
                        <div class="easychat-delivery-mode__switch" role="radiogroup" aria-label="Время отправки">
                            <input type="radio" class="btn-check" name="delivery_mode" id="outbound-delivery-now" value="now" checked>
                            <label class="btn" for="outbound-delivery-now"><i class="fa fa-paper-plane me-1"></i>Сейчас</label>
                            <input type="radio" class="btn-check" name="delivery_mode" id="outbound-delivery-scheduled" value="scheduled">
                            <label class="btn" for="outbound-delivery-scheduled"><i class="fa fa-clock-o me-1"></i>Позже</label>
                        </div>
                        <div id="outbound-schedule-fields" class="easychat-delivery-mode__fields d-none">
                            <label class="form-label small fw-semibold" for="outbound-scheduled-at">Дата и время</label>
                            <input type="datetime-local" id="outbound-scheduled-at" class="form-control" step="60">
                            <div class="form-text"><i class="fa fa-globe me-1"></i>Часовой пояс EasyChat: <?php echo htmlspecialchars($scheduled_timezone_name, ENT_QUOTES, 'UTF-8'); ?></div>
                        </div>
                    </section>
                    <section class="outbound-draft-assistant mb-3" aria-labelledby="outbound-draft-assistant-title">
                        <div class="outbound-draft-assistant__head">
                            <span class="outbound-draft-assistant__icon" aria-hidden="true"><i class="fa fa-magic"></i></span>
                            <span>
                                <strong id="outbound-draft-assistant-title">Помощник текста</strong>
                                <small><?php echo $outbound_draft_ai_available ? 'Меняет только черновик. Отправку подтверждаете вы.' : 'Доступен после настройки AI-ключа.'; ?></small>
                            </span>
                        </div>
                        <?php if ($outbound_draft_ai_available) { ?>
                            <div class="outbound-draft-assistant__controls">
                                <label class="outbound-draft-assistant__action" for="outbound-draft-mode">
                                    <span>Что сделать с текстом</span>
                                    <select id="outbound-draft-mode" class="form-select form-select-sm" autocomplete="off">
                                        <option value="proofread" selected>Исправить ошибки</option>
                                        <option value="improve_current">Улучшить, сохранив стиль</option>
                                        <option value="improve_friendly">Сделать дружелюбнее</option>
                                        <option value="improve_business">Сделать деловее</option>
                                        <option value="improve_caring">Добавить заботы</option>
                                        <option value="improve_concise">Сделать короче</option>
                                    </select>
                                </label>
                                <button type="button" id="btn-outbound-draft-apply" class="btn btn-light border outbound-draft-assistant__apply" aria-describedby="outbound-draft-assistant-title">
                                    <i class="fa fa-magic" aria-hidden="true"></i><span>Применить</span>
                                </button>
                            </div>
                            <div id="outbound-draft-status" class="outbound-draft-assistant__status d-none" role="status" aria-live="polite">
                                <span></span>
                                <button type="button" id="btn-outbound-draft-undo" class="btn btn-link btn-sm d-none">Вернуть</button>
                            </div>
                            <div id="outbound-draft-diff" class="outbound-draft-assistant__diff d-none" aria-label="Изменённые фрагменты текста">
                                <span class="outbound-draft-assistant__diff-label">Что изменилось</span>
                                <div class="outbound-draft-assistant__diff-text"></div>
                            </div>
                        <?php } ?>
                    </section>
                    <div class="small text-muted mb-3" data-outbound-hint="phone">
                        <i class="fa fa-shield me-1"></i>Пишите только если клиент ожидает ответ или сам оставил номер.
                    </div>
                    <div class="small text-muted mb-3 d-none" data-outbound-hint="ozon">
                        <i class="fa fa-shield me-1"></i>EasyChat защитит повторный клик и не отправит первое сообщение дважды.
                    </div>
                    <div class="d-flex justify-content-end gap-2">
                        <button type="button" class="btn btn-light px-3" data-bs-dismiss="modal" style="border-radius: 8px;">Отмена</button>
                        <button type="submit" id="btn-outbound-contact-send" class="btn btn-primary px-4" style="border-radius: 8px; background: <?php echo $theme_color; ?> !important; border: none;">
                            Отправить
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Contextual schedule picker: anchored popover on desktop, bottom sheet on mobile. -->
<div id="scheduled-message-popover" class="easychat-schedule-popover" popover="auto" role="dialog" aria-labelledby="scheduled-message-popover-title" aria-describedby="scheduled-message-summary" hidden>
    <div class="easychat-schedule-popover__handle" aria-hidden="true"></div>
    <div class="easychat-schedule-popover__header">
        <div>
            <div class="easychat-schedule-kicker"><i class="fa fa-clock-o me-1"></i>Отложенная отправка</div>
            <h5 id="scheduled-message-popover-title">Когда отправить?</h5>
            <p id="scheduled-message-popover-hint">Текст останется в поле диалога до подтверждения.</p>
        </div>
        <button type="button" class="easychat-schedule-popover__close" data-schedule-close aria-label="Закрыть выбор времени">
            <i class="fa fa-times" aria-hidden="true"></i>
        </button>
    </div>
    <div class="easychat-schedule-popover__body">
        <div id="scheduled-message-alert" class="easychat-schedule-alert d-none" role="alert"></div>
        <input type="hidden" id="scheduled-message-public-id" value="">
        <input type="hidden" id="scheduled-message-revision" value="0">
        <input type="hidden" id="scheduled-message-at" value="">

        <div id="scheduled-message-editor" class="easychat-schedule-editor d-none">
            <label for="scheduled-message-text">Сообщение</label>
            <textarea id="scheduled-message-text" class="form-control" rows="3" maxlength="10000"></textarea>
        </div>

        <div class="easychat-schedule-section-label">Быстрый выбор</div>
        <div class="easychat-schedule-quick" role="group" aria-label="Быстрый выбор времени">
            <button type="button" class="btn" data-schedule-offset="15">
                <span>15 мин</span><small data-schedule-preview></small>
            </button>
            <button type="button" class="btn" data-schedule-offset="60">
                <span>1 час</span><small data-schedule-preview></small>
            </button>
            <button type="button" class="btn" data-schedule-preset="evening">
                <span data-schedule-label>Сегодня</span><small data-schedule-preview>18:00</small>
            </button>
            <button type="button" class="btn" data-schedule-preset="tomorrow">
                <span data-schedule-label>Завтра</span><small data-schedule-preview>09:00</small>
            </button>
        </div>

        <div class="easychat-schedule-section-label easychat-schedule-section-label--exact">Точная дата и время</div>
        <div class="easychat-schedule-exact">
            <label class="easychat-schedule-field" for="scheduled-message-date">
                <span>Дата</span>
                <span class="easychat-schedule-control">
                    <i class="fa fa-calendar-o" aria-hidden="true"></i>
                    <input type="date" id="scheduled-message-date">
                </span>
            </label>
            <label class="easychat-schedule-field" for="scheduled-message-time">
                <span>Время</span>
                <span class="easychat-schedule-control">
                    <i class="fa fa-clock-o" aria-hidden="true"></i>
                    <input type="time" id="scheduled-message-time" step="60">
                </span>
            </label>
        </div>

        <div class="easychat-schedule-timezone">
            <i class="fa fa-globe" aria-hidden="true"></i>
            <span>Время EasyChat: <strong><?php echo htmlspecialchars($scheduled_timezone_name, ENT_QUOTES, 'UTF-8'); ?></strong></span>
        </div>
        <div id="scheduled-marketplace-warning" class="easychat-schedule-warning d-none">
            <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
            <span>Маркетплейс может закрыть окно ответа. EasyChat проверит доступ ещё раз перед отправкой и сохранит сообщение при ошибке.</span>
        </div>
    </div>
    <div class="easychat-schedule-popover__footer">
        <div class="easychat-schedule-summary">
            <span class="easychat-schedule-summary__icon"><i class="fa fa-calendar-check-o" aria-hidden="true"></i></span>
            <span>
                <strong id="scheduled-message-summary">Выберите время</strong>
                <small>Сообщение отправится автоматически</small>
            </span>
        </div>
        <button type="button" id="btn-confirm-scheduled-message" class="btn btn-primary">
            <i class="fa fa-clock-o" aria-hidden="true"></i><span>Запланировать</span>
        </button>
    </div>
</div>

<!-- Mobile/Tablet: Customer Panel -->
<div class="modal fade" id="modal-customer-panel" tabindex="-1" aria-labelledby="modal-customer-panel-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable easychat-customer-panel-dialog">
        <div class="modal-content border-0 shadow overflow-hidden easychat-customer-panel-modal">
            <div class="modal-header border-0 px-4 py-3 bg-white">
                <h5 class="modal-title fw-bold text-dark" id="modal-customer-panel-title">Карточка клиента</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div id="customer-panel-mobile-body" class="easychat-customer-panel-body"></div>
        </div>
    </div>
</div>

<!-- Modal: Merge Customer Cards -->
<div class="modal fade" id="modal-merge-customer" tabindex="-1" aria-labelledby="modal-merge-customer-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow rounded-4 overflow-hidden" style="border-radius: 16px !important;">
            <div class="modal-header border-0 p-4 pb-2 bg-white">
                <div>
                    <h5 class="modal-title fw-bold text-dark" id="modal-merge-customer-title" style="font-family: 'Outfit', sans-serif;">Объединить карточки клиента</h5>
                    <div class="text-muted small">Проверьте, что это действительно один и тот же клиент.</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="box-shadow: none; outline: none;"></button>
            </div>
            <div class="modal-body p-4 pt-2 bg-white">
                <div id="merge-customer-preview" class="easychat-merge-preview"></div>
                <input type="hidden" id="merge-source-customer-id" value="0">
                <input type="hidden" id="merge-profile-url" value="">
                <input type="hidden" id="merge-reason" value="manual">
            </div>
            <div class="modal-footer border-0 p-4 pt-0 bg-white d-flex justify-content-end gap-2">
                <button type="button" class="btn btn-light py-2 px-4 small fw-semibold text-muted border-0" data-bs-dismiss="modal" style="border-radius: 8px; font-size: 13px;">Отмена</button>
                <button type="button" id="btn-confirm-merge-customer" class="btn btn-primary py-2 px-4 small fw-semibold border-0" style="border-radius: 8px; font-size: 13px; background: <?php echo $theme_color; ?> !important;">
                    <i class="fa fa-compress me-1"></i> Объединить
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modal-unlink-customer-profile" tabindex="-1" aria-labelledby="modal-unlink-customer-profile-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow rounded-4 overflow-hidden" style="border-radius: 16px !important;">
            <div class="modal-header border-0 p-4 pb-2 bg-white">
                <div>
                    <h5 class="modal-title fw-bold text-dark" id="modal-unlink-customer-profile-title" style="font-family: 'Outfit', sans-serif;">Отвязать от клиента</h5>
                    <div class="text-muted small">Профиль и связанный канал будут отделены от текущей карточки.</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="box-shadow: none; outline: none;"></button>
            </div>
            <div class="modal-body p-4 pt-2 bg-white">
                <input type="hidden" id="unlink-profile-id" value="0">
                <input type="hidden" id="unlink-profile-url" value="">
                <div class="easychat-unlink-profile-preview mb-3">
                    <span id="unlink-profile-provider">Профиль</span>
                    <strong id="unlink-profile-url-label"></strong>
                </div>
                <label for="unlink-profile-reason" class="form-label small fw-semibold text-muted mb-1">Причина</label>
                <select id="unlink-profile-reason" class="form-select bg-light border-0 mb-3" style="border-radius: 10px; min-height: 44px;">
                    <option value="wrong_customer">Ошибочно объединен с этим клиентом</option>
                    <option value="outdated">Профиль устарел</option>
                    <option value="duplicate">Дубль другого профиля</option>
                    <option value="privacy_request">Запрос клиента</option>
                    <option value="manual">Другое</option>
                </select>
                <label for="unlink-profile-note" class="form-label small fw-semibold text-muted mb-1">Комментарий</label>
                <textarea id="unlink-profile-note" class="form-control bg-light border-0 mb-3" rows="2" maxlength="255" placeholder="Необязательно" style="border-radius: 10px;"></textarea>
                <label class="easychat-unlink-profile-switch">
                    <input type="checkbox" id="unlink-profile-suppress" value="1" checked>
                    <span>Не предлагать эту ссылку снова для текущей карточки</span>
                </label>
            </div>
            <div class="modal-footer border-0 p-4 pt-0 bg-white d-flex justify-content-end gap-2">
                <button type="button" class="btn btn-light py-2 px-4 small fw-semibold text-muted border-0" data-bs-dismiss="modal" style="border-radius: 8px; font-size: 13px;">Отмена</button>
                <button type="button" id="btn-confirm-unlink-customer-profile" class="btn btn-danger py-2 px-4 small fw-semibold border-0" style="border-radius: 8px; font-size: 13px;">
                    <i class="fa fa-chain-broken me-1"></i> Отвязать
                </button>
            </div>
        </div>
    </div>
</div>

<?php if (!empty($quick_replies)) { ?>
<!-- Modal: Quick Replies Palette -->
<div class="modal fade" id="modal-quick-replies" tabindex="-1" aria-labelledby="modal-quick-replies-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow rounded-4 overflow-hidden" style="border-radius: 12px !important;">
            <div class="modal-header border-0 p-4 pb-2 bg-white">
                <div>
                    <h5 class="modal-title fw-bold text-dark" id="modal-quick-replies-title" style="font-family: 'Outfit', sans-serif;">Быстрые ответы</h5>
                    <div class="text-muted small">Выберите заготовку, чтобы вставить ее в поле ответа.</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="box-shadow: none; outline: none;"></button>
            </div>
            <div class="modal-body p-4 pt-2 bg-white">
                <input type="text" id="quick-reply-search" class="form-control bg-light border-0 mb-3" placeholder="Найти шаблон..." style="border-radius: 10px; min-height: 44px;">
                <div class="quick-reply-palette-list d-flex flex-column gap-2" style="max-height: 420px; overflow-y: auto;">
                    <?php foreach ($quick_replies as $qr) { ?>
                        <?php
                            $qr_full_text = (string)($qr['text'] ?? '');
                            $qr_title = htmlspecialchars((string)($qr['title'] ?? ''), ENT_QUOTES, 'UTF-8');
                            $qr_text = htmlspecialchars($qr_full_text, ENT_QUOTES, 'UTF-8');
                            $qr_scope = (string)($qr['scope'] ?? 'personal') === 'global' ? 'Общий' : 'Мой';
                            $qr_preview_text = mb_strlen($qr_full_text, 'UTF-8') > 120 ? mb_substr($qr_full_text, 0, 120, 'UTF-8') . '...' : $qr_full_text;
                            $qr_preview = htmlspecialchars($qr_preview_text, ENT_QUOTES, 'UTF-8');
                        ?>
                        <button type="button" class="quick-reply-palette-item text-start border bg-white p-3 quick-reply-item" data-text="<?php echo $qr_text; ?>" data-title="<?php echo $qr_title; ?>" style="border-radius: 8px;">
                            <div class="d-flex align-items-center justify-content-between gap-2 mb-1">
                                <span class="fw-bold text-dark"><i class="fa fa-bolt text-warning me-1"></i><?php echo $qr_title; ?></span>
                                <span class="badge bg-light text-muted border"><?php echo $qr_scope; ?></span>
                            </div>
                            <div class="text-muted small"><?php echo $qr_preview; ?></div>
                        </button>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php } ?>

<!-- Modal: Edit Customer Profile -->
<div class="modal fade" id="modal-edit-customer" tabindex="-1" aria-labelledby="modal-edit-customer-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow rounded-4 overflow-hidden" style="border-radius: 16px !important;">
            <!-- Modal Header -->
            <div class="modal-header border-0 p-4 pb-0 bg-white">
                <h5 class="modal-title fw-bold text-dark" id="modal-edit-customer-title" style="font-family: 'Outfit', sans-serif;">Профиль клиента</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="box-shadow: none; outline: none;"></button>
            </div>
            
            <form id="edit-customer-form" autocomplete="off">
                <!-- Modal Body -->
                <div class="modal-body p-4 bg-white">
                    <input type="hidden" name="chat_id" id="edit-customer-chat-id" value="0">
                    
                    <!-- Customer Name Field -->
                    <div class="mb-3">
                        <label for="edit-customer-name-input" class="form-label small fw-semibold text-muted mb-1" style="font-size: 11px;">Имя клиента</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-0 text-muted" style="border-radius: 8px 0 0 8px;"><i class="fa fa-user"></i></span>
                            <input type="text" name="customer_name" id="edit-customer-name-input" class="form-control bg-light border-0 py-2 small" placeholder="Введите имя..." required style="border-radius: 0 8px 8px 0; font-size: 13px; box-shadow: none;">
                        </div>
                    </div>
                    
                    <!-- Customer Email Field -->
                    <div class="mb-3">
                        <label for="edit-customer-email-input" class="form-label small fw-semibold text-muted mb-1" style="font-size: 11px;">Email</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-0 text-muted" style="border-radius: 8px 0 0 8px;"><i class="fa fa-envelope-o"></i></span>
                            <input type="email" name="primary_email" id="edit-customer-email-input" class="form-control bg-light border-0 py-2 small" placeholder="Введите email..." style="border-radius: 0 8px 8px 0; font-size: 13px; box-shadow: none;">
                        </div>
                    </div>
                    
                    <!-- Customer Phone Field -->
                    <div class="mb-3">
                        <label for="edit-customer-phone-input" class="form-label small fw-semibold text-muted mb-1" style="font-size: 11px;">Телефон</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-0 text-muted" style="border-radius: 8px 0 0 8px;"><i class="fa fa-phone"></i></span>
                            <input type="text" name="primary_phone" id="edit-customer-phone-input" class="form-control bg-light border-0 py-2 small" placeholder="Введите телефон..." style="border-radius: 0 8px 8px 0; font-size: 13px; box-shadow: none;">
                        </div>
                    </div>
                </div>
                
                <!-- Modal Footer -->
                <div class="modal-footer border-0 p-4 pt-0 bg-white d-flex justify-content-end gap-2">
                    <button type="button" class="btn btn-light py-2 px-4 small fw-semibold text-muted border-0" data-bs-dismiss="modal" style="border-radius: 8px; font-size: 13px;">Отмена</button>
                    <button type="submit" class="btn btn-primary py-2 px-4 small fw-semibold border-0" style="border-radius: 8px; font-size: 13px; background: <?php echo $theme_color; ?> !important;">Сохранить</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal: Media Gallery -->
<div class="modal fade" id="modal-image-preview" tabindex="-1" aria-labelledby="modal-image-preview-title" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered easychat-image-dialog easychat-media-gallery-dialog">
        <div class="modal-content border-0 shadow overflow-hidden easychat-image-modal easychat-media-gallery-modal">
            <div class="modal-header border-0 py-2 px-3 easychat-media-gallery-header">
                <div class="min-w-0 easychat-media-gallery-title">
                    <h6 class="modal-title fw-semibold text-dark text-truncate mb-0" id="modal-image-preview-title">Медиа диалога</h6>
                    <div class="easychat-media-gallery-meta text-muted small" id="modal-media-gallery-meta"></div>
                </div>
                <div class="easychat-media-gallery-toolbar" aria-label="Действия просмотра">
                    <button type="button" id="modal-media-gallery-rotate" class="btn btn-light btn-sm border-0 easychat-media-gallery-action easychat-media-gallery-control" title="Повернуть просмотр" aria-label="Повернуть просмотр">
                        <i class="fa fa-repeat"></i>
                    </button>
                    <a href="#" id="modal-image-download" class="btn btn-light btn-sm border-0 easychat-media-gallery-control" target="_blank" rel="noopener" title="Открыть полный размер" aria-label="Открыть полный размер">
                        <i class="fa fa-external-link"></i>
                    </a>
                    <button type="button" class="btn-close easychat-media-gallery-control easychat-media-gallery-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
            </div>
            <div class="modal-body p-0 easychat-image-modal-body easychat-media-gallery-body">
                <button type="button" class="easychat-media-gallery-nav easychat-media-gallery-prev" aria-label="Предыдущее вложение">
                    <i class="fa fa-chevron-left"></i>
                </button>
                <div class="easychat-image-loading" aria-hidden="true"></div>
                <div class="easychat-media-gallery-stage" id="modal-media-gallery-stage">
                    <img id="modal-image-preview-img" src="" alt="Просмотр изображения">
                </div>
                <button type="button" class="easychat-media-gallery-nav easychat-media-gallery-next" aria-label="Следующее вложение">
                    <i class="fa fa-chevron-right"></i>
                </button>
            </div>
            <div class="easychat-media-gallery-strip" id="modal-media-gallery-strip" aria-label="Медиа диалога"></div>
        </div>
    </div>
</div>

<style>
:root {
    --easychat-accent: <?php echo htmlspecialchars($theme_color, ENT_QUOTES, 'UTF-8'); ?> !important;
    --easychat-on-accent: <?php echo htmlspecialchars($theme_foreground_color, ENT_QUOTES, 'UTF-8'); ?> !important;
}
</style>

<script type="text/javascript">
window.EasyChatIndexConfig = {
    isManagerAdmin: <?php echo (isset(\EasyChat\Library\RequestContext::session()['manager_role']) && \EasyChat\Library\RequestContext::session()['manager_role'] === 'admin') ? 'true' : 'false'; ?>,
    canDeleteChats: <?php echo !empty($can_delete_chats) ? 'true' : 'false'; ?>,
    managerName: <?php echo json_encode((string)(\EasyChat\Library\RequestContext::session()['manager_name'] ?? 'Оператор'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
    aiSuggestionsCanUse: <?php echo $ai_suggestions_can_use ? 'true' : 'false'; ?>,
    copilotGhostEnabled: <?php echo $copilot_ghost_enabled ? 'true' : 'false'; ?>,
    outboundDraftAiAvailable: <?php echo $outbound_draft_ai_available ? 'true' : 'false'; ?>,
    emojiJsUrl: '<?php echo easychat_asset_versioned_url('js/emoji/easychat_emoji.js'); ?>',
    pdfJsUrl: '<?php echo easychat_asset_versioned_url('js/vendor/pdfjs/pdf.min.js'); ?>',
    pdfWorkerUrl: '<?php echo easychat_asset_versioned_url('js/vendor/pdfjs/pdf.worker.min.js'); ?>',
    version: '<?php echo EASYCHAT_VERSION; ?>',
    assetVersion: '<?php echo easychat_emoji_asset_version(); ?>',
    soundSendMessage: '<?php echo easychat_asset_url('sound/send_message.mp3'); ?>',
    themeColor: '<?php echo $theme_color; ?>',
    maxFileSizeMb: <?php echo max(1, (int)($chat_max_file_size ?? 5)); ?>,
    smsMaxSegments: <?php echo (int)\EasyChat\Library\Messenger\SmsTextMetrics::MAX_SEGMENTS; ?>,
    scheduledTimezone: <?php echo json_encode($scheduled_timezone_name, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
    attachmentCapabilities: <?php echo json_encode(\EasyChat\Library\Messenger\AttachmentCapabilities::clientMatrix(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>,
    marketplaceContextFallbacks: <?php echo json_encode(\EasyChat\Library\Messenger\ChannelCatalog::marketplaceContextFallbacks(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>
};
</script>
<?php echo easychat_script_tag('js/admin_conversation_state.js'); ?>
<?php echo easychat_script_tag('js/admin_instant_conversation_queue.js'); ?>
<?php echo easychat_script_tag('js/views/index.js'); ?>
