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

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

    const calculateScale = () => {
        const viewportWidth = window.innerWidth;
        const padding = 0; // 16px padding on each side
        const availableWidth = viewportWidth - padding;

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

        // Don't scale above 100% and ensure minimum scale for very small screens
        setScale(Math.max(0.3, Math.min(newScale, 1)));
    };

    useLayoutEffect(() => {
        calculateScale();
    }, []);

    useEffect(() => {
        const handleResize = () => calculateScale();

        window.addEventListener('resize', handleResize);
        window.addEventListener('orientationchange', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
            window.removeEventListener('orientationchange', handleResize);
        };
    }, []);

    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="mx-auto p-4">
            <div
                style={{
                    width: `${displayWidth}px`,
                    height: `${displayHeight}px`,
                }}
            >
                <div
                    className="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;
