<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($title ?? 'Admin 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>
        /* Additional Admin Chat Styles */
        .admin-chat-container {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: #f8f9fa;
            z-index: 1050;
        }

        .admin-chat-wrapper {
            display: flex;
            height: 100vh;
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);
        }

        /* Left Panel */
        .chat-left-panel {
            width: 350px;
            border-right: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
            background: #ffffff;
        }

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

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

        .panel-header .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);
        }

        .panel-header .user-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }

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

        .panel-header .online-status {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.8);
        }

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

        .panel-actions button {
            width: 36px;
            height: 36px;
            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;
        }

        .panel-actions button:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }

        /* Search Box */
        .search-box {
            padding: 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #e0e0e0;
        }

        .search-input-wrapper {
            position: relative;
        }

        .search-input {
            width: 100%;
            padding: 10px 15px 10px 40px;
            border: 1px solid #ddd;
            border-radius: 20px;
            font-size: 14px;
            background: white;
            outline: none;
            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: #999;
        }

        /* Conversation List */
        .conversation-list {
            flex: 1;
            overflow-y: auto;
            background: white;
        }

        .conversation-item {
            display: flex;
            align-items: center;
            padding: 15px;
            gap: 12px;
            cursor: pointer;
            transition: all 0.2s;
            border-bottom: 1px solid #f5f5f5;
            position: relative;
        }

        .conversation-item:hover {
            background: #f8fafc;
        }

        .conversation-item.active {
            background: #e8f4ff;
            border-left: 4px solid #4a90e2;
        }

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

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

        .online-dot {
            position: absolute;
            bottom: 2px;
            right: 2px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #28a745;
            border: 2px solid white;
            display: none;
        }

        .online-dot.online {
            display: block;
        }

        .conversation-info {
            flex: 1;
            min-width: 0;
        }

        .conversation-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 4px;
        }

        .conversation-name {
            margin: 0;
            font-size: 15px;
            font-weight: 600;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .conversation-time {
            font-size: 12px;
            color: #999;
            flex-shrink: 0;
        }

        .conversation-preview {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 8px;
        }

        .last-message {
            margin: 0;
            font-size: 13px;
            color: #666;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
        }

        .unread-badge {
            background: #dc3545;
            color: white;
            font-size: 11px;
            font-weight: 600;
            min-width: 20px;
            height: 20px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 6px;
            flex-shrink: 0;
            animation: pulse 2s infinite;
        }

        .conversation-details {
            margin-top: 4px;
        }

        .room-info {
            font-size: 12px;
            color: #999;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .room-info i {
            font-size: 11px;
        }

        /* Right Panel */
        .chat-right-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f8f9fa;
        }

        .empty-chat-state {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px;
            text-align: center;
            color: #999;
        }

        .empty-icon {
            font-size: 64px;
            color: #4a90e2;
            opacity: 0.3;
            margin-bottom: 20px;
        }

        .empty-chat-state h3 {
            margin: 0 0 10px 0;
            color: #666;
            font-weight: 500;
        }

        .empty-chat-state p {
            margin: 0;
            color: #999;
            font-size: 14px;
        }

        .active-chat {
            flex: 1;
            display: none;
            flex-direction: column;
            height: 100%;
        }

        /* Chat Header */
        .chat-header {
            padding: 15px 20px;
            background: white;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

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

        .chat-user-avatar {
            position: relative;
            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;
            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;
        }

        .user-status {
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .user-status.online {
            color: #28a745;
        }

        .user-status.offline {
            color: #dc3545;
        }

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

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

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

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

        .btn-action {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border: none;
            background: transparent;
            color: #666;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .btn-action:hover {
            background: #f5f5f5;
            color: #333;
        }

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

        .message {
            max-width: 70%;
            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: 12px 16px;
            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: #333;
            border: 1px solid #e0e0e0;
            border-bottom-left-radius: 4px;
        }

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

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

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

        .message-received .message-meta {
            color: #999;
        }

        .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 #e0e0e0;
            width: fit-content;
        }

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

        .typing-dots span {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #999;
            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: #999;
            font-style: italic;
        }

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

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

        .message-input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #e0e0e0;
            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: #f8f9fa;
        }

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

        .btn-send {
            width: 44px;
            height: 44px;
            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;
        }

        /* Loading States */
        .loading-conversations,
        .loading-messages {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }

        .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);
            }
        }

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

            50% {
                transform: scale(1.1);
            }

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

        /* Empty States */
        .empty-conversations {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-conversations i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
            color: #4a90e2;
        }

        .empty-messages {
            text-align: center;
            padding: 60px 20px;
            color: #999;
            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;
        }

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

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

        .conversation-list::-webkit-scrollbar-thumb,
        .messages-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        .conversation-list::-webkit-scrollbar-thumb:hover,
        .messages-container::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .admin-chat-wrapper {
                flex-direction: column;
            }

            .chat-left-panel {
                width: 100%;
                height: 40%;
                border-right: none;
                border-bottom: 1px solid #e0e0e0;
            }

            .chat-right-panel {
                height: 60%;
            }

            .message {
                max-width: 85%;
            }
        }

        /* Notification Badge */
        .notification-badge {
            position: fixed;
            top: 10px;
            right: 10px;
            background: #dc3545;
            color: white;
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            z-index: 1060;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            display: none;
            animation: slideIn 0.3s ease;
        }

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

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>

<body data-user-type="admin"
    data-user-id="<?= $admin_info['id'] ?>"
    data-user-name="<?= htmlspecialchars($admin_info['name']) ?>"
    data-user-avatar="<?= isset($admin_info['avatar']) ? base_url($admin_info['avatar']) : '' ?>"
    data-ws-url="ws://<?= $websocket_url ?>"
    data-api-url="<?= base_url('admin/Chat_v2') ?>">
    <!-- Notification Badge -->
    <div id="notificationBadge" class="notification-badge">
        <i class="fas fa-bell me-1"></i>
        <span id="notificationCount">0</span> new messages
    </div>

    <!-- Admin Chat Container -->
    <div class="admin-chat-container">
        <div class="admin-chat-wrapper">
            <!-- Left Panel - Conversation List -->
            <div class="chat-left-panel">
                <div class="panel-header">
                    <div class="user-info">
                        <div class="user-avatar">
                            <?= ($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="user-details">
                            <h4><?= htmlspecialchars($admin_info['name'] ?? 'Admin') ?></h4>
                            <small class="online-status" id="adminStatus">Online</small>
                        </div>
                    </div>
                    <div class="panel-actions">
                        <button class="btn-refresh" id="refreshBtn" title="Refresh">
                            <i class="fas fa-redo"></i>
                        </button>
                        <button class="btn-settings" id="settingsBtn" title="Settings">
                            <i class="fas fa-cog"></i>
                        </button>
                    </div>
                </div>

                <div class="search-box">
                    <div class="search-input-wrapper">
                        <input type="text" class="search-input" id="searchInput" placeholder="Search conversations...">
                        <i class="fas fa-search search-icon"></i>
                    </div>
                </div>

                <div class="conversation-list" id="conversationList">
                    <div class="loading-conversations">
                        <div class="loading-spinner"></div>
                        <p>Loading conversations...</p>
                    </div>
                </div>
            </div>

            <!-- Right Panel - Chat Area -->
            <div class="chat-right-panel">
                <div class="empty-chat-state" id="emptyChatState">
                    <div class="empty-icon">
                        <i class="fas fa-comments"></i>
                    </div>
                    <h3>Select a conversation</h3>
                    <p>Choose a conversation from the list to start chatting</p>
                </div>

                <div class="active-chat" id="activeChat">
                    <!-- Chat header will be inserted here -->
                    <div class="chat-header" id="chatHeader"></div>

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

                    <!-- Typing indicator -->
                    <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">is typing...</span>
                        </div>
                    </div>

                    <!-- Message input -->
                    <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>
            </div>
        </div>
    </div>

    <div id="chatContainer"></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 src="<?= base_url('asset/js/chat_system.js') ?>"></script>
    <script src="<?= base_url('asset/js/admin_chat.js') ?>"></script>
    <script src="<?= base_url('asset/js/chat_init.js') ?>"></script>
    <script>
        // Initialize admin chat
        $(document).ready(function() {
            console.log('Admin chat page loaded');

            // Play notification sound function
            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);
                }
            }

            // Show notification badge
            function showNotification(count) {
                const badge = $('#notificationBadge');
                const countSpan = $('#notificationCount');

                countSpan.text(count);
                badge.fadeIn(300);

                // Auto hide after 5 seconds
                setTimeout(() => {
                    badge.fadeOut(300);
                }, 5000);
            }

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

            // Create browser notification
            function createBrowserNotification(title, body, userId) {
                if (Notification.permission === 'granted') {
                    const notification = new Notification(title, {
                        body: body,
                        icon: '<?= base_url("asset/img/favicon.png") ?>',
                        tag: `chat_${userId}`
                    });

                    notification.onclick = () => {
                        window.focus();
                        // Open conversation if chat system is initialized
                        if (window.chatSystem && window.chatSystem.openConversation) {
                            window.chatSystem.openConversation(userId);
                        }
                        notification.close();
                    };

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

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

                // Play sound
                playNotificationSound();

                // Show notification badge
                if (!data.isCurrentConversation) {
                    const currentCount = parseInt($('#notificationCount').text()) || 0;
                    showNotification(currentCount + 1);

                    // Show browser notification
                    createBrowserNotification(
                        data.from.name || 'Penghuni',
                        data.message.content,
                        data.from.id
                    );
                }
            });

            $(document).on('chat:user_online', function(e, data) {
                console.log('User online:', data);
                // Update UI for online status
                $(`.conversation-item[data-user-id="${data.user.id}"] .online-dot`)
                    .addClass('online');
            });

            $(document).on('chat:user_offline', function(e, data) {
                console.log('User offline:', data);
                // Update UI for offline status
                $(`.conversation-item[data-user-id="${data.user.id}"] .online-dot`)
                    .removeClass('online');
            });

            $(document).on('chat:typing', function(e, data) {
                console.log('Typing indicator:', data);

                if (data.isTyping) {
                    // Show typing indicator in current conversation
                    if (window.chatSystem &&
                        window.chatSystem.activeConversationId === data.from.id) {
                        $('#typingIndicator').show();
                        $('#typingText').text(`${data.from.name || 'User'} is typing...`);
                    }
                } else {
                    $('#typingIndicator').hide();
                }
            });
        });
    </script>
</body>

</html>