let admin_chat_ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
let protocol = window.location.protocol === "https:" ? "https" : "http";
let admin_chat_domain = "osina.ositcom.com";
let userId = document.getElementById('userId').textContent.trim();
let osichatadminroomSocket = null;
let currentChatId = null;
let whereAmI = null;

// FUNCTIONS TO SHOW & HIDE THE LOADER
function showLoader() {
    const roomsLoader = document.getElementById('roomsLoader');
    if (roomsLoader) {
        roomsLoader.classList.remove('hidden');
    }
}

function hideLoader() {
    const roomsLoader = document.getElementById('roomsLoader');
    if (roomsLoader) {
        roomsLoader.classList.add('hidden');
    }
}


function appendInnerConversationScript(div) {
    const innerConversationScript = document.createElement('script');
    innerConversationScript.type = 'text/javascript';
    innerConversationScript.src = `${protocol}://${admin_chat_domain}/static/js/osichat-admin/inner-conversation.js`;
    div.appendChild(innerConversationScript);
}



function initializeOsichat(){
    osichatroomsSocket = new WebSocket(`${admin_chat_ws_scheme}://${admin_chat_domain}/ws/osichat/`);

    osichatroomsSocket.onopen = function () {
        console.log('WebSocket connection to rooms established');
        osichatroomsSocket.send(JSON.stringify({
            'event_type': 'set_client_type',
            'client_type': 'website_admin',
            'user_id': userId,
            'whereAmI': whereAmI === 'Visitors' ? 'Visitors' : 'Chats' // Default to 'Chats' if not 'Visitors'         
        }));
    };

    osichatroomsSocket.onmessage = function (e) {
        const data = JSON.parse(e.data);
        const leftDiv = document.getElementById('widgetLeftSide');
        const leftDynamicDiv = document.getElementById('leftDynamic');
        switch (data.event_type) {
            case 'get_chats':
                hideLoader();
                leftDynamicDiv.innerHTML = data.html;
                appendInnerConversationScript(leftDiv);
                break;

            case 'get_visitors':
                hideLoader();
                leftDynamicDiv.innerHTML = data.html;
                setupDurationUpdater();
                break;

            case 'new_chat_update':
                const roomsContainer = document.getElementById('chatrooms');
                const chatRoomDiv = roomsContainer.querySelector(`.chat-room[data-roomid='${data.chatroom_id}']`);
        
                if (chatRoomDiv) {
                    chatRoomDiv.remove();  // Remove the existing chat room div
                }
                // Insert the new chat room HTML at the top of the container
                const newChatRoomDiv = document.createElement('div');
                newChatRoomDiv.innerHTML = data.html;
                roomsContainer.insertAdjacentElement('afterbegin', newChatRoomDiv.firstElementChild);

                if (parseInt(currentChatId) === parseInt(data.chatroom_id)) { 
                    const unreadIndicator = roomsContainer.querySelector(`.unread[data-roomid='${data.chatroom_id}']`);
                    if (unreadIndicator) {
                        unreadIndicator.classList.add('hidden');  
                    }
                    if (!data.user) { // If it is sent by a guest play a notification sound for the guest
                        const notificationSound = document.getElementById('notification-sound');
                        notificationSound.play();

                    }
                    } else {
                        const unreadIndicator = roomsContainer.querySelector(`.unread[data-roomid='${data.chatroom_id}']`);
                        if (unreadIndicator) {
                            unreadIndicator.classList.remove('hidden');  
                        }
                        if (!data.user) { // If it is sent by a guest play a notification sound for the guest
                            const notificationSound = document.getElementById('out-notification-sound');
                            notificationSound.play();
                        }
                    }

                    setInterval(updateOnlineDurations, 1000);
                    appendInnerConversationScript(leftDiv);
                    break;

            case 'new_visitor_update':
                const visitorsContainer = document.getElementById('visitors');
                const visitorDiv = visitorsContainer.querySelector(`.visitor[data-visitorid='${data.visitor_id}']`);
                if (data.action === 'new_log') {
                    if (visitorDiv){
                        visitorDiv.remove();
                    }
                    const newVisitorDiv = document.createElement('div');
                    newVisitorDiv.innerHTML = data.html;
                    visitorsContainer.insertAdjacentElement('afterbegin', newVisitorDiv.firstElementChild);
                    const visitorNotificationSound = document.getElementById('visitor-notification-sound');
                    visitorNotificationSound.play();
                }  else if (data.action === 'end_log') {
                    const newVisitorDiv = document.createElement('div');
                    newVisitorDiv.innerHTML = data.html;
                    visitorDiv.replaceWith(newVisitorDiv.firstElementChild);
                }

                
                setupDurationUpdater();
                break;
        
            default:
                console.log('Unknown event type:', data.event_type);
        }
    };

    osichatroomsSocket.onclose = function () {
        showLoader();
        setTimeout(() => {
            console.log('Attempting to reconnect to WebSocket...');
            initializeOsichat();
        }, 2000);
    };

    osichatroomsSocket.onerror = function (error) {
        showLoader();
        console.error('WebSocket error:', error);
    };

    window.addEventListener('offline', () => {
        showLoader();
        if (osichatroomsSocket) {
            osichatroomsSocket.close();
        }
    });

}

const chatsTab = document.getElementById('chatsTab');
const visitorsTab = document.getElementById('visitorsTab');

function switchToChats() {
    showLoader();
    whereAmI = 'Chats';
    chatsTab.classList.add('bg-white', 'text-secondosiblue', 'shadow-md');
    chatsTab.classList.remove('bg-gray-100', 'text-gray-400');
    visitorsTab.classList.add('bg-gray-100', 'text-gray-400');
    visitorsTab.classList.remove('bg-white', 'text-secondosiblue', 'shadow-md');

    osichatroomsSocket.send(JSON.stringify({
        event_type: 'get_chats'
    }));
}

function switchToVisitors() {
    showLoader();
    whereAmI = 'Visitors';
    visitorsTab.classList.add('bg-white', 'text-secondosiblue', 'shadow-md');
    visitorsTab.classList.remove('bg-gray-100', 'text-gray-400');
    chatsTab.classList.add('bg-gray-100', 'text-gray-400');
    chatsTab.classList.remove('bg-white', 'text-secondosiblue', 'shadow-md');

    osichatroomsSocket.send(JSON.stringify({
        event_type: 'get_visitors'
    }));
}

chatsTab.addEventListener('click', switchToChats);
visitorsTab.addEventListener('click', switchToVisitors);



let updateInterval;
function updateOnlineDurations() {
    document.querySelectorAll('.visitor').forEach(visitorDiv => {
        const onlineIndicator = visitorDiv.querySelector('.online');
        if (onlineIndicator) {
            const durationElem = visitorDiv.querySelector('.duration');
            const currentText = durationElem.textContent;
            const parts = currentText.split(':').map(Number);

            let hours = 0, minutes = 0, seconds = 0;

            if (parts.length === 3) {
                [hours, minutes, seconds] = parts;
            } else if (parts.length === 2) {
                [minutes, seconds] = parts;
            }

            const totalSeconds = hours * 3600 + minutes * 60 + seconds;
            const updatedTotalSeconds = totalSeconds + 1;
            const updatedHours = Math.floor(updatedTotalSeconds / 3600);
            const updatedMinutes = Math.floor((updatedTotalSeconds % 3600) / 60);
            const updatedSeconds = updatedTotalSeconds % 60;

            const formattedDuration = 
                (updatedHours > 0 ? `${String(updatedHours).padStart(2, '0')}:` : '') +
                `${String(updatedMinutes).padStart(2, '0')}:${String(updatedSeconds).padStart(2, '0')}`;

            durationElem.textContent = formattedDuration;
        }
    });
}

function setupDurationUpdater() {
    // Clear any existing interval to avoid multiple intervals
    if (updateInterval) {
        clearInterval(updateInterval);
    }
    // Set up a new interval
    updateInterval = setInterval(updateOnlineDurations, 1000);
}


initializeOsichat();