<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($title ?? 'Chat List') ?> - SistemKOS</title>

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        /* Chat List Specific Styles */
        .chat-list-container {
            min-height: calc(100vh - 100px);
        }
        
        .chat-user-card {
            cursor: pointer;
            transition: all 0.3s;
            border-left: 4px solid transparent;
            margin-bottom: 12px;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .chat-user-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border-left-color: #4a90e2;
            background-color: #f8fafc;
        }
        
        .chat-user-card.active {
            background: #e8f4ff;
            border-left-color: #4a90e2;
            box-shadow: 0 3px 10px rgba(74, 144, 226, 0.15);
        }
        
        .user-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            font-weight: bold;
            flex-shrink: 0;
            border: 3px solid white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .user-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .unread-badge {
            min-width: 22px;
            height: 22px;
            border-radius: 11px;
            background: #dc3545;
            color: white;
            font-size: 12px;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 6px;
            position: absolute;
            top: -5px;
            right: -5px;
            z-index: 2;
            animation: badgePulse 2s infinite;
            border: 2px solid white;
        }
        
        .last-message {
            font-size: 13px;
            color: #6c757d;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .time-ago {
            font-size: 12px;
            color: #adb5bd;
            white-space: nowrap;
            flex-shrink: 0;
        }
        
        .online-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #28a745;
            position: absolute;
            bottom: 2px;
            right: 2px;
            border: 2px solid white;
            z-index: 1;
            animation: pulse 2s infinite;
        }
        
        .search-box {
            margin-bottom: 20px;
            position: relative;
        }
        
        .search-input {
            padding-left: 45px;
            border-radius: 25px;
            border: 2px solid #e2e8f0;
            transition: all 0.3s;
        }
        
        .search-input:focus {
            border-color: #4a90e2;
            box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
        }
        
        .search-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            z-index: 10;
        }
        
        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: #6c757d;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
            color: #4a90e2;
        }
        
        .user-info-row {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
            min-width: 0;
            padding: 15px;
        }
        
        .user-details {
            flex: 1;
            min-width: 0;
        }
        
        .user-name {
            font-weight: 600;
            margin-bottom: 2px;
            color: #2c3e50;
            font-size: 15px;
        }
        
        .user-room {
            font-size: 13px;
            color: #6c757d;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .user-room i {
            font-size: 12px;
        }
        
        .card-header {
            background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
            padding: 20px;
        }
        
        .card-header h5 {
            margin: 0;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
            background: white;
        }
        
        .status-badge.online {
            background: #d4edda;
            color: #155724;
        }
        
        .status-badge.offline {
            background: #f8d7da;
            color: #721c24;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            vertical-align: -0.125em;
            border: 0.2em solid currentColor;
            border-right-color: transparent;
            border-radius: 50%;
            animation: spinner-border 0.75s linear infinite;
        }
        
        .ws-status {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 10px 16px;
            border-radius: 25px;
            font-size: 13px;
            font-weight: 500;
            z-index: 1000;
            box-shadow: 0 3px 15px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 8px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
        }
        
        .ws-status.connected {
            background: rgba(212, 237, 218, 0.9);
            color: #155724;
        }
        
        .ws-status.disconnected {
            background: rgba(248, 215, 218, 0.9);
            color: #721c24;
        }
        
        .ws-status.connecting {
            background: rgba(255, 243, 205, 0.9);
            color: #856404;
        }
        
        .ws-status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
        }
        
        .ws-status.connected .ws-status-dot {
            background: #28a745;
            animation: pulse 2s infinite;
        }
        
        .ws-status.disconnected .ws-status-dot {
            background: #dc3545;
        }
        
        .ws-status.connecting .ws-status-dot {
            background: #ffc107;
            animation: pulse 1s infinite;
        }
        
        @keyframes spinner-border {
            to { transform: rotate(360deg); }
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        @keyframes badgePulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }
        
        @keyframes newMessageHighlight {
            0% { background-color: rgba(255, 255, 0, 0.2); }
            100% { background-color: transparent; }
        }
        
        .new-message {
            animation: newMessageHighlight 2s ease-out;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .chat-user-card {
                margin-bottom: 8px;
            }
            
            .user-info-row {
                padding: 12px;
            }
            
            .empty-state {
                padding: 60px 15px;
            }
            
            .empty-state i {
                font-size: 48px;
            }
        }
        
        /* Scrollbar */
        .conversation-list-container {
            max-height: 600px;
            overflow-y: auto;
        }
        
        .conversation-list-container::-webkit-scrollbar {
            width: 6px;
        }
        
        .conversation-list-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        
        .conversation-list-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        
        .conversation-list-container::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }
        
        /* Chat Stats */
        .chat-stats {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border: 1px solid #e2e8f0;
        }
        
        .stat-item {
            text-align: center;
            padding: 15px;
        }
        
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #4a90e2;
            margin-bottom: 5px;
        }
        
        .stat-label {
            font-size: 13px;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        /* Quick Actions */
        .quick-actions {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .btn-quick-action {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 15px;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            color: #4a90e2;
            text-decoration: none;
            transition: all 0.3s;
        }
        
        .btn-quick-action:hover {
            background: #f8fafc;
            border-color: #4a90e2;
            transform: translateY(-2px);
        }
        
        .btn-quick-action i {
            font-size: 24px;
            margin-bottom: 8px;
        }
        
        .btn-quick-action span {
            font-size: 12px;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <!-- Audio for notifications -->
    <audio id="notificationSound" preload="auto" style="display: none;">
        <source src="<?= base_url('asset/sounds/notification.mp3') ?>" type="audio/mpeg">
    </audio>
    
    <!-- WebSocket Status Indicator -->
    <div id="wsStatus" class="ws-status disconnected" style="display: none;">
        <span class="ws-status-dot"></span>
        <span id="wsStatusText">Disconnected</span>
    </div>
    
    <!-- Toast Container -->
    <div id="toastContainer" class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1050;"></div>
    
    <!-- Top Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container-fluid">
            <a class="navbar-brand" href="<?= site_url('admin/dashboard') ?>">
                <i class="fas fa-arrow-left me-2"></i>Kembali ke Dashboard
            </a>
            <span class="navbar-text">
                <i class="fas fa-comments me-2"></i>Daftar Chat
                <small class="ms-2 badge bg-danger" id="unreadTotal" style="display: none;"></small>
            </span>
            <div class="d-flex align-items-center">
                <a href="<?= site_url('admin/chat') ?>" class="btn btn-outline-light btn-sm">
                    <i class="fas fa-comment-dots me-1"></i>Chat Baru
                </a>
            </div>
        </div>
    </nav>
    
    <div class="container-fluid chat-list-container">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <!-- Chat Stats -->
                <div class="chat-stats">
                    <div class="row text-center">
                        <div class="col-md-3 col-6">
                            <div class="stat-item">
                                <div class="stat-number" id="totalConversations"><?= count($chat_sessions ?? []) ?></div>
                                <div class="stat-label">Total Chat</div>
                            </div>
                        </div>
                        <div class="col-md-3 col-6">
                            <div class="stat-item">
                                <div class="stat-number" id="unreadMessages">0</div>
                                <div class="stat-label">Belum Dibaca</div>
                            </div>
                        </div>
                        <div class="col-md-3 col-6">
                            <div class="stat-item">
                                <div class="stat-number" id="onlineUsers">0</div>
                                <div class="stat-label">Online</div>
                            </div>
                        </div>
                        <div class="col-md-3 col-6">
                            <div class="stat-item">
                                <div class="stat-number" id="totalMessages">0</div>
                                <div class="stat-label">Total Pesan</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Actions -->
                <div class="quick-actions">
                    <a href="javascript:void(0)" class="btn-quick-action" onclick="refreshChatList()">
                        <i class="fas fa-redo"></i>
                        <span>Refresh</span>
                    </a>
                    <a href="javascript:void(0)" class="btn-quick-action" onclick="markAllAsRead()">
                        <i class="fas fa-check-double"></i>
                        <span>Tandai Semua Dibaca</span>
                    </a>
                    <a href="<?= site_url('admin/penghuni') ?>" class="btn-quick-action">
                        <i class="fas fa-users"></i>
                        <span>Daftar Penghuni</span>
                    </a>
                    <a href="javascript:void(0)" class="btn-quick-action" onclick="testWebSocket()">
                        <i class="fas fa-wifi"></i>
                        <span>Test Koneksi</span>
                    </a>
                </div>
                
                <!-- Search Box -->
                <div class="search-box">
                    <i class="fas fa-search search-icon"></i>
                    <input type="text" 
                           class="form-control form-control-lg search-input" 
                           id="searchInput" 
                           placeholder="Cari penghuni berdasarkan nama, kamar, atau email...">
                    <div class="mt-2 d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <span id="filteredCount"><?= count($chat_sessions ?? []) ?></span> dari 
                            <span id="totalCount"><?= count($chat_sessions ?? []) ?></span> percakapan
                        </small>
                        <button class="btn btn-sm btn-outline-primary" id="clearSearch" style="display: none;">
                            <i class="fas fa-times me-1"></i>Clear
                        </button>
                    </div>
                </div>
                
                <!-- Chat List -->
                <div class="card border-0 shadow-sm">
                    <div class="card-header border-0">
                        <h5 class="mb-0">
                            <i class="fas fa-users me-2"></i>Daftar Percakapan
                        </h5>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="conversation-list-container">
                            <div id="chatList">
                                <?php if (!empty($chat_sessions)): ?>
                                    <?php foreach ($chat_sessions as $session): ?>
                                        <?php 
                                        $lastMessage = $session->last_message ?? '';
                                        $lastMessageTime = $session->last_message_time ?? $session->last_message_at ?? null;
                                        $timeAgo = '';
                                        
                                        if ($lastMessageTime) {
                                            $timestamp = strtotime($lastMessageTime);
                                            if ($timestamp) {
                                                $diff = time() - $timestamp;
                                                
                                                if ($diff < 60) {
                                                    $timeAgo = 'Baru saja';
                                                } elseif ($diff < 3600) {
                                                    $minutes = floor($diff / 60);
                                                    $timeAgo = $minutes . ' menit lalu';
                                                } elseif ($diff < 86400) {
                                                    $hours = floor($diff / 3600);
                                                    $timeAgo = $hours . ' jam lalu';
                                                } elseif ($diff < 604800) {
                                                    $days = floor($diff / 86400);
                                                    $timeAgo = $days . ' hari lalu';
                                                } else {
                                                    $timeAgo = date('d M Y', $timestamp);
                                                }
                                            }
                                        }
                                        
                                        $unreadCount = $session->unread_count_admin ?? 0;
                                        $isOnline = $session->is_online ?? false;
                                        $userInitial = strtoupper(substr($session->nama_penghuni ?? '?', 0, 1));
                                        ?>
                                        
                                        <div class="card chat-user-card" 
                                             data-user-id="<?= $session->id_penghuni ?? '' ?>"
                                             data-user-name="<?= htmlspecialchars($session->nama_penghuni ?? '') ?>"
                                             data-unread-count="<?= $unreadCount ?>"
                                             onclick="openChat(<?= $session->id_penghuni ?? 'null' ?>)">
                                            
                                            <?php if ($unreadCount > 0): ?>
                                                <div class="unread-badge" data-user-id="<?= $session->id_penghuni ?? '' ?>">
                                                    <?= $unreadCount > 9 ? '9+' : $unreadCount ?>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <div class="user-info-row">
                                                <div class="position-relative">
                                                    <div class="user-avatar">
                                                        <?php if (isset($session->foto) && !empty($session->foto)): ?>
                                                            <img src="<?= htmlspecialchars($session->foto) ?>" alt="<?= htmlspecialchars($session->nama_penghuni ?? '') ?>">
                                                        <?php else: ?>
                                                            <?= htmlspecialchars($userInitial) ?>
                                                        <?php endif; ?>
                                                    </div>
                                                    <?php if ($isOnline): ?>
                                                        <span class="online-indicator" data-user-id="<?= $session->id_penghuni ?? '' ?>"></span>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <div class="user-details">
                                                    <div class="d-flex justify-content-between align-items-start mb-1">
                                                        <div class="d-flex align-items-center">
                                                            <h6 class="user-name mb-0">
                                                                <?= htmlspecialchars($session->nama_penghuni ?? 'Unknown') ?>
                                                            </h6>
                                                            <?php if ($isOnline): ?>
                                                                <span class="status-badge online ms-2" data-user-id="<?= $session->id_penghuni ?? '' ?>">
                                                                    <i class="fas fa-circle" style="font-size: 8px;"></i>
                                                                    Online
                                                                </span>
                                                            <?php else: ?>
                                                                <span class="status-badge offline ms-2" data-user-id="<?= $session->id_penghuni ?? '' ?>">
                                                                    <i class="fas fa-circle" style="font-size: 8px;"></i>
                                                                    Offline
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <?php if ($timeAgo): ?>
                                                            <div class="time-ago" data-user-id="<?= $session->id_penghuni ?? '' ?>">
                                                                <?= htmlspecialchars($timeAgo) ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                    <p class="user-room mb-2">
                                                        <i class="fas fa-door-open"></i>
                                                        Kamar <?= htmlspecialchars($session->kamar ?? 'N/A') ?>
                                                    </p>
                                                    
                                                    <?php if ($lastMessage): ?>
                                                        <p class="last-message mb-0" data-user-id="<?= $session->id_penghuni ?? '' ?>">
                                                            <?php 
                                                            $trimmedMessage = htmlspecialchars($lastMessage);
                                                            echo strlen($trimmedMessage) > 100 ? 
                                                                substr($trimmedMessage, 0, 100) . '...' : 
                                                                $trimmedMessage;
                                                            ?>
                                                        </p>
                                                    <?php else: ?>
                                                        <p class="last-message mb-0 text-muted fst-italic" data-user-id="<?= $session->id_penghuni ?? '' ?>">
                                                            Belum ada pesan
                                                        </p>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="empty-state">
                                        <i class="fas fa-comments"></i>
                                        <h5 class="mb-3">Belum ada percakapan</h5>
                                        <p class="text-muted mb-4">Belum ada chat dengan penghuni kos</p>
                                        <a href="<?= site_url('admin/penghuni') ?>" class="btn btn-primary">
                                            <i class="fas fa-users me-2"></i>Lihat Daftar Penghuni
                                        </a>
                                        <p class="mt-3 text-muted small">
                                            <i class="fas fa-info-circle me-1"></i>
                                            Penghuni akan muncul di sini setelah mengirim pesan pertama
                                        </p>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Loading indicator -->
                            <div id="loadingIndicator" class="text-center py-5" style="display: none;">
                                <div class="loading-spinner text-primary"></div>
                                <p class="text-muted mt-2 mb-0">Memuat percakapan...</p>
                            </div>
                            
                            <!-- No results -->
                            <div id="noResultsMessage" class="empty-state" style="display: none;">
                                <i class="fas fa-search"></i>
                                <h5>Tidak ditemukan</h5>
                                <p class="text-muted">Tidak ada penghuni yang cocok dengan pencarian</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Footer Info -->
                <div class="mt-4 text-center text-muted small">
                    <p class="mb-0">
                        <i class="fas fa-info-circle me-1"></i>
                        Sistem Chat Real-time - Klik pada percakapan untuk memulai chat
                    </p>
                    <p class="mb-0">
                        Status: <span id="connectionInfo" class="badge bg-secondary">Loading...</span>
                        <span class="mx-2">•</span>
                        Terakhir diperbarui: <span id="lastUpdate"><?= date('H:i:s') ?></span>
                    </p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Configuration
    const config = {
        adminId: '<?= $this->session->userdata('admin_id') ?? 'admin' ?>',
        adminName: '<?= $this->session->userdata('admin_name') ?? 'Admin' ?>',
        wsUrl: '<?= $ws_config['ws_url'] ?? 'ws://localhost:3001' ?>',
        apiUrl: '<?= site_url('admin/chat') ?>'
    };
    
    // Global variables
    let ws = null;
    let isWsConnected = false;
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    let unreadMessages = 0;
    let onlineUsers = 0;
    
    $(document).ready(function() {
        console.log('Chat list page loaded');
        
        // Initialize
        updateStats();
        initWebSocket();
        setupEventListeners();
        
        // Request notification permission
        if ('Notification' in window && Notification.permission === 'default') {
            Notification.requestPermission();
        }
    });
    
    function initWebSocket() {
        try {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            ws = new WebSocket(`${protocol}//${config.wsUrl}`);
            
            ws.onopen = () => {
                console.log('WebSocket connected');
                isWsConnected = true;
                reconnectAttempts = 0;
                updateWsStatus('connected');
                authenticate();
            };
            
            ws.onmessage = (event) => {
                handleWebSocketMessage(event.data);
            };
            
            ws.onclose = () => {
                console.log('WebSocket disconnected');
                isWsConnected = false;
                updateWsStatus('disconnected');
                scheduleReconnect();
            };
            
            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
                updateWsStatus('disconnected');
            };
            
        } catch (error) {
            console.error('Failed to connect WebSocket:', error);
            updateWsStatus('disconnected');
        }
    }
    
    function updateWsStatus(status) {
        const wsStatus = $('#wsStatus');
        const wsStatusText = $('#wsStatusText');
        const connectionInfo = $('#connectionInfo');
        
        wsStatus.removeClass('connected disconnected connecting').addClass(status);
        
        switch (status) {
            case 'connected':
                wsStatusText.text('Connected');
                connectionInfo.removeClass('bg-secondary bg-danger').addClass('bg-success').text('Online');
                break;
            case 'disconnected':
                wsStatusText.text('Disconnected');
                connectionInfo.removeClass('bg-secondary bg-success').addClass('bg-danger').text('Offline');
                break;
            case 'connecting':
                wsStatusText.text('Connecting...');
                connectionInfo.removeClass('bg-secondary bg-success bg-danger').addClass('bg-warning').text('Connecting');
                break;
        }
        
        wsStatus.fadeIn();
    }
    
    function authenticate() {
        if (!ws || ws.readyState !== WebSocket.OPEN) return;
        
        const authData = {
            type: 'auth',
            userType: 'admin',
            userId: config.adminId,
            userName: config.adminName
        };
        
        ws.send(JSON.stringify(authData));
    }
    
    function scheduleReconnect() {
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++;
            console.log(`Reconnecting in 3 seconds... (Attempt ${reconnectAttempts}/${maxReconnectAttempts})`);
            
            setTimeout(() => {
                updateWsStatus('connecting');
                initWebSocket();
            }, 3000);
        }
    }
    
    function handleWebSocketMessage(data) {
        try {
            const message = JSON.parse(data);
            
            switch (message.type) {
                case 'auth_success':
                    console.log('Authenticated successfully');
                    break;
                    
                case 'message':
                    handleNewMessage(message);
                    break;
                    
                case 'typing':
                    handleTypingIndicator(message);
                    break;
                    
                case 'online_status':
                    handleOnlineStatus(message);
                    break;
                    
                case 'message_delivered':
                    handleMessageDelivered(message);
                    break;
                    
                case 'read_receipt':
                    handleReadReceipt(message);
                    break;
                    
                case 'user_connected':
                    handleUserConnected(message);
                    break;
                    
                case 'user_disconnected':
                    handleUserDisconnected(message);
                    break;
            }
        } catch (error) {
            console.error('Error parsing WebSocket message:', error);
        }
    }
    
    function handleNewMessage(message) {
        const senderId = message.from?.id;
        const isFromAdmin = message.from?.type === 'admin';
        
        // Only process messages from penghuni
        if (!isFromAdmin && senderId) {
            // Update conversation in list
            updateConversation(senderId, {
                lastMessage: message.content,
                lastMessageTime: message.timestamp,
                incrementUnread: true
            });
            
            // Play notification sound
            playNotificationSound();
            
            // Show notification
            showNotification(
                message.from?.name || 'Penghuni',
                message.content,
                senderId
            );
            
            // Update stats
            updateStats();
        }
    }
    
    function handleTypingIndicator(message) {
        // Can show typing indicator in conversation list if needed
        console.log('Typing:', message);
    }
    
    function handleOnlineStatus(message) {
        updateConversationStatus(message.user.id, message.isOnline);
        updateStats();
    }
    
    function handleMessageDelivered(message) {
        // Update message status if needed
        console.log('Message delivered:', message);
    }
    
    function handleReadReceipt(message) {
        // Update unread count
        updateConversationUnread(message.reader.id, false);
        updateStats();
    }
    
    function handleUserConnected(message) {
        updateConversationStatus(message.user.id, true);
        onlineUsers++;
        updateStats();
    }
    
    function handleUserDisconnected(message) {
        updateConversationStatus(message.user.id, false);
        onlineUsers = Math.max(0, onlineUsers - 1);
        updateStats();
    }
    
    function updateConversation(userId, updates) {
        const conversation = $(`.chat-user-card[data-user-id="${userId}"]`);
        
        if (conversation.length) {
            // Update last message
            if (updates.lastMessage) {
                const lastMessageEl = conversation.find('.last-message');
                const messageText = updates.lastMessage.length > 100 ? 
                    updates.lastMessage.substring(0, 100) + '...' : 
                    updates.lastMessage;
                lastMessageEl.text(escapeHtml(messageText));
                
                // Update timestamp
                const timeEl = conversation.find('.time-ago');
                timeEl.text('Baru saja');
                
                // Move to top
                conversation.prependTo('#chatList');
                
                // Highlight
                conversation.addClass('new-message');
                setTimeout(() => conversation.removeClass('new-message'), 2000);
            }
            
            // Update unread count
            if (updates.incrementUnread) {
                let currentUnread = parseInt(conversation.data('unread-count') || 0);
                currentUnread++;
                conversation.data('unread-count', currentUnread);
                
                let badge = conversation.find('.unread-badge');
                if (currentUnread > 0) {
                    if (!badge.length) {
                        conversation.append(`
                            <div class="unread-badge" data-user-id="${userId}">
                                ${currentUnread > 9 ? '9+' : currentUnread}
                            </div>
                        `);
                    } else {
                        badge.text(currentUnread > 9 ? '9+' : currentUnread);
                    }
                }
            }
        }
    }
    
    function updateConversationStatus(userId, isOnline) {
        const conversation = $(`.chat-user-card[data-user-id="${userId}"]`);
        
        if (conversation.length) {
            const onlineIndicator = conversation.find('.online-indicator');
            const statusBadge = conversation.find('.status-badge');
            
            if (isOnline) {
                if (!onlineIndicator.length) {
                    conversation.find('.position-relative').append(
                        `<span class="online-indicator" data-user-id="${userId}"></span>`
                    );
                }
                if (statusBadge.length) {
                    statusBadge.removeClass('offline').addClass('online')
                        .html('<i class="fas fa-circle" style="font-size: 8px;"></i> Online');
                }
            } else {
                onlineIndicator.remove();
                if (statusBadge.length) {
                    statusBadge.removeClass('online').addClass('offline')
                        .html('<i class="fas fa-circle" style="font-size: 8px;"></i> Offline');
                }
            }
        }
    }
    
    function updateConversationUnread(userId, hasUnread) {
        const conversation = $(`.chat-user-card[data-user-id="${userId}"]`);
        
        if (conversation.length) {
            if (!hasUnread) {
                const badge = conversation.find('.unread-badge');
                if (badge.length) {
                    badge.remove();
                }
                conversation.data('unread-count', 0);
            }
        }
    }
    
    function updateStats() {
        // Calculate total unread
        let totalUnread = 0;
        let totalConversations = 0;
        
        $('.chat-user-card').each(function() {
            totalUnread += parseInt($(this).data('unread-count') || 0);
            totalConversations++;
        });
        
        // Update UI
        $('#totalConversations').text(totalConversations);
        $('#unreadMessages').text(totalUnread);
        
        const unreadTotal = $('#unreadTotal');
        if (totalUnread > 0) {
            unreadTotal.text(totalUnread > 99 ? '99+' : totalUnread).show();
        } else {
            unreadTotal.hide();
        }
        
        // Update online users count
        const onlineCount = $('.online-indicator').length;
        $('#onlineUsers').text(onlineCount);
        
        // Update total messages (simulated)
        $('#totalMessages').text(totalConversations * 3); // Simulated
        
        // Update last update time
        $('#lastUpdate').text(new Date().toLocaleTimeString('id-ID'));
    }
    
    function setupEventListeners() {
        // Search functionality
        $('#searchInput').on('input', function() {
            const searchText = $(this).val().toLowerCase().trim();
            const clearSearchBtn = $('#clearSearch');
            
            let visibleCount = 0;
            
            $('.chat-user-card').each(function() {
                const userName = $(this).find('.user-name').text().toLowerCase();
                const userRoom = $(this).find('.user-room').text().toLowerCase();
                const lastMessage = $(this).find('.last-message').text().toLowerCase();
                
                if (searchText === '' || 
                    userName.includes(searchText) || 
                    userRoom.includes(searchText) ||
                    lastMessage.includes(searchText)) {
                    $(this).show();
                    visibleCount++;
                } else {
                    $(this).hide();
                }
            });
            
            $('#filteredCount').text(visibleCount);
            
            if (searchText !== '') {
                clearSearchBtn.show();
                
                if (visibleCount === 0) {
                    $('#noResultsMessage').show();
                    $('#chatList').hide();
                } else {
                    $('#noResultsMessage').hide();
                    $('#chatList').show();
                }
            } else {
                clearSearchBtn.hide();
                $('#noResultsMessage').hide();
                $('#chatList').show();
            }
        });
        
        // Clear search
        $('#clearSearch').on('click', function() {
            $('#searchInput').val('').trigger('input');
            $(this).hide();
        });
        
        // Refresh chat list
        $('#refreshBtn').on('click', refreshChatList);
    }
    
    function refreshChatList() {
        $('#loadingIndicator').show();
        
        $.ajax({
            url: config.apiUrl + '/get_chat_list',
            method: 'GET',
            data: {
                refresh: true,
                timestamp: Date.now()
            },
            success: function(response) {
                if (response.status === 'success') {
                    // Update UI with new data
                    updateChatList(response.data);
                }
            },
            error: function() {
                showToast('Gagal memuat data', 'danger');
            },
            complete: function() {
                $('#loadingIndicator').hide();
            }
        });
    }
    
    function updateChatList(data) {
        // This would update the chat list with new data
        // For now, just update the stats
        updateStats();
        showToast('Daftar chat diperbarui', 'success');
    }
    
    function markAllAsRead() {
        $.ajax({
            url: config.apiUrl + '/mark_all_read',
            method: 'POST',
            data: {
                admin_id: config.adminId
            },
            success: function(response) {
                if (response.status === 'success') {
                    // Clear all unread badges
                    $('.unread-badge').remove();
                    $('.chat-user-card').data('unread-count', 0);
                    
                    // Update stats
                    updateStats();
                    
                    showToast('Semua pesan ditandai sebagai dibaca', 'success');
                }
            },
            error: function() {
                showToast('Gagal menandai pesan sebagai dibaca', 'danger');
            }
        });
    }
    
    function testWebSocket() {
        if (isWsConnected) {
            showToast('WebSocket terhubung dengan baik', 'success');
        } else {
            showToast('WebSocket terputus, mencoba menyambung kembali...', 'warning');
            initWebSocket();
        }
    }
    
    function playNotificationSound() {
        try {
            const audio = document.getElementById('notificationSound');
            if (audio) {
                audio.currentTime = 0;
                audio.play().catch(e => console.log('Audio play failed:', e));
            }
        } catch (error) {
            console.error('Error playing notification sound:', error);
        }
    }
    
    function showNotification(title, body, userId) {
        // Update browser tab title
        document.title = `(${unreadMessages}) ${document.title.replace(/^\(\d+\)\s*/, '')}`;
        
        // Show toast notification
        showToast(`Pesan baru dari ${title}: ${body.substring(0, 50)}...`, 'info');
        
        // Browser notification
        if ('Notification' in window && Notification.permission === 'granted') {
            const notification = new Notification(title, {
                body: body.length > 100 ? body.substring(0, 100) + '...' : body,
                icon: '<?= base_url("asset/img/favicon.png") ?>',
                tag: `chat_${userId}`
            });
            
            notification.onclick = () => {
                window.focus();
                openChat(userId);
                notification.close();
            };
            
            setTimeout(() => notification.close(), 5000);
        }
    }
    
    function showToast(message, type = 'info') {
        const toast = $(`
            <div class="toast align-items-center text-bg-${type} border-0" role="alert">
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="fas fa-${getToastIcon(type)} me-2"></i>
                        ${escapeHtml(message)}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `);
        
        $('#toastContainer').append(toast);
        const bsToast = new bootstrap.Toast(toast[0], {
            autohide: true,
            delay: 3000
        });
        bsToast.show();
        
        setTimeout(() => toast.remove(), 4000);
    }
    
    function getToastIcon(type) {
        switch (type) {
            case 'success': return 'check-circle';
            case 'danger': return 'exclamation-circle';
            case 'warning': return 'exclamation-triangle';
            default: return 'info-circle';
        }
    }
    
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // Open chat function (redirect to chat page)
    window.openChat = function(userId) {
        if (!userId) return;
        
        // Mark as read via WebSocket
        if (ws && ws.readyState === WebSocket.OPEN) {
            const readData = {
                type: 'mark_as_read',
                reader: {
                    type: 'admin',
                    id: config.adminId
                },
                userId: userId
            };
            ws.send(JSON.stringify(readData));
        }
        
        // Navigate to chat page
        window.location.href = '<?= site_url("admin/chat/") ?>' + userId;
    };
    
    // Make functions available globally
    window.refreshChatList = refreshChatList;
    window.markAllAsRead = markAllAsRead;
    window.testWebSocket = testWebSocket;
    
    // Clean up on page unload
    $(window).on('beforeunload', function() {
        if (ws) {
            ws.close();
        }
    });
    </script>
</body>
</html>