/**
 * Mobile Printer Setup & Test Logic
 * Handled direct Web Bluetooth and App-based printing schemes
 */

let printerDevice = null;
let printerCharacteristic = null;

document.addEventListener('DOMContentLoaded', () => {
    checkContext();
    const btnSearch = document.getElementById('btnSearch');
    if (btnSearch) btnSearch.addEventListener('click', connectPrinter);
    
    const btnDisconnect = document.getElementById('btnDisconnect');
    if (btnDisconnect) btnDisconnect.addEventListener('click', disconnectPrinter);
});

function addLog(msg) {
    const logPanel = document.getElementById('logPanel');
    const time = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });
    logPanel.innerHTML += `> [${time}] ${msg}<br>`;
    logPanel.scrollTop = logPanel.scrollHeight;
}

function clearLogs() {
    document.getElementById('logPanel').innerHTML = '> Logs cleared.<br>';
}

function checkContext() {
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    if (!navigator.bluetooth) {
        document.getElementById('unsupportedWarning').style.display = 'block';
        const warningText = document.getElementById('unsupportedWarning');
        
        if (isIOS) {
            warningText.innerHTML = `<i class="fa-solid fa-apple me-2"></i> <strong>iPhone Safari detected!</strong><br>Safari does not support direct Bluetooth. Please use the <b>"iPhone / Share"</b> button below to print via Express Print.`;
        } else if (!window.isSecureContext) {
            warningText.innerHTML = `<i class="fa-solid fa-lock me-2"></i> <strong>Insecure Context!</strong><br>Web Bluetooth requires <b>HTTPS</b>. Please ensure your URL starts with https://`;
        }
        
        document.getElementById('btnSearch').style.display = 'none';
        document.getElementById('btnTestDirect').style.opacity = '0.5';
        document.getElementById('btnTestDirect').style.pointerEvents = 'none';
        addLog('NOTICE: Direct Web Bluetooth is unavailable on this device/browser.');
    }
}

async function connectPrinter() {
    try {
        addLog('Searching for Bluetooth devices...');
        
        // Typical Thermal Printer services
        // Most use 000018f0-0000-1000-8000-00805f9b34fb or 0000ff00-0000-1000-8000-00805f9b34fb
        printerDevice = await navigator.bluetooth.requestDevice({
            acceptAllDevices: true,
            optionalServices: [
                '000018f0-0000-1000-8000-00805f9b34fb',
                '0000ff00-0000-1000-8000-00805f9b34fb',
                '49535053-fe7d-4ae5-8fa9-9fafd205e455'
            ]
        });

        addLog(`Found: ${printerDevice.name}`);
        updateUI('searching', printerDevice.name);

        printerDevice.addEventListener('gattserverdisconnected', onDisconnected);

        addLog('Connecting to GATT server...');
        const server = await printerDevice.gatt.connect();

        addLog('Getting primary service...');
        // Try to find a writable service
        let service;
        try {
            service = await server.getPrimaryService('000018f0-0000-1000-8000-00805f9b34fb');
        } catch (e) {
            try {
                service = await server.getPrimaryService('0000ff00-0000-1000-8000-00805f9b34fb');
            } catch (e2) {
                // Last ditch effort - find ANY service
                const services = await server.getPrimaryServices();
                if (services.length > 0) service = services[0];
            }
        }

        if (!service) throw new Error('No compatible print service found on device.');

        addLog('Finding writable characteristic...');
        const characteristics = await service.getCharacteristics();
        printerCharacteristic = characteristics.find(c => c.properties.write || c.properties.writeWithoutResponse);

        if (!printerCharacteristic) throw new Error('No writable characteristic found.');

        addLog('✅ Connected and Ready!');
        updateUI('connected', printerDevice.name);
        
        Swal.fire({
            icon: 'success',
            title: 'Printer Connected',
            text: `Successfully paired with ${printerDevice.name}`,
            timer: 2000,
            showConfirmButton: false
        });

    } catch (error) {
        addLog(`Error: ${error.message}`);
        updateUI('disconnected');
        if (error.name !== 'NotFoundError') {
            Swal.fire('Connection Failed', error.message, 'error');
        }
    }
}

function onDisconnected() {
    addLog('Device disconnected.');
    updateUI('disconnected');
}

function disconnectPrinter() {
    if (printerDevice && printerDevice.gatt.connected) {
        printerDevice.gatt.disconnect();
    }
    updateUI('disconnected');
}

function updateUI(status, name = '') {
    const statusBadge = document.getElementById('printerStatus');
    const nameView = document.getElementById('printerNameView');
    const btnSearch = document.getElementById('btnSearch');
    const btnDisconnect = document.getElementById('btnDisconnect');

    if (status === 'connected') {
        statusBadge.className = 'status-badge status-connected';
        statusBadge.innerHTML = '<i class="fa-solid fa-check"></i> Connected';
        nameView.innerText = name;
        btnSearch.style.display = 'none';
        btnDisconnect.style.display = 'flex';
    } else if (status === 'searching') {
        statusBadge.className = 'status-badge status-searching pulse';
        statusBadge.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Connecting...';
        nameView.innerText = name;
    } else {
        statusBadge.className = 'status-badge status-disconnected';
        statusBadge.innerHTML = '<i class="fa-solid fa-circle"></i> Not Connected';
        nameView.innerText = 'Select Thermal Printer';
        btnSearch.style.display = 'flex';
        btnDisconnect.style.display = 'none';
    }
}

async function testDirectBT() {
    if (!printerCharacteristic) {
        Swal.fire('Not Connected', 'Please connect a printer via Direct BT first.', 'warning');
        return;
    }

    try {
        addLog('Sending test print command...');
        const encoder = new TextEncoder();
        
        // Basic ESC/POS Test
        const testData = new Uint8Array([
            0x1B, 0x40, // Initialize
            ...encoder.encode("\n\n"),
            ...encoder.encode("   JUSTSALE POS TEST   \n"),
            ...encoder.encode("-----------------------\n"),
            ...encoder.encode("Status: SUCCESSFUL\n"),
            ...encoder.encode(`Time: ${new Date().toLocaleString()}\n`),
            ...encoder.encode("-----------------------\n"),
            ...encoder.encode("\n\n\n\n"),
            0x1D, 0x56, 0x42, 0x00 // Paper cut (partial)
        ]);

        // Break into chunks if needed (MTU limits)
        const CHUNK_SIZE = 20;
        for (let i = 0; i < testData.length; i += CHUNK_SIZE) {
            const chunk = testData.slice(i, i + CHUNK_SIZE);
            await printerCharacteristic.writeValue(chunk);
        }

        addLog('✅ Test sequence sent.');
    } catch (error) {
        addLog(`Print Error: ${error.message}`);
        Swal.fire('Print Failed', error.message, 'error');
    }
}

function testRawBT() {
    addLog('Triggering RawBT Test...');
    const baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
    const testUrl = `${baseUrl}api/print.php?action=get_test`;
    
    // RawBT scheme works on HTTP
    window.location.href = `rawbt:${testUrl}`;
}

function testIOS() {
    addLog('Opening Test Receipt...');
    const baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
    const testUrl = `${baseUrl}api/print.php?action=get_test`;
    
    if (navigator.share && window.isSecureContext) {
        addLog('Using native share sheet...');
        navigator.share({
            title: 'Test Receipt',
            url: testUrl
        }).catch(() => {
            window.open(testUrl, '_blank');
        });
    } else {
        addLog('Insecure context: Opening file directly...');
        window.open(testUrl, '_blank');
    }
}
