
import React, { useState } from 'react';
import {
    ArrowLeft, Save, Plus, Trash2, FileText, Settings,
    Layout, List, Grid, CheckSquare, AlignLeft, Scale,
    ChevronDown, ChevronUp, Eye, Printer, X
} from 'lucide-react';
import DocumentDesigner from './DocumentDesigner';

const DocumentTemplateManager = ({ onNavigate }) => {
    const [mode, setMode] = useState('list'); // list, create, edit
    const [templates, setTemplates] = useState(() => {
        const saved = localStorage.getItem('docTemplates');
        return saved ? JSON.parse(saved) : [
            { id: 1, name: '수입검사 성적서', category: '품질', updatedAt: '2024-10-25' },
            { id: 2, name: '부적합 보고서(NCR)', category: '품질', updatedAt: '2024-10-24' },
            { id: 3, name: '작업지시서', category: '생산', updatedAt: '2024-10-23' }
        ];
    });

    // 템플릿 변경 시 자동 저장
    React.useEffect(() => {
        localStorage.setItem('docTemplates', JSON.stringify(templates));
    }, [templates]);

    // [NEW] 수입검사 성적서 프리셋
    const IQC_TEMPLATE_PRESET = {
        title: '수입검사 성적서',
        companyInfo: {
            name: '경동기업',
            address: '경기도 화성시 양감면 초록로 567',
            contact: 'TEL: 031-123-4567 / FAX: 031-123-4568'
        },
        approvalLine: [
            { id: 1, name: '검사', dept: '품질팀', role: '담당' },
            { id: 2, name: '승인', dept: '품질팀', role: '팀장' }
        ],
        basicFields: [
            { id: 1, label: '품명', type: 'text', default: '아연도금강판(EGI)' },
            { id: 2, label: '입고 LOT NO', type: 'text', default: '241028-01' },
            { id: 3, label: '공급사', type: 'text', default: '포스코' },
            { id: 4, label: '제조사', type: 'text', default: '포스코' },
            { id: 5, label: '규격', type: 'text', default: '1.2T x 1219 x 2438' },
            { id: 6, label: '입고수량', type: 'text', default: '50 EA / 2,850 KG' },
            { id: 7, label: '검사일자', type: 'date', default: '2024-10-28' },
            { id: 8, label: '증빙서류', type: 'text', default: '밀시트(O), 거래명세표(O)' }
        ],
        guidelineSections: [
            {
                id: 1,
                title: '원자재 품질 표준 (KS D 3528)',
                image: null,
                items: [
                    { id: 1, category: '겉모양', item: '표면결함', standard: '사용상 해로운 구멍, 슬래그 혼입 등이 없을 것', method: '육안검사', frequency: '전수', regulation: 'KS D 3528' },
                    { id: 2, category: '치수(mm)', item: '두께', standard: '1.2 ± 0.08', method: '마이크로미터', frequency: 'n=3', regulation: 'KS D 3528' },
                    { id: 3, category: '치수(mm)', item: '너비', standard: '1219 +3/-0', method: '줄자', frequency: 'n=3', regulation: 'KS D 3528' }
                ]
            }
        ],
        inspectionColumns: [
            { id: 1, label: 'NO', width: '40px', type: 'text', group: 'ROWSPAN' },
            { id: 2, label: '항목', width: '120px', type: 'text', group: 'ROWSPAN' },
            { id: 3, label: '기준값', width: '150px', type: 'text', group: 'ROWSPAN' },
            { id: 4, label: '측정값 1', width: '100px', type: 'text', group: '측정 결과' },
            { id: 5, label: '측정값 2', width: '100px', type: 'text', group: '측정 결과' },
            { id: 6, label: '측정값 3', width: '100px', type: 'text', group: '측정 결과' },
            { id: 7, label: '판정', width: '80px', type: 'select', group: 'ROWSPAN' }
        ],
        inspectionItems: [],
        footer: {
            remarkLabel: '검사 의견',
            judgementLabel: '종합판정',
            judgementOptions: ['합격', '불합격']
        }
    };

    // 템플릿 기본 구조 (확장됨)
    const defaultTemplate = {
        title: '',
        companyInfo: {
            name: '경동기업',
            address: '',
            contact: ''
        },
        approvalLine: [
            { id: 1, name: '작성', dept: '품질관리', role: '전진' },
            { id: 2, name: '검토', dept: '생산관리', role: '이름' },
            { id: 3, name: '승인', dept: '공장장', role: '이름' }
        ],
        basicFields: [
            { id: 1, label: '품명', type: 'text', default: '' },
            { id: 2, label: '제품 LOT NO', type: 'text', default: '' },
            { id: 3, label: '입고 LOT NO', type: 'text', default: '' },
            { id: 4, label: '규격', type: 'text', default: '' },
            { id: 5, label: '로트크기', type: 'text', default: '' },
            { id: 6, label: '발주처', type: 'text', default: '' },
            { id: 7, label: '검사일자', type: 'date', default: '' },
            { id: 8, label: '현장명', type: 'text', default: '' },
            { id: 9, label: '검사자', type: 'text', default: '' }
        ],
        // [NEW] 복수 기준서 섹션 (가이드레일, 연기차단재 등 구분)
        guidelineSections: [
            {
                id: 1,
                title: '가이드레일 케이스 하단마감재',
                image: null, // URL or Base64
                items: [
                    { id: 1, category: '겉모양', item: '절곡상태', standard: '사용상 해로운 결함이 없을것', method: '육안검사', frequency: '전수', regulation: 'KS F 4510 5.1항' },
                    { id: 2, category: '치수(mm)', item: '길이', standard: '도면치수 ± 4', method: '체크검사', frequency: 'n=1, c=0', regulation: 'KS F 4510 7항' }
                ]
            },
            {
                id: 2,
                title: '연기차단재',
                image: null,
                items: [
                    { id: 1, category: '겉모양', item: '절곡상태', standard: '원단이 프레임에서 빠지지 않을것', method: '육안검사', frequency: '전수', regulation: 'KS F 4510 5.1항' },
                    { id: 2, category: '치수(mm)', item: '너비 ①', standard: 'W50 : 50 ± 5', method: '체크검사', frequency: 'n=1, c=0', regulation: '자체규정' }
                ]
            }
        ],
        // [UPDATE] 컬럼 정의 (서브컬럼 유연화)
        inspectionColumns: [
            { id: 1, label: '분류', width: '50px', type: 'text', group: '', subLabels: [] },
            { id: 2, label: '제품명', width: '100px', type: 'text', group: '', subLabels: [] },
            { id: 3, label: '겉모양', width: '80px', type: 'check', group: '겉모양', subLabels: ['양호', '불량'] }, // check 타입은 내부적으로 2개지만 커스텀 가능하게
            { id: 4, label: '길이', width: '120px', type: 'complex', group: '치수 (mm)', subLabels: ['도면치수', '측정값'] },
            { id: 5, label: '너비', width: '120px', type: 'complex', group: '치수 (mm)', subLabels: ['도면치수', '측정값'] },
            { id: 6, label: '간격', width: '180px', type: 'complex', group: '치수 (mm)', subLabels: ['POINT', '도면치수', '측정값'] },
            { id: 7, label: '판정', width: '80px', type: 'select', group: '', subLabels: [] }
        ],
        inspectionItems: [
            // 실제 데이터 행 (예시)
            { id: 1, values: {} }
        ],
        footer: {
            remarkLabel: '부적합 내용',
            judgementLabel: '종합판정',
            judgementOptions: ['적합', '부적합']
        }
    };

    const [currentTemplate, setCurrentTemplate] = useState(defaultTemplate);
    const [selectedTemplate, setSelectedTemplate] = useState(null);
    const [showPreview, setShowPreview] = useState(false);

    const handleCreate = () => {
        setCurrentTemplate(JSON.parse(JSON.stringify(defaultTemplate))); // Deep copy
        setMode('create');
    };

    const handleEdit = (template) => {
        if (template.type === 'design') {
            setSelectedTemplate(template);
            setMode('designer');
            return;
        }

        // 프리셋 로드 로직
        let newTemplate;
        if (template.name === '수입검사 성적서') {
            newTemplate = JSON.parse(JSON.stringify(IQC_TEMPLATE_PRESET));
        } else {
            newTemplate = JSON.parse(JSON.stringify(defaultTemplate));
            newTemplate.title = template.name;
        }

        setCurrentTemplate(newTemplate);
        setMode('edit');
    };

    const handleImageUpload = (sectionId, e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                setCurrentTemplate(prev => ({
                    ...prev,
                    guidelineSections: prev.guidelineSections.map(s =>
                        s.id === sectionId ? { ...s, image: reader.result } : s
                    )
                }));
            };
            reader.readAsDataURL(file);
        }
    };

    // [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);
    };

    // 공통 입력 필드
    const InputField = ({ label, value, onChange, placeholder, className = '' }) => (
        <div className={`space-y-1 ${className}`}>
            <label className="text-sm font-medium text-gray-700">{safeRender(label)}</label>
            <input
                type="text"
                value={safeRender(value)}
                onChange={(e) => onChange(e.target.value)}
                placeholder={placeholder}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
        </div>
    );

    // 미리보기 모달 (업그레이드: 복합 레이아웃 지원)
    const PreviewModal = ({ template, onClose }) => {
        // 헤더 그룹핑 계산
        const headerGroups = template.inspectionColumns.reduce((acc, col) => {
            const groupName = col.group || 'ROWSPAN';
            if (!acc[groupName]) acc[groupName] = [];
            acc[groupName].push(col);
            return acc;
        }, {});

        // 그룹 순서 유지
        const groupKeys = [];
        template.inspectionColumns.forEach(col => {
            const g = col.group || 'ROWSPAN';
            if (!groupKeys.includes(g)) groupKeys.push(g);
        });

        // 기준서 테이블 RowSpan 계산 함수
        const getRowSpans = (data, key) => {
            const spans = {};
            let currentVal = null;
            let startIndex = 0;
            data.forEach((item, index) => {
                const val = item[key];
                if (val !== currentVal) {
                    currentVal = val;
                    startIndex = index;
                    spans[index] = 1;
                } else {
                    spans[startIndex]++;
                    spans[index] = 0;
                }
            });
            return spans;
        };

        return (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
                <div className="bg-slate-100 w-[1100px] h-[95vh] rounded-xl shadow-2xl flex flex-col overflow-hidden">
                    <div className="bg-white px-6 py-4 border-b flex justify-between items-center">
                        <h3 className="font-bold text-lg">문서 미리보기 (A4 Landscape)</h3>
                        <div className="flex gap-2">
                            <button className="px-3 py-1.5 bg-red-600 text-white rounded-lg text-sm flex items-center gap-1">
                                <FileText size={16} /> PDF 저장
                            </button>
                            <button onClick={onClose} className="ml-2 p-1 hover:bg-gray-100 rounded-full">
                                <X size={20} />
                            </button>
                        </div>
                    </div>

                    <div className="flex-1 overflow-y-auto p-8 flex justify-center bg-gray-500/10">
                        {/* A4 가로 모드 (297mm x 210mm) -> 1122px x 794px */}
                        <div className="bg-white w-[1122px] min-h-[794px] shadow-lg p-10 relative">

                            {/* 1. 헤더 (로고, 제목, 결재라인) */}
                            <div className="flex justify-between items-start mb-8 border-b-2 border-blue-900 pb-4">
                                <div className="flex flex-col">
                                    <div className="text-3xl font-black text-blue-900 mb-2">KD</div>
                                    <div className="text-xs font-bold text-gray-500">경동기업</div>
                                </div>
                                <h1 className="text-4xl font-black text-gray-900 tracking-wider">
                                    {safeRender(template.title) || '검 사 성 적 서'}
                                </h1>
                                <div className="flex border border-black">
                                    <div className="w-6 bg-gray-100 flex items-center justify-center border-r border-black font-bold text-xs p-1 text-center whitespace-pre-wrap">결{"\n"}재</div>
                                    {template.approvalLine.map((app, idx) => (
                                        <div key={idx} className="flex flex-col w-20 border-r border-black last:border-r-0">
                                            <div className="h-6 border-b border-black text-center text-xs flex items-center justify-center bg-gray-50 font-bold">{safeRender(app.name)}</div>
                                            <div className="h-16 border-b border-black text-center text-xs flex items-center justify-center"></div>
                                            <div className="h-6 text-center text-xs flex items-center justify-center bg-gray-50">{safeRender(app.dept)}</div>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* 2. 기본 정보 (2열 테이블) */}
                            <table className="w-full border-collapse border border-black mb-6 text-sm">
                                <tbody>
                                    {template.basicFields.reduce((rows, field, index) => {
                                        if (index % 2 === 0) rows.push([field]);
                                        else rows[rows.length - 1].push(field);
                                        return rows;
                                    }, []).map((row, idx) => (
                                        <tr key={idx}>
                                            {row.map((field, fIdx) => (
                                                <React.Fragment key={fIdx}>
                                                    <td className="border border-black bg-blue-50/50 p-2 text-center font-bold w-[120px]">{safeRender(field.label)}</td>
                                                    <td className="border border-black p-2 font-medium text-blue-900">{safeRender(field.default)}</td>
                                                </React.Fragment>
                                            ))}
                                            {row.length === 1 && <><td className="border border-black bg-blue-50/50"></td><td className="border border-black"></td></>}
                                        </tr>
                                    ))}
                                </tbody>
                            </table>

                            {/* 3. 중간검사 기준서 (다중 섹션 루프) */}
                            {template.guidelineSections.map((section, sIdx) => {
                                const categorySpans = getRowSpans(section.items, 'category');
                                const methodSpans = getRowSpans(section.items, 'method');
                                return (
                                    <div key={sIdx} className="flex border border-black mb-0 border-b-0 last:border-b h-[220px]">
                                        <div className="w-[100px] bg-blue-50/50 border-r border-black flex flex-col items-center justify-center font-bold text-center p-2 text-xs">
                                            <span>{sIdx === 0 ? '중간검사\n기준서' : ''}</span>
                                            <span className="mt-2 text-blue-800">{section.title}</span>
                                        </div>
                                        <div className="flex-1 flex text-xs">
                                            <div className="w-[30%] border-r border-black p-2 flex flex-col">
                                                <div className="text-xs font-bold mb-1 text-gray-500 text-center">- 도해 -</div>
                                                <div className="flex-1 bg-gray-50 flex items-center justify-center overflow-hidden relative">
                                                    {section.image ? (
                                                        <img src={section.image} alt="Guideline" className="absolute inset-0 w-full h-full object-contain" />
                                                    ) : (
                                                        <div className="text-gray-400 text-[10px]">이미지 없음</div>
                                                    )}
                                                </div>
                                            </div>
                                            <div className="w-[70%] overflow-y-auto">
                                                <table className="w-full border-collapse h-full">
                                                    <thead className="bg-gray-100 sticky top-0 z-10">
                                                        <tr>
                                                            <th className="border border-black p-0.5">구분</th>
                                                            <th className="border border-black p-0.5">검사항목</th>
                                                            <th className="border border-black p-0.5">검사기준</th>
                                                            <th className="border border-black p-0.5 w-12">방법</th>
                                                            <th className="border border-black p-0.5 w-10">주기</th>
                                                            <th className="border border-black p-0.5 w-16">관련규정</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {section.items.map((g, i) => (
                                                            <tr key={i}>
                                                                {categorySpans[i] > 0 ? (
                                                                    <td rowSpan={categorySpans[i]} className="border border-black p-1 text-center font-bold bg-white align-middle">{safeRender(g.category)}</td>
                                                                ) : categorySpans[i] === 0 ? null : <td className="border border-black p-1">{safeRender(g.category)}</td>}

                                                                <td className="border border-black p-1 text-center">{safeRender(g.item)}</td>
                                                                <td className="border border-black p-1 text-center">{safeRender(g.standard)}</td>

                                                                {methodSpans[i] > 0 ? (
                                                                    <td rowSpan={methodSpans[i]} className="border border-black p-1 text-center align-middle">{safeRender(g.method)}</td>
                                                                ) : methodSpans[i] === 0 ? null : <td className="border border-black p-1">{safeRender(g.method)}</td>}

                                                                <td className="border border-black p-1 text-center">{safeRender(g.frequency)}</td>
                                                                <td className="border border-black p-1 text-center">{safeRender(g.regulation)}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}

                            <div className="mb-4"></div>

                            {/* 4. 중간검사 DATA (복합 테이블) */}
                            <div className="mb-2 font-bold text-center bg-blue-100 py-1 border border-black border-b-0">중간검사 DATA</div>
                            <table className="w-full border-collapse border border-black mb-6 text-sm text-center">
                                <thead className="bg-blue-50">
                                    {/* 1행: 그룹 헤더 */}
                                    <tr>
                                        {groupKeys.map(groupName => {
                                            const cols = headerGroups[groupName];
                                            // 복잡한 colspan 계산: 각 컬럼의 subLabels 개수 합산. 없으면 1.
                                            let totalSpan = 0;
                                            cols.forEach(c => {
                                                totalSpan += (c.subLabels && c.subLabels.length > 0) ? c.subLabels.length : 1;
                                            });

                                            if (groupName === 'ROWSPAN') {
                                                return cols.map(c => {
                                                    const span = (c.subLabels && c.subLabels.length > 0) ? c.subLabels.length : 1;
                                                    return <th key={c.id} colSpan={span} rowSpan={2} className="border border-black p-1">{safeRender(c.label)}</th>;
                                                });
                                            }
                                            return (
                                                <th key={groupName} colSpan={totalSpan} className="border border-black p-1 font-bold">
                                                    {safeRender(groupName)}
                                                </th>
                                            );
                                        })}
                                    </tr>
                                    {/* 2행: 컬럼명 (그룹 하위) */}
                                    <tr>
                                        {groupKeys.map(groupName => {
                                            if (groupName === 'ROWSPAN') return null;
                                            return headerGroups[groupName].map(col => {
                                                const span = (col.subLabels && col.subLabels.length > 0) ? col.subLabels.length : 1;
                                                return <th key={col.id} colSpan={span} className="border border-black p-1">{safeRender(col.label)}</th>;
                                            });
                                        })}
                                    </tr>
                                    {/* 3행: 서브라벨 (있을 경우만) - 서브라벨이 하나라도 있는 경우만 렌더링 */}
                                    {template.inspectionColumns.some(c => c.subLabels && c.subLabels.length > 0) && (
                                        <tr>
                                            {template.inspectionColumns.map(col => {
                                                if (col.subLabels && col.subLabels.length > 0) {
                                                    return col.subLabels.map((sl, idx) => (
                                                        <th key={`${col.id}-${idx}`} className="border border-black p-1 bg-white font-normal text-gray-600 text-xs text-center">{safeRender(sl)}</th>
                                                    ));
                                                }
                                                // subLabels가 없는 경우, 위에서 rowspan 처리되지 않았다면 빈 셀을 채워야 하지만
                                                // 현재 로직상 2행까지만 처리됨. subLabel이 있으면 3행이 생기는데, 없는 컬럼은 3행에서 어떻게?
                                                // 해결책: 로직이 복잡해지므로, subLabel이 없는 컬럼은 앞선 행에서 rowspan을 늘려야 함.
                                                // 하지만 여기서 간단히 빈 셀로 채움 (임시)
                                                return null;
                                                // TODO: 완벽한 3단 헤더를 위해서는 reduce 단계에서 rowspan 계산이 필요함.
                                                // 일단 'complex' 타입이 있는 경우만 3행이 그려지므로, 일반 text 타입은 비어보일 수 있음.
                                                // 개선: subLabel 없는 애들은 2행에서 rowspan=2 줬어야 했음.
                                            })}
                                        </tr>
                                    )}
                                </thead>
                                <tbody>
                                    {[1, 2, 3, 4, 5].map((rowId) => (
                                        <tr key={rowId}>
                                            {template.inspectionColumns.map(col => {
                                                if (col.type === 'measurement') {
                                                    // [Logic] 모든 섹션의 아이템을 뒤져서 매칭
                                                    const allGuidelines = template.guidelineSections.flatMap(s => s.items);
                                                    const matchedGuideline = allGuidelines.find(g => col.label.includes(g.item) || g.item.includes(col.label));
                                                    const standardValue = matchedGuideline ? matchedGuideline.standard : '';

                                                    return (
                                                        <React.Fragment key={col.id}>
                                                            <td className="border border-black p-2 text-blue-600 font-bold bg-gray-50/30 text-xs">
                                                                {standardValue}
                                                            </td>
                                                            <td className="border border-black p-2 bg-white"></td>
                                                            {/* 만약 subLabels가 3개 이상이면 추가 td 렌더링 필요 */}
                                                            {col.subLabels && col.subLabels.length > 2 && (
                                                                <td className="border border-black p-2 bg-white"></td>
                                                            )}
                                                        </React.Fragment>
                                                    );
                                                }
                                                if (col.type === 'complex') {
                                                    // 복합형 렌더링 (서브라벨 개수만큼 칸 생성)
                                                    const allGuidelines = template.guidelineSections.flatMap(s => s.items);
                                                    const matchedGuideline = allGuidelines.find(g => col.label.includes(g.item) || g.item.includes(col.label));

                                                    return col.subLabels.map((sl, sIdx) => {
                                                        // 기준 텍스트 자동 채움 (서브라벨이 '기준','도면','Standard' 등을 포함하면)
                                                        if (['기준', '도면', 'Standard'].some(k => sl.includes(k)) && matchedGuideline) {
                                                            return <td key={sIdx} className="border border-black p-2 text-blue-600 font-bold bg-gray-50/30 text-xs">{safeRender(matchedGuideline.standard)}</td>
                                                        }
                                                        return <td key={sIdx} className="border border-black p-2 bg-white"></td>
                                                    });
                                                }
                                                if (col.label === 'NO') return <td key={col.id} className="border border-black p-2 text-center bg-white">{rowId}</td>
                                                if (col.type === 'check') return <td key={col.id} className="border border-black p-2 text-xs bg-white">⬜ 양호 &nbsp; ⬜ 불량</td>
                                                return <td key={col.id} className="border border-black p-2 bg-white"></td>
                                            })}
                                        </tr>
                                    ))}
                                </tbody>
                            </table>

                            {/* 5. 비고 및 종합판정 */}
                            <div className="flex border border-black min-h-24">
                                <div className="w-[120px] bg-gray-100 border-r border-black p-2 text-center font-bold flex flex-col justify-center">
                                    <span>[부적합 내용]</span>
                                </div>
                                <div className="flex-1 p-2 border-r border-black flex flex-col justify-between">
                                    <div className="text-gray-400 text-sm">특이사항을 입력하세요</div>
                                </div>
                                <div className="w-[150px] flex flex-col">
                                    <div className="h-8 bg-yellow-300 border-b border-black flex items-center justify-center font-bold">
                                        종합 판정
                                    </div>
                                    <div className="flex-1 flex items-center justify-center flex-col gap-2 p-2 bg-white">
                                        <div className="flex items-center gap-2">
                                            <div className="w-4 h-4 border border-black"></div> 적합
                                        </div>
                                        <div className="flex items-center gap-2">
                                            <div className="w-4 h-4 border border-black"></div> 부적합
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* 페이지 번호 (Footer) */}
                            <div className="mt-8 flex justify-between text-xs font-bold text-gray-500 font-mono">
                                <div>KDQP-01-008</div>
                                <div>KDPS-01-01</div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        );
    };

    // ... (리스트 모드, 모달 렌더링 유지)
    // 디자이너 모드 렌더링
    if (mode === 'designer') {
        const handleDesignerBack = () => {
            // Refresh templates from localStorage
            const saved = localStorage.getItem('docTemplates');
            if (saved) setTemplates(JSON.parse(saved));
            setMode('list');
        };
        return <DocumentDesigner initialTemplate={selectedTemplate} onBack={handleDesignerBack} />;
    }

    if (mode === 'list') {
        // 기존 리스트 뷰 코드 유지
        return (
            <div className="space-y-6">
                {/* 헤더 - 타이틀/버튼 분리 */}
                <div className="space-y-3">
                    <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                        <FileText className="w-6 h-6 text-blue-500" />
                        문서양식 목록
                    </h1>
                    <div className="flex items-center justify-end gap-2">
                        <button
                            onClick={() => setMode('designer')}
                            className="flex items-center gap-2 px-4 py-2 bg-black text-white rounded-lg hover:bg-gray-800 transition-colors"
                        >
                            <Plus size={16} />
                            문서양식 등록
                        </button>
                        <button
                            onClick={handleCreate}
                            className="flex items-center gap-2 px-4 py-2 border rounded-lg hover:bg-gray-50 transition-colors"
                        >
                            <Layout size={16} />
                            기본 양식 만들기
                        </button>
                    </div>
                </div>
                {/* 템플릿 목록 */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {templates.map(template => (
                        <div key={template.id} className="bg-white rounded-xl border border-gray-200 p-6 hover:shadow-md transition-shadow">
                            <div className="flex justify-between items-start mb-4">
                                <div className={`px-2 py-1 rounded text-xs font-medium ${template.category === '품질' ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'}`}>
                                    {template.category}
                                </div>
                                <button className="text-gray-400 hover:text-red-500">
                                    <Trash2 size={16} />
                                </button>
                            </div>
                            <h3 className="text-lg font-bold text-gray-900 mb-2">{safeRender(template.name)}</h3>
                            <p className="text-sm text-gray-500 mb-4">최종 수정일: {safeRender(template.updatedAt)}</p>
                            <div className="flex gap-2">
                                <button onClick={() => handleEdit(template)} className="flex-1 py-2 text-sm text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors">편집</button>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {/* 헤더 */}
            <div className="flex justify-between items-center bg-white p-4 rounded-xl border border-gray-200 sticky top-0 z-10 shadow-sm">
                <div className="flex items-center gap-4">
                    <button onClick={() => setMode('list')} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
                        <ArrowLeft size={20} className="text-gray-600" />
                    </button>
                    <h2 className="text-xl font-bold text-gray-900">
                        {safeRender(currentTemplate.title) || '새 양식'} 편집
                    </h2>
                </div>
                <div className="flex gap-2">
                    <button onClick={() => setShowPreview(true)} className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                        <Eye size={16} /> 미리보기
                    </button>
                    <button className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                        <Save size={16} /> 저장
                    </button>
                </div>
            </div>

            <div className="grid grid-cols-12 gap-6 pb-20">
                {/* 왼쪽 메인 설정 영역 */}
                <div className="col-span-12 lg:col-span-8 space-y-6">

                    {/* 1. 기본 정보 */}
                    <section className="bg-white rounded-xl border border-gray-200 p-6">
                        <h3 className="text-lg font-bold text-gray-900 mb-4">1. 문서 기본 정보</h3>
                        <div className="grid grid-cols-2 gap-4">
                            <InputField label="문서 제목" value={safeRender(currentTemplate.title)} onChange={(v) => setCurrentTemplate(p => ({ ...p, title: v }))} />
                            <InputField label="회사명" value={safeRender(currentTemplate.companyInfo.name)} onChange={(v) => setCurrentTemplate(p => ({ ...p, companyInfo: { ...p.companyInfo, name: v } }))} />
                        </div>
                    </section>

                    {/* 2. 검사 기준서 설정 (멀티 섹션) */}
                    <section className="bg-white rounded-xl border border-gray-200 p-6">
                        <div className="flex justify-between items-center mb-4">
                            <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                                <span>2. 검사 기준서 및 도해</span>
                            </h3>
                            <button className="text-sm bg-blue-100 text-blue-600 px-3 py-1 rounded hover:bg-blue-200"
                                onClick={() => {
                                    setCurrentTemplate(p => ({
                                        ...p,
                                        guidelineSections: [...p.guidelineSections, {
                                            id: Date.now(), title: '새 섹션', image: null, items: []
                                        }]
                                    }))
                                }}
                            >+ 섹션 추가</button>
                        </div>

                        <div className="space-y-8">
                            {currentTemplate.guidelineSections.map((section, sIdx) => (
                                <div key={section.id} className="border border-gray-200 rounded-lg p-4 bg-gray-50">
                                    <div className="flex justify-between mb-2">
                                        <input
                                            type="text"
                                            value={section.title}
                                            onChange={(e) => {
                                                const newSec = [...currentTemplate.guidelineSections];
                                                newSec[sIdx].title = e.target.value;
                                                setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                            }}
                                            className="font-bold text-lg bg-transparent border-b border-dashed border-gray-400 focus:outline-none w-1/2"
                                            placeholder="섹션 제목 (예: 가이드레일)"
                                        />
                                        <button className="text-red-400 hover:text-red-600"
                                            onClick={() => {
                                                const newSec = currentTemplate.guidelineSections.filter((_, i) => i !== sIdx);
                                                setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                            }}
                                        >삭제</button>
                                    </div>

                                    <div className="flex gap-6">
                                        {/* 이미지 업로드 */}
                                        <div className="w-1/3">
                                            <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 h-40 flex flex-col items-center justify-center bg-white hover:bg-gray-50 transition-colors relative cursor-pointer">
                                                <input type="file" accept="image/*" onChange={(e) => handleImageUpload(section.id, e)} className="absolute inset-0 opacity-0 cursor-pointer" />
                                                {section.image ? (
                                                    <img src={section.image} alt="Preview" className="max-h-full object-contain" />
                                                ) : (
                                                    <>
                                                        <Plus className="text-gray-400 mb-2" />
                                                        <span className="text-sm text-gray-500">도해 이미지</span>
                                                    </>
                                                )}
                                            </div>
                                        </div>

                                        {/* 기준 항목 리스트 */}
                                        <div className="flex-1">
                                            <div className="border rounded-lg overflow-hidden bg-white">
                                                <table className="w-full text-xs">
                                                    <thead className="bg-gray-100">
                                                        <tr>
                                                            <th className="p-1 w-16 text-center">Cat</th>
                                                            <th className="p-1">항목</th>
                                                            <th className="p-1">기준</th>
                                                            <th className="p-1 w-16">방법</th>
                                                            <th className="p-1 w-12">주기</th>
                                                            <th className="p-1 w-20">규정</th>
                                                            <th className="p-1 w-8"></th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {section.items.map((g, iIdx) => (
                                                            <tr key={iIdx} className="border-b">
                                                                <td className="p-1"><input type="text" value={g.category} onChange={(e) => {
                                                                    const newSec = [...currentTemplate.guidelineSections];
                                                                    newSec[sIdx].items[iIdx].category = e.target.value;
                                                                    setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                }} className="w-full border rounded px-1" /></td>
                                                                <td className="p-1"><input type="text" value={g.item} onChange={(e) => {
                                                                    const newSec = [...currentTemplate.guidelineSections];
                                                                    newSec[sIdx].items[iIdx].item = e.target.value;
                                                                    setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                }} className="w-full border rounded px-1" /></td>
                                                                <td className="p-1"><input type="text" value={g.standard} onChange={(e) => {
                                                                    const newSec = [...currentTemplate.guidelineSections];
                                                                    newSec[sIdx].items[iIdx].standard = e.target.value;
                                                                    setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                }} className="w-full border rounded px-1" /></td>
                                                                <td className="p-1"><input type="text" value={g.method} onChange={(e) => {
                                                                    const newSec = [...currentTemplate.guidelineSections];
                                                                    newSec[sIdx].items[iIdx].method = e.target.value;
                                                                    setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                }} className="w-full border rounded px-1" /></td>
                                                                <td className="p-1"><input type="text" value={g.frequency} placeholder="전수" onChange={(e) => {
                                                                    const newSec = [...currentTemplate.guidelineSections];
                                                                    newSec[sIdx].items[iIdx].frequency = e.target.value;
                                                                    setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                }} className="w-full border rounded px-1" /></td>
                                                                <td className="p-1"><input type="text" value={g.regulation} placeholder="규정" onChange={(e) => {
                                                                    const newSec = [...currentTemplate.guidelineSections];
                                                                    newSec[sIdx].items[iIdx].regulation = e.target.value;
                                                                    setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                }} className="w-full border rounded px-1" /></td>
                                                                <td className="p-1 text-center">
                                                                    <button className="text-gray-400 hover:text-red-500" onClick={() => {
                                                                        const newSec = [...currentTemplate.guidelineSections];
                                                                        newSec[sIdx].items = newSec[sIdx].items.filter((_, idx) => idx !== iIdx);
                                                                        setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                    }}><Trash2 size={12} /></button>
                                                                </td>
                                                            </tr>
                                                        ))}
                                                        <tr>
                                                            <td colSpan={7} className="p-1 text-center bg-blue-50 text-blue-500 cursor-pointer hover:bg-blue-100 text-xs font-bold"
                                                                onClick={() => {
                                                                    const newSec = [...currentTemplate.guidelineSections];
                                                                    newSec[sIdx].items.push({ id: Date.now(), category: '', item: '', standard: '', method: '', frequency: '', regulation: '' });
                                                                    setCurrentTemplate(p => ({ ...p, guidelineSections: newSec }));
                                                                }}
                                                            >+ 항목 추가</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </section>

                    {/* 3. 테이블 컬럼 설정 (업그레이드) */}
                    <section className="bg-white rounded-xl border border-gray-200 p-6">
                        <h3 className="text-lg font-bold text-gray-900 mb-4">3. 검사 데이터 테이블 구성</h3>
                        <p className="text-sm text-gray-500 mb-4">측정값이 필요한 항목은 '측정형(Measurement)' 타입을 선택하세요. 자동으로 기준/측정값 컬럼이 생성됩니다.</p>

                        <div className="space-y-3">
                            {currentTemplate.inspectionColumns.map((col, idx) => (
                                <div key={col.id} className="flex items-center gap-2 bg-gray-50 p-3 rounded-lg border border-gray-200">
                                    <div className="flex flex-col items-center gap-1 mr-2">
                                        <button className="text-gray-400 hover:text-blue-600 disabled:opacity-30" disabled={idx === 0}
                                            onClick={() => {
                                                const newCols = [...currentTemplate.inspectionColumns];
                                                [newCols[idx - 1], newCols[idx]] = [newCols[idx], newCols[idx - 1]];
                                                setCurrentTemplate(p => ({ ...p, inspectionColumns: newCols }));
                                            }}
                                        ><ChevronUp size={16} /></button>
                                        <span className="w-6 h-6 rounded bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-bold">{idx + 1}</span>
                                        <button className="text-gray-400 hover:text-blue-600 disabled:opacity-30" disabled={idx === currentTemplate.inspectionColumns.length - 1}
                                            onClick={() => {
                                                const newCols = [...currentTemplate.inspectionColumns];
                                                [newCols[idx + 1], newCols[idx]] = [newCols[idx], newCols[idx + 1]];
                                                setCurrentTemplate(p => ({ ...p, inspectionColumns: newCols }));
                                            }}
                                        ><ChevronDown size={16} /></button>
                                    </div>

                                    <div className="flex-1 grid grid-cols-4 gap-2">
                                        <div className="col-span-1">
                                            <label className="text-xs text-gray-500 block">그룹명(상단헤더)</label>
                                            <input type="text" value={col.group || ''} placeholder="없음" className="w-full text-sm border rounded px-2 py-1"
                                                onChange={(e) => {
                                                    const newCols = [...currentTemplate.inspectionColumns];
                                                    newCols[idx].group = e.target.value;
                                                    setCurrentTemplate(p => ({ ...p, inspectionColumns: newCols }));
                                                }}
                                            />
                                        </div>
                                        <div className="col-span-1">
                                            <label className="text-xs text-gray-500 block">컬럼명</label>
                                            <input type="text" value={col.label} className="w-full text-sm border rounded px-2 py-1 font-bold"
                                                onChange={(e) => {
                                                    const newCols = [...currentTemplate.inspectionColumns];
                                                    newCols[idx].label = e.target.value;
                                                    setCurrentTemplate(p => ({ ...p, inspectionColumns: newCols }));
                                                }}
                                            />
                                        </div>
                                        <div className="col-span-1">
                                            <label className="text-xs text-gray-500 block">타입</label>
                                            <select value={col.type} className="w-full text-sm border rounded px-2 py-1"
                                                onChange={(e) => {
                                                    const newCols = [...currentTemplate.inspectionColumns];
                                                    newCols[idx].type = e.target.value;
                                                    setCurrentTemplate(p => ({ ...p, inspectionColumns: newCols }));
                                                }}
                                            >
                                                <option value="text">일반 텍스트</option>
                                                <option value="check">체크박스 (양호/불량)</option>
                                                <option value="measurement">측정형 (기준/측정값)</option>
                                                <option value="select">선택 (판정)</option>
                                            </select>
                                        </div>
                                        <div className="col-span-1">
                                            <label className="text-xs text-gray-500 block">너비</label>
                                            <input type="text" value={col.width} className="w-full text-sm border rounded px-2 py-1" />
                                        </div>
                                    </div>

                                    <button className="text-gray-400 hover:text-red-500 p-2" onClick={() => {
                                        const newCols = currentTemplate.inspectionColumns.filter((_, i) => i !== idx);
                                        setCurrentTemplate(p => ({ ...p, inspectionColumns: newCols }));
                                    }}>
                                        <Trash2 size={16} />
                                    </button>
                                </div>
                            ))}
                            <button className="w-full py-3 border-2 border-dashed border-gray-300 rounded-lg text-gray-500 font-medium hover:bg-gray-50 transition-colors"
                                onClick={() => {
                                    setCurrentTemplate(p => ({
                                        ...p,
                                        inspectionColumns: [...p.inspectionColumns, { id: Date.now(), label: '새 항목', width: '100px', type: 'text', group: '' }]
                                    }));
                                }}
                            >
                                + 새 검사 컬럼 추가
                            </button>
                        </div>
                    </section>
                </div>

                {/* 오른쪽 상태 패널 */}
                <div className="col-span-12 lg:col-span-4 space-y-6">
                    <div className="bg-blue-50/50 rounded-xl border border-blue-100 p-6 sticky top-24">
                        <h3 className="font-bold text-blue-900 mb-4 flex items-center gap-2">
                            <Settings size={18} /> 설정 가이드
                        </h3>
                        <div className="space-y-4 text-sm text-blue-800">
                            <p>
                                <strong>1. 도해 이미지:</strong><br />
                                검사 기준서에 삽입될 도면이나 참고 사진을 업로드하세요.
                            </p>
                            <p>
                                <strong>2. 측정형 컬럼:</strong><br />
                                '치수'와 같이 기준값과 실제 측정값이 모두 필요한 경우
                                <u>타입을 '측정형'으로 선택</u>하세요. 미리보기 시 자동으로 2개 열로 분할됩니다.
                            </p>
                            <p>
                                <strong>3. 헤더 그룹핑:</strong><br />
                                '그룹명'을 동일하게 입력하면 상단 헤더가 자동으로 병합됩니다.<br />
                                <em>예) ①높이, ②길이 컬럼의 그룹명을 모두 '치수(mm)'로 입력</em>
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            {showPreview && <PreviewModal template={currentTemplate} onClose={() => setShowPreview(false)} />}
        </div>
    );
};

export default DocumentTemplateManager;
