/**
 * Enhanced Printer Manager
 * Supports multiple print methods with smart fallback
 * - Web Bluetooth (BLE)
 * - RawBT Intent (Bluetooth Classic)
 * - Web Print API
 * - Share API
 */

class PrinterManager {
    constructor() {
        this.thermalPrinter = window.ThermalPrinter ? new ThermalPrinter() : null;
        this.printMethod = null;
        this.detectedMethod = this.detectPrintMethod();
    }

    /**
     * Detect best available print method
     */
    detectPrintMethod() {
        // Check if RawBT is installed
        if (this.isRawBTInstalled()) {
            console.log('[PrinterManager] RawBT detected');
            return 'rawbt';
        }

        // Check if Web Bluetooth is available
        if (navigator.bluetooth) {
            console.log('[PrinterManager] Web Bluetooth available');
            return 'web-bluetooth';
        }

        // Fallback to standard print
        console.log('[PrinterManager] Using standard print');
        return 'standard';
    }

    /**
     * Check if RawBT app is installed
     */
    isRawBTInstalled() {
        // RawBT intent: rawbt:
        // We can't directly detect, but we can try to use it
        return /Android/i.test(navigator.userAgent);
    }

    /**
     * Print via RawBT Intent (for Bluetooth Classic printers)
     */
    async printViaRawBT(estrut) {
        try {
            // Convert receipt data to ESC/POS commands
            const escposData = this.generateESCPOS(estrut);
            
            // Encode to base64 for intent
            const base64Data = btoa(escposData);
            
            // Build RawBT intent URL
            // Format: rawbt:base64:{base64_encoded_data}
            const intentUrl = `rawbt:base64:${base64Data}`;
            
            console.log('[PrinterManager] Opening RawBT intent...');
            
            // Try to open intent
            window.location.href = intentUrl;
            
            // Alternative method: use intent:// scheme
            // const fallbackUrl = `intent://send/#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;S.base64=${base64Data};end`;
            // window.location.href = fallbackUrl;
            
            return true;
        } catch (error) {
            console.error('[PrinterManager] RawBT print failed:', error);
            throw new Error('RawBT print failed: ' + error.message);
        }
    }

    /**
     * Print via Web Bluetooth (BLE)
     */
    async printViaWebBluetooth(data) {
        if (!this.thermalPrinter) {
            throw new Error('ThermalPrinter not available');
        }

        await this.thermalPrinter.connect();
        await this.thermalPrinter.printReceipt(data);
        this.thermalPrinter.disconnect();
    }

    /**
     * Print via standard browser print
     */
    printViaStandard() {
        window.print();
    }

    /**
     * Smart print - automatically choose best method
     */
    async smartPrint(data) {
        console.log('[PrinterManager] Smart print with method:', this.detectedMethod);

        try {
            switch (this.detectedMethod) {
                case 'rawbt':
                    await this.printViaRawBT(data);
                    break;

                case 'web-bluetooth':
                    await this.printViaWebBluetooth(data);
                    break;

                default:
                    this.printViaStandard();
                    break;
            }
        } catch (error) {
            console.error('[PrinterManager] Print failed, trying fallback...', error);
            
            // Try fallback
            if (this.detectedMethod !== 'standard') {
                this.printViaStandard();
            } else {
                throw error;
            }
        }
    }

    /**
     * Show print method selector dialog
     */
    showPrintDialog(data) {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
        modal.innerHTML = `
            <div class="bg-white rounded-lg max-w-md w-full p-6">
                <h3 class="text-xl font-bold mb-4">Pilih Metode Print</h3>
                
                <div class="space-y-3 mb-6">
                    ${this.isRawBTInstalled() ? `
                    <button onclick="printerManager.handlePrintMethod('rawbt')" 
                            class="w-full bg-blue-500 hover:bg-blue-600 text-white p-4 rounded-lg text-left flex items-center gap-3">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                        </svg>
                        <div>
                            <div class="font-semibold">RawBT (Bluetooth Classic)</div>
                            <div class="text-sm opacity-90">Untuk printer thermal Bluetooth</div>
                        </div>
                    </button>
                    ` : ''}
                    
                    ${navigator.bluetooth ? `
                    <button onclick="printerManager.handlePrintMethod('web-bluetooth')" 
                            class="w-full bg-indigo-500 hover:bg-indigo-600 text-white p-4 rounded-lg text-left flex items-center gap-3">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"></path>
                        </svg>
                        <div>
                            <div class="font-semibold">Web Bluetooth (BLE)</div>
                            <div class="text-sm opacity-90">Untuk printer BLE modern</div>
                        </div>
                    </button>
                    ` : ''}
                    
                    <button onclick="printerManager.handlePrintMethod('standard')" 
                            class="w-full bg-gray-500 hover:bg-gray-600 text-white p-4 rounded-lg text-left flex items-center gap-3">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path>
                        </svg>
                        <div>
                            <div class="font-semibold">Printer Biasa</div>
                            <div class="text-sm opacity-90">Print dialog browser</div>
                        </div>
                    </button>
                </div>
                
                <button onclick="document.getElementById('print-method-modal').remove()" 
                        class="w-full border border-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-50">
                    Batal
                </button>
            </div>
        `;
        
        modal.id = 'print-method-modal';
        document.body.appendChild(modal);

        // Store data for later use
        this.pendingPrintData = data;
    }

    /**
     * Handle print method selection
     */
    async handlePrintMethod(method) {
        const modal = document.getElementById('print-method-modal');
        if (modal) modal.remove();

        const data = this.pendingPrintData;
        if (!data) return;

        try {
            switch (method) {
                case 'rawbt':
                    await this.printViaRawBT(data);
                    if (window.showToast) {
                        showToast('Data dikirim ke RawBT!', 'success');
                    }
                    break;

                case 'web-bluetooth':
                    await this.printViaWebBluetooth(data);
                    if (window.showToast) {
                        showToast('Print berhasil!', 'success');
                    }
                    break;

                case 'standard':
                    this.printViaStandard();
                    break;
            }
        } catch (error) {
            console.error('[PrinterManager] Print error:', error);
            if (window.showToast) {
                showToast('Print gagal: ' + error.message, 'error');
            } else {
                alert('Print gagal: ' + error.message);
            }
        }
    }

    /**
     * Generate ESC/POS commands from receipt data
     */
    generateESCPOS(data) {
        const ESC = '\x1B';
        const GS = '\x1D';
        let commands = '';

        // Initialize
        commands += ESC + '@';

        // Header - Center, Bold, Double
        commands += ESC + 'a' + '\x01'; // Center
        commands += GS + '!' + '\x11';  // Double size
        commands += ESC + 'E' + '\x01'; // Bold on
        commands += 'UMBUL Sungsang\n';
        commands += ESC + 'E' + '\x00'; // Bold off
        commands += GS + '!' + '\x00';  // Normal size
        commands += 'Aryaguna Nusantara\n';
        commands += 'Pengging, Boyolali\n';
        commands += '\n';
        commands += ESC + 'a' + '\x00'; // Left align
        commands += '================================\n';

        // Info
        commands += `No: ${data.id}\n`;
        commands += `Tgl: ${data.tanggal}\n`;
        commands += `Kasir: ${data.kasir}\n`;
        commands += '--------------------------------\n';

        // Items
        for (const item of data.items) {
            commands += item.nama + '\n';
            const qty = `${item.quantity} x Rp ${this.formatNumber(item.harga)}`;
            const subtotal = `Rp ${this.formatNumber(item.subtotal)}`;
            const itemLine = qty.padEnd(20) + subtotal.padStart(12);
            commands += itemLine + '\n';
        }

        commands += '--------------------------------\n';

        // Total
        commands += ESC + 'E' + '\x01'; // Bold on
        commands += GS + '!' + '\x11';  // Double size
        const totalLine = 'TOTAL:'.padEnd(14) + `Rp ${this.formatNumber(data.total)}`.padStart(18);
        commands += totalLine + '\n';
        commands += ESC + 'E' + '\x00'; // Bold off
        commands += GS + '!' + '\x00';  // Normal size

        commands += '================================\n';
        commands += ESC + 'a' + '\x01'; // Center
        commands += '\n';
        commands += 'Terima Kasih\n';
        commands += 'Selamat Berkunjung Kembali\n';
        commands += '\n\n\n';

        // Cut paper
        commands += ESC + 'd' + '\x03'; // Feed 3 lines
        commands += GS + 'V' + '\x00';   // Cut

        return commands;
    }

    /**
     * Format number helper
     */
    formatNumber(num) {
        return Number(num).toLocaleString('id-ID');
    }
}

// Initialize
const printerManager = new PrinterManager();
window.printerManager = printerManager;

console.log('[PrinterManager] Initialized with method:', printerManager.detectedMethod);
