/**
 * Audace — Document sidebar panel: toggle to hide the post/page title.
 * Reads/writes the `_audace_hide_title` post meta.
 */
(function (wp) {
    'use strict';
    if (!wp || !wp.plugins || !wp.editor) return;

    var __                           = wp.i18n.__;
    var registerPlugin               = wp.plugins.registerPlugin;
    var PluginDocumentSettingPanel   = (wp.editor && wp.editor.PluginDocumentSettingPanel) || (wp.editPost && wp.editPost.PluginDocumentSettingPanel);
    var ToggleControl                = wp.components.ToggleControl;
    var useSelect                    = wp.data.useSelect;
    var useDispatch                  = wp.data.useDispatch;
    var createElement                = wp.element.createElement;

    if (!PluginDocumentSettingPanel) return;

    function Panel() {
        var postType = useSelect(function (select) {
            return select('core/editor').getCurrentPostType();
        }, []);
        if (postType !== 'post' && postType !== 'page') return null;

        var meta = useSelect(function (select) {
            return select('core/editor').getEditedPostAttribute('meta') || {};
        }, []);
        var editPost = useDispatch('core/editor').editPost;

        var hidden = !!meta._audace_hide_title;

        return createElement(
            PluginDocumentSettingPanel,
            { name: 'audace-hide-title', title: __('Audace', 'audace'), className: 'audace-hide-title-panel' },
            createElement(ToggleControl, {
                label: __('Masquer le titre', 'audace'),
                help: __('Cache le titre de cette page sur le front.', 'audace'),
                checked: hidden,
                onChange: function (v) {
                    editPost({ meta: { _audace_hide_title: !!v } });
                }
            })
        );
    }

    registerPlugin('audace-hide-title', { render: Panel });
})(window.wp);
