/* ============================================================
   DroidTester — Campaigns JS
   ============================================================ */

(function () {
    'use strict';

    // ── App Icon Upload Preview ──
    const iconInput = document.getElementById('appIconInput');
    const iconPreview = document.getElementById('appIconPreview');
    const iconPlaceholder = document.getElementById('iconUploadPlaceholder');

    if (iconInput) {
        iconInput.addEventListener('change', function () {
            const file = this.files[0];
            if (!file) return;
            if (!file.type.startsWith('image/')) {
                alert('Please select an image file.');
                return;
            }
            const reader = new FileReader();
            reader.onload = function (e) {
                if (iconPreview) {
                    iconPreview.src = e.target.result;
                    iconPreview.style.display = 'block';
                }
                if (iconPlaceholder) iconPlaceholder.style.display = 'none';
            };
            reader.readAsDataURL(file);
        });
    }

    // Drag-and-drop on upload box
    const uploadBox = document.getElementById('iconUploadBox');
    if (uploadBox) {
        ['dragover', 'dragenter'].forEach(function (e) {
            uploadBox.addEventListener(e, function (ev) {
                ev.preventDefault();
                uploadBox.classList.add('drag-over');
            });
        });
        ['dragleave', 'drop'].forEach(function (e) {
            uploadBox.addEventListener(e, function (ev) {
                uploadBox.classList.remove('drag-over');
                if (e === 'drop' && iconInput) {
                    ev.preventDefault();
                    iconInput.files = ev.dataTransfer.files;
                    iconInput.dispatchEvent(new Event('change'));
                }
            });
        });
        uploadBox.addEventListener('click', function () { if (iconInput) iconInput.click(); });
    }

    // ── Package Selection (Radio Behavior) ──
    const packageCards = document.querySelectorAll('.package-card-select');
    packageCards.forEach(function (card) {
        card.addEventListener('click', function () {
            packageCards.forEach(function (c) { c.classList.remove('selected'); });
            this.classList.add('selected');
            const pkgName = this.dataset.package || '';
            const pkgPrice = this.dataset.price || '';
            // Update publish button tooltip or credit check
            const creditDisplay = document.getElementById('creditDisplay');
            if (creditDisplay) {
                creditDisplay.textContent = 'Package: ' + pkgName + ' — ₹' + pkgPrice;
            }
        });
    });

    // ── Add Campaign Form Validation ──
    const addCampaignForm = document.getElementById('addCampaignForm');
    if (addCampaignForm) {
        const publishBtn = document.getElementById('publishBtn');
        if (publishBtn) {
            publishBtn.addEventListener('click', function (e) {
                e.preventDefault();
                const appName = document.getElementById('appName');
                const appDev = document.getElementById('appDeveloper');
                const appLink = document.getElementById('appLink');
                const selectedPkg = document.querySelector('.package-card-select.selected');

                let valid = true;
                [appName, appDev, appLink].forEach(function (field) {
                    if (field && !field.value.trim()) {
                        field.style.borderColor = '#E85050';
                        valid = false;
                    } else if (field) {
                        field.style.borderColor = '';
                    }
                });

                if (!selectedPkg) {
                    valid = false;
                    alert('Please select a package before publishing.');
                    return;
                }

                // Simulate insufficient credits modal
                const creditsEl = document.getElementById('availableCredits');
                const credits = creditsEl ? parseInt(creditsEl.dataset.credits || '0', 10) : 100;
                const pkgCost = selectedPkg ? parseInt(selectedPkg.dataset.price || '0', 10) : 0;

                if (credits < pkgCost) {
                    if (typeof bootstrap !== 'undefined') {
                        const modal = new bootstrap.Modal(document.getElementById('insufficientCreditsModal'));
                        modal.show();
                    }
                    return;
                }

                if (valid) {
                    alert('Campaign published successfully!');
                }
            });
        }
    }

    // ── Campaign Pagination ──
    let currentPage = 1;
    const totalPages = 9;
    const prevBtn = document.getElementById('prevPage');
    const nextBtn = document.getElementById('nextPage');
    const pageDisplay = document.getElementById('pageDisplay');

    function updatePagination() {
        if (pageDisplay) pageDisplay.textContent = String(currentPage).padStart(2, '0') + '/' + String(totalPages).padStart(2, '0');
        if (prevBtn) prevBtn.disabled = currentPage === 1;
        if (nextBtn) nextBtn.disabled = currentPage === totalPages;
    }

    if (prevBtn) {
        prevBtn.addEventListener('click', function () {
            if (currentPage > 1) { currentPage--; updatePagination(); }
        });
    }
    if (nextBtn) {
        nextBtn.addEventListener('click', function () {
            if (currentPage < totalPages) { currentPage++; updatePagination(); }
        });
    }

    updatePagination();

})();
