/**
 * @file assets/js/blocks/block-reading-order.js
 * Registers the mbs/reading-order Gutenberg block.
 * Depends on mbs-blocks-editor (wp.* globals + window.mbsBlocksCore helpers).
 * Helpers used: getTermOptions
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( wp, mbsCore ) {
    'use strict';

    const { registerBlockType } = wp.blocks;
    const { InspectorControls, useBlockProps } = wp.blockEditor;
    const { ServerSideRender } = wp.serverSideRender;
    const { PanelBody, SelectControl, TextControl, RangeControl, ToggleControl } = wp.components;
    const { createElement: el, Fragment } = wp.element;

    // Shared helpers provided by blocks-editor.js via window.mbsBlocksCore.
    const getTermOptions  = mbsCore.getTermOptions  || function() { return []; };

    // ============================================================================
    registerBlockType('mbs/reading-order', {
        apiVersion: 3,
        title: 'Reading Order (PRO)',
        description: 'Numbered reading-order list for a series. Requires PRO license.',
        icon: 'list-view',
        category: 'mbs',
        keywords: [ 'reading order', 'series', 'sequence', 'numbered list' ],

        attributes: {
            slug: { type: 'string', default: '' },
        },

        edit: function (props) {
            const { attributes, setAttributes } = props;
            const termOptions = getTermOptions('mbs_series');

            return el(
                Fragment,
                {},
                el(
                    InspectorControls,
                    {},
                    el(
                        PanelBody,
                        { title: 'Reading Order Settings', initialOpen: true },
                        el(SelectControl, {
                            label: 'Select Series',
                            value: attributes.slug,
                            options: termOptions,
                            onChange: function (value) {
                                setAttributes({ slug: value });
                            },
                        })
                    )
                ),
                el(
                    'div',
                    useBlockProps({ className: 'mbs-block mbs-block-reading-order' }),
                    attributes.slug
                        ? el(ServerSideRender, {
                            block: 'mbs/reading-order',
                            attributes: attributes,
                          })
                        : el(
                            'div',
                            { className: 'mbs-block-placeholder' },
                            'Select a series from the block settings. Requires PRO license.'
                          )
                )
            );
        },

        save: function () {
            return null; // Dynamic block - rendered by PHP via render_callback
        },
    });


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