// PWA Install Handler
let deferredPrompt;
let installButton;

// Register Service Worker
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js')
            .then(reg => console.log('SW registrado:', reg.scope))
            .catch(err => console.log('Erro SW:', err));
    });
}

// Capture install prompt
window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPrompt = e;
    showInstallBanner();
});

// Show install banner
function showInstallBanner() {
    // Remove existing banner
    const existing = document.getElementById('pwa-install-banner');
    if (existing) existing.remove();
    
    const banner = document.createElement('div');
    banner.id = 'pwa-install-banner';
    banner.innerHTML = `
        <style>
            #pwa-install-banner {
                position: fixed;
                bottom: 0;
                left: 0;
                right: 0;
                background: linear-gradient(135deg, #1a73e8 0%, #0d47a1 100%);
                color: white;
                padding: 16px 20px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 15px;
                z-index: 10000;
                box-shadow: 0 -4px 20px rgba(0,0,0,0.3);
                animation: slideUp 0.4s ease;
            }
            @keyframes slideUp {
                from { transform: translateY(100%); }
                to { transform: translateY(0); }
            }
            #pwa-install-banner .content {
                display: flex;
                align-items: center;
                gap: 15px;
                flex: 1;
            }
            #pwa-install-banner .icon {
                width: 50px;
                height: 50px;
                background: white;
                border-radius: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 28px;
                flex-shrink: 0;
            }
            #pwa-install-banner .text h4 {
                font-size: 16px;
                font-weight: 600;
                margin-bottom: 2px;
            }
            #pwa-install-banner .text p {
                font-size: 13px;
                opacity: 0.9;
            }
            #pwa-install-banner .buttons {
                display: flex;
                gap: 10px;
                flex-shrink: 0;
            }
            #pwa-install-banner .btn-install {
                background: white;
                color: #1a73e8;
                border: none;
                padding: 12px 24px;
                border-radius: 25px;
                font-size: 14px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s;
            }
            #pwa-install-banner .btn-install:hover {
                transform: scale(1.05);
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            }
            #pwa-install-banner .btn-close {
                background: transparent;
                color: white;
                border: 2px solid rgba(255,255,255,0.5);
                padding: 10px 16px;
                border-radius: 25px;
                font-size: 14px;
                cursor: pointer;
            }
            @media (max-width: 500px) {
                #pwa-install-banner {
                    flex-direction: column;
                    text-align: center;
                }
                #pwa-install-banner .content {
                    flex-direction: column;
                }
            }
        </style>
        <div class="content">
            <div class="icon">🚚</div>
            <div class="text">
                <h4>Instale o Já EntreGo</h4>
                <p>Adicione à tela inicial para acesso rápido!</p>
            </div>
        </div>
        <div class="buttons">
            <button class="btn-install" onclick="installPWA()">Instalar App</button>
            <button class="btn-close" onclick="closeBanner()">Agora não</button>
        </div>
    `;
    document.body.appendChild(banner);
}

// Install PWA
function installPWA() {
    if (!deferredPrompt) {
        alert('Para instalar, use o menu do navegador > "Adicionar à tela inicial"');
        return;
    }
    
    deferredPrompt.prompt();
    deferredPrompt.userChoice.then((choiceResult) => {
        if (choiceResult.outcome === 'accepted') {
            console.log('PWA instalado');
        }
        deferredPrompt = null;
        closeBanner();
    });
}

// Close banner
function closeBanner() {
    const banner = document.getElementById('pwa-install-banner');
    if (banner) {
        banner.style.animation = 'slideDown 0.3s ease forwards';
        setTimeout(() => banner.remove(), 300);
    }
    // Don't show again for 24h
    localStorage.setItem('pwa-banner-closed', Date.now());
}

// Check if should show banner
function shouldShowBanner() {
    const closed = localStorage.getItem('pwa-banner-closed');
    if (closed) {
        const hoursPassed = (Date.now() - parseInt(closed)) / (1000 * 60 * 60);
        return hoursPassed > 24;
    }
    return true;
}

// App installed
window.addEventListener('appinstalled', () => {
    console.log('App instalado com sucesso!');
    closeBanner();
});

// iOS detection and instructions
function isIOS() {
    return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
}

function isInStandaloneMode() {
    return window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;
}

// Show iOS instructions
function showIOSInstructions() {
    if (isIOS() && !isInStandaloneMode() && shouldShowBanner()) {
        const banner = document.createElement('div');
        banner.id = 'pwa-install-banner';
        banner.innerHTML = `
            <style>
                #pwa-install-banner {
                    position: fixed;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background: linear-gradient(135deg, #1a73e8 0%, #0d47a1 100%);
                    color: white;
                    padding: 20px;
                    z-index: 10000;
                    box-shadow: 0 -4px 20px rgba(0,0,0,0.3);
                    animation: slideUp 0.4s ease;
                    text-align: center;
                }
                @keyframes slideUp {
                    from { transform: translateY(100%); }
                    to { transform: translateY(0); }
                }
                #pwa-install-banner .icon { font-size: 40px; margin-bottom: 10px; }
                #pwa-install-banner h4 { font-size: 18px; margin-bottom: 10px; }
                #pwa-install-banner p { font-size: 14px; opacity: 0.9; margin-bottom: 15px; }
                #pwa-install-banner .steps { font-size: 13px; background: rgba(255,255,255,0.1); padding: 12px; border-radius: 10px; }
                #pwa-install-banner .btn-close { background: transparent; color: white; border: none; font-size: 14px; cursor: pointer; margin-top: 15px; text-decoration: underline; }
            </style>
            <div class="icon">🚚</div>
            <h4>Instale o Já EntreGo</h4>
            <p>Adicione à tela inicial para uma experiência completa!</p>
            <div class="steps">
                1. Toque em <strong>Compartilhar</strong> ⬆️<br>
                2. Role e toque em <strong>"Adicionar à Tela de Início"</strong>
            </div>
            <button class="btn-close" onclick="closeBanner()">Entendi</button>
        `;
        document.body.appendChild(banner);
    }
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    if (isIOS()) {
        showIOSInstructions();
    }
});

// Função para tocar som de notificação
function tocarSomNotificacao(tipo = 'default') {
    try {
        // Tentar tocar som personalizado primeiro
        const audio = new Audio('/assets/sounds/notificacao.mp3');
        audio.volume = 0.7;
        audio.play().catch(() => {
            // Fallback para som sintético se falhar
            tocarSomSintetico(tipo);
        });
    } catch (e) {
        // Fallback para som sintético
        tocarSomSintetico(tipo);
    }
    
    // Vibração
    if ('vibrate' in navigator) {
        if (tipo === 'entregue') {
            navigator.vibrate([200, 100, 200, 100, 300]);
        } else {
            navigator.vibrate([200, 100, 200]);
        }
    }
}

// Som sintético como fallback
function tocarSomSintetico(tipo) {
    try {
        const ctx = new (window.AudioContext || window.webkitAudioContext)();
        
        // Frequências diferentes por tipo
        const freq1 = tipo === 'entregue' ? 523 : 880; // C5 ou A5
        const freq2 = tipo === 'entregue' ? 659 : 1100; // E5 ou C#6
        const freq3 = tipo === 'entregue' ? 784 : 0; // G5 (só para entregue)
        
        // Primeira nota
        const osc1 = ctx.createOscillator();
        const gain1 = ctx.createGain();
        osc1.connect(gain1);
        gain1.connect(ctx.destination);
        osc1.frequency.setValueAtTime(freq1, ctx.currentTime);
        osc1.type = 'sine';
        gain1.gain.setValueAtTime(0, ctx.currentTime);
        gain1.gain.linearRampToValueAtTime(0.5, ctx.currentTime + 0.1);
        gain1.gain.linearRampToValueAtTime(0, ctx.currentTime + 0.4);
        osc1.start(ctx.currentTime);
        osc1.stop(ctx.currentTime + 0.4);
        
        // Segunda nota
        setTimeout(() => {
            const osc2 = ctx.createOscillator();
            const gain2 = ctx.createGain();
            osc2.connect(gain2);
            gain2.connect(ctx.destination);
            osc2.frequency.setValueAtTime(freq2, ctx.currentTime);
            osc2.type = 'sine';
            gain2.gain.setValueAtTime(0, ctx.currentTime);
            gain2.gain.linearRampToValueAtTime(0.5, ctx.currentTime + 0.1);
            gain2.gain.linearRampToValueAtTime(0, ctx.currentTime + 0.4);
            osc2.start(ctx.currentTime);
            osc2.stop(ctx.currentTime + 0.4);
        }, 150);
        
        // Terceira nota (só para entregue - som de vitória)
        if (freq3) {
            setTimeout(() => {
                const osc3 = ctx.createOscillator();
                const gain3 = ctx.createGain();
                osc3.connect(gain3);
                gain3.connect(ctx.destination);
                osc3.frequency.setValueAtTime(freq3, ctx.currentTime);
                osc3.type = 'sine';
                gain3.gain.setValueAtTime(0, ctx.currentTime);
                gain3.gain.linearRampToValueAtTime(0.6, ctx.currentTime + 0.1);
                gain3.gain.linearRampToValueAtTime(0, ctx.currentTime + 0.6);
                osc3.start(ctx.currentTime);
                osc3.stop(ctx.currentTime + 0.6);
            }, 300);
        }
    } catch (e) {
        console.log('Erro ao tocar som:', e);
    }
}

// Disponibilizar globalmente
window.tocarSomNotificacao = tocarSomNotificacao;