/**
 * File Path: assets/js/wizard.js
 *
 * MBS Setup Wizard -- Entry point: AJAX helpers + mount.
 * Component files are in assets/js/wizard/ and enqueued first.
 * All React components are attached to window.MBSWizardParts.
 *
 * Written in plain wp.element.createElement() -- no JSX, no build step.
 * All layout options pulled from MBSWizard.layouts.
 * AJAX target: MBSWizard.ajaxUrl with nonce MBSWizard.nonce.
 *
 * Steps:
 *   1 -- Welcome      (full-width)
 *   2 -- First book   (split: form + book-page preview)
 *   3 -- Layout       (split: option list + catalog preview)
 *   4 -- Finish       (full-width: shortcode card + license card)
 *   5 -- All set      (full-width: celebration + confetti)
 *
 * @package MyBookShowroom
 * @since   1.2.0
 */

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

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

    var P = window.MBSWizardParts = window.MBSWizardParts || {};
    const { createRoot, createElement: h } = wp.element;

    /* =========================================================
       AJAX helpers (shared via P.post and P.openMediaPicker)
    ========================================================= */

    function post( action, data ) {
        var body = new FormData();
        body.append( 'action', action );
        body.append( '_wpnonce', Wizard.nonce );
        Object.entries( data || {} ).forEach( function( entry ) {
            body.append( entry[0], entry[1] );
        });
        return fetch( Wizard.ajaxUrl, { method: 'POST', body: body, credentials: 'same-origin' } )
            .then( function( r ) { return r.json(); } );
    }

    function openMediaPicker( onSelect ) {
        if ( ! wp.media ) { return; }
        var frame = wp.media({
            title:   __( 'Select cover', 'my-book-showroom' ),
            button:  { text: __( 'Use this cover', 'my-book-showroom' ) },
            library: { type: 'image' },
            multiple: false,
        });
        frame.on( 'select', function() {
            var att = frame.state().get('selection').first().toJSON();
            onSelect({
                id:     att.id,
                url:    att.url,
                name:   att.filename,
                width:  att.width,
                height: att.height,
                sizeKb: Math.round( att.filesizeInBytes / 1024 ),
            });
        });
        frame.open();
    }

    P.post             = post;
    P.openMediaPicker  = openMediaPicker;

    /* =========================================================
       Mount
    ========================================================= */

    document.addEventListener( 'DOMContentLoaded', function() {
        var root = document.getElementById( 'mbs-wizard-root' );
        if ( root && P.App ) {
            createRoot( root ).render( h( P.App ) );
        }
    });

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