/**
 * MassPost Target - Gutenberg Panel
 * Renders in the post sidebar using PluginDocumentSettingPanel
 * No JSX - uses wp.element.createElement for compatibility without build step
 */
(function (wp) {
    'use strict';

    // Debug logging
    console.log('[MassPost] Gutenberg panel script loaded');

    if (!wp || !wp.plugins || !wp.editPost) {
        console.error('[MassPost] Required wp modules not available:', {
            wp: !!wp,
            plugins: !!(wp && wp.plugins),
            editPost: !!(wp && wp.editPost)
        });
        return;
    }

    var registerPlugin = wp.plugins.registerPlugin;
    var PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;
    var CheckboxControl = wp.components.CheckboxControl;
    var createElement = wp.element.createElement;
    var useState = wp.element.useState;
    var useEffect = wp.element.useEffect;
    var useSelect = wp.data.useSelect;
    var useDispatch = wp.data.useDispatch;
    var __ = wp.i18n.__;

    // Get the localized data from PHP
    var masspostData = window.masspostPanelData || { websites: [], nonce: '', selectedSites: [] };
    console.log('[MassPost] Panel data:', masspostData);

    /**
     * MassPost Target Panel Component
     */
    function MassPostTargetPanel() {
        var _useState = useState([]);
        var selectedSites = _useState[0];
        var setSelectedSites = _useState[1];

        var _useState2 = useState(false);
        var initialized = _useState2[0];
        var setInitialized = _useState2[1];

        // Get post meta from Gutenberg data store
        var editorSelect = useSelect(function (select) {
            var editor = select('core/editor');
            return {
                postId: editor.getCurrentPostId(),
                currentMeta: editor.getEditedPostAttribute('meta') || {}
            };
        }, []);

        var postId = editorSelect.postId;
        var currentMeta = editorSelect.currentMeta;

        var dispatch = useDispatch('core/editor');
        var editPost = dispatch.editPost;

        // Initialize selected sites from post meta or localized data
        useEffect(function () {
            if (initialized) return;

            var initial = [];

            // Try to get from post meta first
            if (currentMeta && currentMeta._masspost_selected_sites && Array.isArray(currentMeta._masspost_selected_sites)) {
                initial = currentMeta._masspost_selected_sites;
            } else if (masspostData.selectedSites && masspostData.selectedSites.length > 0) {
                // Fall back to PHP-localized data
                initial = masspostData.selectedSites;
            }

            if (Array.isArray(initial)) {
                setSelectedSites(initial.map(String));
            }
            setInitialized(true);
        }, [postId, currentMeta, initialized]);

        // Handle checkbox toggle
        function handleSiteToggle(siteIndex, isChecked) {
            var indexStr = String(siteIndex);
            var newSelection;

            if (isChecked) {
                newSelection = selectedSites.concat([indexStr]);
            } else {
                newSelection = selectedSites.filter(function (s) {
                    return s !== indexStr;
                });
            }

            setSelectedSites(newSelection);

            // Update post meta
            editPost({
                meta: Object.assign({}, currentMeta, {
                    _masspost_selected_sites: newSelection
                })
            });
        }

        // Build the panel content
        var panelContent;

        if (!masspostData.websites || masspostData.websites.length === 0) {
            // No websites configured
            panelContent = createElement('p', {
                style: { color: '#757575', fontStyle: 'italic', margin: 0 }
            }, __('No websites have been added yet.', 'masspost'));
        } else {
            // Build checkboxes for each website
            var checkboxes = masspostData.websites.map(function (website, index) {
                var indexStr = String(index);
                var isChecked = selectedSites.indexOf(indexStr) !== -1;
                var siteName = website.name || website.url || 'Site ' + (index + 1);

                return createElement('div', {
                    key: index,
                    style: { marginBottom: '8px' }
                },
                    createElement(CheckboxControl, {
                        label: siteName,
                        checked: isChecked,
                        onChange: function (checked) {
                            handleSiteToggle(index, checked);
                        },
                        __nextHasNoMarginBottom: true
                    })
                );
            });

            panelContent = createElement('div', null,
                createElement('p', {
                    style: { marginTop: 0, marginBottom: '12px', color: '#1e1e1e' }
                }, __('Select the website(s) to publish to:', 'masspost')),
                createElement('div', {
                    className: 'masspost-sites-list',
                    style: {
                        maxHeight: '250px',
                        overflowY: 'auto',
                        padding: '8px',
                        background: '#fff'
                    }
                }, checkboxes)
            );
        }

        // Return the panel
        return createElement(PluginDocumentSettingPanel, {
            name: 'masspost-target-panel',
            title: __('MassPost Target', 'masspost'),
            className: 'masspost-target-panel'
        }, panelContent);
    }

    // Register the plugin
    registerPlugin('masspost-target', {
        render: MassPostTargetPanel
    });
    console.log('[MassPost] Plugin registered successfully');

})(window.wp);
