/**
 * Blog Template Settings Panel
 *
 * Creates a Gutenberg sidebar panel for Blog Grid template settings.
 * Only shows when the Blog Grid template is selected.
 * Premium-style compact UI with button-style controls.
 *
 * @package Blog_Over
 */
(function (wp) {
    const { registerPlugin } = wp.plugins;
    // WP 6.6+ moved PluginDocumentSettingPanel from wp.editPost to wp.editor
    const { PluginDocumentSettingPanel } = wp.editor || wp.editPost;
    const { useSelect, useDispatch } = wp.data;
    const {
        PanelRow,
        RangeControl,
        SelectControl,
        ToggleControl,
        CheckboxControl,
        Button,
        ButtonGroup,
        Flex,
        FlexItem,
        Icon,
        Tooltip
    } = wp.components;
    const { createElement: el, useState, Fragment } = wp.element;
    const { __ } = wp.i18n;

    // Custom Button Group Control Component
    function ButtonGroupControl({ label, value, options, onChange, columns = 'auto' }) {
        return el('div', { className: 'blog-over-button-group-control' },
            label && el('label', { className: 'blog-over-control-label' }, label),
            el(ButtonGroup, {
                className: 'blog-over-button-group',
                style: {
                    display: 'grid',
                    gridTemplateColumns: columns === 'auto' ? `repeat(${options.length}, 1fr)` : columns,
                    gap: '0'
                }
            },
                options.map((option) =>
                    el(Button, {
                        key: option.value,
                        variant: value === option.value ? 'primary' : 'secondary',
                        onClick: () => onChange(option.value),
                        className: `blog-over-btn-option ${value === option.value ? 'is-active' : ''}`,
                        icon: option.icon || null,
                    }, option.icon ? null : (option.shortLabel || option.label))
                )
            )
        );
    }

    // Compact Toggle Row Component
    function CompactToggle({ label, checked, onChange, icon }) {
        return el('div', { className: 'blog-over-compact-toggle' },
            el('div', { className: 'blog-over-toggle-content' },
                icon && el(Icon, { icon: icon, size: 16, className: 'blog-over-toggle-icon' }),
                el('span', { className: 'blog-over-toggle-label' }, label)
            ),
            el(ToggleControl, {
                checked: checked,
                onChange: onChange,
                className: 'blog-over-toggle-control'
            })
        );
    }

    // Template Settings Panel Component
    function NovaTemplateSettings() {
        const { editPost } = useDispatch('core/editor');
        const [showCategories, setShowCategories] = useState(false);

        // Get current template and meta values
        const { template, meta } = useSelect((select) => {
            const editor = select('core/editor');
            return {
                template: editor.getEditedPostAttribute('template'),
                meta: editor.getEditedPostAttribute('meta') || {},
            };
        }, []);

        // Check which template is selected
        const isBlogGridTemplate = template === 'template-blog-custom.php';
        const isPageLayoutTemplate = template === 'template-page-layout.php';
        const isNovaTemplate = isBlogGridTemplate || isPageLayoutTemplate;

        // Get meta values with defaults
        const sidebarPosition = meta._blog_over_template_sidebar || 'right-sidebar';
        const blogStyle = meta._blog_over_template_blog_style || 'default';
        const gridColumns = meta._blog_over_template_grid_columns || 3;
        const postsPerPage = meta._blog_over_template_posts_per_page || 9;
        const categories = meta._blog_over_template_categories || '';
        const orderBy = meta._blog_over_template_orderby || 'date';
        const order = meta._blog_over_template_order || 'DESC';
        const showPagination = meta._blog_over_template_show_pagination !== '0';
        const sectionWidth = meta._blog_over_template_section_width || 'boxed';

        // Update meta helper
        const updateMeta = (key, value) => {
            editPost({
                meta: {
                    ...meta,
                    [key]: value,
                },
            });
        };

        // Don't render if not a Nova template
        if (!isNovaTemplate) {
            return null;
        }

        // Get categories from localized data
        const categoryOptions = window.novaTemplateData?.categories || [];

        // Handle category selection
        const selectedCategories = categories ? categories.split(',').map(Number) : [];

        const toggleCategory = (catId) => {
            let newCats = [...selectedCategories];
            if (newCats.includes(catId)) {
                newCats = newCats.filter(id => id !== catId);
            } else {
                newCats.push(catId);
            }
            updateMeta('_blog_over_template_categories', newCats.join(','));
        };

        // Dynamic panel title and icon based on template
        const panelTitle = isBlogGridTemplate
            ? __('Blog Custom Layout', 'blog-over-blog')
            : __('Page Layout Settings', 'blog-over-blog');
        const panelIcon = isBlogGridTemplate ? 'admin-post' : 'admin-page';

        // Show columns control only for grid-based styles
        const showColumnsControl = isBlogGridTemplate && blogStyle !== 'list';

        return el(
            PluginDocumentSettingPanel,
            {
                name: 'blog-over-template-settings',
                title: panelTitle,
                className: 'blog-over-template-settings-panel blog-over-premium-panel',
                icon: panelIcon,
            },

            // Sidebar Position
            el('div', { className: 'blog-over-control-group' },
                el(ButtonGroupControl, {
                    label: __('Sidebar', 'blog-over-blog'),
                    value: sidebarPosition,
                    options: [
                        { value: 'left-sidebar', label: __('Left', 'blog-over-blog'), shortLabel: 'Left' },
                        { value: 'no-sidebar', label: __('None', 'blog-over-blog'), shortLabel: 'None' },
                        { value: 'right-sidebar', label: __('Right', 'blog-over-blog'), shortLabel: 'Right' },
                    ],
                    onChange: (value) => updateMeta('_blog_over_template_sidebar', value),
                })
            ),

            // Blog-specific controls (only for Blog Custom Layout template)
            isBlogGridTemplate && el('div', { className: 'blog-over-control-group' },
                el(ButtonGroupControl, {
                    label: __('Blog Style', 'blog-over-blog'),
                    value: blogStyle,
                    options: [
                        { value: 'list', label: __('Default', 'blog-over-blog') },
                        { value: 'default', label: __('Classic', 'blog-over-blog') },
                        { value: 'modern-cards', label: __('Modern', 'blog-over-blog') },
                    ],
                    onChange: (value) => updateMeta('_blog_over_template_blog_style', value),
                })
            ),

            // Grid Columns — hidden when Default (List) style is selected
            showColumnsControl && el('div', { className: 'blog-over-control-group' },
                el(ButtonGroupControl, {
                    label: __('Columns', 'blog-over-blog'),
                    value: String(gridColumns),
                    options: [
                        { value: '2', label: '2' },
                        { value: '3', label: '3' },
                        { value: '4', label: '4' },
                    ],
                    onChange: (value) => updateMeta('_blog_over_template_grid_columns', parseInt(value)),
                })
            ),

            // Section Width (shared by both templates)
            el('div', { className: 'blog-over-control-group' },
                el(ButtonGroupControl, {
                    label: __('Width', 'blog-over-blog'),
                    value: sectionWidth,
                    options: [
                        { value: 'boxed', label: __('Boxed', 'blog-over-blog') },
                        { value: 'full-width', label: __('Full', 'blog-over-blog') },
                    ],
                    onChange: (value) => updateMeta('_blog_over_template_section_width', value),
                })
            ),

            // Blog-specific controls below divider (Blog Grid only)
            isBlogGridTemplate && el('hr', { className: 'blog-over-divider' }),

            // Posts Per Page - Compact (Blog Grid only)
            isBlogGridTemplate && el('div', { className: 'blog-over-control-group blog-over-range-compact' },
                el(RangeControl, {
                    label: __('Posts', 'blog-over-blog'),
                    value: postsPerPage,
                    onChange: (value) => updateMeta('_blog_over_template_posts_per_page', value),
                    min: 3,
                    max: 24,
                    step: 3,
                    withInputField: true,
                    renderTooltipContent: (value) => `${value} posts`,
                })
            ),

            // Order By - Dropdown compact (Blog Grid only)
            isBlogGridTemplate && el('div', { className: 'blog-over-control-group blog-over-select-compact' },
                el(SelectControl, {
                    label: __('Order By', 'blog-over-blog'),
                    value: orderBy,
                    options: [
                        { label: __('Date', 'blog-over-blog'), value: 'date' },
                        { label: __('Title', 'blog-over-blog'), value: 'title' },
                        { label: __('Random', 'blog-over-blog'), value: 'rand' },
                        { label: __('Comments', 'blog-over-blog'), value: 'comment_count' },
                        { label: __('Modified', 'blog-over-blog'), value: 'modified' },
                    ],
                    onChange: (value) => updateMeta('_blog_over_template_orderby', value),
                })
            ),

            // Order Direction (Blog Grid only)
            isBlogGridTemplate && el('div', { className: 'blog-over-control-group' },
                el(ButtonGroupControl, {
                    label: __('Order', 'blog-over-blog'),
                    value: order,
                    options: [
                        { value: 'DESC', label: '↓ Desc' },
                        { value: 'ASC', label: '↑ Asc' },
                    ],
                    onChange: (value) => updateMeta('_blog_over_template_order', value),
                })
            ),

            // Pagination Toggle (Blog Grid only)
            isBlogGridTemplate && el(CompactToggle, {
                label: __('Show Pagination', 'blog-over-blog'),
                checked: showPagination,
                onChange: (value) => updateMeta('_blog_over_template_show_pagination', value ? '1' : '0'),
            }),

            // Categories Section - Collapsible (Blog Grid only)
            isBlogGridTemplate && categoryOptions.length > 0 && el(Fragment, null,
                el('hr', { className: 'blog-over-divider' }),
                el(Button, {
                    className: 'blog-over-collapsible-header',
                    onClick: () => setShowCategories(!showCategories),
                    icon: showCategories ? 'arrow-up-alt2' : 'arrow-down-alt2',
                },
                    el('span', null,
                        __('Filter Categories', 'blog-over-blog'),
                        selectedCategories.length > 0 && el('span', { className: 'blog-over-cat-badge' }, selectedCategories.length)
                    )
                ),
                showCategories && el('div', { className: 'blog-over-category-list' },
                    categoryOptions.slice(0, 10).map((cat) =>
                        el(CheckboxControl, {
                            key: cat.value,
                            label: cat.label,
                            checked: selectedCategories.includes(cat.value),
                            onChange: () => toggleCategory(cat.value),
                        })
                    ),
                    categoryOptions.length > 10 && el('p', { className: 'blog-over-cat-note' },
                        __('+ more categories available', 'blog-over-blog')
                    )
                )
            )
        );
    }

    // Register the plugin
    registerPlugin('blog-over-template-settings', {
        render: NovaTemplateSettings,
        icon: 'grid-view',
    });
})(window.wp);
