/**
 * SearchFIT Admin JavaScript
 *
 * @package SearchFIT
 * @since   1.0.0
 */

( function( $ ) {
    'use strict';

    $( document ).ready( function() {

        // API Documentation Sheet.
        var $sheet = $( '#searchfit-api-docs-sheet' );
        var $body = $( 'body' );

        // Open sheet.
        $( '#searchfit-api-docs-trigger' ).on( 'click', function() {
            $sheet.addClass( 'open' );
            $body.addClass( 'searchfit-sheet-open' );
        } );

        // Close sheet - close button.
        $( '.searchfit-sheet-close' ).on( 'click', function() {
            $sheet.removeClass( 'open' );
            $body.removeClass( 'searchfit-sheet-open' );
        } );

        // Close sheet - backdrop click.
        $( '.searchfit-sheet-backdrop' ).on( 'click', function() {
            $sheet.removeClass( 'open' );
            $body.removeClass( 'searchfit-sheet-open' );
        } );

        // Close sheet - Escape key.
        $( document ).on( 'keydown', function( e ) {
            if ( 'Escape' === e.key && $sheet.hasClass( 'open' ) ) {
                $sheet.removeClass( 'open' );
                $body.removeClass( 'searchfit-sheet-open' );
            }
        } );

        // Copy to clipboard functionality.
        $( '.searchfit-copy-btn' ).on( 'click', function() {
            var $btn = $( this );
            var targetId = $btn.data( 'copy-target' );
            var $input = $( '#' + targetId );
            var textToCopy = $input.val();

            // Use modern clipboard API if available.
            if ( navigator.clipboard && navigator.clipboard.writeText ) {
                navigator.clipboard.writeText( textToCopy ).then( function() {
                    showCopyFeedback( $btn );
                } ).catch( function() {
                    fallbackCopy( $input, $btn );
                } );
            } else {
                fallbackCopy( $input, $btn );
            }
        } );

        /**
         * Fallback copy method for older browsers.
         *
         * @param {jQuery} $input The input element.
         * @param {jQuery} $btn   The button element.
         */
        function fallbackCopy( $input, $btn ) {
            var wasReadonly = $input.prop( 'readonly' );
            $input.prop( 'readonly', false );
            $input.select();

            try {
                document.execCommand( 'copy' );
                showCopyFeedback( $btn );
            } catch ( err ) {
                if ( 'undefined' !== typeof searchfitAdmin && searchfitAdmin.i18n ) {
                    alert( searchfitAdmin.i18n.copyFailed ); // eslint-disable-line no-alert
                }
            }

            $input.prop( 'readonly', wasReadonly );
            $input.blur();
        }

        /**
         * Show copy feedback tooltip.
         *
         * @param {jQuery} $btn The button element.
         */
        function showCopyFeedback( $btn ) {
            $btn.addClass( 'copied' );

            setTimeout( function() {
                $btn.removeClass( 'copied' );
            }, 2000 );
        }

        // Regenerate API key functionality.
        $( '#searchfit-regenerate-api-key' ).on( 'click', function() {
            var $btn = $( this );

            // Check if searchfitAdmin is available.
            if ( 'undefined' === typeof searchfitAdmin ) {
                return;
            }

            // Confirm action.
            var confirmMessage = searchfitAdmin.i18n ? searchfitAdmin.i18n.regenerateConfirm : 'Are you sure you want to regenerate the API key?';
            if ( ! confirm( confirmMessage ) ) { // eslint-disable-line no-alert
                return;
            }

            // Disable button and show loading state.
            var originalText = $btn.html();
            var regeneratingText = searchfitAdmin.i18n ? searchfitAdmin.i18n.regenerating : 'Regenerating...';
            $btn.prop( 'disabled', true ).text( regeneratingText );

            // Make AJAX request.
            $.ajax( {
                url: searchfitAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'searchfit_regenerate_api_key',
                    nonce: searchfitAdmin.nonce
                },
                success: function( response ) {
                    if ( response.success ) {
                        // Update the API key input.
                        $( '#searchfit_webhook_api_key' ).val( response.data.api_key );

                        // Show success feedback.
                        $btn.text( 'Done!' );

                        setTimeout( function() {
                            $btn.prop( 'disabled', false ).html( originalText );
                        }, 2000 );
                    } else {
                        var errorMsg = searchfitAdmin.i18n ? searchfitAdmin.i18n.regenerateError : 'Failed to regenerate API key.';
                        alert( response.data && response.data.message ? response.data.message : errorMsg ); // eslint-disable-line no-alert
                        $btn.prop( 'disabled', false ).html( originalText );
                    }
                },
                error: function() {
                    var errorMsg = searchfitAdmin.i18n ? searchfitAdmin.i18n.regenerateError : 'Failed to regenerate API key.';
                    alert( errorMsg ); // eslint-disable-line no-alert
                    $btn.prop( 'disabled', false ).html( originalText );
                }
            } );
        } );
    } );
} )( jQuery );
