document.addEventListener('DOMContentLoaded', function () {
    var wp = window.wp;
    if (!wp || !wp.blocks || !wp.element || !wp.i18n) {
        return; // Ensure WordPress dependencies are loaded
    }

    var registerBlockType = wp.blocks.registerBlockType;
    var el = wp.element.createElement;
    var __ = wp.i18n.__;

    // Function to get the title from localStorage and ensure it's a string
    function getLocalStorageTitle() {
        var title = localStorage.getItem('app_Title');
        return typeof title === 'string' ? title : 'AI App Onsite '; // Default title if app_Title is not set
    }

    // Retrieve the title from localStorage
    var blockTitle = getLocalStorageTitle();
    var gutenberg = localStorage.getItem('app_Title_gutenberg_block');
    var gutenberg = gutenberg.replace(/_/g, ' ');
    if (gutenberg) {
        gutenberg = gutenberg;
    } else {
        gutenberg = 'AI APP Onsite';
    }


    // Convert the first letter of each word to uppercase
    gutenberg = gutenberg.split(' ').map(function (word) {
        return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
    }).join(' ');


    // Register the block with the title from localStorage
    registerBlockType('ai-app-onsite-form-block/form-block', {
        //Old title: __(gutenberg + ' Forms', 'aiAppOnsite-form'), // Set title from localStorage
        title: __(gutenberg + ' Aiao', 'aiAppOnsite-form'), // Set title from localStorage

        icon: 'forms',
        category: 'common',
        attributes: {},
        edit: function () {
            return el(
                'div',
                { className: 'ai-app-onsite-form-block' },
                el('div', {}, `[${blockTitle}_aiao]`)
            );
        },
        save: function () {
            return el(
                'div',
                { className: 'ai_app_onsite_openAi_app_user_form' },
                `[${blockTitle}_aiao]`  //old _openAi_app_form
            );
        },
    });
});
