// DOM elements
const activeDevice = document.getElementById('active-device');
const joinQueueBtn = document.getElementById('join-queue');
const leaveQueueBtn = document.getElementById('leave-queue');
const queueStatus = document.getElementById('queue-status');
const screenContainer = document.getElementById('screen-container');
const touchOverlay = document.getElementById('touch-overlay');
const screenImage = document.getElementById('screen-image');
const textInput = document.getElementById('text-input');
const sendTextBtn = document.getElementById('send-text-btn');
const timer = document.getElementById('timer');
const timeRemainingSpan = document.getElementById('time-remaining');

// Queue state
let currentUserId = null;
let queueUpdateInterval = null;
let screenUpdateInterval = null;
let timeUpdateInterval = null;
let deviceCheckInterval = null;
let isRefreshing = false;

// Initialize app
document.addEventListener('DOMContentLoaded', () => {
    initializeQueueEvents();
    initializeTouchEvents();
    initializeControlEvents();
    startQueueStatusUpdates();
    startDeviceAvailabilityCheck();

    // Check if user is already in queue on page load
    checkExistingQueueStatus();

    console.log('Queue system initialized. Click "Join Queue" to get started.');
});

// Check if user is already in queue on page load
async function checkExistingQueueStatus() {
    try {
        const response = await fetch('/api/queue-status');
        const queueData = await response.json();

        if (queueData.userId) {
            currentUserId = queueData.userId;

            if (queueData.inQueue) {
                // User is in queue
                joinQueueBtn.style.display = 'none';
                leaveQueueBtn.style.display = 'block';
                updateQueueDisplay(queueData);
                console.log(`Resumed queue session! Position: ${queueData.position}, Wait time: ${queueData.waitTime} minutes`);
            } else if (queueData.active && queueData.deviceId) {
                // User is active (has a device assigned)
                joinQueueBtn.style.display = 'none';
                leaveQueueBtn.style.display = 'block';
                updateQueueDisplay(queueData);
                console.log('Resumed active session!');
            } else {
                // User not in queue but has a userId - they're not in the current queue
                resetToWelcomeState();
            }
        } else {
            // No existing session
            resetToWelcomeState();
        }
    } catch (error) {
        console.error('Error checking existing queue status:', error);
        resetToWelcomeState();
    }
}

// Queue management
async function joinQueue() {
    try {
        const response = await fetch('/api/join-queue', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });
        const result = await response.json();

        if (result.success) {
            currentUserId = result.userId;
            joinQueueBtn.style.display = 'none';
            leaveQueueBtn.style.display = 'block';

            updateQueueDisplay(result);
            console.log(`Joined queue! Position: ${result.position}, Wait time: ${result.waitTime} minutes`);
        } else {
            addStatusMessage(`Error: ${result.error}`, 'error');
        }
    } catch (error) {
        addStatusMessage('Error joining queue', 'error');
    }
}

async function leaveQueue() {
    try {
        const response = await fetch('/api/leave-queue', {
            method: 'POST'
        });
        const result = await response.json();

        if (result.success) {
            joinQueueBtn.style.display = 'block';
            leaveQueueBtn.style.display = 'none';
            currentUserId = null;

            resetToWelcomeState();
            addStatusMessage('Left queue');
        }
    } catch (error) {
        addStatusMessage('Error leaving queue', 'error');
    }
}

function resetToWelcomeState() {
    queueStatus.innerHTML = `
        <div class="queue-info">
            <div class="queue-position">
                <h3>Welcome!</h3>
                <p>Click "Join Queue" to get access to Android devices</p>
            </div>
        </div>
    `;

    stopScreenStreaming();
    disableControls();
    hideTimer();
}

function updateQueueDisplay(queueData) {
    if (queueData.active && queueData.deviceId) {
        // User's turn - show active device interface
        showActiveDeviceInterface(queueData.timeRemaining, queueData.deviceId);
    } else if (queueData.inQueue) {
        // User is in queue - show queue position
        showQueuePosition(queueData);
    } else {
        // Not in queue - show general queue info
        showGeneralQueueInfo(queueData);
    }
}

function showActiveDeviceInterface(timeRemaining, deviceId = 'Unknown') {
    queueStatus.innerHTML = `
        <div class="queue-info active-user">
            <div class="queue-position">
                <h3>🎉 Your Turn!</h3>
                <p>Device: ${deviceId}</p>
                <p>You have <span id="queue-timer">${formatTime(timeRemaining)}</span></p>
            </div>
        </div>
    `;

    enableControls();
    showTimer();
    startScreenStreaming();
    updateTimeDisplay(timeRemaining);
}

function showQueuePosition(queueData) {
    const waitTimeFormatted = formatTime(queueData.waitTime * 60);

    queueStatus.innerHTML = `
        <div class="queue-info">
            <div class="queue-position">
                <h3>You are ${queueData.position}${getOrdinalSuffix(queueData.position)} in queue</h3>
                <p>Estimated wait time: ${waitTimeFormatted}</p>
                <p>Queue length: ${queueData.queueLength} users</p>
            </div>
        </div>
    `;
}

function showGeneralQueueInfo(queueData) {
    const activeCount = queueData.activeDevices ? queueData.activeDevices.length : 0;
    queueStatus.innerHTML = `
        <div class="queue-info">
            <div class="queue-position">
                <h3>Queue Status</h3>
                <p>Queue length: ${queueData.queueLength} users</p>
                <p>Active devices: ${activeCount}</p>
                <p>Available devices: ${queueData.availableDevices || 0}</p>
            </div>
        </div>
    `;
}

function getOrdinalSuffix(position) {
    const j = position % 10;
    const k = position % 100;
    if (j === 1 && k !== 11) return 'st';
    if (j === 2 && k !== 12) return 'nd';
    if (j === 3 && k !== 13) return 'rd';
    return 'th';
}

function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')} minutes, ${remainingSeconds.toString().padStart(2, '0')} seconds.`;
}

// Queue status updates
function startQueueStatusUpdates() {
    // Update queue status every 5 seconds
    queueUpdateInterval = setInterval(async () => {
        await updateQueueStatus();
    }, 5000);

    // Initial update
    updateQueueStatus();
}

async function updateQueueStatus() {
    if (!currentUserId) {
        // Use the IP-based endpoint if no userId is set
        try {
            const response = await fetch('/api/queue-status');
            const queueData = await response.json();
            if (queueData.userId) {
                currentUserId = queueData.userId;
            }
            updateQueueDisplay(queueData);
        } catch (error) {
            // Silent error handling
        }
        return;
    }

    try {
        const response = await fetch(`/api/queue-status/${currentUserId}`);
        const queueData = await response.json();
        updateQueueDisplay(queueData);
    } catch (error) {
        // Silent error handling
    }
}

// Device availability check for auto-refresh
function startDeviceAvailabilityCheck() {
    // Check for device availability every 10 seconds when user is in queue
    deviceCheckInterval = setInterval(async () => {
        if (currentUserId && !isUserActive()) {
            try {
                const response = await fetch('/api/queue-status');
                const queueData = await response.json();

                // If it's now the user's turn but they weren't active, refresh immediately
                if (queueData.active && queueData.deviceId && !isUserActive()) {
                    addStatusMessage('Device is now available! Starting your session...');
                    updateQueueDisplay(queueData);
                    // Force immediate refresh
                    setTimeout(() => updateQueueStatus(), 1000);
                }
            } catch (error) {
                // Silent error handling
            }
        }
    }, 10000);
}

function isUserActive() {
    // Check if user is currently active (has access to device)
    return document.getElementById('home-btn') && !document.getElementById('home-btn').disabled;
}

// Screen streaming
function startScreenStreaming() {
    stopScreenStreaming(); // Clear any existing interval

    // Hide placeholder and show image
    const placeholder = screenContainer.querySelector('.screen-placeholder');
    if (placeholder) {
        placeholder.style.display = 'none';
    }
    screenImage.style.display = 'block';

    // Update screen every 2 seconds
    screenUpdateInterval = setInterval(() => {
        updateScreenImage();
    }, 2000);

    // Update immediately
    updateScreenImage();
}

function stopScreenStreaming() {
    if (screenUpdateInterval) {
        clearInterval(screenUpdateInterval);
        screenUpdateInterval = null;
    }

    // Show placeholder and hide image
    const placeholder = screenContainer.querySelector('.screen-placeholder');
    if (placeholder) {
        placeholder.style.display = 'flex';
    }
    screenImage.style.display = 'none';
}

async function updateScreenImage() {
    try {
        const timestamp = new Date().getTime();
        screenImage.src = `/screen.png?t=${timestamp}`;
    } catch (error) {
        // Silent error handling
    }
}

// Timer functions
function showTimer() {
    timer.style.display = 'block';
}

function hideTimer() {
    timer.style.display = 'none';
}

function updateTimeDisplay(seconds) {
    if (timeUpdateInterval) {
        clearInterval(timeUpdateInterval);
    }

    timeUpdateInterval = setInterval(() => {
        seconds--;
        timeRemainingSpan.textContent = formatTime(seconds);

        if (seconds <= 0) {
            clearInterval(timeUpdateInterval);
            // Time's up - this will be handled by the queue status update
            location.reload()
        }
    }, 1000);
}

// Control functions
function enableControls() {
    document.getElementById('home-btn').disabled = false;
    document.getElementById('back-btn').disabled = false;
    document.getElementById('recent-btn').disabled = false;
    textInput.disabled = false;
    sendTextBtn.disabled = false;
}

function disableControls() {
    document.getElementById('home-btn').disabled = true;
    document.getElementById('back-btn').disabled = true;
    document.getElementById('recent-btn').disabled = true;
    textInput.disabled = true;
    sendTextBtn.disabled = true;
}

// Touch events
function initializeTouchEvents() {
    touchOverlay.addEventListener('touchstart', handleTouchStart);
    touchOverlay.addEventListener('touchend', handleTouchEnd);
    touchOverlay.addEventListener('mousedown', handleMouseDown);
    touchOverlay.addEventListener('mouseup', handleMouseUp);
}

function handleTouchStart(e) {
    e.preventDefault();
    for (let i = 0; i < e.touches.length; i++) {
        const touch = e.touches[i];
        const x = touch.clientX;
        const y = touch.clientY;
        sendTap(x, y);
        showTouchPoint(x - touchOverlay.getBoundingClientRect().left, y - touchOverlay.getBoundingClientRect().top, touch.identifier);
    }
}

function handleTouchEnd(e) {
    e.preventDefault();
    for (let i = 0; i < e.changedTouches.length; i++) {
        const touch = e.changedTouches[i];
        removeTouchPoint(touch.identifier);
    }
}

function handleMouseDown(e) {
    const x = e.clientX;
    const y = e.clientY;
    sendTap(x, y);
    showTouchPoint(x - touchOverlay.getBoundingClientRect().left, y - touchOverlay.getBoundingClientRect().top, 0);
}

function handleMouseUp(e) {
    removeTouchPoint(0);
}

function showTouchPoint(x, y, id) {
    removeTouchPoint(id);
    const touchPoint = document.createElement('div');
    touchPoint.className = 'touch-point active';
    touchPoint.id = `touch-${id}`;
    touchPoint.style.left = `${x}px`;
    touchPoint.style.top = `${y}px`;
    touchOverlay.appendChild(touchPoint);
}

function removeTouchPoint(id) {
    const touchPoint = document.getElementById(`touch-${id}`);
    if (touchPoint) {
        touchPoint.remove();
    }
}

// Queue events
function initializeQueueEvents() {
    joinQueueBtn.addEventListener('click', joinQueue);
    leaveQueueBtn.addEventListener('click', leaveQueue);
}

// Control events
function initializeControlEvents() {
    sendTextBtn.addEventListener('click', sendText);
    textInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendText();
        }
    });

    document.getElementById('home-btn').addEventListener('click', () => sendCommand('home'));
    document.getElementById('back-btn').addEventListener('click', () => sendCommand('back'));
    document.getElementById('recent-btn').addEventListener('click', () => sendCommand('recent'));
}

// API functions
async function sendCommand(command) {
    try {
        const response = await fetch('/api/command', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ command })
        });
        const result = await response.json();

        if (result.success) {
            addStatusMessage(`Command executed: ${command}`);
        } else {
            addStatusMessage(`Error: ${result.error}`, 'error');
        }
    } catch (error) {
        addStatusMessage('Error sending command', 'error');
    }
}

async function sendTap(x, y) {
    try {
        // Get the actual screen image dimensions for accurate scaling
        const imageRect = screenImage.getBoundingClientRect();
        const overlayRect = touchOverlay.getBoundingClientRect();

        // Calculate the actual position within the image bounds
        const imageX = Math.max(0, Math.min(x - imageRect.left, imageRect.width));
        const imageY = Math.max(0, Math.min(y - imageRect.top, imageRect.height));

        // Use image dimensions for scaling (more accurate than overlay)
        const containerWidth = imageRect.width || 720;
        const containerHeight = imageRect.height || 1280;

        console.log(`Tap coordinates - Image: ${imageX}x${imageY}, Container: ${containerWidth}x${containerHeight}`);

        const response = await fetch('/api/tap', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ x: imageX, y: imageY, containerWidth, containerHeight })
        });
        const result = await response.json();

        if (result.success) {
            // Show feedback at the original touch location for visual accuracy
            const feedbackX = (imageX / imageRect.width) * overlayRect.width;
            const feedbackY = (imageY / imageRect.height) * overlayRect.height;

            showTouchFeedback(feedbackX, feedbackY);
            addStatusMessage(`Tap at ${Math.round(imageX)}, ${Math.round(imageY)} (scaled to ${Math.round(result.x)}, ${Math.round(result.y)})`);
        } else {
            addStatusMessage(`Error: ${result.error}`, 'error');
        }
    } catch (error) {
        addStatusMessage('Error sending tap', 'error');
    }
}

async function sendText() {
    const text = textInput.value.trim();
    if (text) {
        try {
            const response = await fetch('/api/text', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ text })
            });
            const result = await response.json();

            if (result.success) {
                textInput.value = '';
                addStatusMessage(`Text sent: "${text}"`);
            } else {
                addStatusMessage(`Error: ${result.error}`, 'error');
            }
        } catch (error) {
            addStatusMessage('Error sending text', 'error');
        }
    }
}

// Utility functions
function addStatusMessage(message, type = 'info') {
    const messageDiv = document.createElement('div');
    messageDiv.className = `status-message ${type}`;
    messageDiv.textContent = `${new Date().toLocaleTimeString()}: ${message}`;

    statusMessages.appendChild(messageDiv);

    // Keep only last 10 messages
    while (statusMessages.children.length > 10) {
        statusMessages.removeChild(statusMessages.firstChild);
    }

    messageDiv.scrollIntoView();
}

// Cleanup on page unload
window.addEventListener('beforeunload', () => {
    if (currentUserId) {
        // Try to leave queue when page is closed
        fetch(`/api/leave-queue`, { method: 'POST' }).catch(() => {});
    }

    if (queueUpdateInterval) clearInterval(queueUpdateInterval);
    if (screenUpdateInterval) clearInterval(screenUpdateInterval);
    if (timeUpdateInterval) clearInterval(timeUpdateInterval);
    if (deviceCheckInterval) clearInterval(deviceCheckInterval);
});
