/**
 * WHATS CRM - Notification & Patch Service
 * Força o status Premium e gerencia notificações administrativas.
 */

(function() {
    console.log('WHATS CRM: Patch Service Ativo');

    // 1. Monitor de Estado Premium (Garante persistência local)
    setInterval(() => {
        try {
            // Verifica o core state no localStorage
            const session = localStorage.getItem('core_wam_meta');
            if (session) {
                const data = JSON.parse(session);
                let changed = false;

                if (data.session && (data.session.user_status !== 'active' || !data.session.is_premium)) {
                    data.session.user_status = 'active';
                    data.session.is_premium = true;
                    changed = true;
                }

                if (data.user && data.user.user_premium?.status !== 'active') {
                    data.user.user_premium = {
                        data_liberacao: "2099-12-31T23:59:59Z",
                        status: "active"
                    };
                    changed = true;
                }

                if (changed) {
                    localStorage.setItem('core_wam_meta', JSON.stringify(data));
                    // console.log('WHATS CRM: Status Premium Restaurado');
                }
            }
            
            // Força o token de bypass no localStorage se necessário
            if (localStorage.getItem('wam_session_state') !== 'true') {
                localStorage.setItem('wam_session_state', 'true');
            }
        } catch (e) {}
    }, 10000);

    // 2. Sistema de Notificações
    async function buscarNotificacoes() {
        try {
            const response = await fetch('https://whats-crm-api-production.up.railway.app/notifications');
            if (!response.ok) return;
            
            const notificacoes = await response.json();
            // Notificações da API geralmente vem como um array de objetos { id, title, content, active }
            const ativas = notificacoes.filter(n => n.active);
            
            for (const notif of ativas) {
                const vistaKey = `wac_notif_v74_${notif.id}`;
                if (!localStorage.getItem(vistaKey)) {
                    exibirModalNotificacao(notif);
                    break; // Mostra apenas uma por vez
                }
            }
        } catch (error) {
            // Silencioso em caso de erro de rede
        }
    }

    function exibirModalNotificacao(notif) {
        const modalId = `wac-notif-container-${notif.id}`;
        if (document.getElementById(modalId)) return;

        const overlay = document.createElement('div');
        overlay.id = modalId;
        overlay.style.cssText = `
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.75); display: flex; align-items: center;
            justify-content: center; z-index: 9999999; font-family: sans-serif;
            backdrop-filter: blur(4px);
        `;

        const modal = document.createElement('div');
        modal.style.cssText = `
            background: #fff; width: 500px; max-width: 90%; border-radius: 16px;
            overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            animation: wacSlideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
            border: 1px solid rgba(255,255,255,0.1);
        `;

        const header = document.createElement('div');
        header.style.cssText = `
            padding: 24px; background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
            color: #fff; position: relative;
        `;
        header.innerHTML = `
            <h2 style="margin:0; font-size: 20px; font-weight: 700; line-height: 1.2;">${notif.title}</h2>
            <p style="margin: 8px 0 0 0; opacity: 0.9; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px;">Comunicado Oficial</p>
        `;

        const closeBtn = document.createElement('button');
        closeBtn.innerHTML = '&times;';
        closeBtn.style.cssText = `
            position: absolute; top: 16px; right: 16px; background: rgba(0,0,0,0.1);
            border: none; color: #fff; font-size: 28px; cursor: pointer;
            width: 32px; height: 32px; border-radius: 50%; display: flex;
            align-items: center; justify-content: center; transition: all 0.2s;
        `;
        closeBtn.onclick = () => {
            overlay.style.opacity = '0';
            overlay.style.transition = 'opacity 0.3s';
            setTimeout(() => {
                if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
            }, 300);
            localStorage.setItem(`wac_notif_v74_${notif.id}`, 'true');
        };
        header.appendChild(closeBtn);

        const body = document.createElement('div');
        body.style.cssText = `
            padding: 32px; color: #1c1e21; line-height: 1.6; font-size: 16px;
            max-height: 60vh; overflow-y: auto;
        `;
        body.innerHTML = notif.content;

        const footer = document.createElement('div');
        footer.style.cssText = `
            padding: 20px 32px; background: #f0f2f5; text-align: right;
            border-top: 1px solid #e4e6eb;
        `;

        const okBtn = document.createElement('button');
        okBtn.innerText = 'Entendi';
        okBtn.style.cssText = `
            background: #128C7E; color: #fff; border: none; padding: 12px 32px;
            border-radius: 8px; font-weight: 600; cursor: pointer;
            transition: transform 0.1s, background 0.2s; font-size: 15px;
        `;
        okBtn.onmouseover = () => okBtn.style.background = '#075E54';
        okBtn.onmouseout = () => okBtn.style.background = '#128C7E';
        okBtn.onmousedown = () => okBtn.style.transform = 'scale(0.96)';
        okBtn.onmouseup = () => okBtn.style.transform = 'scale(1)';
        okBtn.onclick = closeBtn.onclick;
        
        footer.appendChild(okBtn);

        modal.appendChild(header);
        modal.appendChild(body);
        modal.appendChild(footer);
        overlay.appendChild(modal);
        document.body.appendChild(overlay);

        if (!document.getElementById('wac-notif-styles')) {
            const style = document.createElement('style');
            style.id = 'wac-notif-styles';
            style.innerHTML = `
                @keyframes wacSlideUp {
                    from { opacity: 0; transform: translateY(40px) scale(0.95); }
                    to { opacity: 1; transform: translateY(0) scale(1); }
                }
                #wac-notif-container-${notif.id} b { color: #128C7E; }
            `;
            document.head.appendChild(style);
        }
    }

    // Inicialização
    if (document.readyState === 'complete') {
        setTimeout(buscarNotificacoes, 4000);
    } else {
        window.addEventListener('load', () => setTimeout(buscarNotificacoes, 4000));
    }
})();
