(function (wp) {
    var el = wp.element.createElement;
    var useState = wp.element.useState;
    var useEffect = wp.element.useEffect;

    function ProductSearch(props) {
        var blockProps = wp.blockEditor.useBlockProps();
        var attrs = props.attributes;
        var setAttrs = props.setAttributes;
        var productId = attrs.productId || 0;

        var load = useState(false);
        var setIsLoading = load[1];

        var sel = useState('');
        var selectedName = sel[0];
        var setSelectedName = sel[1];

        var search = useState('');
        var setSearchTerm = search[1];

        var res = useState([]);
        var setResults = res[1];

        var timer = useState(null);
        var setDebounce = timer[1];

        useEffect(function () {
            if (productId) {
                setIsLoading(true);
                wp.apiFetch({ path: '/wc/v3/products/' + productId }).then(function (p) {
                    setSelectedName(p.name);
                    setIsLoading(false);
                }).catch(function () {
                    setSelectedName('#' + productId);
                    setIsLoading(false);
                });
            } else {
                setSelectedName('');
            }
        }, [productId]);

        function doSearch(value) {
            setSearchTerm(value);
            if (timer[0]) clearTimeout(timer[0]);
            if (value.length < 2) { setResults([]); return; }
            setDebounce(setTimeout(function () {
                setIsLoading(true);
                wp.apiFetch({ path: '/wc/v3/products?search=' + encodeURIComponent(value) + '&per_page=10' }).then(function (products) {
                    setResults(products);
                    setIsLoading(false);
                }).catch(function () { setResults([]); setIsLoading(false); });
            }, 300));
        }

        function pickProduct(id, name) {
            setAttrs({ productId: id });
            setSelectedName(name);
            setSearchTerm('');
            setResults([]);
        }

        var preview;
        if (productId && selectedName) {
            preview = el('div', { style: { padding: '20px', border: '2px dashed #007cba', borderRadius: '4px', background: '#f0f6fc', textAlign: 'center' } },
                el('p', { style: { margin: '0', fontWeight: 'bold' } }, '3D Product Customizer'),
                el('p', { style: { margin: '8px 0 0', color: '#333' } }, selectedName + ' (#' + productId + ')'),
                el('p', { style: { margin: '8px 0 0', fontSize: '12px', color: '#666' } }, 'Click to configure in the sidebar.')
            );
        } else {
            preview = el('div', { style: { padding: '20px', border: '2px dashed #ccc', borderRadius: '4px', background: '#f9f9f9', textAlign: 'center' } },
                el('p', { style: { margin: '0', fontWeight: 'bold' } }, '3D Product Customizer'),
                el('p', { style: { margin: '8px 0 0', color: '#666' } }, 'Click to select a product in the sidebar.')
            );
        }

        return el(wp.element.Fragment, null,
            el(wp.blockEditor.InspectorControls, null,
                el(wp.components.PanelBody, { title: 'Product Selection', initialOpen: true },
                    productId && selectedName
                        ? el('div', { style: { marginBottom: '12px' } },
                            el('p', { style: { margin: '0 0 4px', fontWeight: '600' } }, 'Selected:'),
                            el('p', { style: { margin: '0 0 8px' } }, selectedName + ' (#' + productId + ')'),
                            el(wp.components.Button, { isSecondary: true, onClick: function () { setAttrs({ productId: 0 }); setSelectedName(''); } }, 'Remove')
                        )
                        : null,
                    el(wp.components.TextControl, {
                        label: 'Search Products',
                        value: search[0],
                        onChange: doSearch,
                        placeholder: 'Type product name...'
                    }),
                    load[0]
                        ? el(wp.components.Spinner, null)
                        : null,
                    res[0].length > 0
                        ? el('ul', { style: { margin: '0', padding: '0', listStyle: 'none', border: '1px solid #e0e0e0', borderRadius: '4px', maxHeight: '200px', overflowY: 'auto' } },
                            res[0].map(function (p) {
                                return el('li', {
                                    key: p.id,
                                    onClick: function () { pickProduct(p.id, p.name); },
                                    style: { padding: '8px 12px', cursor: 'pointer', borderBottom: '1px solid #f0f0f0' },
                                    onMouseEnter: function (e) { e.target.style.background = '#f0f0f0'; },
                                    onMouseLeave: function (e) { e.target.style.background = ''; }
                                }, p.name + ' (#' + p.id + ')');
                            })
                        )
                        : null,
                    res[0].length === 0 && search[0].length >= 2 && !load[0]
                        ? el('p', { style: { color: '#999' } }, 'No products found.')
                        : null
                )
            ),
            el('div', blockProps,
                preview
            )
        );
    }

    wp.blocks.registerBlockType('dprcu/customizer', {
        edit: ProductSearch,
        save: function () { return null; }
    });
})(window.wp);
