import { useEffect, useRef, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { useBlockProps, InnerBlocks, InspectorControls } from '@wordpress/block-editor';
import { SelectControl, BaseControl, ToggleControl, __experimentalUnitControl as UnitControl } from '@wordpress/components';
import './editor.scss';

export default function Edit({ attributes, setAttributes }) {
    const [isIndependentLarge, setIsIndependentLarge] = useState(false);
    const { sticky } = attributes;

    const blockRef = useRef(null); // Ref to the block container element

    // Block props for the outer block
    const blockProps = useBlockProps({
        ref: blockRef,
    });

    // Use ResizeObserver to monitor height changes
    useEffect(() => {
        const blockElement = blockRef.current;
        if (!blockElement) return;

        // ResizeObserver to monitor changes in the block's size
        const resizeObserver = new ResizeObserver(() => {
            // Get the height using getBoundingClientRect (this avoids issues with offsets)
            const rect = blockElement.getBoundingClientRect();
            const height = rect.height;  // Use the height property from getBoundingClientRect()

            // Send the height to a custom REST API endpoint
            fetch('/wp-json/lcp/v1/set-header-height', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': wpApiSettings.nonce, // Ensure you have the nonce for security
                },
                body: JSON.stringify({
                    height,
                }),
            })
                .then((response) => response.json())
                .then((data) => {
                    console.log('Height saved:', data);
                })
                .catch((error) => {
                    console.error('Error saving height:', error);
                });
        });

        // Observe the block element for resize changes
        resizeObserver.observe(blockElement);

        // Cleanup the observer when the component unmounts
        return () => resizeObserver.disconnect();
    }, []);

    return (
        <div {...blockProps}>
            {/* Inspector Controls */}
            <InspectorControls>
                <SelectControl
                    label={__('Sticky Behavior', 'lcp')}
                    value={sticky}
                    options={[
                        { label: __('Never', 'lcp'), value: 'never' },
                        { label: __('On Scroll', 'lcp'), value: 'onScroll' },
                        { label: __('Always', 'lcp'), value: 'always' },
                    ]}
                    onChange={(value) => setAttributes({ sticky: value })}
                />
                {/* Other controls */}
            </InspectorControls>

            <div id="lcp-header-container">
                <InnerBlocks />
            </div>
        </div>
    );
}
