// ==========================================
// GridDisplay Component
// ==========================================

const GridDisplay = ({ imageUrl, settings, pixelated }) => {
    const [isZipping, setIsZipping] = React.useState(false);
    const [naturalSize, setNaturalSize] = React.useState({ w: 0, h: 0 });
    const imageRef = React.useRef(null);

    const totalCells = settings.rows * settings.columns;

    const onImageLoad = (e) => {
        setNaturalSize({ w: e.target.naturalWidth, h: e.target.naturalHeight });
    };

    const handleDownloadZip = async () => {
        if (!imageRef.current || isZipping) return;
        setIsZipping(true);

        try {
            const zip = new JSZip();
            const img = imageRef.current;
            const frameWidth = Math.floor(img.naturalWidth / settings.columns);
            const frameHeight = Math.floor(img.naturalHeight / settings.rows);

            const canvas = document.createElement('canvas');
            canvas.width = frameWidth;
            canvas.height = frameHeight;
            const ctx = canvas.getContext('2d');

            if (!ctx) throw new Error("No context");

            for (let i = 0; i < totalCells; i++) {
                const col = i % settings.columns;
                const row = Math.floor(i / settings.columns);

                ctx.clearRect(0, 0, frameWidth, frameHeight);
                ctx.drawImage(
                    img,
                    col * frameWidth, row * frameHeight, frameWidth, frameHeight,
                    0, 0, frameWidth, frameHeight
                );

                const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
                if (blob) zip.file(`frame_${i + 1}.png`, blob);
            }

            const content = await zip.generateAsync({ type: "blob" });
            saveAs(content, "frames.zip");

        } catch (e) {
            console.error(e);
            alert("打包失败: " + e.message);
        } finally {
            setIsZipping(false);
        }
    };

    const cellW = Math.floor(naturalSize.w / (settings.columns || 1));
    const cellH = Math.floor(naturalSize.h / (settings.rows || 1));

    return (
        <div className="flex flex-col h-full w-full">
            <div className="flex justify-between items-end mb-2">
                <div className="flex gap-4">
                    {naturalSize.w > 0 && (
                        <div className="flex gap-2 text-[10px] font-mono font-bold text-indigo-300 bg-indigo-500/10 px-2 py-1 rounded border border-indigo-500/20">
                            <span>TOTAL: {naturalSize.w}x{naturalSize.h}</span>
                            <span className="text-slate-500">|</span>
                            <span>CELL: {cellW}x{cellH}</span>
                        </div>
                    )}
                </div>

                <span className="text-xs text-slate-500 italic">
                    * 右键另存为图片可保存原始素材
                </span>
            </div>

            <div className="relative flex-grow w-full bg-[#1a1a1a] rounded overflow-auto flex justify-center items-start p-4">
                <div className="relative inline-block shadow-2xl">
                    <img
                        ref={imageRef}
                        src={imageUrl}
                        onLoad={onImageLoad}
                        alt="Sprite Sheet"
                        className="max-w-full h-auto object-contain block"
                        style={{ imageRendering: pixelated ? 'pixelated' : 'auto' }}
                    />

                    <div
                        className="absolute inset-0 grid border-t border-l border-blue-400/30"
                        style={{
                            gridTemplateColumns: `repeat(${settings.columns}, 1fr)`,
                            gridTemplateRows: `repeat(${settings.rows}, 1fr)`
                        }}
                    >
                        {Array.from({ length: totalCells }).map((_, i) => (
                            <div
                                key={i}
                                className="border-r border-b border-blue-400/30 relative box-border"
                            >
                                <span className="absolute top-0.5 left-0.5 bg-slate-800/80 text-blue-200 text-[9px] font-mono px-1 rounded-sm select-none pointer-events-none z-10">
                                    {i + 1}
                                </span>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
};

window.GridDisplay = GridDisplay;
