/**
 * EarthPure Setup Wizard - Admin JavaScript
 */
(function($) {
    'use strict';

    const AJAX  = epwData.ajaxUrl;
    const NONCE = epwData.nonce;

    /* ========================
       LOG HELPER
       ======================== */
    function log(msg, type = 'info') {
        const logEl = document.getElementById('epw-install-log');
        if (!logEl) return;
        logEl.style.display = 'block';
        const colors = { success: '#81C784', error: '#EF9A9A', info: '#81C784', warn: '#FFD54F' };
        const icons  = { success: '✅', error: '❌', info: '▶', warn: '⚠️' };
        logEl.innerHTML += `<div style="color:${colors[type]}">${icons[type]} ${msg}</div>`;
        logEl.scrollTop = logEl.scrollHeight;
    }

    /* ========================
       STAP 1: Plugin installeren
       ======================== */
    $(document).on('click', '.epw-install-plugin', function() {
        const btn  = $(this);
        const slug = btn.data('slug');
        btn.text('⏳ Installeren...').prop('disabled', true);
        log('Plugin installeren: ' + slug + '...');

        $.post(AJAX, { action: 'epw_install_plugin', nonce: NONCE, slug: slug })
            .done(function(r) {
                if (r.success) {
                    log(r.data.msg, 'success');
                    btn.closest('.epw-plugin-card').addClass('installed');
                    btn.replaceWith('<span class="epw-installed-badge">✅ Actief</span>');
                } else {
                    log(r.data?.msg || 'Fout bij installatie', 'error');
                    btn.text('❌ Mislukt').prop('disabled', false);
                }
            })
            .fail(function() {
                log('Verbindingsfout', 'error');
                btn.text('❌ Probeer opnieuw').prop('disabled', false);
            });
    });

    // WordPress.org plugin install (opent nieuwe tab naar plugin admin)
    $(document).on('click', '.epw-install-wp-plugin', function() {
        const slug = $(this).data('slug');
        window.open(`plugin-install.php?s=${slug}&tab=search&type=term`, '_blank');
    });

    /* ========================
       STAP 2: Pagina's aanmaken
       ======================== */
    $('#epw-create-pages').on('click', function() {
        const btn = $(this);
        btn.text('⏳ Aanmaken...').prop('disabled', true);

        $.post(AJAX, { action: 'epw_create_pages', nonce: NONCE })
            .done(function(r) {
                if (r.success) {
                    // Update UI
                    r.data.created.forEach(function(title) {
                        // Find matching item and update status
                        $('#epw-pages-list .epw-page-item').each(function() {
                            if ($(this).find('strong').text() === title) {
                                $(this).find('.epw-pending-badge').replaceWith('<span class="epw-installed-badge">✅ Aangemaakt</span>');
                            }
                        });
                    });

                    btn.text('✅ Pagina\'s aangemaakt!');
                    setTimeout(function() {
                        window.location.href = `admin.php?page=earthpure-wizard&step=3`;
                    }, 1200);
                } else {
                    btn.text('❌ Fout - probeer opnieuw').prop('disabled', false);
                }
            })
            .fail(function() {
                btn.text('❌ Verbindingsfout').prop('disabled', false);
            });
    });

    /* ========================
       PROGRESS BAR ANIMATION
       ======================== */
    $(function() {
        const bar = document.querySelector('.epw-progress-bar');
        if (bar) {
            const target = bar.style.width;
            bar.style.width = '0%';
            setTimeout(() => { bar.style.width = target; }, 200);
        }
    });

    /* ========================
       KEYBOARD: ESC handler
       ======================== */
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            // nothing to close in wizard
        }
    });

})(jQuery);
