const { registerBlockType } = wp.blocks;
const { TextControl, SelectControl, PanelBody, Notice } = wp.components;
const { useBlockProps, InspectorControls } = wp.blockEditor;
const { useState, useEffect } = wp.element;
const { domReady } = wp;

domReady(() => {
    const settings = window.dakidarts_block_settings || {};
    const adminStyles = settings.styles || {};
    const pluginEndpoints = settings.endpoints || {};
    const pluginUrl = settings.plugin_url || '';

    if (!pluginEndpoints || Object.keys(pluginEndpoints).length === 0) {
        console.warn('Dakidarts Numerology block settings missing or empty.');
        return;
    }

    const el = wp.element.createElement;

    // Front-end AJAX handling for block forms
        const initFrontendBlocks = () => {
        const blocks = document.querySelectorAll('.dakidarts-block');

        blocks.forEach(block => {
            const form = block.querySelector('.dakidarts-block-form');
            const resultContainer = block.querySelector('.dakidarts-block-result');
            if (!form || !resultContainer) return;

            // Store original form HTML for Try Again reset
            const originalFormHTML = form.outerHTML;

            form.addEventListener('submit', (e) => {
                e.preventDefault();
                const endpoint = block.dataset.endpoint;
                const params = {};
                form.querySelectorAll('input, select, textarea').forEach(input => {
                    params[input.name] = input.value;
                });

                const requiredSelects = Array.from(form.querySelectorAll('select[name="reduce"], select[name="include_gaps"]'));
                let hasError = false;
                requiredSelects.forEach(select => {
                    const existing = select.parentElement.querySelector('.dakidarts-inline-error');
                    if (existing) existing.remove();

                    if (!select.value) {
                        const error = document.createElement('div');
                        error.className = 'dakidarts-inline-error';
                        error.textContent = (settings.i18n && settings.i18n.select_true_false) ? settings.i18n.select_true_false : 'Please choose True or False.';
                        select.parentElement.appendChild(error);
                        hasError = true;
                    }
                });
                if (hasError) {
                    return;
                }

                const button = form.querySelector('button');
                const originalText = button.textContent;
                button.textContent = 'Calculating...';
                button.disabled = true;

                jQuery.post(settings.ajax_url, {
                    action: 'dakidarts_block_calculate',
                    nonce: settings.nonce,
                    endpoint: endpoint,
                    params: params
                }).done(response => {
                    if (response.success && response.data.output) {
                        // Inject result HTML
                        resultContainer.innerHTML = response.data.output;
                        form.style.display = 'none';

                        // Dynamically bind Try Again button
                        const tryAgainBtn = resultContainer.querySelector('.dakidarts-try-again');
                        if (tryAgainBtn) {
                            tryAgainBtn.addEventListener('click', () => {
                                // Clear results
                                resultContainer.innerHTML = '';
                                // Reset & show form
                                form.reset();
                                form.style.display = '';
                            });
                        }

                    } else {
                        alert(response.data || 'Error occurred. Check console.');
                    }
                }).fail(err => {
                    console.error(err);
                    alert('AJAX error. See console.');
                }).always(() => {
                    button.textContent = originalText;
                    button.disabled = false;
                });
            });

            const inlineValidateSelect = (select) => {
                const existing = select.parentElement.querySelector('.dakidarts-inline-error');
                if (select.value) {
                    if (existing) existing.remove();
                    return;
                }
                if (!existing) {
                    const error = document.createElement('div');
                    error.className = 'dakidarts-inline-error';
                    error.textContent = (settings.i18n && settings.i18n.select_true_false) ? settings.i18n.select_true_false : 'Please choose True or False.';
                    select.parentElement.appendChild(error);
                }
            };

            form.querySelectorAll('select[name="reduce"], select[name="include_gaps"]').forEach(select => {
                select.addEventListener('change', () => inlineValidateSelect(select));
            });
        });
    };

    // Initialize front-end blocks
    initFrontendBlocks();

    // Gutenberg editor registration
   registerBlockType('dakidarts/numerology', {
    title: 'Dakidarts Numerology',
    icon: el('img', {
        src: pluginUrl + 'assets/images/pluginIcon.png',
        style: { width: '24px', height: '24px' }
    }),
    description: 'Insert an interactive numerology report form.',
    category: 'dakidarts',
    attributes: {
        endpoint: { type: 'string', default: 'life-path' },
        template: { type: 'string', default: 'default' },
    },

    // 🖼️ Add your cover image preview
    example: {
        attributes: {
            endpoint: 'life-path',
            template: 'default',
            preview: true
        },
        
        // This is where WP looks for preview cover
        preview: pluginUrl + 'assets/images/block-preview.jpg'
    },

        
        
        edit: (props) => {
            const { attributes, setAttributes } = props;
            const blockProps = useBlockProps({
                style: {
                    background: adminStyles.form_bg || '#fff',
                    padding: adminStyles.form_padding || '10px',
                    margin: adminStyles.form_margin || '0',
                    borderRadius: adminStyles.form_radius || '8px',
                    border: '1px dashed #ccc',
                    textAlign: 'center'
                }
            });

            const [formData, setFormData] = useState({});
            const fields = pluginEndpoints[attributes.endpoint] || [];
            const hasReduce = fields && fields.params && fields.params.includes('reduce');
            const hasIncludeGaps = fields && fields.params && fields.params.includes('include_gaps');
            const hasExpanded = fields && fields.params && fields.params.includes('expanded');
            const hasAllowMasters = fields && fields.params && fields.params.includes('allow_masters');

            const handleChange = (key, value) => setFormData({ ...formData, [key]: value });

            return el(
                'div',
                { ...blockProps, className: 'dakidarts-block-editor' },
                el(
                    InspectorControls,
                    null,
                    el(
                        PanelBody,
                        { title: 'Block Settings', initialOpen: true },
                        el(SelectControl, {
                            label: 'Select Endpoint',
                            value: attributes.endpoint,
                            options: Object.keys(pluginEndpoints).map(key => ({
                                label: key.replace(/-/g,' ').replace(/\b\w/g, l => l.toUpperCase()),
                                value: key
                            })),
                            onChange: endpoint => setAttributes({ endpoint })
                        }),
                        (hasReduce || hasIncludeGaps) && el(Notice, {
                            status: 'info',
                            isDismissible: false
                        }, 'Tip: reduce=true reduces sums; reduce=false keeps raw values. include_gaps=true includes gap resonance; include_gaps=false omits it.'),
                        hasExpanded && el(Notice, {
                            status: 'info',
                            isDismissible: false
                        }, (settings.i18n && settings.i18n.expanded_help) ? settings.i18n.expanded_help : 'Tip: expanded=true returns full cycles and detailed meanings. expanded=false keeps output brief.'),
                        hasAllowMasters && el(Notice, {
                            status: 'info',
                            isDismissible: false
                        }, (settings.i18n && settings.i18n.allow_masters_help) ? settings.i18n.allow_masters_help : 'Tip: allow_masters is reserved for future master-number support. Keep false for now.'),
                        el(TextControl, {
                            label: 'Template',
                            value: attributes.template,
                            onChange: template => setAttributes({ template })
                        })
                    )
                ),
                el(
                    'div',
                    { style: { padding: '10px' } },
                    el('h4', { style: { margin: '0 0 5px 0' } }, 'Dakidarts Numerology Block'),
                    el('p', { style: { margin: '5px 0' } },
                        el('strong', null, 'Endpoint:'), ' ', attributes.endpoint
                    ),
                    el('p', { style: { margin: '5px 0' } },
                        el('strong', null, 'Template:'), ' ', attributes.template
                    ),
                    el('div', {
                        style: {
                            background: adminStyles.button_bg || '#0073aa',
                            color: adminStyles.button_color || '#fff',
                            padding: adminStyles.button_padding || '10px 20px',
                            margin: adminStyles.button_margin || '10px 0',
                            borderRadius: adminStyles.button_radius || '4px',
                            border: `${adminStyles.button_border_width || '1px'}px ${adminStyles.button_border_style || 'solid'} ${adminStyles.button_border_color || '#0073aa'}`,
                            display: adminStyles.button_position === 'inherit' ? 'inline-block' : 'block',
                            textAlign: adminStyles.button_position !== 'inherit' ? adminStyles.button_position : 'center'
                        }
                    }, adminStyles.calculate_text || 'Calculate')
                )
            );
        },
        save: () => null // Dynamic block via PHP
    });
});
