import { __ } from '@wordpress/i18n';
import { InspectorControls, PanelColorSettings, useBlockProps } from '@wordpress/block-editor';
import { PanelBody, RangeControl, ToggleControl, TextControl } from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
import { useEffect, useRef, useState } from '@wordpress/element';
import metadata from './block.json';

export default function Edit({ attributes, setAttributes }) {
    const {
        postCount,
        columns,
        gap,
        enableAutoplay,
        autoplaySpeed,
        enableTitleTrim,
        titleTrimLength,
        sectionBgColor,
        cardBgColor,
        titleColor,
        authorColor,
        priceColor,
        accentColor,
        arrowBgColor,
        arrowIconColor,
        sectionTitle,
        sectionSubtitle,
        showSectionTitle,
        viewAllText,
        viewAllLink,
        showViewAll
    } = attributes;

    const blockProps = useBlockProps();

    const blockRef = useRef(null);
    const glideRef = useRef(null);
    const [isGlideLoaded, setIsGlideLoaded] = useState(false);

    // 1. Wait for window.Glide to be available
    useEffect(() => {
        if (typeof window !== 'undefined' && window.Glide) {
            setIsGlideLoaded(true);
            return;
        }

        const intervalId = setInterval(() => {
            if (typeof window !== 'undefined' && window.Glide) {
                setIsGlideLoaded(true);
                clearInterval(intervalId);
            }
        }, 200);

        return () => clearInterval(intervalId);
    }, []);

    // 2. Initialize Glide safely observing DOM changes
    useEffect(() => {
        const wrapper = blockRef.current;
        if (!wrapper || !isGlideLoaded) return;

        const initGlide = () => {
            const carouselEl = wrapper.querySelector('.glide');

            // If no carousel element found, cleanup existing instance and return
            if (!carouselEl) {
                if (glideRef.current) {
                    try {
                        glideRef.current.destroy();
                    } catch (e) {
                        // Ignore errors if destroying on removed DOM
                    }
                    glideRef.current = null;
                }
                return;
            }

            // Check specifically if THIS element is already initialized
            // We use a custom data attribute to track this reliably
            if (carouselEl.getAttribute('data-glide-initialized') === 'true') {
                return;
            }

            // If we have an existing instance but found a new uninitialized element,
            // it means SSR replaced the DOM. We must destroy the old instance first.
            if (glideRef.current) {
                try {
                    glideRef.current.destroy();
                } catch (e) {
                    // Ignore errors
                }
                glideRef.current = null;
            }

            const config = {
                type: 'carousel',
                perView: columns,
                gap: attributes.gap || 32,
                autoplay: false, // Disable autoplay in editor to prevent issues
                hoverpause: true,
                breakpoints: {
                    1024: { perView: 2 },
                    640: { perView: 1 }
                }
            };

            try {
                const glide = new window.Glide(carouselEl, config);

                // Mark this specific element as initialized BEFORE mounting
                // to prevent race conditions or observer loops
                carouselEl.setAttribute('data-glide-initialized', 'true');

                glide.mount();
                glideRef.current = glide;
            } catch (e) {
                console.error('Glide init error:', e);
            }
        };

        // MutationObserver to detect when ServerSideRender updates the DOM
        const observer = new MutationObserver((mutations) => {
            // Check if mutations are relevant (i.e., new nodes added)
            let shouldCheck = false;
            for (const mutation of mutations) {
                if (mutation.type === 'childList') {
                    shouldCheck = true;
                    break;
                }
            }

            if (shouldCheck) {
                initGlide();
            }
        });

        // Observe changes. We use childList and subtree because ServerSideRender
        // replaces content deep inside the wrapper. By marking the element with 
        // data-glide-initialized, we prevent the infinite loop even if subtree is true.
        observer.observe(wrapper, { childList: true, subtree: true });

        // Initial attempt
        initGlide();

        return () => {
            observer.disconnect();
            if (glideRef.current) {
                try {
                    glideRef.current.destroy();
                } catch (e) {
                    // Ignore
                }
                glideRef.current = null;
            }
        };
    }, [attributes, isGlideLoaded]); // Re-run when attributes change (triggering SSR) or Glide loads

    return (
        <div {...blockProps}>
            <InspectorControls>
                <PanelBody title={__('Settings', 'author-website-templates')} initialOpen={true}>
                    <RangeControl
                        label={__('Post Count', 'author-website-templates')}
                        value={postCount}
                        onChange={(value) => setAttributes({ postCount: value })}
                        min={1}
                        max={50}
                    />
                    <RangeControl
                        label={__('Columns (Desktop)', 'author-website-templates')}
                        value={columns}
                        onChange={(value) => setAttributes({ columns: value })}
                        min={1}
                        max={4}
                    />
                    <RangeControl
                        label={__('Gap (px)', 'author-website-templates')}
                        value={gap}
                        onChange={(value) => setAttributes({ gap: value })}
                        min={0}
                        max={100}
                    />
                    <ToggleControl
                        label={__('Enable Autoplay', 'author-website-templates')}
                        checked={enableAutoplay}
                        onChange={(value) => setAttributes({ enableAutoplay: value })}
                        help={__('Autoplay is disabled inside the editor to prevent layout issues.', 'author-website-templates')}
                    />
                    {enableAutoplay && (
                        <RangeControl
                            label={__('Autoplay Speed (ms)', 'author-website-templates')}
                            value={autoplaySpeed}
                            onChange={(value) => setAttributes({ autoplaySpeed: value })}
                            min={1000}
                            max={10000}
                            step={100}
                        />
                    )}

                    <ToggleControl
                        label={__('Trim Titles', 'author-website-templates')}
                        checked={enableTitleTrim}
                        onChange={(value) => setAttributes({ enableTitleTrim: value })}
                    />
                    {enableTitleTrim && (
                        <RangeControl
                            label={__('Title Length (Words)', 'author-website-templates')}
                            value={titleTrimLength}
                            onChange={(value) => setAttributes({ titleTrimLength: value })}
                            min={2}
                            max={30}
                        />
                    )}

                    <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={false}>
                        <ToggleControl
                            label={__('Show Section Title', 'author-website-templates')}
                            checked={showSectionTitle}
                            onChange={(value) => setAttributes({ showSectionTitle: value })}
                        />
                        {showSectionTitle && (
                            <>
                                <TextControl
                                    label={__('Section Title', 'author-website-templates')}
                                    value={sectionTitle}
                                    onChange={(value) => setAttributes({ sectionTitle: value })}
                                />
                                <TextControl
                                    label={__('Section Subtitle', 'author-website-templates')}
                                    value={sectionSubtitle}
                                    onChange={(value) => setAttributes({ sectionSubtitle: value })}
                                />
                            </>
                        )}
                        <ToggleControl
                            label={__('Show "View All" Link', 'author-website-templates')}
                            checked={showViewAll}
                            onChange={(value) => setAttributes({ showViewAll: value })}
                        />
                        {showViewAll && (
                            <>
                                <TextControl
                                    label={__('Link Text', 'author-website-templates')}
                                    value={viewAllText}
                                    onChange={(value) => setAttributes({ viewAllText: value })}
                                />
                                <TextControl
                                    label={__('Link URL', 'author-website-templates')}
                                    value={viewAllLink}
                                    onChange={(value) => setAttributes({ viewAllLink: value })}
                                />
                            </>
                        )}
                    </PanelBody>

                    <PanelColorSettings
                        title={__('Color Settings', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            {
                                value: sectionBgColor,
                                onChange: (value) => setAttributes({ sectionBgColor: value }),
                                label: __('Section Background', 'author-website-templates'),
                            },
                            {
                                value: cardBgColor,
                                onChange: (value) => setAttributes({ cardBgColor: value }),
                                label: __('Card Background', 'author-website-templates'),
                            },
                            {
                                value: titleColor,
                                onChange: (value) => setAttributes({ titleColor: value }),
                                label: __('Title Color', 'author-website-templates'),
                            },
                            {
                                value: authorColor,
                                onChange: (value) => setAttributes({ authorColor: value }),
                                label: __('Author Color', 'author-website-templates'),
                            },
                            {
                                value: priceColor,
                                onChange: (value) => setAttributes({ priceColor: value }),
                                label: __('Price Color', 'author-website-templates'),
                            },
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Accent Color (Button/Links)', 'author-website-templates'),
                            },
                            {
                                value: arrowBgColor,
                                onChange: (value) => setAttributes({ arrowBgColor: value }),
                                label: __('Arrow Background', 'author-website-templates'),
                            },
                            {
                                value: arrowIconColor,
                                onChange: (value) => setAttributes({ arrowIconColor: value }),
                                label: __('Arrow Icon Color', 'author-website-templates'),
                            },
                        ]}
                    />
                </PanelBody>
            </InspectorControls>

            {/* Inner Wrapper for Slider Logic */}
            <div ref={blockRef} style={{ position: 'relative' }}>
                {/* Click Shield Overlay to fix selection issues */}
                <div
                    style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: '100%',
                        height: '100%',
                        zIndex: 50,
                        cursor: 'default',
                    }}
                    aria-hidden="true"
                />

                {/* ServerSideRender with pointer-events: none */}
                <div style={{ pointerEvents: 'none' }}>
                    <ServerSideRender
                        block={metadata.name}
                        attributes={attributes}
                        LoadingResponsePlaceholder={() => <div style={{ height: '300px', background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Loading...</div>}
                    />
                </div>
            </div>
        </div>
    );
}