import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { useRef, useState, useMemo, useEffect, useCallback } from 'react';
import styles from './GameAsset2dEditor.module.css.js';
import { useGameAssetEditor } from './useGameAssetEditor.js';
import { NiceButton as We, NiceTextInput as Tt, NiceSelect as fn, NiceNumberInput as ir } from '../packages/ui/dist/index.js';

/* ────────────────────────────────────────────────────────────────
   MENU BAR
──────────────────────────────────────────────────────────────── */
const MenuBar = ({ api }) => {
    const fileInputRef = useRef(null);
    return (jsxs("div", { className: styles.menuBar, children: [jsx("h3", { children: "\uD83C\uDFAE Game Asset Editor" }), jsxs("div", { className: styles.menuGroup, children: [jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: () => api.newProject('New Project'), children: "\uD83D\uDCC4 New" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: () => { var _a; return (_a = fileInputRef.current) === null || _a === void 0 ? void 0 : _a.click(); }, children: "\uD83D\uDCC2 Open" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: api.saveProject, children: "\uD83D\uDCBE Save" })] }), jsx("div", { className: styles.spacer }), jsxs("div", { className: styles.menuGroup, children: [jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: api.undo, disabled: !api.canUndo, children: "\u21A9 Undo" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: api.redo, disabled: !api.canRedo, children: "\u21AA Redo" })] }), jsx("input", { ref: fileInputRef, type: "file", accept: ".json", style: { display: 'none' }, onChange: e => {
                    var _a;
                    const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
                    if (file)
                        api.loadProject(file);
                    e.target.value = '';
                } })] }));
};
/* ────────────────────────────────────────────────────────────────
   MODE TABS
──────────────────────────────────────────────────────────────── */
const ModeTabs = ({ api }) => {
    const modes = [
        { id: 'tilemap', label: 'Tile Map', icon: '🗺️' },
        { id: 'spritesheet', label: 'Sprite Sheet', icon: '🖼️' },
        { id: 'animation', label: 'Animation', icon: '🎬' },
        { id: 'effects', label: 'Effects', icon: '✨' },
    ];
    return (jsx("div", { className: styles.modeTabs, children: modes.map(mode => (jsxs(We, { className: `${styles.modeTab} ${api.editorState.mode === mode.id ? styles.active : ''}`, variant: api.editorState.mode === mode.id ? 'primary' : 'ghost', onClick: () => api.setMode(mode.id), children: [mode.icon, " ", mode.label] }, mode.id))) }));
};
/* ────────────────────────────────────────────────────────────────
   TILE MAP TOOLBAR
──────────────────────────────────────────────────────────────── */
const TileMapToolbar = ({ api }) => {
    const tools = [
        { id: 'select', icon: '⬚', label: 'Select' },
        { id: 'brush', icon: '✏', label: 'Brush' },
        { id: 'eraser', icon: '⌫', label: 'Eraser' },
        { id: 'fill', icon: '🪣', label: 'Fill' },
        { id: 'rectangle', icon: '▢', label: 'Rectangle' },
        { id: 'line', icon: '╱', label: 'Line' },
        { id: 'eyedropper', icon: '💧', label: 'Eyedropper' },
    ];
    return (jsxs("div", { className: styles.toolbar, children: [jsx("div", { className: styles.toolGroup, children: tools.map(tool => (jsx(We, { className: `${styles.toolBtn} ${api.editorState.tileMapTool === tool.id ? styles.active : ''}`, variant: api.editorState.tileMapTool === tool.id ? 'primary' : 'ghost', size: "sm", onClick: () => api.setTileMapTool(tool.id), title: tool.label, children: tool.icon }, tool.id))) }), jsx("div", { className: styles.spacer }), jsx(We, { className: `${styles.toolBtn} ${api.editorState.showGrid ? styles.active : ''}`, variant: api.editorState.showGrid ? 'primary' : 'ghost', size: "sm", onClick: api.toggleGrid, title: "Toggle Grid", children: "\u229E" }), jsx(We, { className: `${styles.toolBtn} ${api.editorState.showCollision ? styles.active : ''}`, variant: api.editorState.showCollision ? 'primary' : 'ghost', size: "sm", onClick: api.toggleCollision, title: "Show Collision", children: "\u25C7" }), jsx(We, { className: `${styles.toolBtn} ${api.editorState.snapToGrid ? styles.active : ''}`, variant: api.editorState.snapToGrid ? 'primary' : 'ghost', size: "sm", onClick: api.toggleSnap, title: "Snap to Grid", children: "\u22A1" })] }));
};
/* ────────────────────────────────────────────────────────────────
   SPRITE SHEET TOOLBAR
──────────────────────────────────────────────────────────────── */
const SpriteSheetToolbar = ({ api }) => {
    const [sliceWidth, setSliceWidth] = useState(16);
    const [sliceHeight, setSliceHeight] = useState(16);
    return (jsxs("div", { className: styles.toolbar, children: [jsxs("div", { className: styles.toolGroup, children: [jsx(We, { className: `${styles.toolBtn} ${api.editorState.spriteSheetTool === 'select' ? styles.active : ''}`, variant: api.editorState.spriteSheetTool === 'select' ? 'primary' : 'ghost', size: "sm", onClick: () => api.setSpriteSheetTool('select'), title: "Select", children: "\u2B1A" }), jsx(We, { className: `${styles.toolBtn} ${api.editorState.spriteSheetTool === 'slice' ? styles.active : ''}`, variant: api.editorState.spriteSheetTool === 'slice' ? 'primary' : 'ghost', size: "sm", onClick: () => api.setSpriteSheetTool('slice'), title: "Manual Slice", children: "\u2702" })] }), jsx("div", { className: styles.spacer }), jsxs("label", { style: { fontSize: 11, color: '#8892a8' }, children: ["Frame size:", jsx(ir, { value: sliceWidth, onChange: val => setSliceWidth(val !== null && val !== void 0 ? val : 16), style: { width: 40, margin: '0 4px' }, className: styles.panelInput }), "\u00D7", jsx(ir, { value: sliceHeight, onChange: val => setSliceHeight(val !== null && val !== void 0 ? val : 16), style: { width: 40, marginLeft: 4 }, className: styles.panelInput })] }), jsx(We, { className: styles.btnSecondary, variant: "ghost", onClick: () => api.autoSlice(sliceWidth, sliceHeight), style: { marginLeft: 8 }, children: "Auto Slice" }), jsx(We, { className: styles.btnSecondary, variant: "ghost", onClick: api.detectSprites, style: { marginLeft: 4 }, children: "Detect Sprites" })] }));
};
/* ────────────────────────────────────────────────────────────────
   TILE PALETTE (LEFT PANEL)
──────────────────────────────────────────────────────────────── */
const TilePalette = ({ api }) => {
    const fileInputRef = useRef(null);
    return (jsxs("div", { className: styles.leftPanel, children: [jsxs("div", { className: styles.panelHeader, children: [jsx("span", { children: "Tiles" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: () => { var _a; return (_a = fileInputRef.current) === null || _a === void 0 ? void 0 : _a.click(); }, children: "+ Add" })] }), jsx("div", { className: styles.panelContent, children: api.project.tileSets.length === 0 ? (jsxs("div", { className: styles.emptyState, children: [jsx("div", { className: styles.emptyStateText, children: "No tiles yet" }), jsx(We, { className: styles.btnSecondary, variant: "ghost", onClick: () => { var _a; return (_a = fileInputRef.current) === null || _a === void 0 ? void 0 : _a.click(); }, children: "Import Tiles" })] })) : (jsx("div", { className: styles.tilePalette, children: api.project.tileSets.map(tile => (jsx("div", { className: `${styles.tileItem} ${api.editorState.selectedTileId === tile.id ? styles.selected : ''}`, onClick: () => api.selectTile(tile.id), title: tile.name, children: jsx("img", { src: tile.thumbnail, alt: tile.name }) }, tile.id))) })) }), jsx("input", { ref: fileInputRef, type: "file", accept: "image/*", style: { display: 'none' }, onChange: e => {
                    var _a;
                    const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
                    if (file)
                        api.importTileSet(file);
                    e.target.value = '';
                } })] }));
};
/* ────────────────────────────────────────────────────────────────
   LAYERS PANEL (RIGHT PANEL)
──────────────────────────────────────────────────────────────── */
const LayersPanel = ({ api }) => {
    const activeMap = api.project.tileMaps.find(m => m.id === api.editorState.activeTileMapId);
    return (jsxs("div", { className: styles.rightPanel, children: [jsxs("div", { className: styles.panelHeader, children: [jsx("span", { children: "Layers" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: api.addLayer, disabled: !activeMap, children: "+ Add" })] }), jsx("div", { className: styles.panelContent, children: activeMap ? (jsx("div", { className: styles.layersList, children: [...activeMap.layers].reverse().map(layer => (jsxs("div", { className: `${styles.layerItem} ${api.editorState.activeLayerId === layer.id ? styles.selected : ''}`, onClick: () => api.selectLayer(layer.id), children: [jsx(We, { className: `${styles.layerVisibility} ${!layer.visible ? styles.hidden : ''}`, variant: "ghost", size: "sm", onClick: e => {
                                    e.stopPropagation();
                                    api.toggleLayerVisibility(layer.id);
                                }, children: layer.visible ? '👁' : '○' }), jsx("span", { className: styles.layerName, children: layer.name }), jsxs("span", { className: styles.layerOpacity, children: [Math.round(layer.opacity * 100), "%"] })] }, layer.id))) })) : (jsx("div", { className: styles.emptyState, children: jsx("div", { className: styles.emptyStateText, children: "No tile map selected" }) })) }), jsxs("div", { className: styles.panelHeader, children: [jsx("span", { children: "Maps" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: () => api.createTileMap('New Map', 32, 32), children: "+ New" })] }), jsx("div", { className: styles.panelContent, children: api.project.tileMaps.map(map => (jsxs("div", { className: `${styles.layerItem} ${api.editorState.activeTileMapId === map.id ? styles.selected : ''}`, onClick: () => api.selectTileMap(map.id), children: [jsx("span", { className: styles.layerName, children: map.name }), jsxs("span", { className: styles.layerOpacity, children: [map.width, "\u00D7", map.height] })] }, map.id))) })] }));
};
/* ────────────────────────────────────────────────────────────────
   TILE MAP CANVAS
──────────────────────────────────────────────────────────────── */
const TileMapCanvas = ({ api }) => {
    const canvasRef = useRef(null);
    const containerRef = useRef(null);
    const [isDragging, setIsDragging] = useState(false);
    const activeMap = api.project.tileMaps.find(m => m.id === api.editorState.activeTileMapId);
    // Render the tile map
    useEffect(() => {
        var _a;
        const canvas = canvasRef.current;
        if (!canvas || !activeMap)
            return;
        const ctx = canvas.getContext('2d');
        if (!ctx)
            return;
        canvas.width = activeMap.width * activeMap.tileWidth;
        canvas.height = activeMap.height * activeMap.tileHeight;
        // Background
        ctx.fillStyle = activeMap.backgroundColor;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        // Render layers
        for (const layer of activeMap.layers.filter(l => l.visible)) {
            ctx.globalAlpha = layer.opacity;
            for (let y = 0; y < activeMap.height; y++) {
                for (let x = 0; x < activeMap.width; x++) {
                    const tileId = (_a = layer.tiles[y]) === null || _a === void 0 ? void 0 : _a[x];
                    if (tileId) {
                        const tile = api.project.tileSets.find(t => t.id === tileId);
                        if (tile === null || tile === void 0 ? void 0 : tile.thumbnail) {
                            const img = new Image();
                            img.src = tile.thumbnail;
                            ctx.drawImage(img, x * activeMap.tileWidth, y * activeMap.tileHeight, activeMap.tileWidth, activeMap.tileHeight);
                        }
                    }
                }
            }
        }
        // Grid overlay
        if (api.editorState.showGrid) {
            ctx.globalAlpha = 0.3;
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 1;
            for (let x = 0; x <= activeMap.width; x++) {
                ctx.beginPath();
                ctx.moveTo(x * activeMap.tileWidth, 0);
                ctx.lineTo(x * activeMap.tileWidth, canvas.height);
                ctx.stroke();
            }
            for (let y = 0; y <= activeMap.height; y++) {
                ctx.beginPath();
                ctx.moveTo(0, y * activeMap.tileHeight);
                ctx.lineTo(canvas.width, y * activeMap.tileHeight);
                ctx.stroke();
            }
        }
        ctx.globalAlpha = 1;
    }, [activeMap, api.project.tileSets, api.editorState.showGrid]);
    const handleCanvasClick = useCallback((e) => {
        if (!activeMap || !api.editorState.activeLayerId || !api.editorState.selectedTileId)
            return;
        const canvas = canvasRef.current;
        if (!canvas)
            return;
        const rect = canvas.getBoundingClientRect();
        const scaleX = canvas.width / rect.width;
        const scaleY = canvas.height / rect.height;
        const x = Math.floor((e.clientX - rect.left) * scaleX / activeMap.tileWidth);
        const y = Math.floor((e.clientY - rect.top) * scaleY / activeMap.tileHeight);
        if (api.editorState.tileMapTool === 'brush') {
            api.setTile(api.editorState.activeLayerId, x, y, api.editorState.selectedTileId);
        }
        else if (api.editorState.tileMapTool === 'eraser') {
            api.setTile(api.editorState.activeLayerId, x, y, null);
        }
        else if (api.editorState.tileMapTool === 'fill') {
            api.fillTiles(api.editorState.activeLayerId, x, y, api.editorState.selectedTileId);
        }
    }, [activeMap, api]);
    return (jsx("div", { className: styles.viewport, ref: containerRef, children: activeMap ? (jsx("canvas", { ref: canvasRef, className: styles.viewportCanvas, style: {
                transform: `translate(-50%, -50%) scale(${api.editorState.zoom})`,
            }, onClick: handleCanvasClick, onMouseDown: () => setIsDragging(true), onMouseUp: () => setIsDragging(false), onMouseMove: e => {
                if (isDragging && (api.editorState.tileMapTool === 'brush' || api.editorState.tileMapTool === 'eraser')) {
                    handleCanvasClick(e);
                }
            } })) : (jsxs("div", { className: styles.emptyState, children: [jsx("div", { className: styles.emptyStateText, children: "Create or select a tile map to start editing" }), jsx(We, { className: styles.btnPrimary, variant: "primary", onClick: () => api.createTileMap('New Map', 32, 32), children: "Create Tile Map" })] })) }));
};
/* ────────────────────────────────────────────────────────────────
   SPRITE SHEET CANVAS
──────────────────────────────────────────────────────────────── */
const SpriteSheetCanvas = ({ api }) => {
    const canvasRef = useRef(null);
    const fileInputRef = useRef(null);
    const activeSheet = api.project.spriteSheets.find(s => s.id === api.editorState.activeSpriteSheetId);
    // Render sprite sheet with frame overlays
    useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas || !(activeSheet === null || activeSheet === void 0 ? void 0 : activeSheet.image))
            return;
        const ctx = canvas.getContext('2d');
        if (!ctx)
            return;
        canvas.width = activeSheet.width;
        canvas.height = activeSheet.height;
        // Draw image
        ctx.drawImage(activeSheet.image, 0, 0);
        // Draw frame overlays
        ctx.strokeStyle = '#ffd369';
        ctx.lineWidth = 2;
        for (const frame of activeSheet.frames) {
            const isSelected = api.editorState.selectedFrameIds.includes(frame.id);
            ctx.strokeStyle = isSelected ? '#ffd369' : '#4a5a7e';
            ctx.strokeRect(frame.x, frame.y, frame.width, frame.height);
            // Draw pivot point
            const pivotX = frame.x + frame.width * frame.pivotX;
            const pivotY = frame.y + frame.height * frame.pivotY;
            ctx.fillStyle = isSelected ? '#ffd369' : '#4a5a7e';
            ctx.beginPath();
            ctx.arc(pivotX, pivotY, 3, 0, Math.PI * 2);
            ctx.fill();
        }
    }, [activeSheet, api.editorState.selectedFrameIds]);
    const handleFrameClick = useCallback((e) => {
        if (!activeSheet)
            return;
        const canvas = canvasRef.current;
        if (!canvas)
            return;
        const rect = canvas.getBoundingClientRect();
        const scaleX = canvas.width / rect.width;
        const scaleY = canvas.height / rect.height;
        const x = (e.clientX - rect.left) * scaleX;
        const y = (e.clientY - rect.top) * scaleY;
        // Find clicked frame
        const clickedFrame = activeSheet.frames.find(f => x >= f.x && x <= f.x + f.width && y >= f.y && y <= f.y + f.height);
        if (clickedFrame) {
            if (e.ctrlKey || e.metaKey) {
                // Toggle selection
                const newSelection = api.editorState.selectedFrameIds.includes(clickedFrame.id)
                    ? api.editorState.selectedFrameIds.filter(id => id !== clickedFrame.id)
                    : [...api.editorState.selectedFrameIds, clickedFrame.id];
                api.selectFrames(newSelection);
            }
            else {
                api.selectFrames([clickedFrame.id]);
            }
        }
        else {
            api.selectFrames([]);
        }
    }, [activeSheet, api]);
    return (jsx("div", { className: styles.viewport, children: activeSheet ? (jsx("canvas", { ref: canvasRef, className: styles.viewportCanvas, style: {
                transform: `translate(-50%, -50%) scale(${api.editorState.zoom})`,
            }, onClick: handleFrameClick })) : (jsxs("div", { className: styles.emptyState, children: [jsx("div", { className: styles.emptyStateText, children: "Import a sprite sheet to start" }), jsx(We, { className: styles.btnPrimary, variant: "primary", onClick: () => { var _a; return (_a = fileInputRef.current) === null || _a === void 0 ? void 0 : _a.click(); }, children: "Import Sprite Sheet" }), jsx("input", { ref: fileInputRef, type: "file", accept: "image/*", style: { display: 'none' }, onChange: e => {
                        var _a;
                        const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
                        if (file)
                            api.importSpriteSheet(file);
                        e.target.value = '';
                    } })] })) }));
};
/* ────────────────────────────────────────────────────────────────
   SPRITE SHEETS LIST
──────────────────────────────────────────────────────────────── */
const SpriteSheetsList = ({ api }) => {
    const fileInputRef = useRef(null);
    return (jsxs("div", { className: styles.leftPanel, children: [jsxs("div", { className: styles.panelHeader, children: [jsx("span", { children: "Sprite Sheets" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: () => { var _a; return (_a = fileInputRef.current) === null || _a === void 0 ? void 0 : _a.click(); }, children: "+ Import" })] }), jsx("div", { className: styles.panelContent, children: api.project.spriteSheets.length === 0 ? (jsx("div", { className: styles.emptyState, children: jsx("div", { className: styles.emptyStateText, children: "No sprite sheets" }) })) : (jsx("div", { className: styles.layersList, children: api.project.spriteSheets.map(sheet => (jsxs("div", { className: `${styles.layerItem} ${api.editorState.activeSpriteSheetId === sheet.id ? styles.selected : ''}`, onClick: () => api.selectSpriteSheet(sheet.id), children: [jsx("span", { className: styles.layerName, children: sheet.name }), jsxs("span", { className: styles.layerOpacity, children: [sheet.frames.length, " frames"] })] }, sheet.id))) })) }), jsx("input", { ref: fileInputRef, type: "file", accept: "image/*", style: { display: 'none' }, onChange: e => {
                    var _a;
                    const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
                    if (file)
                        api.importSpriteSheet(file);
                    e.target.value = '';
                } })] }));
};
/* ────────────────────────────────────────────────────────────────
   FRAMES & ANIMATIONS PANEL
──────────────────────────────────────────────────────────────── */
const FramesPanel = ({ api }) => {
    var _a;
    const [animName, setAnimName] = useState('');
    const activeSheet = api.project.spriteSheets.find(s => s.id === api.editorState.activeSpriteSheetId);
    const createAnimationFromSelection = useCallback(() => {
        if (animName && api.editorState.selectedFrameIds.length > 0) {
            api.createAnimation(animName, api.editorState.selectedFrameIds);
            setAnimName('');
        }
    }, [animName, api]);
    return (jsxs("div", { className: styles.rightPanel, children: [jsx("div", { className: styles.panelHeader, children: jsxs("span", { children: ["Frames (", (_a = activeSheet === null || activeSheet === void 0 ? void 0 : activeSheet.frames.length) !== null && _a !== void 0 ? _a : 0, ")"] }) }), jsx("div", { className: styles.panelContent, style: { maxHeight: 200 }, children: activeSheet === null || activeSheet === void 0 ? void 0 : activeSheet.frames.map(frame => (jsxs("div", { className: `${styles.layerItem} ${api.editorState.selectedFrameIds.includes(frame.id) ? styles.selected : ''}`, onClick: () => api.selectFrames([frame.id]), children: [jsx("span", { className: styles.layerName, children: frame.name }), jsxs("span", { className: styles.layerOpacity, children: [frame.width, "\u00D7", frame.height] })] }, frame.id))) }), jsx("div", { className: styles.panelHeader, children: jsx("span", { children: "Animations" }) }), jsxs("div", { className: styles.panelContent, children: [api.editorState.selectedFrameIds.length > 0 && (jsxs("div", { className: styles.panelSection, children: [jsx(Tt, { className: styles.panelInput, placeholder: "Animation name...", value: animName, onChange: val => setAnimName(val) }), jsxs(We, { className: styles.btnPrimary, variant: "primary", onClick: createAnimationFromSelection, style: { marginTop: 8, width: '100%' }, disabled: !animName, children: ["Create from ", api.editorState.selectedFrameIds.length, " frames"] })] })), activeSheet === null || activeSheet === void 0 ? void 0 : activeSheet.animations.map(anim => (jsxs("div", { className: styles.layerItem, children: [jsx("span", { className: styles.layerName, children: anim.name }), jsxs("span", { className: styles.layerOpacity, children: [anim.frameIds.length, "f"] }), jsx(We, { className: styles.effectRemove, variant: "ghost", size: "sm", onClick: () => api.removeAnimation(anim.id), children: "\u00D7" })] }, anim.id)))] })] }));
};
/* ────────────────────────────────────────────────────────────────
   ANIMATION STATE MACHINE
──────────────────────────────────────────────────────────────── */
const AnimationStateMachineView = ({ api }) => {
    var _a;
    const [newStateName, setNewStateName] = useState('');
    const activeSM = api.project.stateMachines.find(sm => sm.id === api.editorState.activeStateMachineId);
    // Get all animations from all sprite sheets
    const allAnimations = useMemo(() => {
        const result = [];
        for (const sheet of api.project.spriteSheets) {
            for (const anim of sheet.animations) {
                result.push({ ...anim, sheetName: sheet.name });
            }
        }
        return result;
    }, [api.project.spriteSheets]);
    return (jsxs("div", { style: { display: 'flex', flex: 1, overflow: 'hidden' }, children: [jsxs("div", { className: styles.leftPanel, children: [jsxs("div", { className: styles.panelHeader, children: [jsx("span", { children: "State Machines" }), jsx("button", { className: styles.menuBtn, onClick: () => api.createStateMachine('New State Machine'), children: "+ New" })] }), jsx("div", { className: styles.panelContent, style: { maxHeight: 150 }, children: api.project.stateMachines.map(sm => (jsxs("div", { className: `${styles.layerItem} ${api.editorState.activeStateMachineId === sm.id ? styles.selected : ''}`, onClick: () => api.selectStateMachine(sm.id), children: [jsx("span", { className: styles.layerName, children: sm.name }), jsxs("span", { className: styles.layerOpacity, children: [sm.states.length, " states"] })] }, sm.id))) }), activeSM && (jsxs(Fragment, { children: [jsx("div", { className: styles.panelHeader, children: jsx("span", { children: "States" }) }), jsxs("div", { className: styles.panelContent, children: [jsxs("div", { className: styles.panelSection, children: [jsx(Tt, { className: styles.panelInput, placeholder: "State name...", value: newStateName, onChange: val => setNewStateName(val) }), allAnimations.length > 0 && newStateName && (jsx(fn, { className: styles.panelInput, style: { marginTop: 4 }, onChange: val => {
                                                    if (val) {
                                                        api.addState(newStateName, val);
                                                        setNewStateName('');
                                                    }
                                                }, options: [
                                                    { value: '', label: 'Select animation...' },
                                                    ...allAnimations.map(anim => ({
                                                        value: anim.id,
                                                        label: `${anim.sheetName}: ${anim.name}`
                                                    }))
                                                ] }))] }), activeSM.states.map(state => (jsxs("div", { className: `${styles.layerItem} ${api.editorState.selectedStateId === state.id ? styles.selected : ''} ${activeSM.entryStateId === state.id ? styles.entry : ''}`, onClick: () => api.selectState(state.id), children: [jsxs("span", { className: styles.layerName, children: [activeSM.entryStateId === state.id && '▶ ', state.name] }), jsx(We, { className: styles.effectRemove, variant: "ghost", size: "sm", onClick: e => {
                                                    e.stopPropagation();
                                                    api.removeState(state.id);
                                                }, children: "\u00D7" })] }, state.id)))] })] }))] }), jsx("div", { className: styles.stateGraph, children: activeSM ? (jsxs("svg", { width: "100%", height: "100%", children: [jsx("defs", { children: jsx("marker", { id: "arrowhead", markerWidth: "10", markerHeight: "7", refX: "9", refY: "3.5", orient: "auto", children: jsx("polygon", { points: "0 0, 10 3.5, 0 7", fill: "#4a5a7e" }) }) }), activeSM.transitions.map(trans => {
                            const from = activeSM.states.find(s => s.id === trans.fromStateId);
                            const to = activeSM.states.find(s => s.id === trans.toStateId);
                            if (!from || !to)
                                return null;
                            return (jsx("line", { x1: from.position.x + 60, y1: from.position.y + 20, x2: to.position.x + 60, y2: to.position.y + 20, className: styles.transition, onClick: () => api.removeTransition(trans.id) }, trans.id));
                        }), activeSM.states.map(state => {
                            var _a, _b;
                            return (jsx("foreignObject", { x: state.position.x, y: state.position.y, width: 120, height: 50, children: jsxs("div", { className: `${styles.stateNode} ${api.editorState.selectedStateId === state.id ? styles.selected : ''} ${activeSM.entryStateId === state.id ? styles.entry : ''}`, onClick: () => api.selectState(state.id), children: [jsx("div", { className: styles.stateNodeName, children: state.name }), jsx("div", { className: styles.stateNodeAnim, children: (_b = (_a = allAnimations.find(a => a.id === state.animationId)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : 'No animation' })] }) }, state.id));
                        })] })) : (jsx("div", { className: styles.emptyState, children: jsx("div", { className: styles.emptyStateText, children: "Create a state machine to design animation flows" }) })) }), jsxs("div", { className: styles.rightPanel, children: [jsxs("div", { className: styles.panelHeader, children: [jsx("span", { children: "Parameters" }), jsx(We, { className: styles.menuBtn, variant: "ghost", size: "sm", onClick: () => api.addParameter('new_param', 'trigger'), disabled: !activeSM, children: "+ Add" })] }), jsx("div", { className: styles.panelContent, children: activeSM === null || activeSM === void 0 ? void 0 : activeSM.parameters.map(param => (jsxs("div", { className: styles.layerItem, children: [jsx("span", { className: styles.layerOpacity, children: param.type }), jsx("span", { className: styles.layerName, children: param.name }), jsx(We, { className: styles.effectRemove, variant: "ghost", size: "sm", onClick: () => api.removeParameter(param.id), children: "\u00D7" })] }, param.id))) }), jsx("div", { className: styles.panelHeader, children: jsx("span", { children: "Transitions" }) }), jsxs("div", { className: styles.panelContent, children: [activeSM === null || activeSM === void 0 ? void 0 : activeSM.transitions.map(trans => {
                                var _a, _b;
                                const from = activeSM.states.find(s => s.id === trans.fromStateId);
                                const to = activeSM.states.find(s => s.id === trans.toStateId);
                                return (jsxs("div", { className: styles.layerItem, children: [jsxs("span", { className: styles.layerName, children: [(_a = from === null || from === void 0 ? void 0 : from.name) !== null && _a !== void 0 ? _a : '?', " \u2192 ", (_b = to === null || to === void 0 ? void 0 : to.name) !== null && _b !== void 0 ? _b : '?'] }), jsx(We, { className: styles.effectRemove, variant: "ghost", size: "sm", onClick: () => api.removeTransition(trans.id), children: "\u00D7" })] }, trans.id));
                            }), api.editorState.selectedStateId && (jsxs("div", { className: styles.panelSection, style: { marginTop: 12 }, children: [jsx("label", { className: styles.panelLabel, children: "Add transition to:" }), jsx(fn, { className: styles.panelInput, onChange: val => {
                                            if (val && api.editorState.selectedStateId) {
                                                api.addTransition(api.editorState.selectedStateId, val);
                                            }
                                        }, options: [
                                            { value: '', label: 'Select target state...' },
                                            ...((_a = activeSM === null || activeSM === void 0 ? void 0 : activeSM.states.filter(s => s.id !== api.editorState.selectedStateId).map(s => ({ value: s.id, label: s.name }))) !== null && _a !== void 0 ? _a : [])
                                        ] })] }))] })] })] }));
};
/* ────────────────────────────────────────────────────────────────
   EFFECTS PANEL
──────────────────────────────────────────────────────────────── */
const EffectsView = ({ api }) => {
    const [currentEffects, setCurrentEffects] = useState([]);
    const [presetName, setPresetName] = useState('');
    const effectTypes = [
        { type: 'brightness', label: 'Brightness' },
        { type: 'contrast', label: 'Contrast' },
        { type: 'saturation', label: 'Saturation' },
        { type: 'hue-shift', label: 'Hue Shift' },
        { type: 'invert', label: 'Invert' },
        { type: 'pixelate', label: 'Pixelate' },
        { type: 'outline', label: 'Outline' },
        { type: 'tint', label: 'Tint' },
        { type: 'blur', label: 'Blur' },
        { type: 'glow', label: 'Glow' },
        { type: 'shadow', label: 'Shadow' },
        { type: 'palette-swap', label: 'Palette Swap' },
    ];
    return (jsxs("div", { style: { display: 'flex', flex: 1, overflow: 'hidden' }, children: [jsxs("div", { className: styles.leftPanel, children: [jsx("div", { className: styles.panelHeader, children: jsx("span", { children: "Add Effect" }) }), jsx("div", { className: styles.panelContent, children: effectTypes.map(({ type, label }) => (jsx(We, { className: styles.layerItem, variant: "ghost", onClick: () => api.addEffect(type), style: { cursor: 'pointer', border: 'none', textAlign: 'left' }, children: jsx("span", { className: styles.layerName, children: label }) }, type))) }), jsx("div", { className: styles.panelHeader, children: jsx("span", { children: "Presets" }) }), jsxs("div", { className: styles.panelContent, children: [jsxs("div", { className: styles.panelSection, children: [jsx(Tt, { className: styles.panelInput, placeholder: "Preset name...", value: presetName, onChange: val => setPresetName(val) }), jsx(We, { className: styles.btnSecondary, variant: "ghost", style: { marginTop: 4, width: '100%' }, onClick: () => {
                                            if (presetName) {
                                                api.saveEffectPreset(presetName);
                                                setPresetName('');
                                            }
                                        }, disabled: !presetName, children: "Save Current Effects" })] }), api.project.effectPresets.map(preset => (jsxs("div", { className: styles.layerItem, onClick: () => api.loadEffectPreset(preset.id), style: { cursor: 'pointer' }, children: [jsx("span", { className: styles.layerName, children: preset.name }), jsxs("span", { className: styles.layerOpacity, children: [preset.effects.length, " effects"] })] }, preset.id)))] })] }), jsx("div", { className: styles.viewport, children: jsx("div", { className: styles.emptyState, children: jsx("div", { className: styles.emptyStateText, children: "Select a sprite or tile to preview effects" }) }) }), jsxs("div", { className: styles.rightPanel, children: [jsx("div", { className: styles.panelHeader, children: jsx("span", { children: "Active Effects" }) }), jsx("div", { className: styles.panelContent, children: jsx("div", { className: styles.effectsList, children: jsx("div", { className: styles.emptyState, children: jsx("div", { className: styles.emptyStateText, children: "Add effects from the left panel" }) }) }) })] })] }));
};
/* ────────────────────────────────────────────────────────────────
   STATUS BAR
──────────────────────────────────────────────────────────────── */
const StatusBar = ({ api }) => {
    const activeMap = api.project.tileMaps.find(m => m.id === api.editorState.activeTileMapId);
    const activeSheet = api.project.spriteSheets.find(s => s.id === api.editorState.activeSpriteSheetId);
    return (jsxs("div", { className: styles.statusBar, children: [jsxs("span", { className: styles.statusItem, children: ["Mode: ", api.editorState.mode] }), api.editorState.mode === 'tilemap' && activeMap && (jsxs(Fragment, { children: [jsxs("span", { className: styles.statusItem, children: ["Map: ", activeMap.name, " (", activeMap.width, "\u00D7", activeMap.height, ")"] }), jsxs("span", { className: styles.statusItem, children: ["Tile: ", activeMap.tileWidth, "\u00D7", activeMap.tileHeight, "px"] })] })), api.editorState.mode === 'spritesheet' && activeSheet && (jsxs(Fragment, { children: [jsxs("span", { className: styles.statusItem, children: ["Sheet: ", activeSheet.name] }), jsxs("span", { className: styles.statusItem, children: ["Selected: ", api.editorState.selectedFrameIds.length, " frames"] })] })), jsxs("div", { className: styles.zoomControl, children: [jsx(We, { className: styles.zoomBtn, variant: "ghost", size: "sm", onClick: () => api.setZoom(api.editorState.zoom - 0.25), children: "\u2212" }), jsxs("span", { children: [Math.round(api.editorState.zoom * 100), "%"] }), jsx(We, { className: styles.zoomBtn, variant: "ghost", size: "sm", onClick: () => api.setZoom(api.editorState.zoom + 0.25), children: "+" }), jsx(We, { className: styles.zoomBtn, variant: "ghost", size: "sm", onClick: () => api.setZoom(1), children: "\u2299" })] })] }));
};
/* ────────────────────────────────────────────────────────────────
   MAIN COMPONENT
──────────────────────────────────────────────────────────────── */
const NiceGameAsset2dEditor = ({ className, onSave, onExport, }) => {
    const api = useGameAssetEditor({ onSave, onExport });
    const renderModeContent = () => {
        switch (api.editorState.mode) {
            case 'tilemap':
                return (jsxs(Fragment, { children: [jsx(TileMapToolbar, { api: api }), jsxs("div", { className: styles.mainArea, children: [jsx(TilePalette, { api: api }), jsx("div", { className: styles.centerArea, children: jsx(TileMapCanvas, { api: api }) }), jsx(LayersPanel, { api: api })] })] }));
            case 'spritesheet':
                return (jsxs(Fragment, { children: [jsx(SpriteSheetToolbar, { api: api }), jsxs("div", { className: styles.mainArea, children: [jsx(SpriteSheetsList, { api: api }), jsx("div", { className: styles.centerArea, children: jsx(SpriteSheetCanvas, { api: api }) }), jsx(FramesPanel, { api: api })] })] }));
            case 'animation':
                return (jsx("div", { className: styles.mainArea, children: jsx(AnimationStateMachineView, { api: api }) }));
            case 'effects':
                return (jsx("div", { className: styles.mainArea, children: jsx(EffectsView, { api: api }) }));
            default:
                return null;
        }
    };
    return (jsxs("div", { className: `${styles.root} ${className || ''}`, children: [jsx(MenuBar, { api: api }), jsx(ModeTabs, { api: api }), renderModeContent(), jsx(StatusBar, { api: api })] }));
};
/** @deprecated Use NiceGameAsset2dEditor */
const GameAsset2dEditor = NiceGameAsset2dEditor;

export { GameAsset2dEditor, NiceGameAsset2dEditor };
//# sourceMappingURL=GameAsset2dEditor.js.map
