document.addEventListener('DOMContentLoaded', () => {
    if (!window.paytoviewLiteItems || !Array.isArray(window.paytoviewLiteItems)) return;

    window.paytoviewLiteItems.forEach(item => {
        const rentButton = document.getElementById(`paytoview-rent-button-${item.slug}`);
        const paypalContainer = document.getElementById(`paypal-button-container-${item.slug}`);
        const videoContainer = document.getElementById(`paytoview-video-container-${item.slug}`);
        if (!rentButton || !paypalContainer || !videoContainer) return;

        const cookieName = `paytoview_rental_${item.slug}`;

        function hasValidCookie() {
            const cookies = document.cookie.split(';').map(c => c.trim());
            const match = cookies.find(c => c.startsWith(cookieName + '='));
            if (!match) return false;
            try {
                const rentalData = JSON.parse(decodeURIComponent(match.split('=')[1]));
                return rentalData.email &&
                       rentalData.expires &&
                       new Date(rentalData.expires) > new Date();
            } catch {
                return false;
            }
        }

        if (hasValidCookie()) {
            videoContainer.style.display = 'block';
            rentButton.style.display = 'none';
            paypalContainer.style.display = 'none';
        } else {
            videoContainer.style.display = 'none';
            rentButton.style.display = 'inline-flex';
            paypalContainer.style.display = 'none';
        }

        rentButton.addEventListener('click', () => {
            rentButton.disabled = true;
            rentButton.style.display = 'none';
            paypalContainer.style.display = 'block';

            if (!window.paypal) {
                console.error('PayPal SDK not loaded.');
                resetUI();
                return;
            }

            paypal.Buttons({
                style: {
                    layout: 'vertical',
                    color: 'gold',
                    shape: 'rect',
                    label: 'paypal'
                },
                createOrder: (data, actions) => actions.order.create({
                    purchase_units: [{ amount: { value: item.price.toFixed(2) } }],
                    application_context: { shipping_preference: 'NO_SHIPPING' }
                }),
                onApprove: (data, actions) => actions.order.capture().then(details => {
                    if (details.status !== 'COMPLETED') {
                        resetUI();
                        return;
                    }
                    const txn_id = details.id;
                    const amount = parseFloat(details.purchase_units[0].amount.value);
                    const email = details.payer.email_address;

                    fetch(`${item.ajaxurl}?action=paytoviewlite_log_rental&_ajax_nonce=${item.nonce}`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            email,
                            txn_id,
                            paymentStatus: details.status,
                            amount,
                            expireHours: item.expireHours,
                            slug: item.slug,
                            mediaFile: item.mediaFile || '',
                            mediaTitle: item.mediaTitle || ''
                        })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            const expireDate = new Date();
                            expireDate.setHours(expireDate.getHours() + parseInt(item.expireHours, 10));
                            const cookieValue = JSON.stringify({
                                email,
                                expires: expireDate.toISOString()
                            });
                            document.cookie = `${cookieName}=${encodeURIComponent(cookieValue)}; path=/; expires=${expireDate.toUTCString()}; SameSite=Lax`;
                            window.location.reload();
                        } else {
                            resetUI();
                        }
                    })
                    .catch(() => {
                        resetUI();
                    });
                }),
                onCancel: () => {
                    resetUI();
                },
                onError: () => {
                    resetUI();
                }
            }).render(`#paypal-button-container-${item.slug}`);
        });

        function resetUI() {
            rentButton.disabled = false;
            rentButton.style.display = 'inline-flex';
            paypalContainer.style.display = 'none';
            videoContainer.style.display = 'none';
        }
    });
});
