// ========================================
// ZENITH PREMIUM - CHECKOUT LOGIC
// ========================================

// --- Tab System ---
function switchTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    document.querySelector(`[data-tab="${tab}"]`).classList.add('active');
    document.getElementById(`tab-${tab}`).classList.add('active');
}

// --- Result Messages ---
function showMessage(message, type) {
    const el = document.getElementById('result-message');
    el.innerHTML = `<div class="result-box ${type === 'success' ? 'result-success' : 'result-error'}">${message}</div>`;
}

// --- PayPal Smart Buttons ---
paypal.Buttons({
    style: {
        shape: 'rect',
        color: 'gold',
        layout: 'vertical',
        label: 'pay',
        height: 50
    },

    createOrder: async function () {
        try {
            const response = await fetch("api/create-order.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    cart: [{ 
                        id: "ZENITH_PREMIUM", 
                        quantity: 1,
                        name: ORDER_DATA.evento,
                        subtotal: ORDER_DATA.subtotal,
                        comision: ORDER_DATA.comision,
                        impuesto: ORDER_DATA.impuesto,
                        total: ORDER_DATA.total
                    }]
                })
            });
            const data = await response.json();
            if (data.id) return data.id;

            const detail = data?.details?.[0];
            const msg = detail
                ? `${detail.issue} ${detail.description} (${data.debug_id})`
                : JSON.stringify(data);
            throw new Error(msg);
        } catch (err) {
            console.error("Create order error:", err);
            showMessage(`No se pudo crear la orden: ${err.message}`, 'error');
        }
    },

    onApprove: async function (data, actions) {
        try {
            const response = await fetch("api/capture-order.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ orderID: data.orderID })
            });
            const orderData = await response.json();
            const detail = orderData?.details?.[0];

            if (detail?.issue === "INSTRUMENT_DECLINED") {
                return actions.restart();
            } else if (detail) {
                throw new Error(`${detail.description} (${orderData.debug_id})`);
            } else if (!orderData.purchase_units) {
                throw new Error(JSON.stringify(orderData));
            } else {
                const tx = orderData.purchase_units[0].payments.captures[0];
                document.getElementById('paypal-button-container').style.display = 'none';
                showMessage(
                    `<span class="material-symbols-outlined align-middle mr-1" style="font-size:20px">check_circle</span> ¡Pago Exitoso! — ID de Transacción: <strong>${tx.id}</strong>`,
                    'success'
                );
            }
        } catch (err) {
            console.error("Capture error:", err);
            showMessage(`Error al procesar el pago: ${err.message}`, 'error');
        }
    },

    onError: function (err) {
        console.error("PayPal error:", err);
        showMessage("Ocurrió un error inesperado con PayPal.", 'error');
    }
}).render("#paypal-button-container").then(function () {
    const spinner = document.querySelector('#paypal-button-container .spinner');
    if (spinner) spinner.remove();
});
