/**
 * Wing Popup — Template Library
 * File: assets/js/template-library.js
 */
( function ( $ ) {
    'use strict';

    const cfg      = window.wdpopTemplates || {};
    const ajaxUrl  = cfg.ajaxUrl || '';
    const nonce    = cfg.nonce   || '';
    const str      = cfg.strings || {};

    let allTemplates = [];   // cache fetched templates
    let fetchDone    = false;

    /* ------------------------------------------------------------------
     * Elements (resolved after DOM ready)
     * ------------------------------------------------------------------ */
    let $overlay, $grid, $search, $openBtn;

    /* ------------------------------------------------------------------
     * Init
     * ------------------------------------------------------------------ */
    $( function () {
        $overlay = $( '#wdpop-library-overlay' );
        $grid    = $( '#wdpop-template-grid' );
        $search  = $( '#wdpop-search' );
        $openBtn = $( '#wdpop-open-library' );

        if ( ! $overlay.length ) return;

        // Open
        $openBtn.on( 'click', function ( e ) {
            e.preventDefault();
            openModal();
        } );

        // Close — overlay background click
        $overlay.on( 'click', function ( e ) {
            if ( $( e.target ).is( $overlay ) ) closeModal();
        } );

        // Close — buttons
        $overlay.on( 'click', '.wdpop-modal__close, .wdpop-modal__close-btn', closeModal );

        // Keyboard close
        $( document ).on( 'keydown.wdpop', function ( e ) {
            if ( e.key === 'Escape' && $overlay.is( ':visible' ) ) closeModal();
        } );

        // Search / filter
        $search.on( 'input', function () {
            const q = $( this ).val().trim().toLowerCase();
            filterGrid( q );
        } );

        // "Use This Template" — delegated
        $grid.on( 'click', '.wdpop-use-btn', function () {
            const $btn  = $( this );
            const slug  = $btn.closest( '.wdpop-card' ).data( 'slug' );
            useTemplate( slug, $btn );
        } );
    } );

    /* ------------------------------------------------------------------
     * Open / close
     * ------------------------------------------------------------------ */
    function openModal() {
        $overlay.fadeIn( 160 );
        $search.val( '' );
        $( 'body' ).addClass( 'wdpop-modal-open' );

        if ( ! fetchDone ) {
            fetchTemplates();
        } else {
            renderGrid( allTemplates );
        }
    }

    function closeModal() {
        $overlay.fadeOut( 140 );
        $( 'body' ).removeClass( 'wdpop-modal-open' );
    }

    /* ------------------------------------------------------------------
     * Fetch preset list from server
     * ------------------------------------------------------------------ */
    function fetchTemplates() {
        $grid.html( '<p class="wdpop-loading">' + escHtml( str.loading ) + '</p>' );

        $.post( ajaxUrl, {
            action : 'wdpop_get_presets',
            nonce  : nonce,
        } )
        .done( function ( res ) {
            if ( res.success && Array.isArray( res.data ) ) {
                allTemplates = res.data;
                fetchDone    = true;
                renderGrid( allTemplates );
            } else {
                showError( str.error );
            }
        } )
        .fail( function () {
            showError( str.error );
        } );
    }

    /* ------------------------------------------------------------------
     * Render grid
     * ------------------------------------------------------------------ */
    function renderGrid( templates ) {
        $grid.empty();

        if ( ! templates || ! templates.length ) {
            $grid.html( '<p class="wdpop-empty">' + escHtml( str.noTemplates ) + '</p>' );
            return;
        }

        templates.forEach( function ( tpl ) {
            $grid.append( buildCard( tpl ) );
        } );
    }

    function buildCard( tpl ) {
        const thumb = tpl.preview_url
            ? '<img src="' + escAttr( tpl.preview_url ) + '" alt="' + escAttr( tpl.title ) + '" loading="lazy" />'
            : '<span class="wdpop-card__thumb--placeholder" aria-hidden="true">&#9741;</span>';

        return $( '<div class="wdpop-card" data-slug="' + escAttr( tpl.slug ) + '" data-title="' + escAttr( tpl.title ).toLowerCase() + '">' +
            '<div class="wdpop-card__thumb">' + thumb + '</div>' +
            '<div class="wdpop-card__footer">' +
                '<p class="wdpop-card__title">' + escHtml( tpl.title ) + '</p>' +
                ( tpl.description ? '<p class="wdpop-card__desc">' + escHtml( tpl.description ) + '</p>' : '' ) +
                '<button class="wdpop-use-btn button button-primary">' + escHtml( str.useThis ) + '</button>' +
            '</div>' +
        '</div>' );
    }

    /* ------------------------------------------------------------------
     * Filter
     * ------------------------------------------------------------------ */
    function filterGrid( query ) {
        if ( ! query ) {
            $grid.find( '.wdpop-card' ).show();
            $grid.find( '.wdpop-empty' ).remove();
            return;
        }

        let visible = 0;

        $grid.find( '.wdpop-card' ).each( function () {
            const title = $( this ).data( 'title' ) || '';
            if ( title.includes( query ) ) {
                $( this ).show();
                visible++;
            } else {
                $( this ).hide();
            }
        } );

        $grid.find( '.wdpop-empty' ).remove();

        if ( visible === 0 ) {
            $grid.append( '<p class="wdpop-empty">' + escHtml( str.noTemplates ) + '</p>' );
        }
    }

    /* ------------------------------------------------------------------
     * Use preset — AJAX → redirect
     * ------------------------------------------------------------------ */
    function useTemplate( slug, $btn ) {
        if ( ! slug ) return;

        $btn
            .prop( 'disabled', true )
            .text( str.creating );

        $.post( ajaxUrl, {
            action : 'wdpop_use_preset',
            nonce  : nonce,
            slug   : slug,
        } )
        .done( function ( res ) {
            if ( res.success && res.data.edit_url ) {
                window.location.href = res.data.edit_url;
            } else {
                const msg = ( res.data && res.data.message ) ? res.data.message : str.error;
                showError( msg );
                resetBtn( $btn );
            }
        } )
        .fail( function () {
            showError( str.error );
            resetBtn( $btn );
        } );
    }

    function resetBtn( $btn ) {
        $btn.prop( 'disabled', false ).text( str.useThis );
    }

    /* ------------------------------------------------------------------
     * Error
     * ------------------------------------------------------------------ */
    function showError( message ) {
        $grid.html( '<p class="wdpop-error">' + escHtml( message ) + '</p>' );
    }

    /* ------------------------------------------------------------------
     * Helpers
     * ------------------------------------------------------------------ */
    function escHtml( str ) {
        return $( '<div>' ).text( str || '' ).html();
    }

    function escAttr( str ) {
        return $( '<div>' ).text( str || '' ).html()
            .replace( /"/g, '&quot;' )
            .replace( /'/g, '&#039;' );
    }

}( jQuery ) );