/* AI Story Prompt Generator — Frontend Script */
( function () {
    'use strict';

    document.addEventListener( 'DOMContentLoaded', function () {
        const widgets = document.querySelectorAll( '.aspg-widget' );
        if ( ! widgets.length ) return;

        widgets.forEach( initWidget );
    } );

    function initWidget( widget ) {
        const genreSelect  = widget.querySelector( '#aspg-genre' );
        const generateBtn  = widget.querySelector( '#aspg-generate-btn' );
        const idleEl       = widget.querySelector( '.aspg-result-idle' );
        const loadingEl    = widget.querySelector( '.aspg-result-loading' );
        const outputEl     = widget.querySelector( '.aspg-result-output' );
        const errorEl      = widget.querySelector( '.aspg-result-error' );
        const promptText   = widget.querySelector( '#aspg-prompt-text' );
        const genreBadge   = widget.querySelector( '#aspg-genre-badge' );
        const errorMsg     = widget.querySelector( '#aspg-error-msg' );
        const copyBtn      = widget.querySelector( '#aspg-copy-btn' );

        // Enable / disable button based on selection
        genreSelect.addEventListener( 'change', function () {
            generateBtn.disabled = ! this.value;
        } );

        // Generate prompt on button click
        generateBtn.addEventListener( 'click', function () {
            const genre = genreSelect.value;
            if ( ! genre ) return;

            showState( 'loading' );

            const formData = new FormData();
            formData.append( 'action', 'aspg_generate' );
            formData.append( 'nonce',  ASPG.nonce );
            formData.append( 'genre',  genre );

            fetch( ASPG.ajax_url, {
                method: 'POST',
                body:   formData,
            } )
            .then( function ( res ) {
                if ( ! res.ok ) throw new Error( 'Server error: ' + res.status );
                return res.json();
            } )
            .then( function ( data ) {
                if ( data.success ) {
                    promptText.textContent = data.data.prompt;
                    genreBadge.textContent = data.data.genre;
                    showState( 'output' );
                } else {
                    const msg = ( data.data && data.data.message ) ? data.data.message : 'Something went wrong. Please try again.';
                    errorMsg.textContent = msg;
                    showState( 'error' );
                }
            } )
            .catch( function ( err ) {
                errorMsg.textContent = err.message || 'Network error. Please check your connection.';
                showState( 'error' );
            } );
        } );

        // Copy to clipboard
        if ( copyBtn ) {
            copyBtn.addEventListener( 'click', function () {
                const text = promptText.textContent;
                if ( ! text ) return;

                navigator.clipboard.writeText( text ).then( function () {
                    const original = copyBtn.innerHTML;
                    copyBtn.innerHTML = '<svg viewBox="0 0 20 20" fill="none" style="width:14px;height:14px"><path d="M5 10l4 4 6-8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg> Copied!';
                    copyBtn.style.color = '#5a7a3a';
                    setTimeout( function () {
                        copyBtn.innerHTML = original;
                        copyBtn.style.color = '';
                    }, 2000 );
                } ).catch( function () {
                    // Fallback for older browsers
                    const ta = document.createElement( 'textarea' );
                    ta.value = text;
                    ta.style.position = 'fixed';
                    ta.style.opacity  = '0';
                    document.body.appendChild( ta );
                    ta.select();
                    document.execCommand( 'copy' );
                    document.body.removeChild( ta );
                } );
            } );
        }

        // Helper: toggle visibility states
        function showState( state ) {
            idleEl.hidden    = state !== 'idle';
            loadingEl.hidden = state !== 'loading';
            outputEl.hidden  = state !== 'output';
            errorEl.hidden   = state !== 'error';
        }
    }

} )();
