<?php
// Prevent direct access
if (!defined('LUNA_APP')) {
    http_response_code(403);
    exit('Forbidden');
}

require_once __DIR__ . '/config/messages.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/modules/zalo_service.php';
$messages = load_messages();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$appLicense = (string)((db_connection_settings()['license'] ?? ''));

// Get Zalo stats
function getZaloStats() {
    $totalUsers = 0;
    $activeUsers = 0;
    $totalMessages = 0;
    
    try {
        $conn = db_connect();
        
        // Total users (count from DataWork table where both Zalo_Id_Bot and So_QDNV have valid values)
        try {
            $sql = "SELECT COUNT(*) as total FROM DataWork 
                    WHERE (Zalo_Id_Bot <> '' AND Zalo_Id_Bot IS NOT NULL) 
                      AND (
                        So_QDNV = '' 
                        Or  So_QDNV = 'Null' 
                        Or So_QDNV IS NULL
                        Or(
                            So_QDNV Is Not Null
                            And Ngayketthuc > GETDATE()
                        )                        
                      )";
            $stmt = sqlsrv_query($conn, $sql);
            if ($stmt && $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $totalUsers = (int)$row['total'];
            }
        } catch (Exception $e) {
            $totalUsers = 0;
        }
        
        // Total Bots (count from Zalo table)
        try {
            $sql = "SELECT COUNT(*) as total FROM Zalo";
            $stmt = sqlsrv_query($conn, $sql);
            if ($stmt && $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $totalBots = (int)$row['total'];
            } else {
                $totalBots = 0;
            }
        } catch (Exception $e) {
            $totalBots = 0;
        }
        
        // Total messages (sum of Message_Number from Zalo table)
        try {
            $sql = "SELECT ISNULL(SUM(Message_Number), 0) as total FROM Zalo";
            $stmt = sqlsrv_query($conn, $sql);
            if ($stmt && $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $totalMessages = (int)$row['total'];
            }
        } catch (Exception $e) {
            $totalMessages = 0;
        }
        
        db_disconnect($conn);
        
    } catch (Exception $e) {
        // Connection error - return zeros
    }
    
    return [
        'totalUsers' => $totalUsers,
        'totalBots' => $totalBots,
        'totalMessages' => $totalMessages
    ];
}

$zaloStats = getZaloStats();
?>

<section class="panel-grid">
    <div class="panel wide">
        <header class="panel-header">
            <h3>
                <span aria-hidden="true" style="display:inline-grid;place-items:center;width:22px;height:22px;margin-right:8px;vertical-align:middle;color:#7adcc9;">
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="5" width="18" height="14" rx="2" />
                        <path d="m3 7 9 6 9-6" />
                    </svg>
                </span>
                ZALO BOT MANAGEMENT
            </h3>
            <div class="panel-controls">
                <a href="index.php?zalo=log" class="btn btn-secondary" style="margin-right: 10px; text-decoration: none;">
                    <span aria-hidden="true" style="display:inline-grid;place-items:center;width:18px;height:18px;margin-right:8px;vertical-align:middle;">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                            <polyline points="14,2 14,8 20,8" />
                        </svg>
                    </span>
                    <?= htmlspecialchars($messages['zalo_view_logs'] ?? 'Xem Log', ENT_QUOTES, 'UTF-8') ?>
                </a>
                <button type="button" class="btn btn-primary" data-zalo-open="create">
                    <span aria-hidden="true" style="display:inline-grid;place-items:center;width:18px;height:18px;margin-right:8px;vertical-align:middle;">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="12" y1="5" x2="12" y2="19" />
                            <line x1="5" y1="12" x2="19" y2="12" />
                        </svg>
                    </span>
                    <?= htmlspecialchars($messages['zalo_btn_add_new'] ?? 'Thêm mới', ENT_QUOTES, 'UTF-8') ?>
                </button>
            </div>
        </header>

        <!-- Statistics Cards -->
        <div id="zalo-stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; width: 100%; max-width: 100%;">
            <div class="zalo-stat-card" style="background: linear-gradient(135deg, rgba(26, 67, 74, 0.85), rgba(17, 46, 51, 0.95)); border: 1px solid rgba(122, 220, 201, 0.28); border-radius: 14px; padding: 24px; box-shadow: 0 8px 16px rgba(3, 15, 21, 0.35);">
                <div style="display: flex; align-items: center; gap: 16px; margin-bottom: 12px;">
                    <div class="stat-icon" style="width: 48px; height: 48px; background: rgba(122, 220, 201, 0.15); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                        <svg viewBox="0 0 24 24" style="width: 28px; height: 28px; fill: #7adcc9;">
                            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                            <circle cx="9" cy="7" r="4"/>
                            <path d="M22 21v-2a4 4 0 0 0-3-3.87"/>
                            <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
                        </svg>
                    </div>
                    <div>
                        <div style="font-size: 14px; color: rgba(232, 251, 246, 0.65); margin-bottom: 4px;"><?= htmlspecialchars($messages['zalo_total_users'] ?? 'Tổng Users', ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="stat-value" style="font-size: 32px; font-weight: 700; color: #e8fbf6;"><?= $zaloStats['totalUsers'] ?></div>
                    </div>
                </div>
            </div>

            <div class="zalo-stat-card" style="background: linear-gradient(135deg, rgba(26, 67, 74, 0.85), rgba(17, 46, 51, 0.95)); border: 1px solid rgba(122, 220, 201, 0.28); border-radius: 14px; padding: 24px; box-shadow: 0 8px 16px rgba(3, 15, 21, 0.35);">
                <div style="display: flex; align-items: center; gap: 16px; margin-bottom: 12px;">
                    <div class="stat-icon" style="width: 48px; height: 48px; background: rgba(122, 220, 201, 0.15); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                        <svg viewBox="0 0 24 24" style="width: 28px; height: 28px; fill: #4ade80;">
                            <rect x="5" y="2" width="14" height="3" rx="1.5"/>
                            <rect x="7" y="6" width="10" height="14" rx="2"/>
                            <circle cx="10" cy="10" r="1.5"/>
                            <circle cx="14" cy="10" r="1.5"/>
                            <rect x="9" y="14" width="6" height="2" rx="1"/>
                            <rect x="6" y="21" width="2" height="2" rx="1"/>
                            <rect x="16" y="21" width="2" height="2" rx="1"/>
                        </svg>
                    </div>
                    <div>
                        <div style="font-size: 14px; color: rgba(232, 251, 246, 0.65); margin-bottom: 4px;"><?= htmlspecialchars($messages['zalo_total_bots'] ?? 'Tổng Bots', ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="stat-value" style="font-size: 32px; font-weight: 700; color: #e8fbf6;"><?= $zaloStats['totalBots'] ?></div>
                    </div>
                </div>
            </div>

            <div class="zalo-stat-card" style="background: linear-gradient(135deg, rgba(26, 67, 74, 0.85), rgba(17, 46, 51, 0.95)); border: 1px solid rgba(122, 220, 201, 0.28); border-radius: 14px; padding: 24px; box-shadow: 0 8px 16px rgba(3, 15, 21, 0.35);">
                <div style="display: flex; align-items: center; gap: 16px; margin-bottom: 12px;">
                    <div class="stat-icon" style="width: 48px; height: 48px; background: rgba(147, 197, 253, 0.15); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                        <svg viewBox="0 0 24 24" style="width: 28px; height: 28px; fill: #93c5fd;">
                            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                        </svg>
                    </div>
                    <div>
                        <div style="font-size: 14px; color: rgba(232, 251, 246, 0.65); margin-bottom: 4px;"><?= htmlspecialchars($messages['zalo_total_messages'] ?? 'Tổng Tin Nhắn', ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="stat-value" style="font-size: 32px; font-weight: 700; color: #e8fbf6;"><?= $zaloStats['totalMessages'] ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Zalo Configs Section -->
        <?php 
        $allZaloConfigs = zalo_list();
        // Calculate totals
        $totalUserNumber = 0;
        $totalMessageNumber = 0;
        foreach ($allZaloConfigs as $cfg) {
            $totalUserNumber += (int)($cfg['user_number'] ?? 0);
            $totalMessageNumber += (int)($cfg['message_number'] ?? 0);
        }
        ?>
        <div class="zalo-configs-wrapper">
            <div style="background: rgba(17, 46, 51, 0.65); border: 1px solid rgba(122, 220, 201, 0.25); border-radius: 12px; padding: 20px;">
                <h4 style="color: #7adcc9; font-size: 18px; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; margin-top: 1px;">
                    <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: currentColor;">
                        <circle cx="12" cy="12" r="10"/>
                        <line x1="12" y1="16" x2="12" y2="12"/>
                        <line x1="12" y1="8" x2="12.01" y2="8"/>
                    </svg>
                    <?= htmlspecialchars($messages['zalo_system_info'] ?? 'Thông Tin Hệ Thống Zalo Bot', ENT_QUOTES, 'UTF-8') ?>
                </h4>
                
                <?php if (empty($allZaloConfigs)): ?>
                    <div style="padding: 40px; text-align: center; color: rgba(232, 251, 246, 0.5);">
                        <svg viewBox="0 0 24 24" style="width: 48px; height: 48px; fill: currentColor; margin: 0 auto 16px;">
                            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                        </svg>
                        <p style="font-size: 16px; margin-bottom: 8px;"><?= htmlspecialchars($messages['zalo_no_bots'] ?? 'Chưa có Zalo Bot nào', ENT_QUOTES, 'UTF-8') ?></p>
                        <p style="font-size: 14px;"><?= htmlspecialchars($messages['zalo_no_bots_desc'] ?? 'Click nút "Thêm mới" để tạo bot đầu tiên', ENT_QUOTES, 'UTF-8') ?></p>
                    </div>
                <?php else: ?>
                    <div class="zalo-bots-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; width: 100%; max-width: 100%; overflow: hidden;">
                        <?php 
                        $colors = [
                            ['border' => '#7adcc9'],
                            ['border' => '#93c5fd'],
                            ['border' => '#fbbf24'],
                            ['border' => '#f87171'],
                            ['border' => '#a78bfa'],
                        ];
                        foreach ($allZaloConfigs as $index => $config): 
                            $color = $colors[$index % count($colors)];
                        ?>
                            <div class="zalo-bot-card-inner" style="display: flex; align-items: center; gap: 10px; padding: 10px; background: rgba(6, 22, 28, 0.4); border-radius: 8px; border-left: 3px solid <?= $color['border'] ?>; overflow: hidden; max-width: 100%; box-sizing: border-box;">
                                
                                <!-- QR Code Left -->
                                <?php if ($config['link_qr']): ?>
                                <?php 
                                $isImageFile = preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $config['link_qr']);
                                if ($isImageFile && file_exists($config['link_qr'])): 
                                ?>
                                    <div class="zalo-qr-section" style="flex-shrink: 0; cursor: pointer; display: flex; align-items: center;" onclick="openQRModal('<?= htmlspecialchars($config['link_qr'], ENT_QUOTES, 'UTF-8') ?>', '<?= htmlspecialchars($config['name'], ENT_QUOTES, 'UTF-8') ?>')">
                                        <img src="<?= htmlspecialchars($config['link_qr'], ENT_QUOTES, 'UTF-8') ?>" 
                                             alt="QR Code" 
                                             style="width: 70px; height: 70px; border-radius: 6px; border: 1px solid rgba(122, 220, 201, 0.3); object-fit: cover; background: rgba(255, 255, 255, 0.95);">
                                            </div>
                                            <?php endif; ?>
                                            <?php endif; ?>

                                <!-- Info Section -->
                                <div style="flex: 1; display: flex; gap: 10px; min-width: 0;">
                                    
                                    <!-- Left: Bot Info (Name, User Count, Message Count) -->
                                    <div style="flex: 1; display: flex; flex-direction: column; gap: 6px; min-width: 0;">
                                        <!-- Row 1: Icon + ID + Name -->
                                        <div style="display: flex; align-items: center; gap: 5px;">
                                            <span style="display:inline-grid;place-items:center;width:16px;height:16px;color: <?= $color['border'] ?>; flex-shrink:0;">
                                                <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <rect x="3" y="5" width="18" height="14" rx="2" />
                                                    <path d="m3 7 9 6 9-6" />
                                                </svg>
                                            </span>
                                            <span class="zalo-bot-badge" style="background: rgba(122, 220, 201, 0.15); border: 1px solid rgba(122, 220, 201, 0.3); color: #7adcc9; font-size: 8px; font-weight: 600; padding: 1px 4px; border-radius: 3px; flex-shrink: 0;">
                                                <?= str_pad($config['id'], 4, '0', STR_PAD_LEFT) ?>
                                                    </span>
                                            <h5 class="zalo-bot-name" style="color: #e8fbf6; font-size: 12px; font-weight: 600; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;">
                                                <?= htmlspecialchars($config['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </h5>
                                    </div>

                                        <!-- Row 2: User Count -->
                                        <div style="display: flex; align-items: center; gap: 6px; background: rgba(3, 12, 16, 0.3); padding: 6px 10px; border-radius: 4px; min-height: 28px;">
                                            <svg viewBox="0 0 24 24" style="width: 14px; height: 14px; fill: #4ade80; flex-shrink: 0;">
                                                <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
                                                </svg>
                                            <span style="color: rgba(74, 222, 128, 0.7); font-size: 11px; font-weight: 500; white-space: nowrap;"><?= htmlspecialchars($messages['zalo_user_label'] ?? 'User', ENT_QUOTES, 'UTF-8') ?>:</span>
                                            <span style="color: #4ade80; font-size: 12px; font-weight: 700; margin-left: auto;"><?= (int)$config['user_number'] ?>/<?= (int)$config['user_max'] ?></span>
                                            </div>

                                        <!-- Row 3: Message Count -->
                                        <div style="display: flex; align-items: center; gap: 6px; background: rgba(3, 12, 16, 0.3); padding: 6px 10px; border-radius: 4px; min-height: 28px;">
                                            <svg viewBox="0 0 24 24" style="width: 14px; height: 14px; fill: #93c5fd; flex-shrink: 0;">
                                                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                                                </svg>
                                            <span style="color: rgba(147, 197, 253, 0.7); font-size: 11px; font-weight: 500; white-space: nowrap;"><?= htmlspecialchars($messages['zalo_message_label'] ?? 'TN', ENT_QUOTES, 'UTF-8') ?>:</span>
                                            <span style="color: #93c5fd; font-size: 12px; font-weight: 700; margin-left: auto;"><?= (int)$config['message_number'] ?>/<?= (int)$config['message_max'] ?></span>
                                        </div>
                                    </div>

                                    <!-- Right: Action Buttons Column -->
                                    <div style="display: flex; flex-direction: column; gap: 6px; justify-content: flex-end;">
                                        <!-- Nhận TN Button -->
                                        <button type="button" 
                                            class="btn btn-info btn-sm" 
                                            onclick="openMessagesModal('<?= (int)$config['id'] ?>', '<?= htmlspecialchars($config['token'], ENT_QUOTES, 'UTF-8') ?>', '<?= htmlspecialchars($config['name'], ENT_QUOTES, 'UTF-8') ?>')"
                                            style="padding: 4px 10px; font-size: 10px; display: flex; align-items: center; gap: 3px; height: 24px; white-space: nowrap; background: linear-gradient(135deg, #3b82f6, #2563eb); border: none; justify-content: center;">
                                            <svg viewBox="0 0 24 24" style="width: 10px; height: 10px; fill: currentColor;">
                                                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                                            </svg>
                                            <span><?= htmlspecialchars($messages['zalo_receive_messages_btn'] ?? 'Nhận TN', ENT_QUOTES, 'UTF-8') ?></span>
                                        </button>

                                        <!-- Edit Button -->
                                        <button type="button" 
                                            class="btn btn-secondary btn-sm" 
                                            data-zalo-edit="<?= (int)$config['id'] ?>"
                                            data-zalo-id="<?= (int)$config['id'] ?>"
                                            data-zalo-name="<?= htmlspecialchars($config['name'], ENT_QUOTES, 'UTF-8') ?>"
                                            data-zalo-user-number="<?= (int)$config['user_number'] ?>"
                                            data-zalo-message-number="<?= (int)$config['message_number'] ?>"
                                            data-zalo-token="<?= htmlspecialchars($config['token'], ENT_QUOTES, 'UTF-8') ?>"
                                            data-zalo-link-qr="<?= htmlspecialchars($config['link_qr'], ENT_QUOTES, 'UTF-8') ?>"
                                            style="padding: 4px 10px; font-size: 10px; display: flex; align-items: center; gap: 3px; height: 24px; white-space: nowrap; justify-content: center;">
                                            <svg viewBox="0 0 24 24" style="width: 10px; height: 10px; fill: currentColor;">
                                                <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
                                            </svg>
                                            <span><?= htmlspecialchars($messages['btn_edit'] ?? 'Sửa', ENT_QUOTES, 'UTF-8') ?></span>
                                        </button>

                                        <!-- Delete Button -->
                                        <form method="post" action="modules/zalo_service.php" style="margin: 0;" class="needs-confirm">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id_zalo" value="<?= (int)$config['id'] ?>">
                                            <input type="hidden" name="license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">
                                            <button type="submit" 
                                                    class="btn btn-danger btn-sm" 
                                                    data-confirm-message="<?= htmlspecialchars($messages['zalo_confirm_delete'] ?? 'Bạn có chắc chắn muốn xóa?', ENT_QUOTES, 'UTF-8') ?>"
                                                    style="padding: 4px 10px; font-size: 10px; display: flex; align-items: center; gap: 3px; height: 24px; white-space: nowrap; width: 100%; justify-content: center;">
                                                <svg viewBox="0 0 24 24" style="width: 10px; height: 10px; fill: currentColor;">
                                                    <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                                                </svg>
                                                <span><?= htmlspecialchars($messages['btn_delete'] ?? 'Xóa', ENT_QUOTES, 'UTF-8') ?></span>
                                            </button>
                                        </form>
                                    </div>

                                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="zalo-quick-actions-wrapper">
            <div class="zalo-quick-actions" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px;">
                <a href="zalo_info.php?key=luna2025" target="_blank" style="display: flex; align-items: center; gap: 10px; padding: 14px 18px; background: linear-gradient(135deg, rgba(122, 220, 201, 0.15), rgba(74, 158, 149, 0.12)); border: 1px solid rgba(122, 220, 201, 0.35); border-radius: 10px; color: #e8fbf6; text-decoration: none; transition: all 0.2s;">
                    <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: #7adcc9;">
                        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
                        <polyline points="9 22 9 12 15 12 15 22"/>
                    </svg>
                    <span style="font-weight: 600; font-size: 14px;"><?= htmlspecialchars($messages['zalo_dashboard_btn'] ?? 'Dashboard', ENT_QUOTES, 'UTF-8') ?></span>
                </a>

                <a href="ZALO_INTEGRATION.txt" target="_blank" style="display: flex; align-items: center; gap: 10px; padding: 14px 18px; background: linear-gradient(135deg, rgba(147, 197, 253, 0.15), rgba(96, 165, 250, 0.12)); border: 1px solid rgba(147, 197, 253, 0.35); border-radius: 10px; color: #e8fbf6; text-decoration: none; transition: all 0.2s;">
                    <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: #93c5fd;">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                        <polyline points="14 2 14 8 20 8"/>
                        <line x1="16" y1="13" x2="8" y2="13"/>
                        <line x1="16" y1="17" x2="8" y2="17"/>
                        <polyline points="10 9 9 9 8 9"/>
                    </svg>
                    <span style="font-weight: 600; font-size: 14px;"><?= htmlspecialchars($messages['zalo_integration_btn'] ?? 'Tài Liệu Tích Hợp', ENT_QUOTES, 'UTF-8') ?></span>
                </a>

                <a href="ZALO_INFO_HUONG_DAN.txt" target="_blank" style="display: flex; align-items: center; gap: 10px; padding: 14px 18px; background: linear-gradient(135deg, rgba(251, 191, 36, 0.15), rgba(245, 158, 11, 0.12)); border: 1px solid rgba(251, 191, 36, 0.35); border-radius: 10px; color: #e8fbf6; text-decoration: none; transition: all 0.2s;">
                    <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: #fbbf24;">
                        <circle cx="12" cy="12" r="10"/>
                        <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
                        <line x1="12" y1="17" x2="12.01" y2="17"/>
                    </svg>
                    <span style="font-weight: 600; font-size: 14px;"><?= htmlspecialchars($messages['zalo_guide_btn'] ?? 'Hướng Dẫn', ENT_QUOTES, 'UTF-8') ?></span>
                </a>

                <a href="modules/zalo/service.php" target="_blank" style="display: flex; align-items: center; gap: 10px; padding: 14px 18px; background: linear-gradient(135deg, rgba(167, 139, 250, 0.15), rgba(139, 92, 246, 0.12)); border: 1px solid rgba(167, 139, 250, 0.35); border-radius: 10px; color: #e8fbf6; text-decoration: none; transition: all 0.2s;">
                    <svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: #a78bfa;">
                        <polyline points="16 18 22 12 16 6"/>
                        <polyline points="8 6 2 12 8 18"/>
                    </svg>
                    <span style="font-weight: 600; font-size: 14px;"><?= htmlspecialchars($messages['zalo_source_code_btn'] ?? 'Source Code', ENT_QUOTES, 'UTF-8') ?></span>
                </a>
            </div>
        </div>
    </div>
</section>

<!-- Zalo Modal -->
<div class="modal-backdrop" id="zalo-modal" aria-hidden="true">
    <div class="modal">
        <div class="modal-header">
            <h4 id="zalo-modal-title"><?= htmlspecialchars($messages['zalo_form_heading'] ?? 'THÊM MỚI / CẬP NHẬT ZALO', ENT_QUOTES, 'UTF-8') ?></h4>
            <button type="button" class="modal-close" data-modal-close>&times;</button>
        </div>
        <div class="modal-body">
        <form method="post" action="modules/zalo_service.php" class="form-grid grid-2" id="zalo-form" novalidate>
            <input type="hidden" name="action" value="create" id="zalo-action">
            <input type="hidden" name="id_zalo" value="0" id="zalo-id">
            <input type="hidden" name="license" id="zalo-license" value="<?= htmlspecialchars($appLicense, ENT_QUOTES, 'UTF-8') ?>">
            
            <!-- Mã Bot (readonly, only show on edit) -->
            <div class="form-row" id="zalo-code-row" style="display: none;">
                <label for="zalo-code">Mã Bot</label>
                <div class="input-wrap">
                    <span class="icon">
                        <svg viewBox="0 0 24 24"><path d="M7 7h10v2H7z"/><path d="M7 11h10v2H7z"/><path d="M7 15h6v2H7z"/><rect x="3" y="3" width="18" height="18" rx="2" fill="none" stroke="currentColor" stroke-width="2"/></svg>
                    </span>
                    <input type="text" id="zalo-code" readonly style="background: rgba(6, 22, 28, 0.5); cursor: not-allowed; color: rgba(232, 251, 246, 0.6);">
                </div>
            </div>
            
            <div class="form-row" id="zalo-name-row">
                <label for="zalo-name"><?= $messages['zalo_form_name_label'] ?? 'Tên Bot' ?></label>
                <div class="input-wrap">
                    <span class="icon">
                        <svg viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                    </span>
                    <input type="text" name="name" id="zalo-name" placeholder="<?= htmlspecialchars($messages['zalo_form_name_placeholder'] ?? 'Nhập tên Bot Zalo', ENT_QUOTES, 'UTF-8') ?>" required>
                </div>
            </div>
            
            <div class="form-row" id="zalo-qr-row">
                <label for="zalo-qr-upload"><?= $messages['zalo_form_link_qr_label'] ?? 'Cập nhật QR Code' ?></label>
                <div>
                    <button type="button" id="upload-qr-btn" style="width: 100%; padding: 12px 20px; background: linear-gradient(135deg, rgba(122, 220, 201, 0.2), rgba(100, 167, 166, 0.15)); border: 1px solid rgba(122, 220, 201, 0.4); border-radius: 16px; color: #e8fbf6; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 14px; font-weight: 500; transition: all 0.2s;">
                        <svg viewBox="0 0 24 24" style="width: 18px; height: 18px; fill: currentColor;">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                            <polyline points="17 8 12 3 7 8"/>
                            <line x1="12" y1="3" x2="12" y2="15"/>
                        </svg>
                        Upload QR
                    </button>
                    <input type="file" id="qr-image-upload" accept="image/*" style="display: none;">
                    <input type="hidden" name="qr_image_path" id="qr-image-path">
                    <input type="hidden" name="link_qr" id="zalo-link-qr">
                </div>
            </div>
            
            <div class="form-row" id="zalo-user-number-row">
                <label for="zalo-user-number"><?= htmlspecialchars($messages['zalo_form_user_number_label'] ?? 'Số User', ENT_QUOTES, 'UTF-8') ?></label>
                <div class="input-wrap">
                    <span class="icon">
                        <svg viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                    </span>
                    <input type="number" name="user_number" id="zalo-user-number" placeholder="<?= htmlspecialchars($messages['zalo_form_user_number_placeholder'] ?? 'Nhập số lượng user', ENT_QUOTES, 'UTF-8') ?>" min="0">
                </div>
            </div>
            
            <div class="form-row" id="zalo-message-number-row">
                <label for="zalo-message-number"><?= htmlspecialchars($messages['zalo_form_message_number_label'] ?? 'Số Tin Nhắn', ENT_QUOTES, 'UTF-8') ?></label>
                <div class="input-wrap">
                    <span class="icon">
                        <svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                    </span>
                    <input type="number" name="message_number" id="zalo-message-number" placeholder="<?= htmlspecialchars($messages['zalo_form_message_number_placeholder'] ?? 'Nhập số lượng tin nhắn', ENT_QUOTES, 'UTF-8') ?>" min="0">
                </div>
            </div>
            
            <div class="form-row full">
                <label for="zalo-token"><?= $messages['zalo_form_token_label'] ?? 'Token' ?></label>
                <div class="input-wrap">
                    <span class="icon">
                        <svg viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                    </span>
                    <input type="text" name="token" id="zalo-token" placeholder="<?= htmlspecialchars($messages['zalo_form_token_placeholder'] ?? 'Nhập Zalo token', ENT_QUOTES, 'UTF-8') ?>" maxlength="500" required>
                </div>
            </div>
            
            <!-- QR Preview (below the form fields) -->
            <div id="qr-preview" class="form-row full" style="margin-top: 12px; display: none;">
                <div style="display: flex; align-items: center; gap: 12px; padding: 12px; background: rgba(122, 220, 201, 0.08); border: 1px solid rgba(122, 220, 201, 0.25); border-radius: 10px;">
                    <img id="qr-preview-img" src="" alt="QR Preview" style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid rgba(122, 220, 201, 0.3);">
                    <div style="flex: 1;">
                        <div style="color: #e8fbf6; font-size: 13px; font-weight: 500; margin-bottom: 4px;" id="qr-file-name"></div>
                        <div style="color: rgba(232, 251, 246, 0.6); font-size: 12px;" id="qr-file-size"></div>
                    </div>
                    <button type="button" id="remove-qr-btn" style="padding: 8px; background: rgba(248, 113, 113, 0.15); border: 1px solid rgba(248, 113, 113, 0.3); border-radius: 8px; color: #f87171; cursor: pointer; transition: all 0.2s;">
                        <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                            <line x1="18" y1="6" x2="6" y2="18"/>
                            <line x1="6" y1="6" x2="18" y2="18"/>
                        </svg>
                    </button>
                </div>
            </div>
            
            <div class="form-actions full">
                <button type="submit" class="btn btn-primary" id="zalo-submit" data-label-save="<?= htmlspecialchars($messages['zalo_btn_save'] ?? 'Lưu', ENT_QUOTES, 'UTF-8') ?>" data-label-update="<?= htmlspecialchars($messages['zalo_btn_update'] ?? 'Cập Nhật', ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($messages['zalo_btn_save'] ?? 'Lưu', ENT_QUOTES, 'UTF-8') ?></button>
                <button type="button" class="btn btn-secondary" data-modal-close><?= htmlspecialchars($messages['zalo_btn_reset'] ?? 'Đặt Lại', ENT_QUOTES, 'UTF-8') ?></button>
            </div>
        </form>
        </div>
    </div>
</div>

<style>
/* Prevent horizontal scroll globally */
html, body {
    overflow-x: hidden;
    max-width: 100vw;
}

.panel-grid {
    max-width: 100%;
    overflow-x: hidden;
}

.panel.wide {
    max-width: 100%;
    box-sizing: border-box;
}

/* Hover effects for quick action links */
.panel a[style*="background: linear-gradient"]:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(3, 15, 21, 0.35);
    filter: brightness(1.1);
}

/* Desktop - Max 3 columns per row */
@media (min-width: 1200px) {
    .zalo-bots-grid {
        grid-template-columns: repeat(3, 1fr) !important;
        overflow: hidden !important;
    }
    
    .zalo-bot-card-inner {
        max-width: 100% !important;
        overflow: hidden !important;
        box-sizing: border-box !important;
    }
}

@media (min-width: 900px) and (max-width: 1199px) {
    .zalo-bots-grid {
        grid-template-columns: repeat(2, 1fr) !important;
        overflow: hidden !important;
    }
    
    .zalo-bot-card-inner {
        max-width: 100% !important;
        overflow: hidden !important;
        box-sizing: border-box !important;
    }
}

@media (min-width: 769px) and (max-width: 899px) {
    .zalo-bots-grid {
        grid-template-columns: repeat(2, 1fr) !important;
        overflow: hidden !important;
    }
    
    .zalo-bot-card-inner {
        max-width: 100% !important;
        overflow: hidden !important;
        box-sizing: border-box !important;
    }
}

/* Global styles to prevent overflow */
.zalo-bot-card-inner * {
    box-sizing: border-box;
}

/* Mobile Responsive Styles */
@media (max-width: 768px) {
    /* Prevent horizontal scroll */
    html, body, .panel-grid, .panel.wide {
        overflow-x: hidden !important;
        max-width: 100vw !important;
    }
    
    /* Panel basics */
    .panel.wide {
        padding: 12px !important;
        margin: 0 !important;
    }
    
    /* Stats Grid */
    #zalo-stats-grid {
        grid-template-columns: 1fr !important;
        gap: 12px !important;
        width: 100% !important;
        max-width: 100% !important;
    }
    
    /* Stats Cards */
    .zalo-stat-card {
        padding: 16px !important;
        max-width: 100% !important;
    }
    
    /* Bot Cards Grid - 1 column on mobile, full display */
    .zalo-bots-grid {
        grid-template-columns: 1fr !important;
        width: 100% !important;
        max-width: 100% !important;
        overflow-x: hidden !important;
        overflow-y: visible !important;
        height: auto !important;
        max-height: none !important;
    }
    
    .zalo-bot-card-inner {
        max-width: 100% !important;
        overflow: hidden !important;
        box-sizing: border-box !important;
    }
    
    /* Configs wrapper - ensure full display without scroll */
    .zalo-configs-wrapper {
        width: 100% !important;
        max-width: 100% !important;
        overflow: visible !important;
        overflow-x: hidden !important;
        overflow-y: visible !important;
        height: auto !important;
        max-height: none !important;
    }
    
    .zalo-configs-wrapper > div {
        max-width: 100% !important;
        box-sizing: border-box !important;
        overflow: visible !important;
        height: auto !important;
        max-height: none !important;
    }
    
    /* Bot Cards */
    .zalo-bot-card-inner {
        padding: 8px !important;
        gap: 8px !important;
    }
    
    /* QR Section */
    .zalo-qr-section img {
        width: 60px !important;
        height: 60px !important;
    }
    
    /* Info Section */
    .zalo-info-section {
        gap: 5px !important;
    }
    
    .zalo-bot-name {
        font-size: 11px !important;
    }
    
    .zalo-bot-badge {
        font-size: 10px !important;
        padding: 1px 3px !important;
    }
    
    /* Row 2 & 3 - Stats and Buttons */
    .zalo-info-section > div {
        gap: 6px !important;
    }
    
    /* User/Msg boxes - flexible width on mobile */
    .zalo-info-section > div > div:first-child {
        flex: 1 !important;
        min-width: 0 !important;
    }
    
    .zalo-info-section button {
        padding: 3px 8px !important;
        font-size: 10px !important;
        height: 22px !important;
    }
    
    .zalo-info-section button svg {
        width: 12px !important;
        height: 12px !important;
    }
    
    .zalo-info-section > div > div {
        padding: 4px 6px !important;
    }
    
    .zalo-info-section > div > div span:nth-child(2) {
        font-size: 10px !important;
    }
    
    .zalo-info-section > div > div span:nth-child(3) {
        font-size: 12px !important;
    }
    
    .zalo-info-section > div > div svg {
        width: 15px !important;
        height: 15px !important;
    }
    
    /* Quick Actions */
    .zalo-quick-actions {
        grid-template-columns: 1fr !important;
    }
    
    /* Panel Header */
    .panel-header {
        flex-direction: column !important;
        align-items: flex-start !important;
    }
}

/* Prevent auto-zoom on input focus - works on all screen sizes */
#zalo-modal input,
#zalo-modal textarea,
#zalo-modal select {
    touch-action: manipulation;
    font-size: 16px;
}

@media (max-width: 480px) {
    /* Prevent overflow on very small screens */
    .panel.wide {
        padding: 8px !important;
    }
    
    #zalo-stats-grid {
        gap: 10px !important;
    }
    
    .zalo-stat-card {
        padding: 12px !important;
    }
    
    /* Extra small - QR even smaller */
    .zalo-qr-section img {
        width: 50px !important;
        height: 50px !important;
    }
    
    .zalo-bot-card-inner {
        padding: 6px !important;
        gap: 6px !important;
        max-width: 100% !important;
    }
    
    .zalo-info-section {
        gap: 4px !important;
    }
    
    /* User/Msg boxes - flexible, more compact */
    .zalo-info-section > div > div:first-child {
        flex: 1 !important;
        min-width: 0 !important;
        padding: 3px 5px !important;
    }
    
    .zalo-bot-name {
        font-size: 10px !important;
    }
    
    /* Buttons smaller */
    .zalo-info-section button {
        padding: 2px 6px !important;
        font-size: 9px !important;
    }
    
    /* Ensure bots grid doesn't overflow but shows all content */
    .zalo-bots-grid {
        max-width: 100% !important;
        overflow-x: hidden !important;
        overflow-y: visible !important;
        height: auto !important;
        max-height: none !important;
    }
    
    .zalo-configs-wrapper,
    .zalo-configs-wrapper > div {
        overflow: visible !important;
        height: auto !important;
        max-height: none !important;
    }
    
    .zalo-info-section button {
        padding: 2px 6px !important;
        font-size: 8px !important;
        height: 20px !important;
    }
}

</style>

<script src="assets/js/zalo.js"></script>

<script>
// Handle flash messages for Zalo page
(function() {
    function waitForFlashAndShow() {
        let attempts = 0;
        const maxAttempts = 20;
        
        function checkAndShow() {
            attempts++;
            
            if (window.__FLASH__ !== undefined) {
                showFlashMessages();
                return;
            }
            
            if (attempts < maxAttempts) {
                setTimeout(checkAndShow, 100);
            }
        }
        
        checkAndShow();
    }
    
    function showFlashMessages() {
        const flash = window.__FLASH__ || {};
        const messages = window.__MESSAGES__ || {};
        
        let hasFlash = false;
        
        // Show success message
        if (flash.success) {
            hasFlash = true;
            const successTitle = messages['success_notification_title'] || 'THÔNG BÁO';
            let successMsg = flash.success;
            
            if (successMsg.indexOf('<div class="success-header">') === -1 && successMsg.indexOf('<div class="error-header">') === -1) {
                successMsg = '<div class="success-header">' + successTitle + '</div>' + successMsg;
            }
            
            if (typeof window.showToast === 'function') {
                window.showToast('success', successMsg);
            }
        }
        
        // Show error message
        if (flash.error) {
            hasFlash = true;
            const errorTitle = messages['error_notification_title'] || 'THÔNG BÁO';
            const errorMsg = '<div class="error-header">' + errorTitle + '</div>' + flash.error;
            
            if (typeof window.showToast === 'function') {
                window.showToast('error', errorMsg, 6000);
            }
        }
        
        // Clear flash immediately to prevent app.js from showing it again
        if (hasFlash) {
            window.__FLASH__ = {success: null, error: null};
        }
        
        // Clean URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('success') || urlParams.has('error')) {
        const newUrl = new URL(window.location);
        newUrl.searchParams.delete('success');
        newUrl.searchParams.delete('error');
        window.history.replaceState({}, '', newUrl);
    }
    }
    
    // Start waiting for flash data
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', waitForFlashAndShow);
    } else {
        waitForFlashAndShow();
    }
})();

// QR Image Upload Handler
(function() {
    const uploadBtn = document.getElementById('upload-qr-btn');
    const fileInput = document.getElementById('qr-image-upload');
    const preview = document.getElementById('qr-preview');
    const previewImg = document.getElementById('qr-preview-img');
    const fileName = document.getElementById('qr-file-name');
    const fileSize = document.getElementById('qr-file-size');
    const removeBtn = document.getElementById('remove-qr-btn');
    const linkInput = document.getElementById('zalo-link-qr');
    const pathInput = document.getElementById('qr-image-path');

    if (!uploadBtn || !fileInput) return;

    // Click upload button to trigger file input
    uploadBtn.addEventListener('click', function() {
        fileInput.click();
    });

    // Hover effect for upload button
    uploadBtn.addEventListener('mouseenter', function() {
        this.style.background = 'linear-gradient(135deg, rgba(122, 220, 201, 0.3), rgba(100, 167, 166, 0.25))';
        this.style.borderColor = 'rgba(122, 220, 201, 0.6)';
        this.style.transform = 'translateY(-1px)';
    });

    uploadBtn.addEventListener('mouseleave', function() {
        this.style.background = 'linear-gradient(135deg, rgba(122, 220, 201, 0.2), rgba(100, 167, 166, 0.15))';
        this.style.borderColor = 'rgba(122, 220, 201, 0.4)';
        this.style.transform = 'translateY(0)';
    });

    // Handle file selection
    fileInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;

        // Validate file type
        if (!file.type.startsWith('image/')) {
            const messages = window.__MESSAGES__ || {};
            const errorTitle = messages['error_notification_title'] || 'THÔNG BÁO';
            const errorMsg = 'Vui lòng chọn file hình ảnh!';
            const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
            
            if (window.showToast) {
                window.showToast('error', errorWithHeader);
            } else {
                alert(errorMsg);
            }
            return;
        }

        // Validate file size (max 5MB)
        if (file.size > 5 * 1024 * 1024) {
            const messages = window.__MESSAGES__ || {};
            const errorTitle = messages['error_notification_title'] || 'THÔNG BÁO';
            const errorMsg = 'Kích thước file không được vượt quá 5MB!';
            const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
            
            if (window.showToast) {
                window.showToast('error', errorWithHeader);
            } else {
                alert(errorMsg);
            }
            return;
        }

        // Read and display preview
        const reader = new FileReader();
        reader.onload = function(e) {
            previewImg.src = e.target.result;
            fileName.textContent = file.name;
            fileSize.textContent = formatFileSize(file.size);
            preview.style.display = 'block';
            
            // Store base64 in hidden input for now
            pathInput.value = e.target.result;
            
            // Clear link input when image is uploaded
            linkInput.value = '';
        };
        reader.readAsDataURL(file);
    });

    // Remove image
    removeBtn.addEventListener('click', function() {
        fileInput.value = '';
        pathInput.value = '';
        preview.style.display = 'none';
        previewImg.src = '';
    });

    // Format file size
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    }

    // Hover effect for remove button
    removeBtn.addEventListener('mouseenter', function() {
        this.style.background = 'rgba(248, 113, 113, 0.25)';
        this.style.borderColor = 'rgba(248, 113, 113, 0.5)';
    });

    removeBtn.addEventListener('mouseleave', function() {
        this.style.background = 'rgba(248, 113, 113, 0.15)';
        this.style.borderColor = 'rgba(248, 113, 113, 0.3)';
    });
})();
</script>

<!-- QR Code Modal -->
<div id="qr-modal" class="modal-backdrop" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(3, 12, 16, 0.9); backdrop-filter: blur(8px); z-index: 9999; align-items: center; justify-content: center;">
    <div style="position: relative; background: linear-gradient(135deg, rgba(17, 46, 51, 0.98), rgba(8, 30, 35, 0.98)); border: 1px solid rgba(122, 220, 201, 0.3); border-radius: 16px; padding: 0; max-width: 90%; max-height: 90vh; overflow: hidden; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);">
        <!-- Header -->
        <div style="padding: 20px 24px; border-bottom: 1px solid rgba(122, 220, 201, 0.2); display: flex; align-items: center; justify-content: center; position: relative;">
            <h3 style="color: #7adcc9; font-size: 20px; font-weight: 600; margin: 0; display: flex; align-items: center; gap: 10px;">
                <svg viewBox="0 0 24 24" style="width: 24px; height: 24px; fill: currentColor;">
                    <rect x="3" y="3" width="7" height="7"/>
                    <rect x="14" y="3" width="7" height="7"/>
                    <rect x="3" y="14" width="7" height="7"/>
                    <rect x="14" y="14" width="7" height="7"/>
                </svg>
                <?= htmlspecialchars($messages['zalo_qr_modal_title'] ?? 'Thông tin QR Code', ENT_QUOTES, 'UTF-8') ?>
            </h3>
            <button onclick="closeQRModal()" style="position: absolute; right: 24px; background: rgba(248, 113, 113, 0.15); border: 1px solid rgba(248, 113, 113, 0.3); color: #f87171; width: 36px; height: 36px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 20px; transition: all 0.2s;" onmouseover="this.style.background='rgba(248, 113, 113, 0.25)'" onmouseout="this.style.background='rgba(248, 113, 113, 0.15)'">&times;</button>
        </div>
        
        <!-- QR Image -->
        <div style="padding: 40px; display: flex; align-items: center; justify-content: center; background: rgba(255, 255, 255, 0.02);">
            <img id="qr-modal-image" src="" alt="QR Code" style="max-width: 400px; max-height: 400px; width: auto; height: auto; border-radius: 12px; border: 3px solid rgba(122, 220, 201, 0.4); background: white; padding: 20px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);">
        </div>
    </div>
</div>

<script>
// QR Modal Functions
function openQRModal(qrSrc, botName) {
    const modal = document.getElementById('qr-modal');
    const modalImage = document.getElementById('qr-modal-image');
    
    modalImage.src = qrSrc;
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closeQRModal() {
    const modal = document.getElementById('qr-modal');
    modal.style.display = 'none';
    document.body.style.overflow = '';
}

// Close modal when clicking outside
document.getElementById('qr-modal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeQRModal();
    }
});

// Close modal with ESC key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeQRModal();
        closeMessagesModal();
    }
});
</script>

<!-- Messages Modal Responsive Styles -->
<style>
/* Ensure header and controls are fixed (not scrollable) */
#messages-modal {
    overflow: hidden !important;
}

#messages-modal-content {
    overflow: hidden !important;
}

#messages-modal-header {
    flex-shrink: 0 !important;
}

#messages-modal-controls {
    flex-shrink: 0 !important;
}

#messages-container {
    flex: 1 !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
    min-height: 0 !important;
    -webkit-overflow-scrolling: touch;
}

@media (max-width: 768px) {
    #messages-modal {
        align-items: flex-start !important;
        padding: 16px !important;
    }
    
    #messages-modal-content {
        width: calc(100% - 32px) !important;
        max-height: 92vh !important;
        border-radius: 12px !important;
        margin: 16px auto !important;
    }
    
    #messages-modal-header {
        padding: 14px 16px !important;
    }
    
    #messages-modal-icon {
        width: 20px !important;
        height: 20px !important;
    }
    
    #messages-modal-title {
        font-size: 16px !important;
    }
    
    #messages-modal-bot-name {
        font-size: 11px !important;
    }
    
    #messages-modal-controls {
        padding: 12px 16px !important;
        gap: 8px !important;
    }
    
    #start-listening-btn,
    #stop-listening-btn {
        padding: 9px 14px !important;
        font-size: 13px !important;
        min-width: 120px !important;
    }
    
    #start-listening-btn svg,
    #stop-listening-btn svg {
        width: 14px !important;
        height: 14px !important;
    }
    
    #messages-modal-controls button[onclick="clearMessages()"] {
        padding: 9px 12px !important;
        font-size: 12px !important;
        min-width: 90px !important;
    }
    
    #listening-status {
        font-size: 12px !important;
        padding: 6px !important;
        margin-top: 2px !important;
    }
    
    #wait-time {
        font-size: 11px !important;
    }
    
    #messages-container {
        padding: 14px 16px !important;
        font-size: 12px !important;
        flex: 1;
        overflow-y: auto !important;
        -webkit-overflow-scrolling: touch;
        touch-action: pan-y;
    }
}

@media (max-width: 480px) {
    #messages-modal {
        padding: 12px !important;
        align-items: flex-start !important;
    }
    
    #messages-modal-content {
        width: calc(100% - 24px) !important;
        max-height: 94vh !important;
        border-radius: 8px !important;
        margin: 12px auto !important;
    }
    
    #messages-modal-header {
        padding: 12px 14px !important;
    }
    
    #messages-modal-title {
        font-size: 14px !important;
    }
    
    #messages-modal-bot-name {
        font-size: 10px !important;
    }
    
    #messages-modal-controls {
        padding: 10px 14px !important;
        gap: 6px !important;
    }
    
    #start-listening-btn,
    #stop-listening-btn {
        padding: 8px 12px !important;
        font-size: 12px !important;
        min-width: 100px !important;
        gap: 4px !important;
    }
    
    #start-listening-btn span,
    #stop-listening-btn span {
        font-size: 12px !important;
    }
    
    #messages-modal-controls button[onclick="clearMessages()"] {
        padding: 8px 10px !important;
        font-size: 11px !important;
        min-width: 80px !important;
    }
    
    #messages-modal-controls button[onclick="clearMessages()"] svg {
        width: 12px !important;
        height: 12px !important;
    }
    
    #listening-status {
        font-size: 11px !important;
        padding: 5px !important;
    }
    
    #status-text {
        font-size: 11px !important;
    }
    
    #wait-time {
        font-size: 10px !important;
    }
    
    #messages-container {
        padding: 12px 14px !important;
        font-size: 11px !important;
        line-height: 1.5 !important;
        overflow-y: auto !important;
        -webkit-overflow-scrolling: touch;
        touch-action: pan-y;
    }
}
</style>

<!-- Messages Modal -->
<div id="messages-modal" class="modal-backdrop" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(3, 12, 16, 0.9); backdrop-filter: blur(8px); z-index: 9999; align-items: center; justify-content: center;">
    <div id="messages-modal-content" style="position: relative; background: linear-gradient(135deg, rgba(17, 46, 51, 0.98), rgba(8, 30, 35, 0.98)); border: 1px solid rgba(122, 220, 201, 0.3); border-radius: 16px; padding: 0; width: 90%; max-width: 900px; max-height: 90vh; overflow: hidden; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); display: flex; flex-direction: column;">
        
        <!-- Header -->
        <div id="messages-modal-header" style="padding: 20px 24px; border-bottom: 1px solid rgba(122, 220, 201, 0.2); display: flex; align-items: center; justify-content: space-between;">
            <div style="display: flex; align-items: center; gap: 12px;">
                <svg id="messages-modal-icon" viewBox="0 0 24 24" style="width: 24px; height: 24px; fill: #7adcc9;">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                </svg>
                <div style="min-width: 0; flex: 1;">
                    <h3 id="messages-modal-title" style="color: #7adcc9; font-size: 18px; font-weight: 600; margin: 0;">
                        <?= htmlspecialchars($messages['zalo_messages_modal_title'] ?? 'Nhận tin nhắn', ENT_QUOTES, 'UTF-8') ?>
                    </h3>
                    <p id="messages-modal-bot-name" style="color: rgba(232, 251, 246, 0.6); font-size: 12px; margin: 4px 0 0 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"></p>
                </div>
            </div>
            <button onclick="closeMessagesModal()" style="background: rgba(248, 113, 113, 0.15); border: 1px solid rgba(248, 113, 113, 0.3); color: #f87171; width: 36px; height: 36px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 20px; transition: all 0.2s; flex-shrink: 0;" onmouseover="this.style.background='rgba(248, 113, 113, 0.25)'" onmouseout="this.style.background='rgba(248, 113, 113, 0.15)'">&times;</button>
        </div>
        
        <!-- Controls -->
        <div id="messages-modal-controls" style="padding: 16px 24px; border-bottom: 1px solid rgba(122, 220, 201, 0.1); display: flex; align-items: center; gap: 12px; background: rgba(3, 12, 16, 0.3); flex-wrap: wrap;">
            <button id="start-listening-btn" onclick="startListening()" style="padding: 10px 20px; background: linear-gradient(135deg, #22c55e, #16a34a); border: 1px solid rgba(34, 197, 94, 0.5); color: white; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 8px; transition: all 0.2s; flex: 1; min-width: 140px; justify-content: center;" onmouseover="this.style.transform='translateY(-1px)'" onmouseout="this.style.transform='translateY(0)'">
                <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                    <circle cx="12" cy="12" r="10"/><polygon points="10 8 16 12 10 16 10 8"/>
                </svg>
                <span><?= htmlspecialchars($messages['zalo_messages_start_listening'] ?? 'Bắt đầu lắng nghe', ENT_QUOTES, 'UTF-8') ?></span>
            </button>
            <button id="stop-listening-btn" onclick="stopListening()" style="display: none; padding: 10px 20px; background: linear-gradient(135deg, #ef4444, #dc2626); border: 1px solid rgba(239, 68, 68, 0.5); color: white; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 14px; align-items: center; gap: 8px; transition: all 0.2s; flex: 1; min-width: 140px; justify-content: center;" onmouseover="this.style.transform='translateY(-1px)'" onmouseout="this.style.transform='translateY(0)'">
                <svg viewBox="0 0 24 24" style="width: 16px; height: 16px; fill: currentColor;">
                    <rect x="6" y="6" width="12" height="12"/>
                </svg>
                <span><?= htmlspecialchars($messages['zalo_messages_stop_listening'] ?? 'Dừng lắng nghe', ENT_QUOTES, 'UTF-8') ?></span>
            </button>
            <button onclick="clearMessages()" style="padding: 10px 16px; background: rgba(122, 220, 201, 0.15); border: 1px solid rgba(122, 220, 201, 0.3); color: #7adcc9; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 13px; transition: all 0.2s; flex: 1; min-width: 100px; display: flex; align-items: center; justify-content: center; gap: 6px;" onmouseover="this.style.background='rgba(122, 220, 201, 0.25)'" onmouseout="this.style.background='rgba(122, 220, 201, 0.15)'">
                <svg viewBox="0 0 24 24" style="width: 14px; height: 14px; fill: currentColor;">
                    <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                </svg>
                <span><?= htmlspecialchars($messages['zalo_messages_clear_log'] ?? 'Xóa log', ENT_QUOTES, 'UTF-8') ?></span>
            </button>
            <div id="listening-status" style="width: 100%; color: rgba(232, 251, 246, 0.6); font-size: 13px; display: flex; align-items: center; justify-content: center; gap: 8px; padding: 8px; background: rgba(3, 12, 16, 0.4); border-radius: 6px; margin-top: 4px;">
                <span id="status-text"><?= htmlspecialchars($messages['zalo_messages_status_not_started'] ?? 'Chưa bắt đầu', ENT_QUOTES, 'UTF-8') ?></span>
                <span id="wait-time" style="color: rgba(232, 251, 246, 0.4); font-size: 12px;"></span>
            </div>
        </div>
        
        <!-- Messages Container -->
        <div id="messages-container" style="flex: 1; padding: 20px 24px; overflow-y: auto; background: rgba(3, 12, 16, 0.2); font-family: 'Courier New', monospace; font-size: 13px; line-height: 1.6; color: #e8fbf6;">
            <div style="color: rgba(232, 251, 246, 0.5); text-align: center; padding: 40px 20px;">
                <svg viewBox="0 0 24 24" style="width: 48px; height: 48px; fill: rgba(122, 220, 201, 0.3); margin: 0 auto 12px;">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                </svg>
                <p><?= htmlspecialchars($messages['zalo_messages_empty_state'] ?? 'Nhấn "Bắt đầu lắng nghe" để nhận tin nhắn từ Zalo Bot', ENT_QUOTES, 'UTF-8') ?></p>
            </div>
        </div>
        
    </div>
</div>

<script>
// Messages Modal Functions - v2.0 (Display all messages)
// Multilingual messages
const zaloMessages = {
    modalTitle: <?= json_encode($messages['zalo_messages_modal_title'] ?? 'Nhận tin nhắn') ?>,
    startListening: <?= json_encode($messages['zalo_messages_start_listening'] ?? 'Bắt đầu lắng nghe') ?>,
    stopListening: <?= json_encode($messages['zalo_messages_stop_listening'] ?? 'Dừng lắng nghe') ?>,
    statusListening: <?= json_encode($messages['zalo_messages_status_listening'] ?? 'Đang lắng nghe...') ?>,
    statusNotStarted: <?= json_encode($messages['zalo_messages_status_not_started'] ?? 'Chưa bắt đầu') ?>,
    statusStopped: <?= json_encode($messages['zalo_messages_status_stopped'] ?? 'Đã dừng') ?>,
    copyId: <?= json_encode($messages['zalo_messages_copy_id'] ?? 'Copy ID') ?>,
    copied: <?= json_encode($messages['zalo_messages_copied'] ?? 'Copied!') ?>,
    copyFailed: <?= json_encode($messages['zalo_messages_copy_failed'] ?? 'Failed') ?>,
    botLabel: <?= json_encode($messages['zalo_messages_bot_label'] ?? 'Bot:') ?>,
    emptyState: <?= json_encode($messages['zalo_messages_empty_state'] ?? 'Nhấn "Bắt đầu lắng nghe" để nhận tin nhắn từ Zalo Bot') ?>
};

let currentBotId = null;
let currentBotToken = null;
let currentBotName = null;
let isListening = false;
let messageOffset = 0;
let waitTimeInterval = null;
let requestStartTime = null;

function openMessagesModal(botId, token, botName) {
    currentBotId = botId;
    currentBotToken = token;
    currentBotName = botName;
    messageOffset = 0;
    
    const modal = document.getElementById('messages-modal');
    const botNameElement = document.getElementById('messages-modal-bot-name');
    
    botNameElement.textContent = zaloMessages.botLabel + ' ' + botName + ' (ID: ' + botId + ')';
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // Reset state
    stopListening();
    clearMessages();
}

function closeMessagesModal() {
    const modal = document.getElementById('messages-modal');
    stopListening();
    stopWaitTimeCounter();
    modal.style.display = 'none';
    document.body.style.overflow = '';
    
    currentBotId = null;
    currentBotToken = null;
    currentBotName = null;
}

function startListening() {
    if (isListening) return;
    
    isListening = true;
    document.getElementById('start-listening-btn').style.display = 'none';
    document.getElementById('stop-listening-btn').style.display = 'flex';
    
    updateStatus(zaloMessages.statusListening, true);
    appendMessage('INFO', '🚀 Bắt đầu lắng nghe tin nhắn từ Bot ID: ' + currentBotId);
    appendMessage('INFO', '⏳ Đang chờ tin nhắn mới (Long Polling)...');
    
    // Start long polling
    fetchMessagesLongPoll();
}

function stopListening() {
    if (!isListening) return;
    
    isListening = false;
    stopWaitTimeCounter();
    
    document.getElementById('start-listening-btn').style.display = 'flex';
    document.getElementById('stop-listening-btn').style.display = 'none';
    
    updateStatus(zaloMessages.statusStopped, false);
    appendMessage('INFO', '⏸️ Đã dừng lắng nghe');
}

function updateStatus(text, isActive) {
    const statusText = document.getElementById('status-text');
    statusText.textContent = text;
    
    if (isActive) {
        statusText.style.color = '#22c55e';
        statusText.innerHTML = '<span style="display: inline-block; width: 8px; height: 8px; background: #22c55e; border-radius: 50%; margin-right: 8px; animation: pulse 1.5s infinite;"></span>' + text;
    } else {
        statusText.style.color = 'rgba(232, 251, 246, 0.6)';
    }
}

async function fetchMessagesLongPoll() {
    if (!isListening || !currentBotToken) return;
    
    // Use PHP proxy to bypass CORS
    const apiUrl = `modules/zalo_proxy.php?token=${encodeURIComponent(currentBotToken)}`;
    
    try {
        requestStartTime = new Date();
        
        // Only show technical logs if JSON toggle is enabled
        const showJsonToggle = document.getElementById('show-json-toggle');
        if (showJsonToggle && showJsonToggle.checked) {
            appendMessage('REQUEST', '📡 Gọi API Long Polling qua Proxy...');
            appendMessage('INFO', '⏳ Đang chờ tin nhắn mới từ người dùng...');
        }
        
        // Start wait time counter
        startWaitTimeCounter();
        
        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        // Stop wait time counter
        stopWaitTimeCounter();
        
        // Check if still listening after response (user might have stopped)
        if (!isListening) {
            appendMessage('INFO', '⏹️ Đã hủy request do dừng lắng nghe');
            return;
        }
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = await response.json();
        const endTime = new Date();
        const waitTime = ((endTime - requestStartTime) / 1000).toFixed(1);
        
        
        // Show raw JSON and technical logs if toggle is enabled
        if (showJsonToggle && showJsonToggle.checked) {
            appendMessage('RESPONSE', `✅ Nhận được phản hồi sau ${waitTime}s`);
            appendMessage('JSON', JSON.stringify(data, null, 2));
        }
        
        // Process messages if available
        if (data.ok && data.result) {
            // Handle both Array (multiple messages) and Object (single message)
            let messages = [];
            
            if (Array.isArray(data.result)) {
                messages = data.result;
            } else if (data.result.message) {
                messages = [data.result];
            }
            
            if (messages.length > 0) {
                messages.forEach((msg) => {
                    // Get message data (handle both formats)
                    const messageData = msg.message || msg;
                    
                    if (messageData && messageData.from) {
                        const from = messageData.from || {};
                        const text = messageData.text || '[Không có nội dung]';
                        
                        // Format time properly
                        let msgTime = '';
                        if (messageData.date) {
                            // Check if date is in seconds (< year 3000 timestamp) or milliseconds
                            const timestamp = messageData.date < 10000000000 ? messageData.date * 1000 : messageData.date;
                            const msgDate = new Date(timestamp);
                            
                            // Format: HH:mm:ss DD/MM/YYYY
                            msgTime = msgDate.toLocaleString('vi-VN', {
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit',
                                day: '2-digit',
                                month: '2-digit',
                                year: 'numeric'
                            });
                        } else {
                            msgTime = new Date().toLocaleString('vi-VN', {
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit',
                                day: '2-digit',
                                month: '2-digit',
                                year: 'numeric'
                            });
                        }
                        
                        // Display simple message card
                        appendSimpleMessage({
                            displayName: from.display_name || 'Unknown',
                            userId: from.id || 'N/A',
                            content: text,
                            time: msgTime
                        });
                    }
                });
            }
        }
        
        // Continue long polling if still listening
        if (isListening) {
            // Add small delay to prevent overwhelming
            setTimeout(() => fetchMessagesLongPoll(), 500);
        }
        
    } catch (error) {
        stopWaitTimeCounter();
        appendMessage('ERROR', '❌ Lỗi: ' + error.message);
        console.error('Fetch error:', error);
        
        // Retry after error if still listening
        if (isListening) {
            appendMessage('INFO', '🔄 Thử lại sau 3 giây...');
            setTimeout(() => fetchMessagesLongPoll(), 3000);
        }
    }
}

function startWaitTimeCounter() {
    stopWaitTimeCounter(); // Clear any existing interval
    
    const waitTimeElement = document.getElementById('wait-time');
    waitTimeInterval = setInterval(() => {
        if (requestStartTime) {
            const elapsed = Math.floor((new Date() - requestStartTime) / 1000);
            const minutes = Math.floor(elapsed / 60);
            const seconds = elapsed % 60;
            waitTimeElement.textContent = `(${minutes}:${seconds.toString().padStart(2, '0')})`;
        }
    }, 1000);
}

function stopWaitTimeCounter() {
    if (waitTimeInterval) {
        clearInterval(waitTimeInterval);
        waitTimeInterval = null;
    }
    const waitTimeElement = document.getElementById('wait-time');
    if (waitTimeElement) {
        waitTimeElement.textContent = '';
    }
    requestStartTime = null;
}

function appendSimpleMessage(data) {
    const container = document.getElementById('messages-container');
    
    // Remove empty state on first message
    if (container.querySelector('div[style*="text-align: center"]')) {
        container.innerHTML = '';
    }
    
    const messageCard = document.createElement('div');
    messageCard.style.marginBottom = '16px';
    messageCard.style.background = 'linear-gradient(135deg, rgba(122, 220, 201, 0.1), rgba(100, 167, 166, 0.08))';
    messageCard.style.border = '1px solid rgba(122, 220, 201, 0.25)';
    messageCard.style.borderRadius = '10px';
    messageCard.style.padding = '16px';
    messageCard.style.transition = 'all 0.2s';
    
    // Add hover effect
    messageCard.addEventListener('mouseenter', function() {
        this.style.background = 'linear-gradient(135deg, rgba(122, 220, 201, 0.15), rgba(100, 167, 166, 0.12))';
        this.style.borderColor = 'rgba(122, 220, 201, 0.4)';
        this.style.transform = 'translateX(4px)';
    });
    
    messageCard.addEventListener('mouseleave', function() {
        this.style.background = 'linear-gradient(135deg, rgba(122, 220, 201, 0.1), rgba(100, 167, 166, 0.08))';
        this.style.borderColor = 'rgba(122, 220, 201, 0.25)';
        this.style.transform = 'translateX(0)';
    });
    
    messageCard.innerHTML = `
        <div style="display: flex; flex-direction: column; gap: 12px;">
            <!-- Row 1: Avatar + Info -->
            <div style="display: flex; gap: 12px; align-items: flex-start;">
                <!-- Column 1: Avatar + Copy ID Button -->
                <div style="display: flex; flex-direction: column; gap: 6px; align-items: center; flex-shrink: 0;">
                    <div style="width: 44px; height: 44px; background: linear-gradient(135deg, #7adcc9, #4a9e95); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; color: white; font-size: 16px; box-shadow: 0 2px 6px rgba(122, 220, 201, 0.3);">
                        ${data.displayName.charAt(0).toUpperCase()}
                    </div>
                    <button onclick="copyToClipboard('${escapeHtml(data.userId)}', this)" title="${zaloMessages.copyId}" style="background: rgba(122, 220, 201, 0.15); border: 1px solid rgba(122, 220, 201, 0.3); color: #7adcc9; padding: 3px 6px; border-radius: 4px; font-size: 9px; font-weight: 600; cursor: pointer; transition: all 0.2s; white-space: nowrap;" onmouseover="this.style.background='rgba(122, 220, 201, 0.25)'" onmouseout="this.style.background='rgba(122, 220, 201, 0.15)'">
                        📋 ${zaloMessages.copyId}
                    </button>
                </div>
                
                <!-- Column 2: Name + ID + Time -->
                <div style="display: flex; flex-direction: column; gap: 3px; flex: 1; min-width: 0;">
                    <div style="color: #7adcc9; font-weight: 700; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                        ${escapeHtml(data.displayName)}
                    </div>
                    <div style="color: rgba(232, 251, 246, 0.5); font-size: 10px; font-family: 'Courier New', monospace; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                        ${escapeHtml(data.userId)}
                    </div>
                    <div style="display: flex; align-items: center; gap: 4px; color: rgba(232, 251, 246, 0.4); font-size: 10px; font-style: italic;">
                        <svg viewBox="0 0 24 24" style="width: 11px; height: 11px; fill: currentColor; opacity: 0.7;">
                            <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
                        </svg>
                        <span>${data.time}</span>
                    </div>
                </div>
            </div>
            
            <!-- Row 2: Content Box (Full Width) -->
            <div style="background: linear-gradient(135deg, rgba(3, 12, 16, 0.4), rgba(3, 12, 16, 0.2)); padding: 12px 14px; border-radius: 8px; border-left: 4px solid #93c5fd; box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);">
                <div style="color: #e8fbf6; font-size: 13px; line-height: 1.6; word-wrap: break-word; word-break: break-word;">
                    ${escapeHtml(data.content)}
                </div>
            </div>
        </div>
    `;
    
    container.appendChild(messageCard);
    container.scrollTop = container.scrollHeight;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function copyToClipboard(text, button) {
    // Use Clipboard API
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
            // Change button text temporarily
            const originalText = button.innerHTML;
            button.innerHTML = '✓ ' + zaloMessages.copied;
            button.style.background = 'rgba(34, 197, 94, 0.2)';
            button.style.borderColor = 'rgba(34, 197, 94, 0.4)';
            button.style.color = '#22c55e';
            
            // Reset after 2 seconds
            setTimeout(() => {
                button.innerHTML = originalText;
                button.style.background = 'rgba(122, 220, 201, 0.15)';
                button.style.borderColor = 'rgba(122, 220, 201, 0.3)';
                button.style.color = '#7adcc9';
            }, 2000);
        }).catch(err => {
            console.error('Failed to copy:', err);
            button.innerHTML = '✗ ' + zaloMessages.copyFailed;
            button.style.color = '#f87171';
            setTimeout(() => {
                button.innerHTML = '📋 ' + zaloMessages.copyId;
                button.style.color = '#7adcc9';
            }, 2000);
        });
    } else {
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        document.body.appendChild(textArea);
        textArea.select();
        
        try {
            document.execCommand('copy');
            button.innerHTML = '✓ ' + zaloMessages.copied;
            button.style.background = 'rgba(34, 197, 94, 0.2)';
            button.style.color = '#22c55e';
            
            setTimeout(() => {
                button.innerHTML = '📋 ' + zaloMessages.copyId;
                button.style.background = 'rgba(122, 220, 201, 0.15)';
                button.style.color = '#7adcc9';
            }, 2000);
        } catch (err) {
            console.error('Fallback copy failed:', err);
            button.innerHTML = '✗ ' + zaloMessages.copyFailed;
            button.style.color = '#f87171';
            setTimeout(() => {
                button.innerHTML = '📋 ' + zaloMessages.copyId;
                button.style.color = '#7adcc9';
            }, 2000);
        }
        
        document.body.removeChild(textArea);
    }
}

function appendMessage(type, message) {
    const container = document.getElementById('messages-container');
    
    // Remove empty state on first message
    if (container.querySelector('div[style*="text-align: center"]')) {
        container.innerHTML = '';
    }
    
    const timestamp = new Date().toLocaleTimeString('vi-VN');
    const messageDiv = document.createElement('div');
    messageDiv.style.marginBottom = '12px';
    messageDiv.style.paddingBottom = '12px';
    messageDiv.style.borderBottom = '1px solid rgba(122, 220, 201, 0.1)';
    
    let color = '#e8fbf6';
    let prefix = '';
    
    switch(type) {
        case 'INFO':
            color = '#93c5fd';
            prefix = 'ℹ️ ';
            break;
        case 'SUCCESS':
            color = '#4ade80';
            prefix = '✅ ';
            break;
        case 'ERROR':
            color = '#f87171';
            prefix = '❌ ';
            break;
        case 'REQUEST':
            color = '#fbbf24';
            prefix = '📡 ';
            break;
        case 'RESPONSE':
            color = '#7adcc9';
            prefix = '📥 ';
            break;
        case 'MESSAGE':
            color = '#a78bfa';
            prefix = '💬 ';
            break;
        case 'JSON':
            messageDiv.style.marginBottom = '16px';
            messageDiv.innerHTML = `
                <div style="color: rgba(232, 251, 246, 0.5); font-size: 11px; margin-bottom: 6px; font-weight: 600;">📄 RAW JSON RESPONSE:</div>
                <pre style="background: rgba(3, 12, 16, 0.5); padding: 12px; border-radius: 6px; border-left: 3px solid #7adcc9; overflow-x: auto; margin: 0; color: #e8fbf6; white-space: pre-wrap; word-wrap: break-word; font-size: 12px; line-height: 1.5;">${message}</pre>
            `;
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
            return;
        case 'MESSAGE_HEADER':
            messageDiv.style.borderBottom = 'none';
            messageDiv.style.marginBottom = '8px';
            messageDiv.style.paddingBottom = '0';
            messageDiv.innerHTML = `
                <div style="background: linear-gradient(135deg, rgba(122, 220, 201, 0.2), rgba(100, 167, 166, 0.15)); padding: 8px 12px; border-radius: 6px; border-left: 3px solid #7adcc9;">
                    <div style="color: #7adcc9; font-weight: 700; font-size: 14px;">${message}</div>
                </div>
            `;
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
            return;
        case 'MESSAGE_INFO':
            messageDiv.style.borderBottom = 'none';
            messageDiv.style.marginBottom = '4px';
            messageDiv.style.paddingBottom = '0';
            messageDiv.innerHTML = `
                <div style="color: rgba(232, 251, 246, 0.8); font-size: 13px; padding-left: 12px;">${message}</div>
            `;
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
            return;
        case 'MESSAGE_CONTENT':
            messageDiv.style.borderBottom = 'none';
            messageDiv.style.marginBottom = '8px';
            messageDiv.style.paddingBottom = '0';
            messageDiv.innerHTML = `
                <div style="background: rgba(147, 197, 253, 0.15); padding: 10px 12px; border-radius: 6px; margin: 8px 0 8px 12px; border-left: 3px solid #93c5fd;">
                    <div style="color: #e8fbf6; font-size: 14px; font-weight: 600; white-space: pre-wrap; word-wrap: break-word;">${message}</div>
                </div>
            `;
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
            return;
        case 'DIVIDER':
            messageDiv.style.borderBottom = 'none';
            messageDiv.style.marginBottom = '12px';
            messageDiv.style.paddingBottom = '0';
            messageDiv.innerHTML = `
                <div style="color: rgba(122, 220, 201, 0.3); font-size: 12px; letter-spacing: 2px;">${message}</div>
            `;
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
            return;
    }
    
    messageDiv.innerHTML = `
        <div style="color: rgba(232, 251, 246, 0.5); font-size: 11px; margin-bottom: 4px;">[${timestamp}]</div>
        <div style="color: ${color}; white-space: pre-wrap; word-wrap: break-word;">${prefix}${message}</div>
    `;
    
    container.appendChild(messageDiv);
    container.scrollTop = container.scrollHeight;
}

function clearMessages() {
    const container = document.getElementById('messages-container');
    container.innerHTML = `
        <div style="color: rgba(232, 251, 246, 0.5); text-align: center; padding: 40px 20px;">
            <svg viewBox="0 0 24 24" style="width: 48px; height: 48px; fill: rgba(122, 220, 201, 0.3); margin: 0 auto 12px;">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
            </svg>
            <p>${zaloMessages.emptyState}</p>
        </div>
    `;
}

// Add CSS for pulse animation
const style = document.createElement('style');
style.textContent = `
    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
    }
`;
document.head.appendChild(style);
</script>

<style>
/* Mobile Responsive Styles for Zalo Bot Management */
@media (max-width: 768px) {
    #zalo-stats-grid {
        grid-template-columns: repeat(2, 1fr) !important;
        gap: 10px !important;
        width: 100% !important;
        max-width: 100% !important;
        margin-bottom: 12px !important;
        box-sizing: border-box !important;
    }
    
    .zalo-stat-card {
        padding: 16px !important;
        box-sizing: border-box !important;
    }
    
    .zalo-stat-card .stat-icon {
        width: 40px !important;
        height: 40px !important;
    }
    
    .zalo-stat-card .stat-icon svg {
        width: 24px !important;
        height: 24px !important;
    }
    
    .zalo-stat-card > div {
        gap: 12px !important;
    }
    
    .zalo-stat-card .stat-value {
        font-size: 24px !important;
    }
    
    .zalo-stat-card > div > div:last-child > div:first-child {
        font-size: 12px !important;
    }
}
</style>
