(function(wp) {
    const { registerBlockType } = wp.blocks;
    const { createElement: el, Fragment, useState, useEffect } = wp.element;
    const { InspectorControls, useBlockProps } = wp.blockEditor;
    const { PanelBody, TextControl, RangeControl, Placeholder, Button, Notice } = wp.components;
    const { __ } = wp.i18n;

    // Get settings from PHP
    const settings = window.calcsliveBlockSettings || {};

    /**
     * CalcsLive Article Embed Block
     */
    registerBlockType('calcslive/article-embed', {
        title: __('CalcsLive Article', 'calcslive-article-embed'),
        description: __('Embed an interactive CalcsLive article with unit-aware calculations.', 'calcslive-article-embed'),
        icon: 'calculator',
        category: 'embed',
        keywords: [
            __('calculator', 'calcslive-article-embed'),
            __('calcslive', 'calcslive-article-embed'),
            __('embed', 'calcslive-article-embed'),
            __('unit', 'calcslive-article-embed'),
            __('calculation', 'calcslive-article-embed'),
        ],
        supports: {
            html: false,
            align: ['wide', 'full'],
        },
        attributes: {
            articleId: {
                type: 'string',
                default: '',
            },
            width: {
                type: 'string',
                default: settings.defaultWidth || '100%',
            },
            height: {
                type: 'number',
                default: parseInt(settings.defaultHeight) || 600,
            },
        },

        /**
         * Edit component
         */
        edit: function(props) {
            const { attributes, setAttributes } = props;
            const { articleId, width, height } = attributes;
            const blockProps = useBlockProps();

            // Build preview URL
            const getPreviewUrl = function() {
                if (!articleId || !settings.apiKey) {
                    return null;
                }
                let url = settings.embedBaseUrl + encodeURIComponent(articleId);
                url += '?key=' + encodeURIComponent(settings.apiKey);
                if (settings.domain) {
                    url += '&domain=' + encodeURIComponent(settings.domain);
                }
                return url;
            };

            const previewUrl = getPreviewUrl();

            // Inspector controls (sidebar)
            const inspectorControls = el(InspectorControls, {},
                el(PanelBody, { title: __('Article Settings', 'calcslive-article-embed') },
                    el(TextControl, {
                        label: __('Article ID', 'calcslive-article-embed'),
                        help: __('The CalcsLive article ID from the URL (e.g., 3M7EJLZQ2-4N5)', 'calcslive-article-embed'),
                        value: articleId,
                        onChange: function(value) {
                            setAttributes({ articleId: value });
                        },
                        placeholder: '3M7EJLZQ2-4N5',
                    })
                ),
                el(PanelBody, { title: __('Display Settings', 'calcslive-article-embed'), initialOpen: false },
                    el(TextControl, {
                        label: __('Width', 'calcslive-article-embed'),
                        help: __('Use percentage (100%) or pixels (800px)', 'calcslive-article-embed'),
                        value: width,
                        onChange: function(value) {
                            setAttributes({ width: value });
                        },
                    }),
                    el(RangeControl, {
                        label: __('Height (px)', 'calcslive-article-embed'),
                        value: height,
                        onChange: function(value) {
                            setAttributes({ height: value });
                        },
                        min: 200,
                        max: 1500,
                        step: 50,
                    })
                )
            );

            // Main block content
            let blockContent;

            // Show API key warning if not configured
            if (!settings.hasApiKey) {
                blockContent = el(Placeholder, {
                    icon: 'warning',
                    label: __('CalcsLive Article', 'calcslive-article-embed'),
                    instructions: __('Please configure your CalcsLive API key in Settings → CalcsLive before using this block.', 'calcslive-article-embed'),
                },
                    el(Button, {
                        isPrimary: true,
                        href: '/wp-admin/options-general.php?page=calcslive-settings',
                    }, __('Configure Settings', 'calcslive-article-embed'))
                );
            }
            // Show article ID input if not set
            else if (!articleId) {
                blockContent = el(Placeholder, {
                    icon: 'calculator',
                    label: __('CalcsLive Article', 'calcslive-article-embed'),
                    instructions: __('Enter your CalcsLive article ID to embed an interactive calculation article.', 'calcslive-article-embed'),
                },
                    el(TextControl, {
                        label: __('Article ID', 'calcslive-article-embed'),
                        value: articleId,
                        onChange: function(value) {
                            setAttributes({ articleId: value });
                        },
                        placeholder: __('e.g., 3M7EJLZQ2-4N5', 'calcslive-article-embed'),
                    }),
                    el('p', { className: 'calcslive-help-text' },
                        __('Find your article ID in the URL: ', 'calcslive-article-embed'),
                        el('code', {}, 'calcslive.com/view/'),
                        el('strong', {}, 'YOUR_ID')
                    )
                );
            }
            // Show preview iframe
            else {
                blockContent = el('div', { className: 'calcslive-embed-preview' },
                    el('div', { className: 'calcslive-embed-header' },
                        el('span', { className: 'calcslive-embed-label' },
                            __('CalcsLive Article: ', 'calcslive-article-embed'),
                            el('code', {}, articleId)
                        )
                    ),
                    el('div', {
                        className: 'calcslive-embed-iframe-wrapper',
                        style: { height: height + 'px' },
                    },
                        el('iframe', {
                            src: previewUrl,
                            width: width,
                            height: height,
                            frameBorder: '0',
                            style: { border: 'none', maxWidth: '100%' },
                            title: __('CalcsLive Article Preview', 'calcslive-article-embed'),
                        })
                    )
                );
            }

            return el(Fragment, {},
                inspectorControls,
                el('div', blockProps, blockContent)
            );
        },

        /**
         * Save component (server-side render, so return null)
         */
        save: function() {
            return null;
        },
    });
})(window.wp);
