/**
 * @file assets/js/blocks-editor.js
 * Shared core for MBS Gutenberg blocks.
 *
 * Provides window.mbsBlocksCore = { getBookOptions, getTermOptions }.
 * Per-block registrations live in assets/js/blocks/block-[name].js, each
 * enqueued individually with this file (mbs-blocks-editor) as a dependency.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

    const { useSelect } = wp.data;

    const getBookOptions = () => {
        const books = useSelect((select) => {
            return select('core').getEntityRecords('postType', 'mbs_book', {
                status: 'publish',
                per_page: -1,
                orderby: 'title',
                order: 'asc',
            }) || [];
        }, []);

        return [
            { label: '-- Select a Book --', value: 0 },
            ...books.map((book) => ({
                label: book.title.rendered,
                value: book.id,
            })),
        ];
    };

    /**
     * Helper: Get list of terms for a given MBS taxonomy for dropdown selectors.
     *
     * @param {string} taxonomy  WP taxonomy slug (e.g. 'mbs_series').
     * @return {Array<{label: string, value: string}>}
     */
    const getTermOptions = (taxonomy) => {
        const terms = useSelect((select) => {
            return select('core').getEntityRecords('taxonomy', taxonomy, {
                per_page: -1,
                orderby: 'name',
                order: 'asc',
                hide_empty: false,
            }) || [];
        }, [taxonomy]);

        return [
            { label: '-- Select --', value: '' },
            ...terms.map((term) => ({
                label: term.name,
                value: term.slug,
            })),
        ];
    };

    /**
     * Expose helpers so per-block files (assets/js/blocks/block-*.js) can
     * access them via window.mbsBlocksCore without duplicating code.
     */
    window.mbsBlocksCore = {
        getBookOptions: getBookOptions,
        getTermOptions: getTermOptions,
    };

    wp.domReady( function () {
        // Reserved for future editor initialization.
    } );

} )( window.wp, jQuery );
