import React, { useState, useEffect, useLayoutEffect } from 'react';

// Move calculation outside the hook for best performance
const calculateResponsiveScale = (maxWidth) => {
    const viewportWidth = window.innerWidth;

    // Very aggressive padding reduction for small screens
    let padding;
    if (viewportWidth < 320) {
        padding = 0; // Almost no padding on very small screens
    } else if (viewportWidth < 400) {
        padding = 0; // Minimal padding on small screens
    } else {
        padding = 0; // Normal padding on larger screens
    }

    const availableWidth = viewportWidth - padding;
    const constrainedWidth = Math.min(availableWidth, maxWidth);
    const newScale = constrainedWidth / 720;

    // Just cap at 100%, no minimum to avoid clipping
    return Math.min(newScale, 1);
};

const useResponsiveCanvas = (maxWidth = 350) => {
    const [scale, setScale] = useState(0.5);

    useLayoutEffect(() => {
        setScale(calculateResponsiveScale(maxWidth));
    }, [maxWidth]);

    useEffect(() => {
        // Update immediately
        setScale(calculateResponsiveScale(maxWidth));

        // Create event handlers inside effect
        const handleResize = () => {
            setScale(calculateResponsiveScale(maxWidth));
        };

        // Multiple event listeners for better coverage
        window.addEventListener('resize', handleResize);
        window.addEventListener('orientationchange', handleResize);

        // ResizeObserver for more reliable detection in dev tools
        let resizeObserver;
        if (window.ResizeObserver) {
            resizeObserver = new ResizeObserver(() => {
                setScale(calculateResponsiveScale(maxWidth));
            });
            resizeObserver.observe(document.body);
        }

        // MutationObserver to catch when dev tools changes the viewport
        let mutationObserver;
        if (window.MutationObserver) {
            mutationObserver = new MutationObserver(() => {
                setTimeout(() => {
                    setScale(calculateResponsiveScale(maxWidth));
                }, 50);
            });
            mutationObserver.observe(document.documentElement, {
                attributes: true,
                attributeFilter: ['style']
            });
        }

        return () => {
            window.removeEventListener('resize', handleResize);
            window.removeEventListener('orientationchange', handleResize);
            if (resizeObserver) resizeObserver.disconnect();
            if (mutationObserver) mutationObserver.disconnect();
        };
    }, [maxWidth]);

    return scale;
};

const EditorCanvas = ({maxWidth = 350}) => {
    const scale = useResponsiveCanvas(maxWidth);
    const canvasWidth = 720;
    const canvasHeight = 1280;
    const displayWidth = canvasWidth * scale;
    const displayHeight = canvasHeight * scale;

    const convertCoordinates = (e) => {
        const rect = e.currentTarget.getBoundingClientRect();
        return {
            x: (e.clientX - rect.left) / scale,
            y: (e.clientY - rect.top) / scale
        };
    };

    return (
        <div className="w-full flex justify-center">
            <div
                style={{
                    width: `${displayWidth}px`,
                    height: `${displayHeight}px`,
                }}
            >
                <div
                    className="border rounded-3xl bg-white shadow-sm origin-top-left"
                    style={{
                        width: `${canvasWidth}px`,
                        height: `${canvasHeight}px`,
                        transform: `scale(${scale})`,
                    }}
                    onClick={(e) => {
                        const { x, y } = convertCoordinates(e);
                        // Handle your canvas interactions here
                        // x, y are the actual canvas coordinates (0-720, 0-1280)
                    }}
                >
                    {/* Your canvas content goes here */}
                </div>
            </div>
        </div>
    );
};

export default EditorCanvas;
