<!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') ?> - 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">

    <!-- Chat System CSS -->
    <link rel="stylesheet" href="<?= base_url('asset/css/chat_system.css') ?>">

    <style>
        /* User Chat Specific Styles */
        body {
            padding-bottom: 100px;
            /* Space for chat bubble */
        }

        /* Chat FAB (Floating Action Button) */
        .chat-fab {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
            color: white;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 15px rgba(74, 144, 226, 0.3);
            z-index: 10000;
            transition: all 0.3s;
        }

        .chat-fab:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(74, 144, 226, 0.4);
        }

        .chat-fab i {
            font-size: 24px;
        }

        .unread-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #dc3545;
            color: white;
            font-size: 12px;
            font-weight: 600;
            min-width: 20px;
            height: 20px;
            border-radius: 10px;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 0 6px;
            animation: badgePulse 2s infinite;
        }

        @keyframes badgePulse {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.1);
            }

            100% {
                transform: scale(1);
            }
        }

        /* Chat Window */
        .chat-window {
            position: fixed;
            bottom: 90px;
            right: 20px;
            width: 350px;
            height: 500px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 30px rgba(0, 0, 0, 0.15);
            z-index: 10001;
            display: none;
            flex-direction: column;
            overflow: hidden;
            border: 1px solid #e0e0e0;
        }

        .chat-window.active {
            display: flex;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .chat-header {
            padding: 15px 20px;
            background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .chat-user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            overflow: hidden;
        }

        .chat-user-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .chat-user-details h4 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: white;
        }

        .user-status {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }

        .user-status.online .status-dot {
            background: #4ade80;
            animation: pulse 2s infinite;
        }

        .user-status.offline .status-dot {
            background: #94a3b8;
        }

        .chat-actions {
            display: flex;
            gap: 8px;
        }

        .btn-minimize,
        .btn-close {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            border: none;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .btn-minimize:hover,
        .btn-close:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }

        /* Messages Container */
        .messages-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            background: #f8fafc;
        }

        .message {
            max-width: 80%;
            display: flex;
            animation: messageAppear 0.3s ease;
        }

        @keyframes messageAppear {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message-sent {
            align-self: flex-end;
        }

        .message-received {
            align-self: flex-start;
        }

        .message-content {
            padding: 10px 14px;
            border-radius: 18px;
            position: relative;
            word-wrap: break-word;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .message-sent .message-content {
            background: linear-gradient(135deg, #4a90e2, #357abd);
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message-received .message-content {
            background: white;
            color: #334155;
            border: 1px solid #e2e8f0;
            border-bottom-left-radius: 4px;
        }

        .message-text {
            font-size: 14px;
            line-height: 1.4;
        }

        .message-meta {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 6px;
            margin-top: 4px;
            font-size: 11px;
        }

        .message-sent .message-meta {
            color: rgba(255, 255, 255, 0.8);
        }

        .message-received .message-meta {
            color: #64748b;
        }

        .message-status {
            font-size: 12px;
        }

        /* Typing Indicator */
        .typing-indicator {
            padding: 0 20px 10px 20px;
            display: none;
        }

        .typing-content {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 14px;
            background: white;
            border-radius: 18px;
            border: 1px solid #e2e8f0;
            width: fit-content;
        }

        .typing-dots {
            display: flex;
            gap: 4px;
        }

        .typing-dots span {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #64748b;
            animation: typingBounce 1.4s infinite ease-in-out;
        }

        .typing-dots span:nth-child(1) {
            animation-delay: -0.32s;
        }

        .typing-dots span:nth-child(2) {
            animation-delay: -0.16s;
        }

        @keyframes typingBounce {

            0%,
            80%,
            100% {
                transform: scale(0);
            }

            40% {
                transform: scale(1);
            }
        }

        .typing-text {
            font-size: 12px;
            color: #64748b;
            font-style: italic;
        }

        /* Message Input */
        .message-input-container {
            padding: 15px 20px;
            background: white;
            border-top: 1px solid #e2e8f0;
        }

        .input-wrapper {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 20px;
            font-size: 14px;
            resize: none;
            max-height: 100px;
            min-height: 40px;
            outline: none;
            transition: border-color 0.2s;
            font-family: inherit;
            background: #f8fafc;
        }

        .message-input:focus {
            border-color: #4a90e2;
            background: white;
            box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
        }

        .btn-send {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4a90e2, #357abd);
            color: white;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            flex-shrink: 0;
        }

        .btn-send:hover:not(:disabled) {
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(74, 144, 226, 0.3);
        }

        .btn-send:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Empty States */
        .empty-messages {
            text-align: center;
            padding: 60px 20px;
            color: #94a3b8;
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .empty-messages i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .loading-messages {
            text-align: center;
            padding: 40px 20px;
            color: #94a3b8;
        }

        .loading-spinner {
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4a90e2;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* Scrollbar */
        .messages-container::-webkit-scrollbar {
            width: 6px;
        }

        .messages-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        .messages-container::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }

        .messages-container::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .chat-window {
                width: calc(100% - 40px);
                height: 70vh;
                bottom: 80px;
                right: 20px;
                left: 20px;
            }

            .chat-fab {
                bottom: 20px;
                right: 20px;
            }
        }

        /* Connection Status */
        .connection-status {
            position: fixed;
            top: 10px;
            right: 10px;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 500;
            z-index: 10002;
            display: none;
            animation: slideDown 0.3s ease;
        }

        .connection-status.connected {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
            display: block;
        }

        .connection-status.disconnected {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
            display: block;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Notification Toast */
        .notification-toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            padding: 15px;
            display: none;
            align-items: center;
            gap: 10px;
            z-index: 10003;
            animation: slideInRight 0.3s ease;
            max-width: 300px;
        }

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(100%);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .notification-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4a90e2, #357abd);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            flex-shrink: 0;
        }

        .notification-content h6 {
            margin: 0 0 5px 0;
            font-size: 14px;
            color: #333;
        }

        .notification-content p {
            margin: 0;
            font-size: 12px;
            color: #666;
            line-height: 1.4;
        }
    </style>
</head>

<body data-user-type="penghuni"
    data-user-id="<?= $user_info['id'] ?>"
    data-user-name="<?= htmlspecialchars($user_info['name']) ?>"
    data-user-avatar="<?= isset($user_info['avatar']) ? base_url($user_info['avatar']) : '' ?>"
    data-admin-id="<?= $admin_info['id'] ?>"
    data-admin-name="<?= htmlspecialchars($admin_info['name']) ?>"
    data-admin-avatar="<?= isset($admin_info['avatar']) ? base_url($admin_info['avatar']) : '' ?>"
    data-ws-url="ws://<?= $websocket_url ?>"
    data-api-url="<?= base_url('user/Chat_v2') ?>">
    <!-- Connection Status -->
    <div class="connection-status disconnected" id="connectionStatus">
        <i class="fas fa-wifi me-1"></i>
        <span>Connecting...</span>
    </div>

    <!-- Notification Toast -->
    <div class="notification-toast" id="notificationToast">
        <div class="notification-avatar" id="notificationAvatar">
            <?= strtoupper(substr($admin_info['name'] ?? 'A', 0, 1)) ?>
        </div>
        <div class="notification-content">
            <h6 id="notificationTitle">New Message</h6>
            <p id="notificationMessage">You have a new message</p>
        </div>
        <button class="btn-close" onclick="closeNotification()">
            <i class="fas fa-times"></i>
        </button>
    </div>

    <!-- Main Content -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container-fluid">
            <a class="navbar-brand" href="<?= site_url('user/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>Chat dengan Admin
            </span>
        </div>
    </nav>

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-10">
                <div class="card mb-4">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-info-circle me-2 text-primary"></i>Informasi Chat
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <div class="user-avatar-lg">
                                    <?= ($admin_info['avatar'] ?? false) ?
                                        '<img src="' . htmlspecialchars($admin_info['avatar']) . '" alt="' . htmlspecialchars($admin_info['name'] ?? 'Admin') . '" class="img-fluid rounded-circle">' :
                                        strtoupper(substr($admin_info['name'] ?? 'A', 0, 1))
                                    ?>
                                </div>
                            </div>
                            <div class="col">
                                <h4><?= htmlspecialchars($admin_info['name'] ?? 'Admin Kos') ?></h4>
                                <p class="text-muted mb-2">
                                    <i class="fas fa-headset me-2"></i>Admin Kos Anda
                                </p>
                                <div class="d-flex align-items-center gap-3">
                                    <div class="online-status" id="adminOnlineStatus">
                                        <span class="status-dot offline"></span>
                                        <span>Offline</span>
                                    </div>
                                    <div class="last-seen text-muted" id="lastSeen">
                                        Last seen: --
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Chat Instructions -->
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">
                            <i class="fas fa-question-circle me-2 text-primary"></i>Cara menggunakan chat:
                        </h6>
                        <ul class="mb-0">
                            <li>Klik tombol chat di pojok kanan bawah untuk membuka chat window</li>
                            <li>Kirim pesan dengan mengetik di kotak pesan dan klik tombol kirim</li>
                            <li>Anda akan menerima notifikasi saat ada pesan baru</li>
                            <li>Status online admin akan ditampilkan di atas</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="chat-window" id="chatWindow">
        <div class="chat-header">
            <div class="chat-user-info">
                <div class="chat-user-avatar" id="chatAdminAvatar">
                    <?= ($admin_info['avatar'] ?? false) ?
                        '<img src="' . htmlspecialchars($admin_info['avatar']) . '" alt="' . htmlspecialchars($admin_info['name'] ?? 'Admin') . '">' :
                        strtoupper(substr($admin_info['name'] ?? 'A', 0, 1))
                    ?>
                </div>
                <div class="chat-user-details">
                    <h4 id="chatAdminName"><?= htmlspecialchars($admin_info['name'] ?? 'Admin') ?></h4>
                    <div class="user-status offline" id="chatAdminStatus">
                        <span class="status-dot"></span>
                        <span>Offline</span>
                    </div>
                </div>
            </div>
            <div class="chat-actions">
                <button class="btn-minimize" id="minimizeBtn">
                    <i class="fas fa-minus"></i>
                </button>
                <button class="btn-close" id="closeBtn">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>

        <div class="messages-container" id="messagesContainer">
            <div class="loading-messages">
                <div class="loading-spinner"></div>
                <p>Loading messages...</p>
            </div>
        </div>

        <div class="typing-indicator" id="typingIndicator">
            <div class="typing-content">
                <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
                <span class="typing-text" id="typingText"><?= htmlspecialchars($admin_info['name'] ?? 'Admin') ?> is typing...</span>
            </div>
        </div>

        <div class="message-input-container">
            <div class="input-wrapper">
                <textarea class="message-input" id="messageInput" placeholder="Type a message..." rows="1"></textarea>
                <button class="btn-send" id="sendButton">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </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>

    <!-- Scripts -->
    <script src="<?= base_url('asset/js/chat_system.js') ?>"></script>
    <script src="<?= base_url('asset/js/user_chat.js') ?>"></script>
    <script src="<?= base_url('asset/js/chat_init.js') ?>"></script>

    <script>
        // Utility functions
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatTime(dateString) {
            const date = new Date(dateString);
            return date.toLocaleTimeString('id-ID', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        function showNotification(title, message) {
            const toast = $('#notificationToast');
            const avatar = $('#notificationAvatar');
            const titleEl = $('#notificationTitle');
            const messageEl = $('#notificationMessage');

            titleEl.text(title);
            messageEl.text(message.length > 50 ? message.substring(0, 50) + '...' : message);

            toast.fadeIn(300);
            setTimeout(() => {
                toast.fadeOut(300);
            }, 5000);
        }

        function closeNotification() {
            $('#notificationToast').fadeOut(300);
        }

        function playNotificationSound() {
            try {
                const audio = new Audio('<?= base_url("asset/sounds/notification.mp3") ?>');
                audio.volume = 0.3;
                audio.play().catch(() => {});
            } catch (error) {
                console.error('Error playing notification sound:', error);
            }
        }

        function updateUnreadBadge(count) {
            const badge = $('#unreadBadge');
            if (count > 0) {
                badge.text(count > 99 ? '99+' : count);
                badge.show();

                // Pulse animation
                $('#chatFab').css('animation', 'none');
                setTimeout(() => {
                    $('#chatFab').css('animation', 'pulse 1s');
                }, 10);
            } else {
                badge.hide();
            }
        }

        function updateAdminStatus(isOnline, lastSeen = null) {
            const statusElements = $('.user-status, .online-status');
            const statusDot = $('.status-dot');
            const lastSeenEl = $('#lastSeen');

            if (isOnline) {
                statusElements.removeClass('offline').addClass('online');
                statusElements.find('span:last').text('Online');
                statusDot.addClass('online').removeClass('offline');
                lastSeenEl.text('Online now');
            } else {
                statusElements.removeClass('online').addClass('offline');
                statusElements.find('span:last').text('Offline');
                statusDot.addClass('offline').removeClass('online');

                if (lastSeen) {
                    const lastSeenDate = new Date(lastSeen);
                    const now = new Date();
                    const diff = now - lastSeenDate;
                    const minutes = Math.floor(diff / 60000);

                    if (minutes < 1) {
                        lastSeenEl.text('Last seen just now');
                    } else if (minutes < 60) {
                        lastSeenEl.text(`Last seen ${minutes} minute${minutes > 1 ? 's' : ''} ago`);
                    } else if (minutes < 1440) {
                        const hours = Math.floor(minutes / 60);
                        lastSeenEl.text(`Last seen ${hours} hour${hours > 1 ? 's' : ''} ago`);
                    } else {
                        lastSeenEl.text(`Last seen ${Math.floor(minutes / 1440)} day${Math.floor(minutes / 1440) > 1 ? 's' : ''} ago`);
                    }
                } else {
                    lastSeenEl.text('Last seen: --');
                }
            }
        }

        function updateConnectionStatus(isConnected) {
            const statusEl = $('#connectionStatus');
            const icon = statusEl.find('i');
            const text = statusEl.find('span');

            if (isConnected) {
                statusEl.removeClass('disconnected').addClass('connected');
                icon.removeClass('fa-wifi').addClass('fa-check-circle');
                text.text('Connected');

                // Auto hide after 3 seconds
                setTimeout(() => {
                    statusEl.fadeOut(300);
                }, 3000);
            } else {
                statusEl.removeClass('connected').addClass('disconnected');
                icon.removeClass('fa-check-circle').addClass('fa-wifi');
                text.text('Disconnected');
                statusEl.fadeIn(300);
            }
        }

        // Event listeners
        $(document).ready(function() {
            console.log('User chat page loaded');

            // Toggle chat window
            $('#chatFab').on('click', function(e) {
                e.stopPropagation();
                $('#chatWindow').toggleClass('active');

                if ($('#chatWindow').hasClass('active')) {
                    // Reset unread count when opening chat
                    updateUnreadBadge(0);

                    // Mark messages as read
                    if (window.chatSystem && window.chatSystem.markMessagesAsRead) {
                        window.chatSystem.markMessagesAsRead();
                    }

                    // Focus input after a delay
                    setTimeout(() => {
                        $('#messageInput').focus();
                    }, 100);
                }
            });

            // Close chat when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.chat-window').length &&
                    !$(e.target).closest('.chat-fab').length &&
                    $('#chatWindow').hasClass('active')) {
                    $('#chatWindow').removeClass('active');
                }
            });

            // Minimize/close buttons
            $('#minimizeBtn').on('click', function() {
                // Toggle minimized state
                $('#chatWindow').toggleClass('minimized');
                $(this).find('i').toggleClass('fa-minus fa-window-restore');
            });

            $('#closeBtn').on('click', function() {
                $('#chatWindow').removeClass('active');
            });

            // Send message on Enter (without Shift)
            $('#messageInput').on('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            // Auto-resize textarea
            $('#messageInput').on('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 100) + 'px';
            });

            // Send button click
            $('#sendButton').on('click', sendMessage);

            // Request notification permission
            if ('Notification' in window && Notification.permission === 'default') {
                Notification.requestPermission();
            }

            // Listen for global chat events
            $(document).on('chat:new_message', function(e, data) {
                console.log('New message received:', data);

                // Play notification sound
                playNotificationSound();

                // Show notification if chat window is not active
                if (!$('#chatWindow').hasClass('active')) {
                    // Update unread badge
                    const currentCount = parseInt($('#unreadBadge').text()) || 0;
                    updateUnreadBadge(currentCount + 1);

                    // Show toast notification
                    showNotification(
                        data.from.name || 'Admin',
                        data.message.content
                    );

                    // Show browser notification
                    if (Notification.permission === 'granted') {
                        const notification = new Notification(
                            data.from.name || 'Admin', {
                                body: data.message.content.length > 50 ?
                                    data.message.content.substring(0, 50) + '...' : data.message.content,
                                icon: '<?= base_url("asset/img/favicon.png") ?>'
                            }
                        );

                        notification.onclick = () => {
                            window.focus();
                            $('#chatWindow').addClass('active');
                            notification.close();
                        };

                        setTimeout(() => notification.close(), 5000);
                    }
                }
            });

            $(document).on('chat:typing', function(e, data) {
                if (data.isTyping) {
                    $('#typingIndicator').show();
                    $('#typingText').text(`${data.from.name || 'Admin'} is typing...`);
                } else {
                    $('#typingIndicator').hide();
                }
            });

            $(document).on('chat:user_online', function(e, data) {
                if (data.user.type === 'admin') {
                    updateAdminStatus(true);
                }
            });

            $(document).on('chat:user_offline', function(e, data) {
                if (data.user.type === 'admin') {
                    updateAdminStatus(false, data.lastSeen);
                }
            });

            $(document).on('chat:connected', function() {
                updateConnectionStatus(true);
            });

            $(document).on('chat:disconnected', function() {
                updateConnectionStatus(false);
            });
        });

        // Send message function
        function sendMessage() {
            const messageInput = $('#messageInput');
            const message = messageInput.val().trim();

            if (!message) {
                alert('Pesan tidak boleh kosong');
                return;
            }

            // Use chat system if available
            if (window.chatSystem && window.chatSystem.sendMessageToAdmin) {
                window.chatSystem.sendMessageToAdmin();
            } else {
                // Fallback AJAX method
                $.ajax({
                    url: '<?= site_url("user/chat_v2/send_message") ?>',
                    method: 'POST',
                    data: {
                        message: message
                    },
                    success: function(response) {
                        if (response.status) {
                            messageInput.val('');
                            messageInput.css('height', 'auto');
                        }
                    },
                    error: function() {
                        alert('Gagal mengirim pesan. Silakan coba lagi.');
                    }
                });
            }
        }
    </script>
</body>

</html>