// ═══════════════════════════════════════════════
// Product Sequencing App — Frontend JS
// ═══════════════════════════════════════════════

document.addEventListener('DOMContentLoaded', () => {

    // ── File Upload & Drag-Drop ──
    const uploadForm  = document.getElementById('upload-form');
    const fileInput   = document.getElementById('excel-file');
    const fileDisplay = document.getElementById('file-name-display');
    const dropzone    = document.getElementById('dropzone');
    const processBtn  = document.getElementById('process-btn');
    const overlay     = document.getElementById('processing-overlay');
    const resultsContainer = document.getElementById('results-container');
    const resultsBody      = document.getElementById('results-body');

    // File input change
    if (fileInput) {
        fileInput.addEventListener('change', () => {
            if (fileInput.files.length > 0) {
                fileDisplay.textContent = fileInput.files[0].name;
                fileDisplay.style.color = '#1a1c1d';
            }
        });
    }

    // Drag & drop
    if (dropzone) {
        ['dragenter', 'dragover'].forEach(evt => {
            dropzone.addEventListener(evt, (e) => {
                e.preventDefault();
                dropzone.classList.add('dragover');
            });
        });

        ['dragleave', 'drop'].forEach(evt => {
            dropzone.addEventListener(evt, (e) => {
                e.preventDefault();
                dropzone.classList.remove('dragover');
            });
        });

        dropzone.addEventListener('drop', (e) => {
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                const dt = new DataTransfer();
                dt.items.add(files[0]);
                fileInput.files = dt.files;
                fileDisplay.textContent = files[0].name;
                fileDisplay.style.color = '#1a1c1d';
            }
        });
    }

    // Form submission via AJAX
    if (uploadForm) {
        uploadForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            if (!fileInput.files.length) {
                showToast('Please select a file first.', 'error');
                return;
            }

            overlay.style.display = 'flex';
            if (processBtn) processBtn.disabled = true;

            const formData = new FormData(uploadForm);

            try {
                const response = await fetch('api/process_upload.php', {
                    method: 'POST',
                    body: formData,
                });

                const data = await response.json();
                overlay.style.display = 'none';
                if (processBtn) processBtn.disabled = false;

                if (data.success) {
                    showToast(`${data.message}`, 'success');
                    renderResults(data.results || []);
                } else {
                    if (data.upgrade) {
                        showToast(data.message, 'error');
                        // Redirect to billing after a moment
                        setTimeout(() => {
                            window.location.href = '?page=billing&shop=' + APP_CONFIG.shop;
                        }, 2500);
                    } else {
                        showToast(data.message || 'Processing failed.', 'error');
                    }
                }

            } catch (err) {
                overlay.style.display = 'none';
                if (processBtn) processBtn.disabled = false;
                showToast('Server error. Please try again.', 'error');
                console.error(err);
            }
        });
    }

    // Render results table
    function renderResults(results) {
        if (!resultsContainer || !resultsBody) return;
        if (results.length === 0) {
            resultsContainer.style.display = 'none';
            return;
        }

        resultsBody.innerHTML = '';
        results.forEach((r, i) => {
            const row = document.createElement('tr');
            const statusClass = r.status === 'success' ? 'success' 
                              : r.status === 'warning' ? 'pending' 
                              : 'error';
            row.innerHTML = `
                <td>${i + 1}</td>
                <td><strong>${escapeHtml(r.sku)}</strong></td>
                <td>${escapeHtml(r.collection || '-')}</td>
                <td>${escapeHtml(r.type || '-')}</td>
                <td>${r.position || '-'}</td>
                <td><span class="status-badge ${statusClass}">${capitalize(r.status)}</span>
                    <small style="display:block;color:#9ca3af;margin-top:2px">${escapeHtml(r.msg || '')}</small>
                </td>
            `;
            resultsBody.appendChild(row);
        });

        resultsContainer.style.display = 'block';
        resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }


    // ── Razorpay Subscription ──
    document.querySelectorAll('.subscribe-btn').forEach(btn => {
        btn.addEventListener('click', async () => {
            const planId   = btn.dataset.planId;
            const planName = btn.dataset.planName;
            const price    = btn.dataset.price;

            btn.disabled = true;
            btn.textContent = 'Processing...';

            try {
                // Step 1: Create subscription on server
                const res = await fetch('razorpay/create_subscription.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ plan_id: parseInt(planId) }),
                });
                const data = await res.json();

                if (!data.success) {
                    showToast(data.message || 'Failed to create subscription', 'error');
                    btn.disabled = false;
                    btn.textContent = 'Subscribe Now';
                    return;
                }

                // Step 2: Open Razorpay Checkout
                const options = {
                    key: data.razorpay_key,
                    subscription_id: data.subscription_id,
                    name: 'Sequencer Pro',
                    description: `${planName} Plan — Monthly Subscription`,
                    image: '', // Add your logo URL
                    prefill: {
                        name: APP_CONFIG.storeName,
                        email: APP_CONFIG.storeEmail,
                    },
                    notes: {
                        shop: APP_CONFIG.shop,
                    },
                    theme: {
                        color: '#008060',
                    },
                    handler: async function(response) {
                        // Step 3: Verify payment on server
                        try {
                            const verifyRes = await fetch('razorpay/verify_payment.php', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({
                                    razorpay_payment_id: response.razorpay_payment_id,
                                    razorpay_subscription_id: response.razorpay_subscription_id,
                                    razorpay_signature: response.razorpay_signature,
                                }),
                            });
                            const verifyData = await verifyRes.json();

                            if (verifyData.success) {
                                showToast('Subscription activated! Refreshing...', 'success');
                                setTimeout(() => location.reload(), 1500);
                            } else {
                                showToast(verifyData.message || 'Verification failed', 'error');
                            }
                        } catch (err) {
                            showToast('Payment verification error', 'error');
                            console.error(err);
                        }
                    },
                    modal: {
                        ondismiss: function() {
                            btn.disabled = false;
                            btn.textContent = 'Subscribe Now';
                            showToast('Payment cancelled.', 'info');
                        }
                    }
                };

                const rzp = new Razorpay(options);
                rzp.on('payment.failed', function(response) {
                    showToast('Payment failed: ' + (response.error?.description || 'Unknown error'), 'error');
                    btn.disabled = false;
                    btn.textContent = 'Subscribe Now';
                });
                rzp.open();

            } catch (err) {
                showToast('Error initiating payment', 'error');
                btn.disabled = false;
                btn.textContent = 'Subscribe Now';
                console.error(err);
            }
        });
    });


    // ── Toast Notification ──
    function showToast(message, type = 'info') {
        // Remove existing toasts
        document.querySelectorAll('.toast-notification').forEach(t => t.remove());

        const toast = document.createElement('div');
        toast.className = `toast-notification toast-${type}`;
        toast.innerHTML = `
            <span class="toast-icon">${type === 'success' ? '✓' : type === 'error' ? '✕' : 'ℹ'}</span>
            <span class="toast-text">${escapeHtml(message)}</span>
        `;

        // Toast styles
        Object.assign(toast.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '14px 22px',
            borderRadius: '10px',
            display: 'flex',
            alignItems: 'center',
            gap: '10px',
            fontSize: '14px',
            fontWeight: '500',
            zIndex: '9999',
            boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
            animation: 'slideIn 0.3s ease',
            maxWidth: '420px',
        });

        const colors = {
            success: { bg: '#dcfce7', color: '#15803d', border: '#bbf7d0' },
            error:   { bg: '#fee2e2', color: '#b91c1c', border: '#fecaca' },
            info:    { bg: '#dbeafe', color: '#1d4ed8', border: '#bfdbfe' },
        };

        const c = colors[type] || colors.info;
        toast.style.background = c.bg;
        toast.style.color = c.color;
        toast.style.border = `1px solid ${c.border}`;

        document.body.appendChild(toast);

        // Add animation keyframes if not already added
        if (!document.getElementById('toast-styles')) {
            const style = document.createElement('style');
            style.id = 'toast-styles';
            style.textContent = `
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOut {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            `;
            document.head.appendChild(style);
        }

        setTimeout(() => {
            toast.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }


    // ── Utilities ──
    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str || '';
        return div.innerHTML;
    }

    function capitalize(str) {
        return str ? str.charAt(0).toUpperCase() + str.slice(1) : '';
    }
});
