(function() {
    'use strict';
    
    // Pega token da URL
    const pathParts = window.location.pathname.split('/');
    const token = pathParts[pathParts.length - 1];
    
    // Limpa token da URL (segurança!)
    window.history.replaceState({}, '', '/receivable');
    
    // Guarda token pra uso posterior
    sessionStorage.setItem('receivable_token', token);
    
    // Busca dados via POST
    fetch('/api/receivables/view.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ token: token })
    })
    .then(function(response) {
        if (!response.ok) {
            return response.json().then(function(data) {
                throw new Error(data.error || 'Erro desconhecido');
            });
        }
        return response.json();
    })
    .then(function(data) {
        document.getElementById('loading').style.display = 'none';
        document.getElementById('content').style.display = 'block';
        renderContent(data);
    })
    .catch(function(error) {
        document.getElementById('loading').style.display = 'none';
        document.getElementById('error').style.display = 'block';
        document.getElementById('error-message').textContent = error.message;
    });
    
    function renderContent(data) {
        const r = data.receivable;
        const c = data.customer;
        const f = data.files;
        
        let html = '<div class="card"><h2>Dados da Cobrança</h2>';
        
        html += createInfoRow('Documento', r.document_number);
        
        if (r.invoice_number) {
            const nf = (r.invoice_series || '') + ' ' + r.invoice_number;
            html += createInfoRow('Nota Fiscal', nf);
        }
        
        html += createInfoRow('Emissão', formatDate(r.issue_date));
        html += createInfoRow('Vencimento', formatDate(r.due_date));
        html += createInfoRow('Valor', r.amount_formatted);
        html += '<div class="info-row">';
        html += '<span class="info-label">Status:</span>';
        html += '<span class="info-value">';
        html += '<span class="status ' + r.status + '">' + r.status_label + '</span>';
        html += '</span></div>';
        html += '</div>';
        
        html += '<div class="card"><h2>Downloads</h2>';
        
        if (f.boleto && f.boleto.available) {
            html += '<a href="' + f.boleto.download_url + '" class="btn" data-action="downloaded_boleto">📄 ' + f.boleto.name + '</a>';
        }
        
        if (f.invoice_pdf && f.invoice_pdf.available) {
            html += '<a href="' + f.invoice_pdf.download_url + '" class="btn" data-action="downloaded_invoice_pdf">📄 ' + f.invoice_pdf.name + '</a>';
        }
        
        if (f.invoice_xml && f.invoice_xml.available) {
            html += '<a href="' + f.invoice_xml.download_url + '" class="btn" data-action="downloaded_invoice_xml">📋 ' + f.invoice_xml.name + '</a>';
        }
        
        html += '</div>';
        
        if (r.barcode) {
            html += '<div class="card">';
            html += '<h2>Código de Barras</h2>';
            html += '<div class="barcode">' + r.barcode + '</div>';
            html += '<button class="btn" data-barcode="' + r.barcode + '">📋 Copiar Código</button>';
            html += '</div>';
        }
        
        document.getElementById('content').innerHTML = html;
        
        attachEventListeners();
    }
    
    function attachEventListeners() {
        // Download buttons
        const downloadButtons = document.querySelectorAll('.btn[data-action]');
        downloadButtons.forEach(function(btn) {
            btn.addEventListener('click', function() {
                const action = this.getAttribute('data-action');
                logAction(action);
            });
        });
        
        // Copy barcode button
        const copyButton = document.querySelector('.btn[data-barcode]');
        if (copyButton) {
            copyButton.addEventListener('click', function() {
                const barcode = this.getAttribute('data-barcode');
                copyBarcode(barcode);
            });
        }
    }
    
    function createInfoRow(label, value) {
        return '<div class="info-row">' +
               '<span class="info-label">' + label + ':</span>' +
               '<span class="info-value">' + value + '</span>' +
               '</div>';
    }
    
    function formatDate(dateStr) {
        if (!dateStr) return '-';
        const parts = dateStr.split('-');
        return parts[2] + '/' + parts[1] + '/' + parts[0];
    }
    
    function copyBarcode(barcode) {
        navigator.clipboard.writeText(barcode).then(function() {
            alert('Código copiado!');
            logAction('copied_barcode');
        });
    }
    
    function logAction(action) {
        const token = sessionStorage.getItem('receivable_token');
        
        fetch('/api/logs/access.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                token: token,
                action: action
            })
        });
    }
    
})();