/**
 * @file assets/js/adminjs/mbs-admin-settings-import.js
 * Two-step Settings JSON import (upload → preview → apply) with inline status panel on Settings → Import / Export.
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
    'use strict';
    var __ = wp.i18n.__;
    var sprintf = wp.i18n.sprintf;

    // ── Preview step ──────────────────────────────────────────────────────

    $( document ).on( 'click', '#mbs-settings-import-btn', function ( e ) {
        e.preventDefault();

        var $btn       = $( this );
        var $fileInput = $( '#mbs-settings-file' );
        var file       = $fileInput[0].files[0];
        var nonce      = $fileInput.data( 'nonce' );

        if ( ! file ) {
            mbsSettingsMessage( __( 'Please choose a JSON file first.', 'my-book-showroom' ), 'error' );
            return;
        }

        if ( ! file.name.endsWith( '.json' ) ) {
            mbsSettingsMessage( __( 'Please select a valid .json file.', 'my-book-showroom' ), 'error' );
            return;
        }

        $btn.prop( 'disabled', true ).text( __( 'Uploading\u2026', 'my-book-showroom' ) );
        mbsSettingsMessage( '', '' );

        MBS_AdminUtils.fileUploadAjax( {
            action: 'mbs_import_settings_preview',
            nonce:  nonce,
            file:   file,
            url:    MBS_Settings.ajaxUrl,
            success: function ( response ) {
                if ( response.success ) {
                    // Auto-apply after preview. A diff review UI can be added
                    // here in a future sprint — pass response.data.diff to a
                    // confirmation step before calling applySettingsImport().
                    applySettingsImport( response.data.token, nonce );
                } else {
                    mbsSettingsMessage(
                        sprintf( __( 'Preview failed: %s', 'my-book-showroom' ), response.data.message || __( 'Unknown error', 'my-book-showroom' ) ),
                        'error'
                    );
                }
            },
            error: function ( jqXHR, textStatus ) {
                mbsSettingsMessage( sprintf( __( 'AJAX error during settings preview: %s', 'my-book-showroom' ), textStatus ), 'error' );
            },
            complete: function () {
                $btn.prop( 'disabled', false ).text( __( 'Import Settings JSON', 'my-book-showroom' ) );
            }
        } );
    } );

    // ── Apply step ────────────────────────────────────────────────────────

    function applySettingsImport( token, nonce ) {
        mbsSettingsMessage( __( 'Applying settings\u2026', 'my-book-showroom' ), 'info' );

        $.post( MBS_Settings.ajaxUrl, {
            action: 'mbs_import_settings_apply',
            nonce:  nonce,
            token:  token
        }, function ( response ) {
            if ( response.success ) {
                mbsSettingsMessage(
                    ( response.data.message || __( 'Settings imported successfully.', 'my-book-showroom' ) ) + ' ' + __( 'Refreshing\u2026', 'my-book-showroom' ),
                    'success'
                );
                setTimeout( function () {
                    location.reload();
                }, 1200 );
            } else {
                mbsSettingsMessage(
                    sprintf( __( 'Apply failed: %s', 'my-book-showroom' ), response.data.message || __( 'Unknown error', 'my-book-showroom' ) ),
                    'error'
                );
            }
        } ).fail( function ( jqXHR, textStatus ) {
            mbsSettingsMessage( sprintf( __( 'AJAX error during settings apply: %s', 'my-book-showroom' ), textStatus ), 'error' );
        } );
    }

    // ── Helper ────────────────────────────────────────────────────────────

    /**
     * Display an inline status message inside the settings import area.
     *
     * Creates the message element lazily next to the import button area.
     *
     * @param {string} text  Message text (empty string clears the element).
     * @param {string} type  'error' | 'success' | 'info'
     */
    function mbsSettingsMessage( text, type ) {
        var $msg = $( '#mbs-settings-import-message' );

        if ( ! $msg.length ) {
            $( '#mbs-settings-import-btn' ).closest( 'p' ).after(
                '<div id="mbs-settings-import-message" style="margin-top:8px; display:none;"></div>'
            );
            $msg = $( '#mbs-settings-import-message' );
        }

        if ( ! text ) {
            $msg.hide().empty();
            return;
        }

        var cls = {
            error:   'notice-error',
            success: 'notice-success',
            info:    'notice-info'
        }[ type ] || 'notice-info';

        $msg
            .removeClass( 'notice-error notice-success notice-info' )
            .addClass( 'notice ' + cls )
            .html( '<p>' + escHtml( text ) + '</p>' )
            .show();
    }

    /* escHtml — use shared MBS_AdminUtils (mbs-admin-utils.js) */
    var escHtml = MBS_AdminUtils.escHtml;

} )( jQuery );
