const buildModalHeader = () => el(
    'div',
    { className: 'vcm-header' },
    [
        // Top row: title + search + close
        el('div', { className: 'vcm-header__top', key: 'top' }, [
            el('div', { className: 'vcm-header__title-group', key: 'tg' }, [
                el('h2', { className: 'vcm-header__title', key: 'title' }, [
                    el('span', { className: 'vcm-header__title-icon', key: 'icon' }, '🧮'),
                    __('Select Calculator', 'vareon-calculator-suite-lite')
                ]),
                el('p', { className: 'vcm-header__subtitle', key: 'sub' },
                    enabledCalcCount + ' ' + __('calculators available', 'vareon-calculator-suite-lite')
                )
            ]),
            el('div', { className: 'vcm-search', key: 'search' }, [
                el('input', {
                    className: 'vcm-search__input',
                    key: 'input',
                    type: 'text',
                    placeholder: __('Search calculators...', 'vareon-calculator-suite-lite'),
                    value: searchTerm,
                    onChange: (e) => setSearchTerm(e.target.value),
                    autoFocus: true
                }),
                el('span', { className: 'vcm-search__icon', key: 'sicon' }, '🔍'),
                searchTerm && el('button', {
                    className: 'vcm-search__clear',
                    key: 'clear',
                    type: 'button',
                    onClick: () => setSearchTerm('')
                }, '×')
            ]),
            el('button', {
                className: 'vcm-close',
                key: 'close',
                type: 'button',
                onClick: () => setIsModalOpen(false),
                'aria-label': __('Close', 'vareon-calculator-suite-lite')
            }, '×')
        ]),
        // Category toolbar
        el('div', { className: 'vcm-toolbar', key: 'toolbar' },
            [
                el('button', {
                    key: 'cat-all',
                    type: 'button',
                    className: 'vcm-pill' + (activeCategory === 'all' ? ' is-active' : ''),
                    onClick: () => setActiveCategory('all')
                }, [
                    __('All', 'vareon-calculator-suite-lite'),
                    el('span', { className: 'vcm-pill__count', key: 'c' }, String(totalCalcCount))
                ])
            ].concat(populatedCategories.map(function (catId) {
                const label = categoryLabels[catId] || catId.replace(/[-_]/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
                const count = categoryMap[catId] || 0;
                return el('button', {
                    key: 'cat-' + catId,
                    type: 'button',
                    className: 'vcm-pill' + (activeCategory === catId ? ' is-active' : ''),
                    onClick: () => setActiveCategory(catId)
                }, [
                    label,
                    el('span', { className: 'vcm-pill__count', key: 'c' }, String(count))
                ]);
            }))
        )
    ]
);

const buildCalculatorGrid = () => {
    const buildCalcCard = function (calc) {
        const isSelected = selectedCalcType === calc.value;
        const isProLocked = calc.version === 'pro' || calc.disabled;
        const cardClass = 'vcm-card' + (isSelected ? ' is-selected' : '') + (isProLocked ? ' vcm-card--pro' : '');

        return el(
            'button',
            {
                key: calc.value,
                type: 'button',
                className: cardClass,
                onClick: () => {
                    if (isProLocked) {
                        window.open('https://vareon.dev', '_blank');
                    } else {
                        setSelectedCalcType(calc.value);
                    }
                },
                onDoubleClick: () => {
                    if (!isProLocked) {
                        setSelectedCalcType(calc.value);
                        setAttributes({
                            type: calc.value,
                            theme: selectedTheme || null
                        });
                        setIsModalOpen(false);
                    }
                }
            },
            [
                isProLocked && el('div', { className: 'vcm-card__pro-badge', key: 'badge' }, '✨ PRO'),
                isSelected && el('div', { className: 'vcm-card__check', key: 'check' }, '✓'),
                el('div', { className: 'vcm-card__icon', key: 'icon' }, calc.icon),
                el('div', { className: 'vcm-card__title', key: 'title' }, calc.title),
                calc.description && el('div', { className: 'vcm-card__desc', key: 'desc' }, calc.description)
            ]
        );
    };

    var gridItems = [];
    if (filteredCalculators.length > 0) {
        filteredCalculators.forEach(function (calc) {
            gridItems.push(buildCalcCard(calc));
        });
    }

    if (gridItems.length === 0) {
        gridItems.push(
            el('div', { className: 'vcm-empty', key: 'no-results' }, [
                el('span', { className: 'vcm-empty__icon', key: 'i' }, '🔍'),
                el('strong', { className: 'vcm-empty__title', key: 't' }, __('No calculators found', 'vareon-calculator-suite-lite')),
                el('span', { className: 'vcm-empty__hint', key: 's' }, __('Try a different search term', 'vareon-calculator-suite-lite'))
            ])
        );
    }

    return el(
        'div',
        { className: 'vcm-grid-area' },
        el('div', { className: 'vcm-grid' }, gridItems)
    );
};

const buildModalFooter = () => {
    // Get selected calc metadata
    const selCalcData = selectedCalcType && allCalculators ? allCalculators[selectedCalcType] : null;
    const selIcon = selCalcData ? (selCalcData.icon || '🧮') : '';
    const selTitle = selCalcData ? selCalcData.title : '';

    return el(
        'div',
        { className: 'vcm-footer' },
        [
            // Left zone - selection preview
            el('div', { className: 'vcm-footer__selection', key: 'sel' },
                selectedCalcType
                    ? [
                        el('span', { className: 'vcm-footer__sel-icon', key: 'icon' }, selIcon),
                        el('div', { className: 'vcm-footer__sel-info', key: 'info' }, [
                            el('div', { className: 'vcm-footer__sel-name', key: 'name' }, selTitle),
                            el('div', { className: 'vcm-footer__sel-hint', key: 'hint' }, __('Selected', 'vareon-calculator-suite-lite'))
                        ])
                    ]
                    : [el('div', { className: 'vcm-footer__sel-hint', key: 'hint' }, __('Click a calculator to select it', 'vareon-calculator-suite-lite'))]
            ),
            // Center zone - theme picker
            el('div', { className: 'vcm-footer__theme', key: 'theme' }, [
                el('span', { className: 'vcm-footer__theme-label', key: 'label' }, __('Theme:', 'vareon-calculator-suite-lite')),
                el(
                    Dropdown,
                    {
                        popoverProps: {
                            placement: 'top-start',
                            offset: 4,
                            noArrow: true
                        },
                        renderToggle: ({ isOpen, onToggle }) => el(
                            'button',
                            {
                                type: 'button',
                                className: 'vcm-theme-btn',
                                onClick: onToggle,
                                'aria-expanded': isOpen
                            },
                            [
                                el('span', { className: 'vcm-theme-btn__label', key: 'l' },
                                    modalThemeOptions.find(opt => opt.value === selectedTheme)?.label || 'Default (from settings)'
                                ),
                                el('span', { className: 'vcm-theme-btn__arrow', key: 'a' }, '▼')
                            ]
                        ),
                        renderContent: ({ onClose }) => el(
                            'div',
                            { className: 'vcm-theme-list' },
                            modalThemeOptions.map(function (option) {
                                var isProTheme = option.version === 'pro';
                                var isThemeSelected = option.value === selectedTheme;
                                var optClass = 'vcm-theme-option' + (isThemeSelected ? ' is-selected' : '') + (isProTheme ? ' vcm-theme-option--pro' : '');
                                return el(
                                    'button',
                                    {
                                        key: option.value || 'default',
                                        type: 'button',
                                        className: optClass,
                                        onClick: () => {
                                            if (isProTheme) {
                                                window.open('https://vareon.dev', '_blank');
                                            } else {
                                                setSelectedTheme(option.value);
                                            }
                                            onClose();
                                        }
                                    },
                                    [
                                        el('span', { key: 'label', style: { display: 'flex', alignItems: 'center', gap: '8px', flex: 1 } }, [
                                            el('span', { key: 'text' }, option.label),
                                            isProTheme && el('span', { className: 'vcm-theme-option__pro-tag', key: 'pro' }, '✨ PRO')
                                        ]),
                                        isThemeSelected && !isProTheme && el('span', { className: 'vcm-theme-option__check', key: 'chk' }, '✓')
                                    ]
                                );
                            })
                        )
                    }
                )
            ]),
            // Right zone - actions
            el('div', { className: 'vcm-footer__actions', key: 'actions' }, [
                el('button', {
                    type: 'button',
                    className: 'vcm-btn-cancel',
                    key: 'cancel',
                    onClick: () => setIsModalOpen(false)
                }, __('Cancel', 'vareon-calculator-suite-lite')),
                el('button', {
                    type: 'button',
                    className: 'vcm-btn-insert',
                    key: 'insert',
                    disabled: !selectedCalcType,
                    onClick: () => {
                        if (selectedCalcType) {
                            setAttributes({
                                type: selectedCalcType,
                                theme: selectedTheme || null
                            });
                            setIsModalOpen(false);
                        }
                    }
                }, [
                    __('Insert Calculator', 'vareon-calculator-suite-lite'),
                    el('span', { className: 'vcm-btn-insert__arrow', key: 'arr' }, '→')
                ])
            ])
        ]
    );
};

const selectionModal = isModalOpen && el(
    Modal,
    {
        title: __('Select Calculator', 'vareon-calculator-suite-lite'),
        onRequestClose: () => setIsModalOpen(false),
        className: 'vcm-modal',
        __experimentalHideHeader: true,
        style: { width: 'min(85vw, 1000px)', maxWidth: '85vw', maxHeight: '90vh' }
    },
    el(
        'div',
        { className: 'vcm-body' },
        [
            buildModalHeader(),
            buildCalculatorGrid(),
            buildModalFooter()
        ]
    )
);
