/**
 * @file assets/js/blocks/block-book-club.js
 * Registers the mbs/book-club Gutenberg block.
 * Depends on mbs-blocks-editor (wp.* globals + window.mbsBlocksCore helpers).
 * Helpers used: getBookOptions
 * @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 getBookOptions = mbsCore.getBookOptions || function() { return []; };

    // ============================================================================
    registerBlockType('mbs/book-club', {
        apiVersion: 3,
        title: 'Book Club (PRO)',
        description: 'Display Book Club Resources — discussion guide, questions, and downloadable files — for a specific book. Requires PRO license.',
        icon: 'groups',
        category: 'mbs',
        keywords: [ 'book club', 'discussion', 'guide', 'reading group', 'questions' ],

        attributes: {
            postId: { type: 'number', default: 0 },
        },

        edit: function (props) {
            const { attributes, setAttributes } = props;
            const bookOptions = getBookOptions();

            return el(
                Fragment,
                {},
                el(
                    InspectorControls,
                    {},
                    el(
                        PanelBody,
                        { title: 'Book Club Settings', initialOpen: true },
                        el(SelectControl, {
                            label: 'Book',
                            help: 'Choose a book, or leave as “Current post” to auto-detect from the page context (single-book template, Query Loop).',
                            value: attributes.postId,
                            options: [
                                { label: '— Current post —', value: 0 },
                                ...bookOptions.filter(function (o) { return o.value !== 0; }),
                            ],
                            onChange: function (value) { setAttributes({ postId: parseInt(value, 10) }); },
                        })
                    )
                ),
                el(
                    'div',
                    useBlockProps({ className: 'mbs-block mbs-block-book-club' }),
                    el(ServerSideRender, {
                        block: 'mbs/book-club',
                        attributes: attributes,
                    })
                )
            );
        },

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

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