import React, { useState, useRef, useEffect } from 'react';
import {
    Save, Plus, Trash2, FileText, Type, Grid, Image as ImageIcon,
    CheckSquare, Settings, Layout, MousePointer, Move,
    ChevronLeft, ChevronRight, Copy, Scissors, Printer,
    Maximize, Database, X, ChevronUp, ChevronDown, AlignLeft,
    Zap, Cpu, Bot, Terminal, Code, AlertTriangle
} from 'lucide-react';

const DocumentDesigner = ({ onBack, initialTemplate }) => {
    // [NEW] 안전한 텍스트 렌더링을 위한 헬퍼 함수
    const safeRender = (val) => {
        if (val === null || val === undefined) return '';
        if (typeof val === 'object') {
            try {
                return JSON.stringify(val);
            } catch (e) {
                return '[Complex Object]';
            }
        }
        return String(val);
    };

    // A4 Size in PX (96 DPI: 794x1123, 150 DPI: 1240x1754). 
    // We'll use a scaled-down view for editing, or standard 794px width for screen.
    const PAGE_SIZES = {
        'A4': { w: 794, h: 1123 },
        'A3': { w: 1123, h: 1587 },
        'Letter': { w: 816, h: 1056 }
    };

    const [pageConfig, setPageConfig] = useState(initialTemplate?.pageConfig || {
        size: 'A4',
        orientation: 'portrait'
    });

    const [pages, setPages] = useState(initialTemplate?.pages || [{
        id: 1,
        grid: {
            rows: 30,
            cols: 12,
            rowHeights: Array(30).fill(30),
            colWidths: Array(12).fill(60),
            cells: {},
            dynamicRows: [] // [5, 12] etc.
        },
        layers: [] // [{ id, type, x, y, w, h, content, style }]
    }]);
    const [activePageId, setActivePageId] = useState(1);
    const [selectedCell, setSelectedCell] = useState(null); // { r, c }
    const [selectedLayerId, setSelectedLayerId] = useState(null);
    const [selectionRange, setSelectionRange] = useState(null); // { start: {r,c}, end: {r,c} }
    const [isSelecting, setIsSelecting] = useState(false);
    const [scale, setScale] = useState(0.8);
    const [tool, setTool] = useState('select');
    const [docName, setDocName] = useState(initialTemplate?.name || '새 디자인형 문서');
    const [showStructure, setShowStructure] = useState(false);
    const [viewMode, setViewMode] = useState('designer'); // designer | developer
    const [scanStep, setScanStep] = useState(0);
    const [logicSections, setLogicSections] = useState([
        { id: 'sec_1', name: '기본 정보 (Header)', items: ['product_name', 'inspection_date', 'inspector'] },
        { id: 'sec_2', name: '상세 내역 (Detail)', items: ['serial_number', 'lot_no', 'quantity'] },
        { id: 'sec_3', name: '검사 항목 (Inspection)', items: ['meas_1', 'meas_2', 'pass_fail'], isDynamic: true }
    ]);
    const [selectedSectionId, setSelectedSectionId] = useState('sec_1');
    const [isAnalyzing, setIsAnalyzing] = useState(false);
    const [registeredSchema, setRegisteredSchema] = useState(null);

    const [borderSettings, setBorderSettings] = useState({ width: 1, color: '#000000' });

    // --- History & Clipboard ---
    const [history, setHistory] = useState([]);
    const [historyIndex, setHistoryIndex] = useState(-1);
    const [clipboard, setClipboard] = useState(null);
    const [contextMenu, setContextMenu] = useState(null); // { x, y, r, c }

    const saveToHistory = (newPages = null) => {
        const stateToSave = JSON.parse(JSON.stringify(newPages || pages));
        const newHistory = history.slice(0, historyIndex + 1);
        newHistory.push(stateToSave);
        if (newHistory.length > 50) newHistory.shift();
        setHistory(newHistory);
        setHistoryIndex(newHistory.length - 1);
    };

    const undo = () => {
        if (historyIndex > 0) {
            const nextIdx = historyIndex - 1;
            setPages(JSON.parse(JSON.stringify(history[nextIdx])));
            setHistoryIndex(nextIdx);
        }
    };

    const redo = () => {
        if (historyIndex < history.length - 1) {
            const nextIdx = historyIndex + 1;
            setPages(JSON.parse(JSON.stringify(history[nextIdx])));
            setHistoryIndex(nextIdx);
        }
    };

    useEffect(() => {
        if (history.length === 0) {
            saveToHistory(pages);
        }

        const closeMenu = () => setContextMenu(null);
        window.addEventListener('click', closeMenu);
        return () => window.removeEventListener('click', closeMenu);
    }, [history]);

    const handleContextMenu = (e, r, c) => {
        e.preventDefault();
        setContextMenu({
            x: e.clientX,
            y: e.clientY,
            r,
            c
        });
        setSelectedCell({ r, c });
    };

    const activePage = pages.find(p => p.id === activePageId);

    // --- Selection Helpers ---
    const isInRange = (r, c) => {
        if (!selectionRange) return false;
        const { start, end } = selectionRange;
        const minR = Math.min(start.r, end.r);
        const maxR = Math.max(start.r, end.r);
        const minC = Math.min(start.c, end.c);
        const maxC = Math.max(start.c, end.c);
        return r >= minR && r <= maxR && c >= minC && c <= maxC;
    };

    const handleCellMouseDown = (r, c) => {
        if (tool !== 'select') return;
        setIsSelecting(true);
        setSelectedCell({ r, c });
        setSelectionRange({ start: { r, c }, end: { r, c } });
    };

    const handleCellMouseEnter = (r, c) => {
        if (isSelecting) {
            setSelectionRange(prev => ({ ...prev, end: { r, c } }));
        }
    };

    // --- Actions ---
    const addPage = () => {
        const newId = Math.max(...pages.map(p => p.id)) + 1;
        setPages([...pages, {
            id: newId,
            grid: {
                rows: 30,
                cols: 12,
                rowHeights: Array(30).fill(30),
                colWidths: Array(12).fill(60),
                cells: {},
                dynamicRows: []
            },
            layers: []
        }]);
        setActivePageId(newId);
    };

    const addLayer = (type, content = '') => {
        const newLayer = {
            id: Date.now(),
            type,
            x: 100,
            y: 100,
            w: 200,
            h: 150,
            content,
            style: { opacity: 1, zIndex: (activePage.layers?.length || 0) + 1 }
        };
        const newLayers = [...(activePage.layers || []), newLayer];
        setPages(pages.map(p => p.id === activePageId ? { ...p, layers: newLayers } : p));
        setSelectedLayerId(newLayer.id);
    };

    const updateLayer = (id, updates) => {
        const newLayers = activePage.layers.map(l => l.id === id ? { ...l, ...updates } : l);
        setPages(pages.map(p => p.id === activePageId ? { ...p, layers: newLayers } : p));
    };

    const deleteLayer = (id) => {
        const newLayers = activePage.layers.filter(l => l.id !== id);
        setPages(pages.map(p => p.id === activePageId ? { ...p, layers: newLayers } : p));
        setSelectedLayerId(null);
    };

    const updateGrid = (updates) => {
        setPages(pages.map(p =>
            p.id === activePageId
                ? { ...p, grid: { ...p.grid, ...updates } }
                : p
        ));
    };

    const updateCell = (r, c, updates) => {
        const key = `${r}:${c}`;
        const newCells = { ...activePage.grid.cells };
        const cell = newCells[key] || {};

        if (updates.style && cell.style) {
            newCells[key] = {
                ...cell,
                ...updates,
                style: { ...cell.style, ...updates.style }
            };
        } else {
            newCells[key] = { ...cell, ...updates };
        }
        updateGrid({ cells: newCells });
    };

    const handleCopy = () => {
        if (!selectionRange) return;
        const { start, end } = selectionRange;
        const minR = Math.min(start.r, end.r);
        const maxR = Math.max(start.r, end.r);
        const minC = Math.min(start.c, end.c);
        const maxC = Math.max(start.c, end.c);

        const data = [];
        for (let r = minR; r <= maxR; r++) {
            const row = [];
            for (let c = minC; c <= maxC; c++) {
                row.push(activePage.grid.cells[`${r}:${c}`] || null);
            }
            data.push(row);
        }
        setClipboard({ rows: data.length, cols: data[0].length, data });
    };

    const handlePaste = () => {
        if (!clipboard || !selectedCell) return;
        const { r: startR, c: startC } = selectedCell;
        const newCells = { ...activePage.grid.cells };

        clipboard.data.forEach((row, ri) => {
            row.forEach((cellData, ci) => {
                const targetR = startR + ri;
                const targetC = startC + ci;
                if (targetR < activePage.grid.rows && targetC < activePage.grid.cols) {
                    if (cellData) {
                        newCells[`${targetR}:${targetC}`] = JSON.parse(JSON.stringify(cellData));
                    } else {
                        delete newCells[`${targetR}:${targetC}`];
                    }
                }
            });
        });

        const updatedPages = pages.map(p => p.id === activePageId ? { ...p, grid: { ...p.grid, cells: newCells } } : p);
        setPages(updatedPages);
        saveToHistory(updatedPages);
    };

    useEffect(() => {
        const handleGlobalKeyDown = (e) => {
            if (['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) return;
            if (!selectedCell) return;

            const { r, c } = selectedCell;

            // 0. Undo/Redo/Copy/Paste
            if (e.ctrlKey || e.metaKey) {
                if (e.key.toLowerCase() === 'z') { e.preventDefault(); undo(); return; }
                if (e.key.toLowerCase() === 'y') { e.preventDefault(); redo(); return; }
                if (e.key.toLowerCase() === 'c') { e.preventDefault(); handleCopy(); return; }
                if (e.key.toLowerCase() === 'v') { e.preventDefault(); handlePaste(); return; }
            }

            // 1. Navigation (Arrows & Enter & Tab)
            if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Enter', 'Tab'].includes(e.key)) {
                e.preventDefault();
                let nr = r, nc = c;
                if (e.key === 'ArrowUp') nr = Math.max(0, r - 1);
                if (e.key === 'ArrowDown' || e.key === 'Enter') nr = Math.min(activePage.grid.rows - 1, r + 1);
                if (e.key === 'ArrowLeft' || (e.key === 'Tab' && e.shiftKey)) nc = Math.max(0, c - 1);
                if (e.key === 'ArrowRight' || (e.key === 'Tab' && !e.shiftKey)) nc = Math.min(activePage.grid.cols - 1, c + 1);
                setSelectedCell({ r: nr, c: nc });
                setSelectionRange({ start: { r: nr, c: nc }, end: { r: nr, c: nc } });
                return;
            }

            // 2. Clear content
            if (e.key === 'Backspace' || e.key === 'Delete') {
                updateCell(r, c, { content: '' });
                saveToHistory();
                return;
            }

            // 3. Direct Typing (Overwrite)
            if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
                updateCell(r, c, { type: 'text', content: e.key });
            }
        };

        window.addEventListener('keydown', handleGlobalKeyDown);
        return () => window.removeEventListener('keydown', handleGlobalKeyDown);
    }, [selectedCell, activePageId, pages, clipboard, historyIndex, history]);

    const loadSampleTemplate = (typeIndex) => {
        const presets = [
            {
                name: "수입검사성적서_표준양식",
                grid: {
                    rows: 40, cols: 10,
                    rowHeights: Array(40).fill(30),
                    colWidths: [60, 100, 100, 100, 80, 80, 80, 80, 80, 80],
                    cells: {
                        "0:0": { content: "KD 경동기업", style: { fontWeight: "bold", fontSize: "18px", color: "#1e40af" }, rowSpan: 3, colSpan: 2 },
                        "0:2": { content: "수 입 검 사 성 적 서", style: { fontWeight: "900", fontSize: "32px", textAlign: "center" }, rowSpan: 3, colSpan: 5 },
                        "0:7": { content: "결재", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, rowSpan: 3, colSpan: 1 },
                        "0:8": { content: "담당", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, colSpan: 1 },
                        "0:9": { content: "부서장", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, colSpan: 1 },
                        "4:0": { content: "품 명", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "4:2": { dataKey: "part_name", content: "전기 아연도금 강판", style: { fontSize: "12px", textAlign: "center" }, colSpan: 3 },
                        "4:5": { content: "납품업체", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "4:7": { dataKey: "supplier", content: "지오TNS", style: { fontSize: "12px", textAlign: "center", color: "#2563eb", fontWeight: "bold" }, colSpan: 3 },
                        "8:0": { content: "NO", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f1f5f9" } },
                        "8:1": { content: "검사항목", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f1f5f9" } },
                        "9:0": { content: "1" }, "9:1": { content: "겉모양" }, "9:5": { type: "checkbox", content: "OK" }, "9:6": { type: "checkbox", content: "NG" }
                    },
                    dynamicRows: [9, 10]
                }
            },
            {
                name: "거래명세서_AI추천",
                grid: {
                    rows: 30, cols: 10,
                    rowHeights: Array(30).fill(30),
                    colWidths: [40, 150, 80, 80, 100, 100, 80, 80, 80, 20],
                    cells: {
                        "0:0": { content: "거 래 명 세 서", style: { fontWeight: "bold", fontSize: "28px", textAlign: "center", letterSpacing: "8px" }, colSpan: 10, rowSpan: 2 },
                        "3:0": { content: "관리번호", style: { backgroundColor: "#f1f5f9", fontWeight: "bold", textAlign: "center" } },
                        "3:1": { dataKey: "doc_no", content: "2025-DESC-001", style: { textAlign: "center" } },
                        "5:0": { content: "번호", style: { backgroundColor: "#e2e8f0", fontWeight: "bold", textAlign: "center" } },
                        "5:1": { content: "품명 및 규격", style: { backgroundColor: "#e2e8f0", fontWeight: "bold", textAlign: "center" } },
                        "5:2": { content: "수량", style: { backgroundColor: "#e2e8f0", fontWeight: "bold", textAlign: "center" } },
                        "5:3": { content: "단가", style: { backgroundColor: "#e2e8f0", fontWeight: "bold", textAlign: "center" } },
                        "5:4": { content: "공급가액", style: { backgroundColor: "#e2e8f0", fontWeight: "bold", textAlign: "center" } },
                        "5:5": { content: "세액", style: { backgroundColor: "#e2e8f0", fontWeight: "bold", textAlign: "center" } },
                        // Row 1
                        "6:0": { content: "1" },
                        "6:1": { content: "알루미늄 앵글 50x50" },
                        "6:2": { content: "10" },
                        "6:3": { content: "15000" },
                        "6:4": { formula: "=C7*D7", style: { color: "#ea580c", fontWeight: "bold" } },
                        "6:5": { formula: "=E7*0.1", style: { color: "#ea580c" } },
                        // Total
                        "15:0": { content: "합계금액", style: { backgroundColor: "#334155", color: "white", fontWeight: "bold", textAlign: "center" }, colSpan: 4 },
                        "15:4": { formula: "=SUM(E7:E15)", style: { backgroundColor: "#fef3c7", fontWeight: "bold", color: "#b45309" } },
                        "15:5": { formula: "=SUM(F7:F15)", style: { backgroundColor: "#fef3c7", fontWeight: "bold", color: "#b45309" } }
                    },
                    dynamicRows: [6, 7, 8]
                }
            },
            {
                name: "수입검사성적서_정밀추출",
                grid: {
                    rows: 40, cols: 12,
                    rowHeights: Array(40).fill(32),
                    colWidths: [40, 100, 150, 80, 80, 80, 80, 80, 80, 80, 80, 80],
                    cells: {
                        // Header
                        "0:0": { content: "KD", style: { fontWeight: "bold", fontSize: "24px", color: "#1e40af" }, rowSpan: 3, colSpan: 1 },
                        "0:1": { content: "경동기업", style: { fontSize: "10px", color: "#666" }, rowSpan: 3, colSpan: 1 },
                        "0:2": { content: "수 입 검 사 성 적 서", style: { fontWeight: "900", fontSize: "36px", textAlign: "center", letterSpacing: "12px" }, rowSpan: 3, colSpan: 8 },
                        "0:10": { content: "결재", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc", borderLeft: "1px solid black" }, rowSpan: 4, colSpan: 1 },
                        "0:11": { content: "담당", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc", borderLeft: "1px solid black" }, colSpan: 1 },
                        "1:11": { content: "노완호\n07/15", style: { fontSize: "10px", textAlign: "center" }, rowSpan: 2 },
                        "3:11": { content: "부서장", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc", borderLeft: "1px solid black" }, colSpan: 1 },
                        "4:8": { content: "입고일자 : 2025-07-15", style: { textAlign: "right", fontSize: "11px", fontWeight: "bold" }, colSpan: 4 },

                        // Info Table
                        "5:0": { content: "품 명", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "5:2": { content: "전기 아연도금 강판\n(KS D 3528, SECC) \"EGI 절곡판\"", style: { fontSize: "11px", textAlign: "center" }, colSpan: 5 },
                        "5:7": { content: "납품업체\n제조업체", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "5:9": { content: "지오TNS\n(KG스틸)", style: { fontSize: "11px", textAlign: "center", color: "#2563eb", fontWeight: "bold" }, colSpan: 3 },

                        "6:0": { content: "규 격\n(두께*너비*길이)", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "6:2": { content: "1.55 * 1218 * 480", style: { fontSize: "11px", textAlign: "center" }, colSpan: 5 },
                        "6:7": { content: "로트번호", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "6:9": { content: "250715-02", style: { fontSize: "11px", textAlign: "center", color: "#2563eb" }, colSpan: 3 },

                        "7:0": { content: "자재번호", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "7:2": { content: "PE02RB", style: { fontSize: "11px", textAlign: "center" }, colSpan: 5 },
                        "7:7": { content: "검사일자", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "7:9": { content: "07/15", style: { fontSize: "11px", textAlign: "center", color: "#2563eb" }, colSpan: 3 },

                        "8:0": { content: "로트크기", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "8:2": { content: "200", style: { fontSize: "11px", textAlign: "center" }, colSpan: 3 },
                        "8:5": { content: "매", style: { textAlign: "center" }, colSpan: 2 },
                        "8:7": { content: "검사자", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#cbd5e1" }, colSpan: 2 },
                        "8:9": { content: "노완호", style: { fontSize: "11px", textAlign: "center" }, colSpan: 3 },

                        // Main Table Header
                        "10:0": { content: "NO", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, rowSpan: 2 },
                        "10:1": { content: "검사항목", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, rowSpan: 2 },
                        "10:2": { content: "검사기준", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, rowSpan: 2 },
                        "10:3": { content: "검사방식", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, rowSpan: 2 },
                        "10:4": { content: "검사주기", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, rowSpan: 2 },
                        "10:5": { content: "측정치", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, colSpan: 6 },
                        "10:11": { content: "판정\n(적/부)", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" }, rowSpan: 2 },
                        "11:5": { content: "n1", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" } },
                        "11:6": { content: "n2", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" } },
                        "11:7": { content: "n3", style: { fontWeight: "bold", textAlign: "center", backgroundColor: "#f8fafc" } },

                        // Item 1: Appearance
                        "12:0": { content: "1" },
                        "12:1": { content: "겉모양" },
                        "12:2": { content: "사용상 해로운\n결함이 없을 것", style: { fontSize: "10px" } },
                        "12:3": { content: "육안검사" },
                        "12:4": { content: "전수" },
                        "12:5": { type: "checkbox", content: "OK" },
                        "12:6": { type: "checkbox", content: "OK" },
                        "12:7": { type: "checkbox", content: "OK" },
                        "12:11": { content: "적" },

                        // Item 2: Dimensions
                        "13:0": { content: "2", rowSpan: 10 },
                        "13:1": { content: "치수\n1.55", rowSpan: 4 },
                        "13:2": { content: "1.25 이상\n~ 1.6 미만", style: { backgroundColor: "#dcfce7" } },
                        "13:3": { content: "체크검사", rowSpan: 10 },
                        "13:4": { content: "n = 3\nc = 0", rowSpan: 10 },
                        "13:5": { content: "1.528" },
                        "13:6": { content: "1.533" },
                        "13:7": { content: "1.521" },
                        "13:11": { content: "적", rowSpan: 10 }
                    }
                }
            }
        ];

        const selected = presets[typeIndex !== undefined ? typeIndex : Math.floor(Math.random() * presets.length)];
        const newPages = pages.map(p => p.id === activePageId ? { ...p, grid: { ...p.grid, ...selected.grid } } : p);

        setPages(newPages);
        setDocName(selected.name);
        alert(`AI 분석 완료: [${selected.name}] 레이아웃이 복원되었습니다.`);
    };

    const handleMergeCells = () => {
        if (!selectionRange) return;
        const { start, end } = selectionRange;
        const minR = Math.min(start.r, end.r);
        const maxR = Math.max(start.r, end.r);
        const minC = Math.min(start.c, end.c);
        const maxC = Math.max(start.c, end.c);

        if (minR === maxR && minC === maxC) return; // Only one cell

        const newCells = { ...activePage.grid.cells };
        const masterKey = `${minR}:${minC}`;
        const masterCell = newCells[masterKey] || {};

        // Calculate spans
        const rowSpan = maxR - minR + 1;
        const colSpan = maxC - minC + 1;

        // Clear other cells in range but keep content if it was in the master
        for (let r = minR; r <= maxR; r++) {
            for (let c = minC; c <= maxC; c++) {
                if (r === minR && c === minC) continue;
                delete newCells[`${r}:${c}`];
            }
        }

        newCells[masterKey] = {
            ...masterCell,
            rowSpan,
            colSpan
        };

        const updatedPages = pages.map(p => p.id === activePageId ? { ...p, grid: { ...p.grid, cells: newCells } } : p);
        setPages(updatedPages);
        saveToHistory(updatedPages);
        setSelectedCell({ r: minR, c: minC });
    };

    const handleUnmergeCells = () => {
        if (!selectedCell) return;
        const key = `${selectedCell.r}:${selectedCell.c}`;
        const cell = activePage.grid.cells[key];
        if (!cell || (!cell.rowSpan && !cell.colSpan)) return;

        const newCells = { ...activePage.grid.cells };
        newCells[key] = {
            ...cell,
            rowSpan: 1,
            colSpan: 1
        };

        const updatedPages = pages.map(p => p.id === activePageId ? { ...p, grid: { ...p.grid, cells: newCells } } : p);
        setPages(updatedPages);
        saveToHistory(updatedPages);
    };

    const applyBorders = (type, width, color) => {
        if (!selectionRange) return;
        const { start, end } = selectionRange;
        const minR = Math.min(start.r, end.r);
        const maxR = Math.max(start.r, end.r);
        const minC = Math.min(start.c, end.c);
        const maxC = Math.max(start.c, end.c);

        const newCells = { ...activePage.grid.cells };
        const borderStyle = `${width}px solid ${color}`;

        for (let r = minR; r <= maxR; r++) {
            for (let c = minC; c <= maxC; c++) {
                const key = `${r}:${c}`;
                const cell = newCells[key] || { style: {} };
                const newStyle = { ...cell.style };

                if (type === 'all') {
                    newStyle.borderTop = borderStyle;
                    newStyle.borderBottom = borderStyle;
                    newStyle.borderLeft = borderStyle;
                    newStyle.borderRight = borderStyle;
                } else if (type === 'outside') {
                    if (r === minR) newStyle.borderTop = borderStyle;
                    if (r === maxR) newStyle.borderBottom = borderStyle;
                    if (c === minC) newStyle.borderLeft = borderStyle;
                    if (c === maxC) newStyle.borderRight = borderStyle;
                } else if (type === 'inside') {
                    if (r > minR) newStyle.borderTop = borderStyle;
                    if (r < maxR) newStyle.borderBottom = borderStyle;
                    if (c > minC) newStyle.borderLeft = borderStyle;
                    if (c < maxC) newStyle.borderRight = borderStyle;
                } else if (type === 'top' && r === minR) {
                    newStyle.borderTop = borderStyle;
                } else if (type === 'bottom' && r === maxR) {
                    newStyle.borderBottom = borderStyle;
                } else if (type === 'left' && c === minC) {
                    newStyle.borderLeft = borderStyle;
                } else if (type === 'right' && c === maxC) {
                    newStyle.borderRight = borderStyle;
                } else if (type === 'none') {
                    delete newStyle.borderTop;
                    delete newStyle.borderBottom;
                    delete newStyle.borderLeft;
                    delete newStyle.borderRight;
                }

                newCells[key] = { ...cell, style: newStyle };
            }
        }
        const updatedPages = pages.map(p => p.id === activePageId ? { ...p, grid: { ...p.grid, cells: newCells } } : p);
        setPages(updatedPages);
        saveToHistory(updatedPages);
    };

    const updateSelectedRange = (updates) => {
        if (!selectionRange) return;
        const { start, end } = selectionRange;
        const minR = Math.min(start.r, end.r);
        const maxR = Math.max(start.r, end.r);
        const minC = Math.min(start.c, end.c);
        const maxC = Math.max(start.c, end.c);

        const newCells = { ...activePage.grid.cells };
        for (let r = minR; r <= maxR; r++) {
            for (let c = minC; c <= maxC; c++) {
                const key = `${r}:${c}`;
                const cell = newCells[key] || {};

                // Deep merge style if it exists in updates
                if (updates.style && cell.style) {
                    newCells[key] = {
                        ...cell,
                        ...updates,
                        style: { ...cell.style, ...updates.style }
                    };
                } else {
                    newCells[key] = { ...cell, ...updates };
                }
            }
        }
        const updatedPages = pages.map(p => p.id === activePageId ? { ...p, grid: { ...p.grid, cells: newCells } } : p);
        setPages(updatedPages);
        saveToHistory(updatedPages);
    };

    // --- Row/Col Resize & Layer Logic ---
    const [isResizing, setIsResizing] = useState(false);
    const [isDragging, setIsDragging] = useState(false);
    const [resizer, setResizer] = useState(null); // { type: 'col' | 'row' | 'layer' | 'layer-resize', index, layerId }
    const [resizeStart, setResizeStart] = useState({ x: 0, y: 0 });
    const [initialPos, setInitialPos] = useState({ x: 0, y: 0, w: 0, h: 0 });

    const handleResizeStart = (e, type, index, layerId = null) => {
        e.stopPropagation();
        setIsResizing(true);
        setResizer({ type, index, layerId });
        setResizeStart({ x: e.clientX, y: e.clientY });

        if (type === 'col') setInitialPos({ w: activePage.grid.colWidths[index] });
        else if (type === 'row') setInitialPos({ h: activePage.grid.rowHeights[index] });
        else if (type === 'layer-resize') {
            const layer = activePage.layers.find(l => l.id === layerId);
            setInitialPos({ w: layer.w, h: layer.h });
        }
    };

    const handleLayerDragStart = (e, layerId) => {
        e.stopPropagation();
        setIsDragging(true);
        setResizer({ type: 'layer', layerId });
        setResizeStart({ x: e.clientX, y: e.clientY });
        const layer = activePage.layers.find(l => l.id === layerId);
        setInitialPos({ x: layer.x, y: layer.y });
        setSelectedLayerId(layerId);
        setSelectedCell(null);
    };

    const handleMouseMove = (e) => {
        if (isResizing && resizer) {
            const deltaX = (e.clientX - resizeStart.x) / scale;
            const deltaY = (e.clientY - resizeStart.y) / scale;

            if (resizer.type === 'col') {
                const newWidths = [...activePage.grid.colWidths];
                newWidths[resizer.index] = Math.max(20, initialPos.w + deltaX);
                updateGrid({ colWidths: newWidths });
            } else if (resizer.type === 'row') {
                const newHeights = [...activePage.grid.rowHeights];
                newHeights[resizer.index] = Math.max(20, initialPos.h + deltaY);
                updateGrid({ rowHeights: newHeights });
            } else if (resizer.type === 'layer-resize') {
                updateLayer(resizer.layerId, {
                    w: Math.max(20, initialPos.w + deltaX),
                    h: Math.max(20, initialPos.h + deltaY)
                });
            }
        } else if (isDragging && resizer && resizer.type === 'layer') {
            const deltaX = (e.clientX - resizeStart.x) / scale;
            const deltaY = (e.clientY - resizeStart.y) / scale;
            updateLayer(resizer.layerId, {
                x: initialPos.x + deltaX,
                y: initialPos.y + deltaY
            });
        }
    };

    const handleMouseUp = () => {
        setIsResizing(false);
        setIsDragging(false);
        setResizer(null);
        setIsSelecting(false);
    };

    // --- Row/Col Management ---
    const addRow = (index) => {
        const newRowHeights = [...activePage.grid.rowHeights];
        newRowHeights.splice(index, 0, 30);

        // Offset existing cells
        const newCells = {};
        Object.entries(activePage.grid.cells).forEach(([key, val]) => {
            const [r, c] = key.split(':').map(Number);
            if (r >= index) {
                newCells[`${r + 1}:${c}`] = val;
            } else {
                newCells[key] = val;
            }
        });

        const updatedPages = pages.map(p =>
            p.id === activePageId
                ? {
                    ...p, grid: {
                        ...p.grid,
                        rows: activePage.grid.rows + 1,
                        rowHeights: newRowHeights,
                        cells: newCells,
                        dynamicRows: activePage.grid.dynamicRows.map(dr => dr >= index ? dr + 1 : dr)
                    }
                }
                : p
        );
        setPages(updatedPages);
        saveToHistory(updatedPages);
    };

    const addCol = (index) => {
        const newColWidths = [...activePage.grid.colWidths];
        newColWidths.splice(index, 0, 60);

        const newCells = {};
        Object.entries(activePage.grid.cells).forEach(([key, val]) => {
            const [r, c] = key.split(':').map(Number);
            if (c >= index) {
                newCells[`${r}:${c + 1}`] = val;
            } else {
                newCells[key] = val;
            }
        });

        const updatedPages = pages.map(p =>
            p.id === activePageId
                ? {
                    ...p, grid: {
                        ...p.grid,
                        cols: activePage.grid.cols + 1,
                        colWidths: newColWidths,
                        cells: newCells
                    }
                }
                : p
        );
        setPages(updatedPages);
        saveToHistory(updatedPages);
    };

    // --- Renderers ---
    const evaluateFormula = (formula, cells) => {
        if (!formula) return '';
        try {
            let evaluated = formula.trim();
            if (evaluated.startsWith('=')) evaluated = evaluated.substring(1);

            // 1. Support Range Functions like SUM(A1:B10)
            const rangeRegex = /(SUM|AVG|MIN|MAX)\(([A-Z])(\d+):([A-Z])(\d+)\)/gi;
            evaluated = evaluated.replace(rangeRegex, (match, fn, startCol, startRow, endCol, endRow) => {
                const sC = startCol.charCodeAt(0) - 65;
                const sR = parseInt(startRow) - 1;
                const eC = endCol.charCodeAt(0) - 65;
                const eR = parseInt(endRow) - 1;

                let values = [];
                for (let r = Math.min(sR, eR); r <= Math.max(sR, eR); r++) {
                    for (let c = Math.min(sC, eC); c <= Math.max(sC, eC); c++) {
                        const cellVal = parseFloat(cells[`${r}:${c}`]?.content) || 0;
                        values.push(cellVal);
                    }
                }

                switch (fn.toUpperCase()) {
                    case 'SUM': return values.reduce((a, b) => a + b, 0);
                    case 'AVG': return values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0;
                    case 'MIN': return Math.min(...values);
                    case 'MAX': return Math.max(...values);
                    default: return 0;
                }
            });

            // 2. Resolve Variables {{key}}
            const varRegex = /{{(.*?)}}/g;
            evaluated = evaluated.replace(varRegex, (match, key) => {
                const cellWithKey = Object.values(cells).find(c => c.dataKey === key.trim());
                const val = parseFloat(cellWithKey?.content) || 0;
                return val;
            });

            // 3. Resolve Individual Cell References like A1, B2
            const cellRefRegex = /([A-Z])(\d+)/g;
            evaluated = evaluated.replace(cellRefRegex, (match, colStr, rowStr) => {
                const col = colStr.charCodeAt(0) - 65;
                const row = parseInt(rowStr) - 1;
                const cell = cells[`${row}:${col}`];
                const val = parseFloat(cell?.content) || 0;
                return val;
            });

            // 4. Eval (Arithmetic)
            // eslint-disable-next-line no-new-func
            const result = new Function(`return ${evaluated}`)();
            return isFinite(result) ? (Number.isInteger(result) ? result : result.toFixed(2)) : '#ERR';
        } catch (e) {
            return '#ERR';
        }
    };

    const handleSave = (asNew = false) => {
        const templateData = {
            id: asNew ? Date.now() : (initialTemplate?.id || Date.now()),
            name: docName,
            type: 'design',
            pageConfig: pageConfig,
            pages: pages,
            updatedAt: new Date().toISOString().split('T')[0]
        };

        const saved = localStorage.getItem('docTemplates');
        const templates = saved ? JSON.parse(saved) : [];
        const existingIdx = templates.findIndex(t => t.id === templateData.id);

        if (existingIdx >= 0) {
            templates[existingIdx] = templateData;
        } else {
            templates.push(templateData);
        }
        localStorage.setItem('docTemplates', JSON.stringify(templates));

        alert(asNew ? '새 템플릿으로 저장되었습니다.' : '디자인이 저장되었습니다.');
        if (onBack) onBack();
    };

    return (
        <div className="flex flex-col h-screen bg-gray-100 overflow-hidden" onMouseMove={handleMouseMove} onMouseUp={handleMouseUp}>
            {/* Header Toolbar - 사용자 요청 레이아웃 */}
            <header className="bg-white border-b border-gray-200 px-6 py-4 shrink-0 z-20 space-y-3">
                {/* 첫째 줄: 양식명, 용지, 미리보기, 저장 */}
                <div className="flex items-center gap-6">
                    <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
                        <ChevronLeft className="text-gray-600" />
                    </button>
                    <div className="flex items-center gap-2 flex-1">
                        <label className="text-sm font-medium whitespace-nowrap">양식명:</label>
                        <input
                            value={docName}
                            onChange={(e) => setDocName(e.target.value)}
                            className="px-3 py-1.5 border rounded-lg text-sm flex-1 max-w-md"
                            placeholder="예: 조인트바 표준 성적서"
                        />
                    </div>
                    <div className="flex items-center gap-2">
                        <label className="text-sm font-medium whitespace-nowrap">용지:</label>
                        <select
                            value={`${pageConfig.size} ${pageConfig.orientation === 'portrait' ? '세로' : '가로'}`}
                            onChange={(e) => {
                                const [size, orient] = e.target.value.split(' ');
                                setPageConfig({ size, orientation: orient === '세로' ? 'portrait' : 'landscape' });
                            }}
                            className="px-3 py-1.5 border rounded-lg text-sm"
                        >
                            <option>A4 세로</option>
                            <option>A4 가로</option>
                            <option>A3 세로</option>
                            <option>A3 가로</option>
                        </select>
                    </div>
                    <button className="flex items-center gap-1 px-3 py-1.5 border rounded-lg text-sm hover:bg-gray-50">
                        <Printer size={16} /> 미리보기
                    </button>
                    <button
                        onClick={() => handleSave(false)}
                        className="flex items-center gap-1 px-4 py-1.5 bg-black text-white rounded-lg text-sm hover:bg-gray-800"
                    >
                        <Save size={16} /> 저장
                    </button>
                </div>

                {/* 둘째 줄: 도구 버튼들 */}
                <div className="flex items-center gap-3">
                    <button className="flex items-center gap-2 bg-gray-50 px-3 py-1 rounded-lg hover:bg-gray-100 cursor-pointer">
                        <Grid size={16} className="text-gray-500" />
                        <span className="text-sm font-medium">그리드</span>
                    </button>
                    <button className="flex items-center gap-2 bg-gray-50 px-3 py-1 rounded-lg hover:bg-gray-100 cursor-pointer">
                        <Layout size={16} className="text-gray-500" />
                        <span className="text-sm font-medium">리스트</span>
                    </button>
                    <button className="flex items-center gap-2 bg-gray-50 px-3 py-1 rounded-lg hover:bg-gray-100 cursor-pointer">
                        <ImageIcon size={16} className="text-gray-500" />
                        <span className="text-sm font-medium">이미지</span>
                    </button>
                    <button className="flex items-center gap-2 bg-gray-50 px-3 py-1 rounded-lg hover:bg-gray-100 cursor-pointer">
                        <Type size={16} className="text-gray-500" />
                        <span className="text-sm font-medium">텍스트</span>
                    </button>
                </div>
            </header>

            {/* Main Content Area */}
            <div className="flex flex-1 overflow-hidden">
                {/* Left Sidebar: Pages */}
                <div className="w-64 bg-white border-r border-gray-200 flex flex-col shrink-0">
                    <div className="p-4 border-b font-bold text-gray-700">페이지 목록</div>
                    <div className="flex-1 overflow-y-auto p-4 space-y-4">
                        {pages.map((page, idx) => (
                            <div
                                key={page.id}
                                onClick={() => setActivePageId(page.id)}
                                className={`aspect-[1/1.414] border-2 rounded-lg relative cursor-pointer group transition-all ${activePageId === page.id ? 'border-blue-500 shadow-md ring-2 ring-blue-100' : 'border-gray-200 hover:border-gray-400'}`}
                            >
                                <div className="absolute top-2 left-2 bg-gray-800/50 text-white text-xs px-2 py-0.5 rounded-full">{idx + 1}</div>
                                <div className="w-full h-full bg-white flex items-center justify-center text-xs text-gray-300">
                                    Page {idx + 1} Preview
                                </div>
                                <button
                                    onClick={(e) => { e.stopPropagation(); deletePage(page.id); }}
                                    className="absolute top-2 right-2 p-1 bg-white text-red-500 rounded shadow opacity-0 group-hover:opacity-100 transition-opacity"
                                >
                                    <Trash2 size={12} />
                                </button>
                            </div>
                        ))}
                        <button onClick={addPage} className="w-full py-3 border-2 border-dashed border-gray-300 rounded-lg text-gray-500 hover:border-blue-500 hover:text-blue-500 flex items-center justify-center gap-2 transition-colors">
                            <Plus size={16} /> 페이지 추가
                        </button>
                    </div>
                </div>

                {/* Main Canvas Area */}
                <div className="flex-1 bg-gray-200/50 overflow-auto flex flex-col relative">
                    {viewMode === 'designer' ? (
                        <div className="flex-1 overflow-auto p-10 flex justify-center">
                            <div
                                style={{
                                    width: (pageConfig.orientation === 'portrait' ? PAGE_SIZES[pageConfig.size].w : PAGE_SIZES[pageConfig.size].h),
                                    height: (pageConfig.orientation === 'portrait' ? PAGE_SIZES[pageConfig.size].h : PAGE_SIZES[pageConfig.size].w),
                                    transform: `scale(${scale})`,
                                    transformOrigin: 'top center'
                                }}
                                className="bg-white shadow-2xl relative transition-transform flex flex-col shrink-0"
                            >
                                {(() => {
                                    let acc = 0;
                                    const limit = (pageConfig.orientation === 'portrait' ? PAGE_SIZES[pageConfig.size].h : PAGE_SIZES[pageConfig.size].w);
                                    return activePage.grid.rowHeights.map((h, i) => {
                                        const prevAcc = acc;
                                        acc += h;
                                        // 32 is the header height
                                        if (prevAcc < (limit - 32) && acc >= (limit - 32)) {
                                            return (
                                                <div key={`break-${i}`} style={{ top: acc + 32, left: 0 }} className="absolute w-full h-0 border-t-2 border-dashed border-red-400/60 z-50 pointer-events-none">
                                                    <div className="absolute top-0 right-4 bg-red-500 text-white text-[9px] px-2 py-0.5 rounded-b font-black animate-pulse shadow-sm flex items-center gap-1">
                                                        <AlertTriangle size={10} /> PAGE BOUNDARY
                                                    </div>
                                                </div>
                                            );
                                        }
                                        return null;
                                    });
                                })()}
                                {/* Grid Headers & Cells */}
                                <div className="flex">
                                    <div className="w-10 h-8 bg-gray-100 border-r border-b border-gray-300 shrink-0"></div>
                                    <div className="flex">
                                        {activePage.grid.colWidths.map((w, i) => (
                                            <div
                                                key={i}
                                                style={{ width: w }}
                                                className="h-8 bg-gray-100 border-r border-b border-gray-300 flex items-center justify-center text-[10px] font-bold text-gray-500 relative group shrink-0 uppercase"
                                            >
                                                {String.fromCharCode(65 + i)}
                                                <div onMouseDown={(e) => handleResizeStart(e, 'col', i)} className="absolute top-0 -right-1 w-2 h-full cursor-col-resize hover:bg-blue-400 z-10"></div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                                <div className="flex flex-1 overflow-hidden relative">
                                    <div className="flex flex-col z-20">
                                        {activePage.grid.rowHeights.map((h, i) => (
                                            <div
                                                key={i}
                                                style={{ height: h }}
                                                className="w-10 bg-gray-100 border-r border-b border-gray-300 flex items-center justify-center text-[10px] font-bold text-gray-500 relative group shrink-0"
                                            >
                                                {i + 1}
                                                {activePage.grid.dynamicRows?.includes(i) && (
                                                    <div className="absolute left-0 top-0 bottom-0 w-1 bg-orange-400" title="Iterative Row"></div>
                                                )}
                                                <div onMouseDown={(e) => handleResizeStart(e, 'row', i)} className="absolute left-0 -bottom-1 w-full h-2 cursor-row-resize hover:bg-blue-400 z-10"></div>
                                            </div>
                                        ))}
                                    </div>
                                    <div className="relative flex-1">
                                        <div
                                            className="grid bg-white relative"
                                            style={{
                                                gridTemplateColumns: activePage.grid.colWidths.map(w => `${w}px`).join(' '),
                                                gridTemplateRows: activePage.grid.rowHeights.map(h => `${h}px`).join(' ')
                                            }}
                                        >
                                            {Array.from({ length: activePage.grid.rows }).map((_, r) => (
                                                Array.from({ length: activePage.grid.cols }).map((_, c) => {
                                                    const key = `${r}:${c}`;
                                                    const cell = activePage.grid.cells[key] || {};

                                                    // Check if this cell is "shadowed" by a merged cell
                                                    let isShadowed = false;
                                                    Object.entries(activePage.grid.cells).forEach(([mKey, mCell]) => {
                                                        if ((mCell.rowSpan > 1 || mCell.colSpan > 1)) {
                                                            const [mr, mc] = mKey.split(':').map(Number);
                                                            const rs = mCell.rowSpan || 1;
                                                            const cs = mCell.colSpan || 1;
                                                            if (r >= mr && r < mr + rs && c >= mc && c < mc + cs) {
                                                                if (r !== mr || c !== mc) isShadowed = true;
                                                            }
                                                        }
                                                    });
                                                    if (isShadowed) return null;

                                                    const isSelected = isInRange(r, c);
                                                    const rs = cell.rowSpan || 1;
                                                    const cs = cell.colSpan || 1;

                                                    return (
                                                        <div
                                                            key={key}
                                                            onMouseDown={() => {
                                                                setSelectedLayerId(null);
                                                                handleCellMouseDown(r, c);
                                                            }}
                                                            onMouseEnter={() => handleCellMouseEnter(r, c)}
                                                            onContextMenu={(e) => handleContextMenu(e, r, c)}
                                                            className={`border-r border-b border-gray-200 relative group flex items-center justify-center ${isSelected ? 'ring-2 ring-blue-500 z-10 bg-blue-50/50' : 'hover:bg-gray-50'}`}
                                                            style={{
                                                                gridColumn: `span ${cs}`,
                                                                gridRow: `span ${rs}`,
                                                                backgroundColor: cell.style?.backgroundColor,
                                                                color: cell.style?.color,
                                                                fontSize: cell.style?.fontSize,
                                                                fontWeight: cell.style?.fontWeight,
                                                                textAlign: cell.style?.textAlign,
                                                                ...cell.style
                                                            }}
                                                        >
                                                            {isSelected && (
                                                                <div className="absolute top-0 right-0 p-0.5 bg-blue-500 text-white rounded-bl z-20 pointer-events-none">
                                                                    <MousePointer size={8} />
                                                                </div>
                                                            )}
                                                            {cell.dataKey && (
                                                                <div className="absolute top-0 left-0 px-1 bg-purple-500 text-white text-[6px] font-bold rounded-br z-20 pointer-events-none">
                                                                    {safeRender(cell.dataKey)}
                                                                </div>
                                                            )}
                                                            {cell.formula && (
                                                                <div className="absolute top-0 right-0 px-1 bg-orange-500 text-white text-[6px] font-bold rounded-bl z-20 pointer-events-none flex items-center gap-0.5">
                                                                    <Zap size={6} /> FX
                                                                </div>
                                                            )}

                                                            {(cell.type === 'text' || !cell.type) && (
                                                                <input
                                                                    autoFocus={isSelected}
                                                                    className={`w-full h-full bg-transparent border-none outline-none px-1 text-inherit text-center px-2 focus:bg-blue-50/20 ${cell.formula ? 'font-mono text-orange-700 font-bold' : ''}`}
                                                                    value={cell.formula ? evaluateFormula(cell.formula, activePage.grid.cells) : safeRender(cell.content)}
                                                                    placeholder={cell.formula ? cell.formula : (cell.dataKey ? `{{${cell.dataKey}}}` : '')}
                                                                    readOnly={!!cell.formula}
                                                                    onChange={(e) => updateCell(r, c, { content: e.target.value })}
                                                                />
                                                            )}
                                                            {cell.type === 'select' && (
                                                                <select
                                                                    className="w-[calc(100%-4px)] h-[calc(100%-4px)] bg-white/50 border border-blue-200 rounded text-[10px] text-center outline-none focus:ring-1 focus:ring-blue-300"
                                                                    value={cell.content || ''}
                                                                    onChange={(e) => updateCell(r, c, { content: e.target.value })}
                                                                >
                                                                    <option value="">선택하세요</option>
                                                                    {(cell.options || ['Option 1', 'Option 2']).map((opt, i) => (
                                                                        <option key={i} value={safeRender(opt)}>{safeRender(opt)}</option>
                                                                    ))}
                                                                </select>
                                                            )}
                                                            {cell.type === 'image' && (
                                                                cell.content ? <img src={cell.content} className="w-full h-full object-contain p-1" alt="" /> : <ImageIcon size={14} className="text-gray-300" />
                                                            )}
                                                            {cell.type === 'checkbox' && (
                                                                <div className="flex items-center gap-1 text-[10px] text-gray-600 font-medium">
                                                                    <input type="checkbox" className="w-3 h-3" readOnly />
                                                                    {safeRender(cell.content) || '체크'}
                                                                </div>
                                                            )}
                                                            {cell.type === 'radio' && (
                                                                <div className="flex items-center gap-1 text-[10px] text-gray-600 font-medium">
                                                                    <input type="radio" className="w-3 h-3" readOnly />
                                                                    {safeRender(cell.content) || '옵션'}
                                                                </div>
                                                            )}
                                                            {cell.type === 'approval' && (
                                                                <div className="w-full h-full flex flex-col border border-gray-400 m-1 bg-white pointer-events-none">
                                                                    <div className="h-4 bg-gray-50 border-b border-gray-400 flex items-center justify-center text-[7px] font-bold">결재</div>
                                                                    <div className="flex-1"></div>
                                                                </div>
                                                            )}
                                                        </div>
                                                    );
                                                })
                                            ))}
                                        </div>

                                        {/* FLOATING LAYERS */}
                                        {activePage.layers?.map(layer => (
                                            <div
                                                key={layer.id}
                                                onMouseDown={(e) => handleLayerDragStart(e, layer.id)}
                                                style={{
                                                    position: 'absolute',
                                                    left: layer.x,
                                                    top: layer.y,
                                                    width: layer.w,
                                                    height: layer.h,
                                                    zIndex: selectedLayerId === layer.id ? 100 : layer.style?.zIndex || 50,
                                                    cursor: isDragging ? 'grabbing' : 'grab',
                                                    outline: selectedLayerId === layer.id ? '2px solid #a855f7' : 'none',
                                                    boxShadow: selectedLayerId === layer.id ? '0 0 10px rgba(168, 85, 247, 0.3)' : 'none'
                                                }}
                                                className="group transition-shadow bg-white/10 backdrop-blur-[1px]"
                                            >
                                                {layer.type === 'image' && (
                                                    <div className="w-full h-full relative">
                                                        {layer.content ? (
                                                            <img src={layer.content} className="w-full h-full object-contain pointer-events-none" alt="" />
                                                        ) : (
                                                            <div className="w-full h-full border-2 border-dashed border-purple-200 flex flex-col items-center justify-center text-purple-300 bg-purple-50/30">
                                                                <ImageIcon size={32} />
                                                                <span className="text-[10px] mt-2 font-bold uppercase">Image Layer</span>
                                                            </div>
                                                        )}
                                                    </div>
                                                )}
                                                {selectedLayerId === layer.id && (
                                                    <>
                                                        <div className="absolute -top-6 left-0 bg-purple-600 text-white text-[10px] px-2 py-1 rounded-t flex items-center gap-2 shadow-sm">
                                                            <Grid size={10} className="rotate-45" /> LAYER #{layer.id.toString().slice(-4)}
                                                        </div>
                                                        <div
                                                            onMouseDown={(e) => handleResizeStart(e, 'layer-resize', null, layer.id)}
                                                            className="absolute -right-2 -bottom-2 w-4 h-4 bg-purple-600 border-2 border-white rounded-full cursor-nwse-resize z-50 shadow-sm"
                                                        ></div>
                                                    </>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </div>
                    ) : (
                        <div className="flex-1 overflow-auto bg-white p-8">
                            <div className="max-w-4xl mx-auto">
                                <div className="flex items-center justify-between mb-8">
                                    <div className="flex items-center gap-3">
                                        <div className="p-3 bg-purple-600 rounded-xl text-white shadow-lg shadow-purple-200">
                                            <Terminal size={24} />
                                        </div>
                                        <div>
                                            <h2 className="text-2xl font-bold text-gray-900 uppercase tracking-tight">Logical Structure View</h2>
                                            <p className="text-sm text-gray-500">Manage data sections, attributes, and validation rules.</p>
                                        </div>
                                    </div>
                                    <button onClick={() => setViewMode('designer')} className="px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50 text-xs font-bold transition-all">
                                        BACK TO CANVAS
                                    </button>
                                </div>

                                <div className="grid grid-cols-3 gap-6">
                                    <div className="col-span-1 space-y-4">
                                        <div className="p-4 bg-gray-50 rounded-xl border border-gray-200">
                                            <h3 className="text-xs font-bold text-gray-400 uppercase mb-3 px-1">Structure Tree</h3>
                                            <div className="space-y-1">
                                                <div className="flex items-center gap-2 p-2 bg-purple-50 text-purple-700 rounded-lg font-bold text-sm">
                                                    <Layout size={14} /> Document Root
                                                </div>
                                                <div className="pl-4 space-y-1 mt-2">
                                                    {logicSections.map(sec => (
                                                        <div
                                                            key={sec.id}
                                                            onClick={() => setSelectedSectionId(sec.id)}
                                                            className={`flex items-center justify-between p-2 rounded text-sm cursor-pointer group transition-all ${selectedSectionId === sec.id ? 'bg-purple-100 text-purple-700 font-bold' : 'text-gray-600 hover:bg-gray-100'}`}
                                                        >
                                                            <div className="flex items-center gap-2">
                                                                {sec.isDynamic ? <Grid size={12} className="text-orange-400" /> : <Plus size={12} className="text-purple-400" />}
                                                                {safeRender(sec.name)}
                                                            </div>
                                                            <div className="flex items-center gap-2">
                                                                <span className="text-[10px] text-gray-400 uppercase">{sec.items.length} Items</span>
                                                                {sec.isDynamic && <span className="text-[8px] bg-orange-100 text-orange-600 px-1 rounded font-black">DYNAMIC</span>}
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                            <button
                                                onClick={() => {
                                                    const newId = `sec_${Date.now()}`;
                                                    setLogicSections([...logicSections, { id: newId, name: 'New Section', items: [] }]);
                                                    setSelectedSectionId(newId);
                                                }}
                                                className="w-full mt-4 py-2 border-2 border-dashed border-gray-300 rounded-lg text-[10px] font-bold text-gray-400 hover:border-purple-300 hover:text-purple-500 uppercase transition-all"
                                            >
                                                Add New Section
                                            </button>
                                        </div>
                                    </div>
                                    <div className="col-span-2 space-y-4">
                                        <div className="p-6 bg-white rounded-xl border border-gray-200 shadow-sm relative overflow-hidden">
                                            <div className="absolute top-0 right-0 p-4 opacity-5 pointer-events-none"><Code size={80} /></div>

                                            {/* Section Title Editor */}
                                            <div className="flex items-center gap-3 mb-6">
                                                <input
                                                    type="text"
                                                    className="text-xl font-bold text-gray-900 bg-transparent border-b border-dashed border-gray-200 focus:border-purple-400 outline-none pb-1 w-full max-w-md"
                                                    value={logicSections.find(s => s.id === selectedSectionId)?.name || ''}
                                                    onChange={(e) => {
                                                        const newSections = logicSections.map(s => s.id === selectedSectionId ? { ...s, name: e.target.value } : s);
                                                        setLogicSections(newSections);
                                                    }}
                                                />
                                                <div className="flex items-center gap-2 text-[10px] font-black text-gray-400 uppercase tracking-widest">
                                                    Section ID: <span className="bg-gray-100 px-2 py-0.5 rounded font-mono text-purple-600">{selectedSectionId}</span>
                                                </div>
                                            </div>

                                            <div className="divide-y divide-gray-100 border rounded-xl overflow-hidden mb-6 bg-gray-50/30">
                                                {(logicSections.find(s => s.id === selectedSectionId)?.items || []).map((dataKey, idx) => {
                                                    const cellK = Object.keys(activePage.grid.cells).find(k => activePage.grid.cells[k].dataKey === dataKey);
                                                    const cell = cellK ? activePage.grid.cells[cellK] : null;

                                                    return (
                                                        <div key={dataKey} className="p-4 flex items-center justify-between hover:bg-white transition-colors group">
                                                            <div className="flex items-center gap-4">
                                                                <div className={`w-8 h-8 rounded-lg flex items-center justify-center font-mono text-[10px] ${cell ? 'bg-purple-100 text-purple-600' : 'bg-gray-200 text-gray-400'}`}>
                                                                    {cell ? cellK : idx + 1}
                                                                </div>
                                                                <div>
                                                                    <div className="text-sm font-bold text-gray-900 flex items-center gap-2">
                                                                        {safeRender(dataKey)}
                                                                        {cell && <span className="text-[9px] px-1 bg-green-100 text-green-600 rounded">MAPPED</span>}
                                                                    </div>
                                                                    <div className="flex items-center gap-2 text-[10px] text-gray-500">
                                                                        Label: <span className="text-gray-900 italic font-medium">{safeRender(cell?.content) || 'Undefined'}</span>
                                                                        <span className="text-gray-300">|</span>
                                                                        Type: <span className="text-blue-600 font-bold uppercase">{safeRender(cell?.type) || 'text'}</span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                                <button className="p-2 text-gray-400 hover:text-blue-500 hover:bg-white rounded border shadow-sm transition-all"><Settings size={14} /></button>
                                                                <button
                                                                    onClick={() => {
                                                                        const newSections = logicSections.map(s => s.id === selectedSectionId ? { ...s, items: s.items.filter(i => i !== dataKey) } : s);
                                                                        setLogicSections(newSections);
                                                                    }}
                                                                    className="p-2 text-gray-400 hover:text-red-500 hover:bg-white rounded border shadow-sm transition-all"
                                                                ><Trash2 size={14} /></button>
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                                {logicSections.find(s => s.id === selectedSectionId)?.items.length === 0 && (
                                                    <div className="p-10 text-center text-gray-400 text-sm italic">
                                                        No logical items in this section. Add items to link with grid cells.
                                                    </div>
                                                )}
                                            </div>

                                            <button
                                                onClick={() => {
                                                    const key = prompt('Enter Data Key (e.g. qty, price):');
                                                    if (key && !logicSections.some(s => s.items.includes(key))) {
                                                        const newSections = logicSections.map(s => s.id === selectedSectionId ? { ...s, items: [...s.items, key] } : s);
                                                        setLogicSections(newSections);
                                                    }
                                                }}
                                                className="w-full py-4 border-2 border-dashed border-purple-200 text-purple-500 rounded-2xl flex items-center justify-center gap-2 hover:bg-purple-50 hover:border-purple-300 transition-all font-black text-sm uppercase shadow-sm active:scale-[0.98]"
                                            >
                                                <Plus size={20} /> ADD NEW LOGICAL ITEM
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
                    {/* Zoom Tools */}
                    <div className="absolute bottom-8 right-8 flex gap-2 bg-white p-1 rounded-lg shadow border">
                        <button onClick={() => setScale(s => Math.max(0.2, s - 0.1))} className="p-2 hover:bg-gray-100 rounded">-</button>
                        <span className="p-2 text-sm font-mono w-16 text-center">{Math.round(scale * 100)}%</span>
                        <button onClick={() => setScale(s => Math.min(2, s + 0.1))} className="p-2 hover:bg-gray-100 rounded">+</button>
                    </div>
                </div>

                {/* AI Analysis Overlay */}
                {isAnalyzing && (
                    <div className="fixed inset-0 z-[200] bg-black/60 flex flex-col items-center justify-center backdrop-blur-sm pointer-events-auto">
                        <style>{`
                            @keyframes scan {
                                0% { top: 0; }
                                50% { top: 100%; }
                                100% { top: 0; }
                            }
                            .animate-scanline {
                                animation: scan 3s ease-in-out infinite;
                            }
                        `}</style>
                        <div className="relative w-96 h-96 bg-white/10 border-4 border-indigo-500/50 rounded-2xl overflow-hidden shadow-2xl">
                            <div className="absolute inset-0 bg-gradient-to-b from-blue-500/10 to-transparent animate-pulse"></div>
                            <div className="absolute top-0 w-full h-1 bg-indigo-400 shadow-[0_0_20px_#6366f1] animate-scanline z-30"></div>

                            {/* Decorative Grid Lines */}
                            <div className="absolute inset-0 grid grid-cols-12 grid-rows-12 opacity-20">
                                {Array.from({ length: 144 }).map((_, i) => (
                                    <div key={i} className="border-[0.5px] border-indigo-200"></div>
                                ))}
                            </div>

                            <div className="absolute inset-0 flex flex-col items-center justify-center gap-4 z-40 text-center px-4">
                                <div className="p-6 bg-white/10 rounded-full border border-white/20 backdrop-blur-md animate-pulse">
                                    <Bot className="w-16 h-16 text-white" />
                                </div>
                                <div className="space-y-2">
                                    <div className="text-white font-black text-xl drop-shadow-lg uppercase tracking-[0.2em] px-6 py-3 bg-indigo-600/80 rounded-full border border-indigo-400">
                                        {["ANALYZING", "DETECTING", "EXTRACTING", "MAPPING", "FINALIZING"][scanStep]}...
                                    </div>
                                    <p className="text-white/80 text-[10px] font-bold uppercase tracking-widest animate-pulse">
                                        {[
                                            "Document Structure & Layout",
                                            "Table Grids & Merged Cells",
                                            "Logical Data Fields & Keys",
                                            "Calculation Formulas & Rules",
                                            "Digital Interactive Template"
                                        ][scanStep]}
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div className="mt-8 space-y-3 text-center">
                            <p className="text-white/90 text-lg font-bold">이미지 레이아웃을 지능적으로 분석하고 있습니다</p>
                            <div className="w-80 h-12 flex flex-col items-center justify-center gap-1 font-mono text-[10px] text-indigo-300">
                                <div className={`transition-opacity duration-300 ${scanStep >= 1 ? 'opacity-100' : 'opacity-30'}`}>✓ Table Structures Detected</div>
                                <div className={`transition-opacity duration-300 ${scanStep >= 2 ? 'opacity-100' : 'opacity-30'}`}>✓ 12 Form Fields Identified</div>
                                <div className={`transition-opacity duration-300 ${scanStep >= 3 ? 'opacity-100' : 'opacity-30'}`}>✓ Logical Mapping Optimized</div>
                            </div>
                            <div className="w-64 h-1.5 bg-gray-800 rounded-full mx-auto overflow-hidden border border-white/10">
                                <div
                                    className="h-full bg-indigo-500 transition-all duration-300 shadow-[0_0_10px_rgba(99,102,241,0.5)]"
                                    style={{ width: `${(scanStep + 1) * 20}%` }}
                                ></div>
                            </div>
                            <style>{`
                                @keyframes progress {
                                    0% { width: 0%; transform: translateX(-100%); }
                                    100% { width: 100%; transform: translateX(100%); }
                                }
                            `}</style>
                        </div>
                    </div>
                )}

                {/* Right Sidebar: Properties */}
                <div className="w-80 bg-white border-l border-gray-200 shrink-0 flex flex-col">
                    <div className="p-4 border-b font-bold text-gray-700 bg-gray-50 flex items-center justify-between">
                        <span>{selectedLayerId ? '레이어 속성 (Layer)' : selectedCell ? '셀 속성 (Cell)' : '페이지 설정 (Page)'}</span>
                        {!selectedCell && !selectedLayerId && <Settings size={16} className="text-gray-400" />}
                    </div>
                    <div className="flex-1 overflow-y-auto p-4">
                        {!selectedCell && !selectedLayerId ? (
                            <div className="space-y-6 animate-in fade-in slide-in-from-right-2 duration-300">
                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-3 flex items-center gap-2 tracking-widest">
                                        <Layout size={14} className="text-blue-500" /> Paper Settings
                                    </h4>
                                    <div className="space-y-4">
                                        <div className="space-y-1.5">
                                            <label className="text-[10px] text-gray-400 uppercase font-black">Sheet Size</label>
                                            <select
                                                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm bg-white shadow-sm focus:ring-2 focus:ring-blue-100 outline-none transition-all font-medium"
                                                value={pageConfig.size}
                                                onChange={(e) => setPageConfig({ ...pageConfig, size: e.target.value })}
                                            >
                                                {Object.keys(PAGE_SIZES).map(size => (
                                                    <option key={size} value={size}>{size} Plane ({PAGE_SIZES[size].w}x{PAGE_SIZES[size].h}px)</option>
                                                ))}
                                            </select>
                                        </div>
                                        <div className="space-y-1.5">
                                            <label className="text-[10px] text-gray-400 uppercase font-black">Orientation</label>
                                            <div className="flex bg-gray-100 p-1 rounded-xl">
                                                <button
                                                    onClick={() => setPageConfig({ ...pageConfig, orientation: 'portrait' })}
                                                    className={`flex-1 py-2 rounded-lg text-xs font-bold transition-all flex items-center justify-center gap-2 ${pageConfig.orientation === 'portrait' ? 'bg-white shadow-sm text-blue-600' : 'text-gray-400 hover:text-gray-600'}`}
                                                >
                                                    <div className="w-2 h-3 border-2 border-current rounded-sm"></div> 세로 (Portrait)
                                                </button>
                                                <button
                                                    onClick={() => setPageConfig({ ...pageConfig, orientation: 'landscape' })}
                                                    className={`flex-1 py-2 rounded-lg text-xs font-bold transition-all flex items-center justify-center gap-2 ${pageConfig.orientation === 'landscape' ? 'bg-white shadow-sm text-blue-600' : 'text-gray-400 hover:text-gray-600'}`}
                                                >
                                                    <div className="w-3 h-2 border-2 border-current rounded-sm"></div> 가로 (Landscape)
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className="p-4 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-2xl border border-blue-100 shadow-sm">
                                    <div className="flex items-center gap-2 text-blue-700 font-black text-xs mb-2 uppercase tracking-tight">
                                        <Cpu size={14} className="text-blue-500" /> Smart Engine v4.0
                                    </div>
                                    <p className="text-[10px] text-blue-600/80 leading-relaxed font-semibold">
                                        이 문서는 동적 데이터 바인딩과 AI 레이아웃 해석 엔진이 활성화되어 있습니다. <br /><br />
                                        - 셀 단위 복합 연산 지원 <br />
                                        - 시스템 필드 자동 매핑 <br />
                                        - 가상 그리드 최적화
                                    </p>
                                </div>
                                <div className="p-4 bg-purple-50 rounded-2xl border border-purple-100">
                                    <h5 className="text-[10px] font-black text-purple-600 uppercase mb-2 flex items-center gap-2">
                                        <Bot size={14} /> AI Context
                                    </h5>
                                    <p className="text-[10px] text-purple-500/80 font-medium">이미지 업로드 기능을 통해 인쇄물을 즉시 디지털 양식으로 전환할 수 있습니다.</p>
                                </div>
                            </div>
                        ) : selectedLayerId ? (
                            <div className="space-y-6">
                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Layer Info</h4>
                                    <div className="text-[10px] font-mono bg-gray-50 p-2 rounded border text-gray-400">
                                        ID: {selectedLayerId} <br />
                                        Type: {activePage.layers.find(l => l.id === selectedLayerId)?.type}
                                    </div>
                                </div>

                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Content</h4>
                                    <div className="border border-dashed border-purple-300 p-4 rounded-lg text-center bg-purple-50/20">
                                        {activePage.layers.find(l => l.id === selectedLayerId)?.content ? (
                                            <img src={activePage.layers.find(l => l.id === selectedLayerId)?.content} className="max-h-32 mx-auto mb-4 rounded shadow-sm" alt="Preview" />
                                        ) : <ImageIcon size={32} className="mx-auto text-purple-200 mb-4" />}
                                        <input
                                            type="file" accept="image/*"
                                            onChange={(e) => {
                                                const file = e.target.files[0];
                                                if (file) {
                                                    const reader = new FileReader();
                                                    reader.onloadend = () => updateLayer(selectedLayerId, { content: reader.result });
                                                    reader.readAsDataURL(file);
                                                }
                                            }}
                                            className="hidden" id="layer-img-upload"
                                        />
                                        <label htmlFor="layer-img-upload" className="inline-block px-4 py-2 bg-purple-600 text-white text-xs font-bold rounded cursor-pointer hover:bg-purple-700 transition-colors uppercase">
                                            Upload Image
                                        </label>
                                    </div>
                                </div>

                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Opacity</h4>
                                    <input
                                        type="range" min="0" max="1" step="0.1"
                                        className="w-full"
                                        value={activePage.layers.find(l => l.id === selectedLayerId)?.style?.opacity || 1}
                                        onChange={(e) => updateLayer(selectedLayerId, { style: { ...activePage.layers.find(l => l.id === selectedLayerId)?.style, opacity: parseFloat(e.target.value) } })}
                                    />
                                </div>

                                <button
                                    onClick={() => deleteLayer(selectedLayerId)}
                                    className="w-full py-2 bg-red-50 text-red-600 rounded border border-red-200 hover:bg-red-100 transition-colors text-xs font-bold uppercase mt-10 flex items-center justify-center gap-2"
                                >
                                    <Trash2 size={14} /> Delete Layer
                                </button>
                            </div>
                        ) : selectedCell ? (
                            <div className="space-y-6">
                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Cell Address</h4>
                                    <div className="text-sm font-mono bg-gray-50 p-2 rounded border space-y-2">
                                        <div className="flex justify-between">
                                            <span>Row: {selectedCell.r + 1}, Col: {String.fromCharCode(65 + selectedCell.c)}</span>
                                            <div className="flex items-center gap-2">
                                                <span className="text-[10px] text-gray-400">Iterative Row</span>
                                                <input
                                                    type="checkbox"
                                                    checked={activePage.grid.dynamicRows?.includes(selectedCell.r)}
                                                    onChange={(e) => {
                                                        const rowExists = activePage.grid.dynamicRows?.includes(selectedCell.r);
                                                        const newDynamicRows = rowExists
                                                            ? activePage.grid.dynamicRows.filter(r => r !== selectedCell.r)
                                                            : [...(activePage.grid.dynamicRows || []), selectedCell.r];
                                                        updateGrid({ dynamicRows: newDynamicRows });
                                                    }}
                                                />
                                            </div>
                                        </div>
                                        <div className="flex gap-2">
                                            <button
                                                onClick={handleMergeCells}
                                                className="flex-1 py-1 bg-orange-50 text-orange-600 border border-orange-200 rounded text-[10px] font-bold hover:bg-orange-100 uppercase"
                                            >Merge</button>
                                            <button
                                                onClick={handleUnmergeCells}
                                                className="flex-1 py-1 bg-gray-50 text-gray-600 border border-gray-200 rounded text-[10px] font-bold hover:bg-gray-100 uppercase"
                                            >Unmerge</button>
                                        </div>
                                    </div>
                                </div>

                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Cell Type</h4>
                                    <div className="grid grid-cols-2 gap-2">
                                        {[
                                            { id: 'text', label: 'Default' },
                                            { id: 'select', label: 'Dropdown' },
                                            { id: 'checkbox', label: 'Checkbox' },
                                            { id: 'radio', label: 'Radio' },
                                            { id: 'image', label: 'Image' },
                                            { id: 'approval', label: 'Approval' }
                                        ].map(t => (
                                            <button
                                                key={t.id}
                                                onClick={() => updateCell(selectedCell.r, selectedCell.c, { type: t.id })}
                                                className={`py-1 text-[10px] font-bold border rounded ${activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.type === t.id || (t.id === 'text' && !activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.type) ? 'bg-blue-600 text-white border-blue-600' : 'text-gray-500 hover:bg-gray-50'}`}
                                            >{t.label}</button>
                                        ))}
                                    </div>

                                    {activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.type === 'select' && (
                                        <div className="mt-3 p-3 bg-blue-50/50 rounded-lg border border-blue-100">
                                            <h5 className="text-[10px] font-bold text-blue-600 uppercase mb-2 flex items-center gap-2">
                                                <Settings size={12} /> Dropdown Options
                                            </h5>
                                            <div className="space-y-1.5">
                                                {(activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.options || ['Option 1', 'Option 2']).map((opt, idx) => (
                                                    <div key={idx} className="flex items-center gap-1">
                                                        <input
                                                            type="text"
                                                            className="flex-1 border border-blue-200 rounded px-2 py-1 text-[10px] focus:ring-1 focus:ring-blue-300 outline-none h-7"
                                                            value={opt}
                                                            onChange={(e) => {
                                                                const currentCell = activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`];
                                                                const newOpts = [...(currentCell.options || ['Option 1', 'Option 2'])];
                                                                newOpts[idx] = e.target.value;
                                                                updateCell(selectedCell.r, selectedCell.c, { options: newOpts });
                                                            }}
                                                        />
                                                        <button
                                                            onClick={() => {
                                                                const currentCell = activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`];
                                                                const newOpts = (currentCell.options || ['Option 1', 'Option 2']).filter((_, i) => i !== idx);
                                                                updateCell(selectedCell.r, selectedCell.c, { options: newOpts });
                                                            }}
                                                            className="p-1.5 text-red-400 hover:bg-white rounded transition-colors"
                                                        ><Trash2 size={12} /></button>
                                                    </div>
                                                ))}
                                                <button
                                                    onClick={() => {
                                                        const currentCell = activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`];
                                                        const currentOpts = currentCell.options || ['Option 1', 'Option 2'];
                                                        updateCell(selectedCell.r, selectedCell.c, { options: [...currentOpts, `Option ${currentOpts.length + 1}`] });
                                                    }}
                                                    className="w-full mt-1 py-1.5 border border-dashed border-blue-300 text-[10px] font-bold text-blue-500 rounded hover:bg-white transition-all uppercase"
                                                >+ Add Option</button>
                                            </div>
                                        </div>
                                    )}
                                </div>

                                <div className="pt-2 border-t border-dashed">
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2 flex items-center gap-1">
                                        <Zap size={14} className="text-orange-400" /> Smart Formula
                                    </h4>
                                    <div className="space-y-2">
                                        <input
                                            type="text"
                                            className="w-full border rounded px-2 py-1.5 text-xs font-mono bg-orange-50/20 border-orange-100 outline-none focus:ring-1 focus:ring-orange-200"
                                            placeholder="e.g. =SUM(B2:B10) or {{qty}}*{{p}}"
                                            value={activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.formula || ''}
                                            onChange={(e) => updateCell(selectedCell.r, selectedCell.c, { formula: e.target.value })}
                                        />
                                        <p className="text-[9px] text-gray-400 italic leading-tight">연산 기능을 활성화하려면 수식을 입력하세요. 변수({{}})와 기본 산식(+,-,*,/)을 지원합니다.</p>
                                    </div>
                                </div>

                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Borders</h4>
                                    <div className="space-y-3">
                                        <div className="grid grid-cols-4 gap-1">
                                            {[
                                                { id: 'all', icon: <Grid size={16} /> },
                                                { id: 'outside', icon: <CheckSquare size={16} /> },
                                                { id: 'inside', icon: <Layout size={16} /> },
                                                { id: 'none', icon: <X size={16} /> },
                                                { id: 'top', icon: <ChevronUp size={16} /> },
                                                { id: 'bottom', icon: <ChevronDown size={16} /> },
                                                { id: 'left', icon: <AlignLeft size={16} className="-rotate-90" /> },
                                                { id: 'right', icon: <AlignLeft size={16} className="rotate-90" /> }
                                            ].map(b => (
                                                <button
                                                    key={b.id}
                                                    onClick={() => applyBorders(b.id, borderSettings.width, borderSettings.color)}
                                                    className="aspect-square border rounded flex items-center justify-center hover:bg-gray-100 text-gray-600"
                                                    title={b.id}
                                                >{b.icon}</button>
                                            ))}
                                        </div>
                                        <div className="flex gap-2">
                                            <select
                                                className="flex-1 border rounded px-1 py-1 text-xs"
                                                value={borderSettings.width}
                                                onChange={(e) => setBorderSettings({ ...borderSettings, width: parseInt(e.target.value) })}
                                            >
                                                <option value="1">1px</option>
                                                <option value="2">2px</option>
                                                <option value="3">3px</option>
                                                <option value="5">5px</option>
                                            </select>
                                            <input
                                                type="color"
                                                className="w-10 h-6 p-0 border rounded overflow-hidden"
                                                value={borderSettings.color}
                                                onChange={(e) => setBorderSettings({ ...borderSettings, color: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                </div>

                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Data Linking</h4>
                                    <div className="space-y-2">
                                        <div className="flex flex-col gap-1">
                                            <label className="text-[10px] text-gray-400">Data Key (Variable Name)</label>
                                            <input
                                                type="text"
                                                className="w-full border rounded px-2 py-1.5 text-sm font-mono"
                                                placeholder="e.g. product_id"
                                                value={activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.dataKey || ''}
                                                onChange={(e) => updateCell(selectedCell.r, selectedCell.c, { dataKey: e.target.value })}
                                            />
                                            <p className="text-[9px] text-gray-500 italic">Use for data association during form filling.</p>
                                        </div>
                                    </div>
                                </div>

                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Typography</h4>
                                    <div className="space-y-2">
                                        <div className="flex gap-2">
                                            <select
                                                className="flex-1 border rounded px-2 py-1 text-sm text-center"
                                                value={activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.style?.fontSize || '12px'}
                                                onChange={(e) => updateSelectedRange({ style: { fontSize: e.target.value } })}
                                            >
                                                <option value="10px">10px</option>
                                                <option value="12px">12px</option>
                                                <option value="14px">14px</option>
                                                <option value="18px">18px</option>
                                                <option value="24px">24px</option>
                                            </select>
                                            <button
                                                className={`p-1 border rounded w-10 font-bold hover:bg-gray-100 ${activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.style?.fontWeight === 'bold' ? 'bg-blue-600 text-white' : ''}`}
                                                onClick={() => {
                                                    const isBold = activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.style?.fontWeight === 'bold';
                                                    updateSelectedRange({ style: { fontWeight: isBold ? 'normal' : 'bold' } });
                                                }}
                                            >B</button>
                                        </div>
                                        <div className="flex gap-1">
                                            {['left', 'center', 'right'].map(align => (
                                                <button
                                                    key={align}
                                                    onClick={() => updateSelectedRange({ style: { textAlign: align } })}
                                                    className={`flex-1 border rounded py-1 text-[10px] uppercase hover:bg-gray-50 ${activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.style?.textAlign === align ? 'bg-gray-200' : ''}`}
                                                >{align[0]}</button>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Appearance</h4>
                                    <div className="grid grid-cols-2 gap-2">
                                        <div>
                                            <label className="text-[10px] text-gray-400 block mb-1">Background</label>
                                            <input
                                                type="color"
                                                value={activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.style?.backgroundColor || '#ffffff'}
                                                className="w-full h-8 p-0 border border-gray-200 rounded cursor-pointer mt-1"
                                                onChange={(e) => updateSelectedRange({ style: { backgroundColor: e.target.value } })}
                                            />
                                        </div>
                                        <div>
                                            <label className="text-[10px] text-gray-400 block mb-1">Text Color</label>
                                            <input
                                                type="color"
                                                value={activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.style?.color || '#000000'}
                                                className="w-full h-8 p-0 border border-gray-200 rounded cursor-pointer mt-1"
                                                onChange={(e) => updateSelectedRange({ style: { color: e.target.value } })}
                                            />
                                        </div>
                                    </div>
                                </div>
                                {activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.type === 'image' && (
                                    <div>
                                        <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Image Content</h4>
                                        <div className="border border-dashed border-gray-300 p-2 rounded text-center bg-gray-50 overflow-hidden">
                                            {activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.content ? (
                                                <img src={activePage.grid.cells[`${selectedCell.r}:${selectedCell.c}`]?.content} className="max-h-20 mx-auto mb-2" alt="Preview" />
                                            ) : <ImageIcon size={20} className="mx-auto text-gray-300 mb-2" />}
                                            <input
                                                type="file"
                                                accept="image/*"
                                                onChange={(e) => {
                                                    const file = e.target.files[0];
                                                    if (file) {
                                                        const reader = new FileReader();
                                                        reader.onloadend = () => updateCell(selectedCell.r, selectedCell.c, { content: reader.result });
                                                        reader.readAsDataURL(file);
                                                    }
                                                }}
                                                className="hidden" id="cell-img-upload"
                                            />
                                            <label htmlFor="cell-img-upload" className="text-[10px] cursor-pointer hover:text-blue-500 underline uppercase font-bold">Upload</label>
                                        </div>
                                    </div>
                                )}
                                <button
                                    onClick={() => updateSelectedRange({ type: null, content: '', style: {}, dataKey: null })}
                                    className="w-full py-2 bg-red-50 text-red-600 rounded border border-red-200 hover:bg-red-100 transition-colors text-xs font-bold uppercase mt-10"
                                >
                                    Clear Selected Cells
                                </button>
                            </div>
                        ) : (
                            <div className="space-y-6">
                                <div>
                                    <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Paper Configuration</h4>
                                    <div className="space-y-4">
                                        <div>
                                            <label className="text-[10px] text-gray-400 block mb-1">Paper Size</label>
                                            <select
                                                className="w-full border rounded px-2 py-1.5 text-sm"
                                                value={pageConfig.size}
                                                onChange={(e) => setPageConfig({ ...pageConfig, size: e.target.value })}
                                            >
                                                <option value="A4">A4 (210 x 297 mm)</option>
                                                <option value="A3">A3 (297 x 420 mm)</option>
                                                <option value="Letter">Letter (215.9 x 279.4 mm)</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label className="text-[10px] text-gray-400 block mb-1">Orientation</label>
                                            <div className="flex gap-2">
                                                <button
                                                    onClick={() => setPageConfig({ ...pageConfig, orientation: 'portrait' })}
                                                    className={`flex-1 py-2 border rounded text-xs font-bold flex items-center justify-center gap-2 ${pageConfig.orientation === 'portrait' ? 'bg-blue-600 text-white' : 'hover:bg-gray-50'}`}
                                                >
                                                    <Layout size={14} /> Portrait
                                                </button>
                                                <button
                                                    onClick={() => setPageConfig({ ...pageConfig, orientation: 'landscape' })}
                                                    className={`flex-1 py-2 border rounded text-xs font-bold flex items-center justify-center gap-2 ${pageConfig.orientation === 'landscape' ? 'bg-blue-600 text-white' : 'hover:bg-gray-50'}`}
                                                >
                                                    <Layout size={14} className="rotate-90" /> Landscape
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div className="p-4 bg-blue-50 border border-blue-100 rounded-lg">
                                    <h5 className="text-xs font-bold text-blue-700 mb-1">Pro Tip</h5>
                                    <p className="text-[10px] text-blue-600 leading-relaxed">
                                        Select a cell to bind it to a data field or mark a row as iterative for dynamic tables. <br /> Use the image icon to add floating layers.
                                    </p>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {showStructure && registeredSchema && (
                <div className="fixed inset-0 bg-black/50 z-[100] flex items-center justify-center p-4">
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[80vh] flex flex-col overflow-hidden">
                        <div className="p-6 border-b flex justify-between items-center bg-purple-50">
                            <div>
                                <h3 className="text-xl font-bold text-purple-900 flex items-center gap-2">
                                    <Database className="w-6 h-6" /> 템플릿 구조 등록 완료
                                </h3>
                                <p className="text-sm text-purple-600">등록된 논리적 데이터 구조 (Sections → Items)</p>
                            </div>
                            <button onClick={() => setShowStructure(false)} className="p-2 hover:bg-purple-100 rounded-full transition-colors">
                                <X size={24} className="text-purple-900" />
                            </button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-6 space-y-6">
                            <div className="space-y-4">
                                <div className="p-4 bg-gray-50 rounded-xl border">
                                    <span className="text-xs font-bold text-gray-500 uppercase">양식명</span>
                                    <div className="text-lg font-bold text-gray-900">{safeRender(registeredSchema.name)}</div>
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="p-4 bg-blue-50 rounded-xl border border-blue-100">
                                        <div className="text-2xl font-bold text-blue-600">{registeredSchema.fields.length}</div>
                                        <div className="text-xs text-blue-500 font-bold uppercase">데이터 연동 필드 (Attributes)</div>
                                    </div>
                                    <div className="p-4 bg-orange-50 rounded-xl border border-orange-100">
                                        <div className="text-2xl font-bold text-orange-600">{registeredSchema.dynamicRows.length}</div>
                                        <div className="text-xs text-orange-500 font-bold uppercase">반복 섹션 개수 (Dynamic Rows)</div>
                                    </div>
                                </div>
                            </div>

                            <div className="space-y-2">
                                <h4 className="font-bold text-gray-700 flex items-center gap-2">
                                    <Layout size={16} /> 추출된 데이터 구조 상세
                                </h4>
                                <div className="border rounded-xl divide-y overflow-hidden">
                                    {registeredSchema.fields.map((f, i) => (
                                        <div key={i} className="p-3 flex justify-between items-center hover:bg-gray-50 bg-white">
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 font-mono text-xs">#{i + 1}</div>
                                                <div>
                                                    <div className="text-sm font-bold text-gray-900">{safeRender(f.label)}</div>
                                                    <div className="text-[10px] font-mono text-blue-500">{safeRender(f.key)}</div>
                                                </div>
                                            </div>
                                            <div className="px-2 py-1 bg-green-100 text-green-700 rounded text-[10px] font-bold">ACTIVE</div>
                                        </div>
                                    ))}
                                    {registeredSchema.fields.length === 0 && (
                                        <div className="p-8 text-center text-gray-400 text-sm italic bg-gray-50">
                                            데이터 키(Data Key)가 지정된 셀이 없습니다. <br /> 셀 속성에서 연동할 키를 지정해주세요.
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                        <div className="p-6 border-t bg-gray-50 flex justify-end">
                            <button
                                onClick={() => setShowStructure(false)}
                                className="px-6 py-2 bg-purple-600 text-white rounded-lg font-bold hover:bg-purple-700 shadow-md transition-all active:scale-95"
                            >
                                확인 및 닫기
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {contextMenu && (
                <div
                    className="fixed z-[100] bg-white border border-gray-200 shadow-xl rounded-lg py-1 w-48 text-[11px] font-medium text-gray-700 pointer-events-auto"
                    style={{ top: contextMenu.y, left: contextMenu.x }}
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className="px-3 py-1.5 text-[10px] text-gray-400 border-b border-gray-100 uppercase font-bold">Grid Actions</div>
                    <button onClick={() => { addRow(contextMenu.r); setContextMenu(null); }} className="w-full text-left px-3 py-2 hover:bg-gray-100 flex items-center justify-between transition-colors">
                        Insert Row Above <span className="text-gray-300">R{contextMenu.r + 1}</span>
                    </button>
                    <button onClick={() => { addRow(contextMenu.r + 1); setContextMenu(null); }} className="w-full text-left px-3 py-2 hover:bg-gray-100 flex items-center justify-between transition-colors">
                        Insert Row Below <span className="text-gray-300">R{contextMenu.r + 2}</span>
                    </button>
                    <div className="h-px bg-gray-100 my-1"></div>
                    <button onClick={() => { addCol(contextMenu.c); setContextMenu(null); }} className="w-full text-left px-3 py-2 hover:bg-gray-100 flex items-center justify-between transition-colors">
                        Insert Column Left <span className="text-gray-300">{String.fromCharCode(65 + contextMenu.c)}</span>
                    </button>
                    <button onClick={() => { addCol(contextMenu.c + 1); setContextMenu(null); }} className="w-full text-left px-3 py-2 hover:bg-gray-100 flex items-center justify-between transition-colors">
                        Insert Column Right <span className="text-gray-300">{String.fromCharCode(66 + contextMenu.c)}</span>
                    </button>
                    <div className="h-px bg-gray-100 my-1"></div>
                    <button onClick={() => { handleMergeCells(); setContextMenu(null); }} className="w-full text-left px-3 py-2 hover:bg-gray-100 transition-colors">
                        Merge Selected Cells
                    </button>
                    <button onClick={() => { handleUnmergeCells(); setContextMenu(null); }} className="w-full text-left px-3 py-2 hover:bg-gray-100 transition-colors">
                        Unmerge Cells
                    </button>
                    <div className="h-px bg-gray-100 my-1"></div>
                    <button
                        onClick={() => {
                            updateSelectedRange({ content: '', style: {}, type: 'text', dataKey: null });
                            setContextMenu(null);
                        }}
                        className="w-full text-left px-3 py-2 hover:bg-gray-100 text-red-500 transition-colors"
                    >
                        Clear Selection
                    </button>
                </div>
            )}
        </div>
    );
};

export default DocumentDesigner;
