/**
 * File Path: assets/js/wizard/wizard-app.js
 *
 * MBS Setup Wizard -- App orchestrator component.
 * Reads all step/rail components from window.MBSWizardParts.
 * Attaches App to window.MBSWizardParts.
 *
 * @package MyBookShowroom
 * @since   1.2.0
 */

(function( wp, Wizard ) {
    'use strict';
    var __ = wp.i18n.__;

    if ( ! wp || ! wp.element ) {
        return;
    }

    var h       = wp.element.createElement;
    var useState = wp.element.useState;
    var P       = window.MBSWizardParts = window.MBSWizardParts || {};
    var layouts = Wizard.layouts || [];

    function App() {
        var stateHook        = useState( 1 );
        var step             = stateHook[0];
        var setStep          = stateHook[1];

        var bookHook         = useState( { title: '', author: '', cover: null } );
        var book             = bookHook[0];
        var setBook          = bookHook[1];

        var layoutHook       = useState( layouts.length ? layouts[0].slug : 'grid' );
        var layout           = layoutHook[0];
        var setLayout        = layoutHook[1];

        var licenseHook      = useState( '' );
        var license          = licenseHook[0];
        var setLicense       = licenseHook[1];

        var activeHook       = useState( false );
        var licenseActive    = activeHook[0];
        var setLicenseActive = activeHook[1];

        var errorHook        = useState( '' );
        var licenseError     = errorHook[0];
        var setLicenseError  = errorHook[1];

        var loadingHook      = useState( false );
        var loading          = loadingHook[0];
        var setLoading       = loadingHook[1];

        var copiedHook       = useState( false );
        var copied           = copiedHook[0];
        var setCopied        = copiedHook[1];

        // WO-007: pre-check unless previously opted out.
        var telemetryHook    = useState( Wizard.telemetryConsent === 'opted_in' );   // V7-E-002: Default unchecked; only check if previously opted in.
        var telemetry        = telemetryHook[0];
        var setTelemetry     = telemetryHook[1];

        function handleSkip() {
            P.post( 'mbs_wizard_skip', {} );
            window.location.href = Wizard.dashboardUrl || Wizard.returnTo || 'index.php';
        }

        function handleStep2Next() {
            if ( ! book.title.trim() ) {
                setStep( 3 );
                return;
            }
            setLoading( true );
            P.post( 'mbs_wizard_save_book', {
                title:    book.title,
                author:   book.author,
                cover_id: book.cover ? book.cover.id : 0,
            }).then( function( r ) {
                setLoading( false );
                if ( r.success ) {
                    setStep( 3 );
                }
            }).catch( function() {
                setLoading( false );
                setStep( 3 );
            });
        }

        function handleLayoutChange( slug ) {
            setLayout( slug );
            P.post( 'mbs_wizard_save_layout', { layout: slug } );
        }

        function handleActivate() {
            if ( ! license.trim() ) { return; }
            setLoading( true );
            setLicenseError( '' );
            P.post( 'mbs_wizard_activate', { license: license } )
                .then( function( r ) {
                    setLoading( false );
                    if ( r.success ) {
                        setLicenseActive( true );
                    } else {
                        setLicenseError( r.data || __( 'Activation failed. Please check your key.', 'my-book-showroom' ) );
                    }
                }).catch( function() {
                    setLoading( false );
                    setLicenseError( __( 'Connection error. Please try again.', 'my-book-showroom' ) );
                });
        }

        function handleFinish() {
            setLoading( true );
            P.post( 'mbs_wizard_finish', { telemetry: telemetry ? 'opted_in' : 'opted_out' } ).then( function() {
                setLoading( false );
                setStep( 5 );
            }).catch( function() {
                setLoading( false );
                setStep( 5 );
            });
        }

        var mainContent;
        switch ( step ) {
            case 1:
                mainContent = h( P.Step1, { onNext: function() { setStep( 2 ); }, onSkip: handleSkip } );
                break;
            case 2:
                mainContent = h( P.Step2, {
                    book: book, setBook: setBook, loading: loading,
                    onNext: handleStep2Next,
                    onBack: function() { setStep( 1 ); },
                });
                break;
            case 3:
                mainContent = h( P.Step3, {
                    layout: layout, setLayout: handleLayoutChange, loading: loading,
                    onNext: function() { setStep( 4 ); },
                    onBack: function() { setStep( 2 ); },
                });
                break;
            case 4:
                mainContent = h( P.Step4, {
                    license: license, setLicense: setLicense,
                    licenseActive: licenseActive,
                    licenseError: licenseError,
                    loading: loading,
                    copied: copied, setCopied: setCopied,
                    telemetry: telemetry, setTelemetry: setTelemetry,
                    onActivate: handleActivate,
                    onFinish: handleFinish,
                    onBack: function() { setStep( 3 ); },
                });
                break;
            case 5:
                mainContent = h( P.Step5, { book: book } );
                break;
            default:
                mainContent = null;
        }

        return h( 'div', { className: 'mbs-wizard-frame' },
            h( P.Rail, { step: step } ),
            mainContent
        );
    }

    P.App = App;

})( window.wp, window.MBSWizard || {} );
