/* ── ASPG Color Customizer Admin Script ─────────────────────────────────── */
( function () {
    'use strict';

    const previewStyle = document.getElementById( 'aspg-preview-style' );
    const schemeStatus = document.querySelector( '.aspg-scheme-status' );

    // Build the preview <style> block from the current color values
    function buildPreviewCSS( colorMap ) {
        const hex   = colorMap.border.replace( '#', '' );
        const br    = parseInt( hex.substring( 0, 2 ), 16 );
        const bg    = parseInt( hex.substring( 2, 4 ), 16 );
        const bb    = parseInt( hex.substring( 4, 6 ), 16 );

        return `
.aspg-widget, .aspg-signup-widget {
    --aspg-ink:        ${ colorMap.text_main };
    --aspg-parchment:  ${ colorMap.background };
    --aspg-cream:      ${ colorMap.surface };
    --aspg-amber:      ${ colorMap.accent };
    --aspg-amber-dark: ${ colorMap.accent_dark };
    --aspg-amber-glow: rgba(${ br },${ bg },${ bb },0.15);
    --aspg-border:     rgba(${ br },${ bg },${ bb },0.5);
    --aspg-text-muted: ${ colorMap.text_muted };
    --aspg-success:    ${ colorMap.success };
    --aspg-error-col:  ${ colorMap.error };
}
.aspg-widget .aspg-btn,
.aspg-signup-widget .aspg-btn { color: ${ colorMap.button_text } !important; }
.aspg-prompt-text  { color: ${ colorMap.prompt_text }  !important; }
.aspg-attribution  { color: ${ colorMap.attribution }  !important; }
        `.trim();
    }

    // Collect current values from all pickers into a plain object
    function collectColors() {
        const map = {};
        document.querySelectorAll( '.aspg-color-picker' ).forEach( function ( input ) {
            map[ input.dataset.key ] = input.value;
        } );
        return map;
    }

    // Update the hex label next to a picker
    function updateHexLabel( input ) {
        const wrap = input.closest( '.aspg-color-input-wrap' );
        if ( wrap ) {
            const label = wrap.querySelector( '.aspg-color-hex' );
            if ( label ) label.textContent = input.value.toUpperCase();
        }
    }

    // Refresh the live preview
    function refreshPreview() {
        if ( previewStyle ) {
            previewStyle.textContent = buildPreviewCSS( collectColors() );
        }
    }

    // Apply a color value to a picker (and update its hex label + preview)
    function applyColor( key, hex ) {
        const input = document.getElementById( 'aspg-color-' + key );
        if ( input ) {
            input.value = hex;
            updateHexLabel( input );
        }
    }

    // ── Wire up pickers ─────────────────────────────────────────────────────

    document.querySelectorAll( '.aspg-color-picker' ).forEach( function ( input ) {
        input.addEventListener( 'input', function () {
            updateHexLabel( this );
            refreshPreview();
        } );
    } );

    // ── Individual reset buttons ─────────────────────────────────────────────

    document.querySelectorAll( '.aspg-reset-single' ).forEach( function ( btn ) {
        btn.addEventListener( 'click', function () {
            const key      = this.dataset.key;
            const input    = document.getElementById( 'aspg-color-' + key );
            const dflt     = input ? input.dataset.default : null;
            if ( dflt ) {
                applyColor( key, dflt );
                refreshPreview();
            }
        } );
    } );

    // ── Reset All button ─────────────────────────────────────────────────────

    const resetAllBtn = document.getElementById( 'aspg-reset-all' );
    if ( resetAllBtn ) {
        resetAllBtn.addEventListener( 'click', function () {
            if ( ! confirm( 'Reset all colors to the default scheme? This will also save the reset to the database.' ) ) return;

            resetAllBtn.disabled    = true;
            resetAllBtn.textContent = 'Resetting…';

            const formData = new FormData();
            formData.append( 'action', 'aspg_reset_colors' );
            formData.append( 'nonce',  ASPG_COLORS.nonce );

            fetch( ASPG_COLORS.ajax_url, { method: 'POST', body: formData } )
                .then( function ( r ) { return r.json(); } )
                .then( function ( data ) {
                    if ( data.success ) {
                        const colors = data.data.colors;
                        Object.keys( colors ).forEach( function ( key ) {
                            applyColor( key, colors[ key ] );
                        } );
                        refreshPreview();

                        if ( schemeStatus ) {
                            schemeStatus.textContent  = 'Using default color scheme';
                            schemeStatus.className    = 'aspg-scheme-status is-default';
                        }

                        // Flash success feedback on the button
                        resetAllBtn.textContent = '✓ Reset!';
                        setTimeout( function () {
                            resetAllBtn.textContent = '↺ Reset All to Defaults';
                            resetAllBtn.disabled    = false;
                        }, 1800 );
                    } else {
                        alert( 'Reset failed. Please try again.' );
                        resetAllBtn.textContent = '↺ Reset All to Defaults';
                        resetAllBtn.disabled    = false;
                    }
                } )
                .catch( function () {
                    alert( 'Network error. Please try again.' );
                    resetAllBtn.textContent = '↺ Reset All to Defaults';
                    resetAllBtn.disabled    = false;
                } );
        } );
    }

    // ── Enqueue the plugin's frontend stylesheet for preview rendering ────────
    // (loaded via PHP in aspg_enqueue_color_admin_assets — this just init-renders)
    ( function loadFrontendStyle() {
        const existing = document.querySelector( 'link[href*="aspg"][href*="style.css"]' );
        if ( ! existing && typeof ASPG_COLORS !== 'undefined' && ASPG_COLORS.plugin_url ) {
            const link  = document.createElement( 'link' );
            link.rel    = 'stylesheet';
            link.href   = ASPG_COLORS.plugin_url + 'assets/style.css';
            document.head.appendChild( link );
        }
    } )();

    // ── Initial preview render ───────────────────────────────────────────────
    refreshPreview();

} )();
