/* global aifiListData, jQuery */
(function ( $ ) {
    'use strict';

    $( document ).on( 'click', '.aifi-generate-link', function ( e ) {
        e.preventDefault();

        var $link    = $( this );
        var postId   = $link.data( 'post-id' );
        var hasThumb = parseInt( $link.data( 'has-thumbnail' ), 10 ) === 1;

        if ( $link.hasClass( 'aifi-generating' ) ) {
            return;
        }

        // Confirm before overwriting an existing image
        if ( hasThumb && ! window.confirm( aifiListData.i18n.confirmOverwrite ) ) {
            return;
        }

        // Disable link and show inline spinner
        $link.addClass( 'aifi-generating' ).text( aifiListData.i18n.generating );
        $link.before( '<span class="spinner aifi-list-spinner is-active"></span>' );

        // Dim existing thumbnail while generating
        var $cell = $link.closest( '.aifi-col-cell' );
        $cell.find( '.aifi-list-thumb' ).css( 'opacity', '0.4' );

        $.ajax( {
            url: aifiListData.restUrl,
            method: 'POST',
            beforeSend: function ( xhr ) {
                xhr.setRequestHeader( 'X-WP-Nonce', aifiListData.nonce );
            },
            contentType: 'application/json',
            data: JSON.stringify( { post_id: postId } ),
        } )
        .done( function ( response ) {
            // Update column thumbnail
            var $thumb = $cell.find( '.aifi-list-thumb' );
            var ts     = '?t=' + Date.now();
            if ( $thumb.length ) {
                $thumb.attr( 'src', response.thumbnail_url + ts ).css( 'opacity', '1' );
            } else {
                // Replace the "No image" placeholder with a real thumbnail
                $cell.find( '.aifi-no-image' ).replaceWith(
                    $( '<img class="aifi-list-thumb" width="60" height="60">' )
                        .attr( 'src', response.thumbnail_url + ts )
                );
            }

            // Update link state
            $link
                .removeClass( 'aifi-generating' )
                .data( 'has-thumbnail', 1 )
                .attr( 'data-has-thumbnail', 1 )
                .text( aifiListData.i18n.regenerate );

            // Remove spinner and show brief success indicator
            $link.siblings( '.aifi-list-spinner' ).remove();
            var $ok = $( '<span class="aifi-list-ok dashicons dashicons-yes-alt"></span>' );
            $link.before( $ok );
            setTimeout( function () { $ok.fadeOut( 400, function () { $( this ).remove(); } ); }, 2000 );

            // Mirror the update in the row-action link (same post-id, different DOM location)
            $( '.aifi-generate-link[data-post-id="' + postId + '"]' )
                .not( $link )
                .data( 'has-thumbnail', 1 )
                .attr( 'data-has-thumbnail', 1 )
                .text( aifiListData.i18n.regenerate );
        } )
        .fail( function ( xhr ) {
            var msg = aifiListData.i18n.error;
            if ( xhr.responseJSON && xhr.responseJSON.message ) {
                msg = xhr.responseJSON.message;
            }

            $link.siblings( '.aifi-list-spinner' ).remove();
            $link
                .removeClass( 'aifi-generating' )
                .text( hasThumb ? aifiListData.i18n.regenerate : aifiListData.i18n.generate );
            $cell.find( '.aifi-list-thumb' ).css( 'opacity', '1' );

            var $err = $( '<span class="aifi-list-error"></span>' ).text( msg );
            $link.after( $err );
            setTimeout( function () { $err.fadeOut( 400, function () { $( this ).remove(); } ); }, 5000 );
        } );
    } );

} )( jQuery );
