// Version: 2.11.57 (Local Template Requisites)
var { useState, useRef, useEffect, useMemo } = React;

const { CheckCircle, AlertTriangle, ArrowLeft, Save, Move, Maximize2, Trash2, Plus, Layout, ChevronUp, ChevronDown, Copy, Loader, Download, ExternalLink, Cloud, UploadCloud, FileText, Send, Search } = window;

// Fallbacks для безопасности
const SafeArrowLeft = ArrowLeft || (({size, className}) => <span className={className} style={{fontSize: size, display: 'inline-block'}}>←</span>);
const SafeMove = Move || (({size, className}) => <span className={className} style={{fontSize: size, display: 'inline-block'}}>✥</span>);
const SafeMaximize2 = Maximize2 || (({size, className}) => <span className={className} style={{fontSize: size, display: 'inline-block'}}>⤡</span>);
const SafeCloud = Cloud || (({size, className}) => <span className={className} style={{fontSize: size, display: 'inline-block'}}>☁</span>);
const SafeUploadCloud = UploadCloud || (({size, className}) => <span className={className} style={{fontSize: size, display: 'inline-block'}}>☁↑</span>);
const SendIcon = Send || Download || (({size, className}) => <span className={className} style={{fontSize: size, display: 'inline-block'}}>➤</span>);

const GRID_SIZE = 20;

window.FurnitureEditor = ({ user, initialProject, onBack }) => {
    const getAutoNumber = () => {
        const today = new Date();
        const dd = String(today.getDate()).padStart(2, '0');
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        return `МЕБ-${dd}/${mm}-`;
    };

    const getSavedSeller = () => {
        try {
            const saved = localStorage.getItem('savedSellerRequisites');
            if (saved) return JSON.parse(saved);
        } catch(e) {}
        return { name: '', inn: '', kpp: '', ogrn: '', account: '', bank: '', bik: '', corr: '', phone: '', site: '', email: '', directorTitle: '', directorName: '', managerName: '', managerPhone: '' };
    };

    const [project, setProject] = useState(initialProject || { name: 'Новое Мебельное КП', data: {} });
    const [clientName, setClientName] = useState(initialProject?.data?.clientName || getAutoNumber());
    const [clientDate, setClientDate] = useState(new Date().toISOString().split('T')[0]);
    const [currentProjectId, setCurrentProjectId] = useState(initialProject?.id || null);

    // Обратная совместимость
    const [showBaseRequisites, setShowBaseRequisites] = useState(() => {
        if (initialProject?.data?.showBaseRequisites !== undefined) return initialProject.data.showBaseRequisites;
        const hasData = initialProject?.data?.requisites && (initialProject.data.requisites.seller.inn || initialProject.data.requisites.buyer.company);
        return initialProject?.data?.showRequisites && !hasData ? true : false;
    });

    const [showFullRequisites, setShowFullRequisites] = useState(() => {
        if (initialProject?.data?.showFullRequisites !== undefined) return initialProject.data.showFullRequisites;
        const hasData = initialProject?.data?.requisites && (initialProject.data.requisites.seller.inn || initialProject.data.requisites.buyer.company);
        return initialProject?.data?.showRequisites && hasData ? true : false;
    });

    const [requisites, setRequisites] = useState(() => {
        if (initialProject?.data?.requisites) return initialProject.data.requisites;
        return {
            seller: getSavedSeller(),
            buyer: { targetTitle: '', company: '', targetName: '' }
        };
    });

    // --- TABS & EXPORT STATE ---
    const [activeTab, setActiveTab] = useState('canvas'); 
    const [isPdf, setIsPdf] = useState(false);
    
    // --- EXPORT TOGGLES ---
    const [exportCanvas, setExportCanvas] = useState(true);
    const [exportTable, setExportTable] = useState(true);
    
    // --- TOOLBAR STATE ---
    const [saving, setSaving] = useState(false);
    const [sendingTg, setSendingTg] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

    // --- CANVAS SETTINGS ---
    const [showGrid, setShowGrid] = useState(true);
    const [snapToGrid, setSnapToGrid] = useState(true);
    const [orientation, setOrientation] = useState('portrait'); 
    const canvasRef = useRef(null);

    const canvasWidth = orientation === 'portrait' ? 794 : 1123;
    const canvasMinHeight = orientation === 'portrait' ? 1110 : 780;

    const [toast, setToast] = useState({ show: false, message: '', type: 'success' });
    
    const showToast = (message, type = 'success') => {
        setToast({ show: true, message, type });
        setTimeout(() => setToast({ show: false, message: '', type: 'success' }), 4000);
    };

    useEffect(() => {
        if (window.loadPdfLibrary) {
            window.loadPdfLibrary().catch(e => console.error("Ошибка загрузки PDF", e));
        }
    }, []);

    // --- CANVAS DATA ---
    const [sketches, setSketches] = useState([]);
    const [draggingImageId, setDraggingImageId] = useState(null);
    const [dragStart, setDragStart] = useState({ mouseX: 0, mouseY: 0, imageX: 0, imageY: 0 });
    const [resizingImageId, setResizingImageId] = useState(null);
    const [resizeStart, setResizeStart] = useState({ scale: 1, x: 0, y: 0, baseWidth: 100, startX: 0 });

    // --- TABLE (СМЕТА) DATA ---
    const [items, setItems] = useState([{ id: Date.now(), type: 'item', title: '', price: 0, quantity: 1, finalPrice: 0, link: '' }]);

    const isManagerOrHigher = user?.is_vip || user?.tier === 'speed' || user?.tier === 'manager';
    const isSpeedOrVip = user?.is_vip || user?.tier === 'speed';
    const canUseLinks = isManagerOrHigher;
    const isExporting = isPdf;

    const isInitialMount = useRef(true);
    useEffect(() => {
        if (isInitialMount.current) isInitialMount.current = false;
        else setHasUnsavedChanges(true);
    }, [items, clientName, clientDate, sketches, orientation, showBaseRequisites, showFullRequisites, requisites]);

    useEffect(() => {
        if (initialProject && initialProject.data) {
            setCurrentProjectId(initialProject.id);
            if (initialProject.data.clientName !== undefined) setClientName(initialProject.data.clientName);
            if (initialProject.data.clientDate) setClientDate(initialProject.data.clientDate);
            if (initialProject.data.sketches) setSketches(initialProject.data.sketches);
            if (initialProject.data.orientation) setOrientation(initialProject.data.orientation);
            if (initialProject.data.items) setItems(initialProject.data.items);
            
            if (initialProject.data.showBaseRequisites !== undefined) setShowBaseRequisites(initialProject.data.showBaseRequisites);
            if (initialProject.data.showFullRequisites !== undefined) setShowFullRequisites(initialProject.data.showFullRequisites);
            
            if (initialProject.data.showBaseRequisites === undefined && initialProject.data.showFullRequisites === undefined && initialProject.data.showRequisites !== undefined) {
                const hasData = initialProject.data.requisites && (initialProject.data.requisites.seller.inn || initialProject.data.requisites.buyer.company);
                if (hasData) setShowFullRequisites(initialProject.data.showRequisites);
                else setShowBaseRequisites(initialProject.data.showRequisites);
            }

            if (initialProject.data.requisites) setRequisites(initialProject.data.requisites);
            
            setTimeout(() => setHasUnsavedChanges(false), 100);
        }
    }, [initialProject]);

    useEffect(() => {
        document.querySelectorAll('.sketch-textarea').forEach(el => {
            el.style.height = 'auto';
            el.style.height = el.scrollHeight + 'px';
        });
    }, [sketches, isExporting]);

    const handleBackClick = () => {
        if (hasUnsavedChanges) {
            if (!confirm("У вас есть несохраненные изменения. Выйти без сохранения?")) return;
        }
        onBack();
    };

    const getFormattedDateForPrint = () => { 
        if (!clientDate) return ''; 
        const parts = clientDate.split('-'); 
        if (parts.length === 3) return `${parts[2]}.${parts[1]}.${parts[0]}`; 
        return clientDate; 
    };

    const setReqField = (section, field, value) => {
        setRequisites(prev => ({
            ...prev,
            [section]: {
                ...prev[section],
                [field]: value
            }
        }));
    };

    const saveSellerToLocal = () => {
        try {
            localStorage.setItem('savedSellerRequisites', JSON.stringify(requisites.seller));
            showToast('Реквизиты продавца успешно сохранены как шаблон!');
        } catch (e) {
            showToast('Ошибка сохранения шаблона', 'error');
        }
    };

    const handleAddImages = (files, startX = 40, startY = 220) => {
        Array.from(files).forEach((file, index) => {
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = async (event) => {
                    let res = event.target.result;
                    if (window.compressImage) {
                        res = await window.compressImage(res, 1500, 0.85);
                    }
                    
                    let safeX = Math.max(0, Math.min(startX + (index * 40), canvasWidth - 100));
                    let safeY = Math.max(0, Math.min(startY + (index * 40), canvasMinHeight - 100));

                    setSketches(prev => [...prev, {
                        id: Date.now() + index + Math.random(),
                        type: 'image',
                        url: res,
                        scale: 1,
                        x: safeX,
                        y: safeY
                    }]);
                };
                reader.readAsDataURL(file);
            }
        });
    };

    const handleAddText = () => {
        let safeX = Math.max(0, Math.min(40, canvasWidth - 100));
        let safeY = Math.max(0, Math.min(220, canvasMinHeight - 100));
        setSketches(prev => [...prev, {
            id: Date.now() + Math.random(),
            type: 'text',
            text: 'Введите текст...',
            scale: 1, 
            width: 250, 
            fontSize: 16, 
            x: safeX,
            y: safeY
        }]);
    };

    const handleFontSize = (e, id, delta) => {
        e.preventDefault();
        e.stopPropagation();
        setSketches(prev => prev.map(s => {
            if (s.id === id && s.type === 'text') {
                const currentSize = s.fontSize || 16;
                const newSize = Math.max(8, Math.min(120, currentSize + delta * 2));
                return { ...s, fontSize: newSize };
            }
            return s;
        }));
    };

    const handleFileInput = (e) => { handleAddImages(e.target.files, 40, 220); e.target.value = ''; };

    const handleCanvasDrop = (e) => {
        if (isExporting) return;
        e.preventDefault(); e.stopPropagation();
        if (!canvasRef.current) return;
        const rect = canvasRef.current.getBoundingClientRect();
        let dropX = e.clientX - rect.left;
        let dropY = e.clientY - rect.top;
        
        if (snapToGrid) {
            dropX = Math.round(dropX / GRID_SIZE) * GRID_SIZE;
            dropY = Math.round(dropY / GRID_SIZE) * GRID_SIZE;
        }

        dropX = Math.max(0, Math.min(dropX, canvasWidth - 100));
        dropY = Math.max(0, Math.min(dropY, canvasMinHeight - 100));

        handleAddImages(e.dataTransfer.files, dropX, dropY);
    };

    const handleDragOver = (e) => { if (!isExporting) { e.preventDefault(); e.stopPropagation(); } };
    const handleRemoveSketch = (id) => { setSketches(prev => prev.filter(s => s.id !== id)); };

    const handleMouseDownPan = (e, sketch) => {
        if (isExporting) return;
        e.preventDefault(); e.stopPropagation(); 
        setDraggingImageId(sketch.id);
        setDragStart({ mouseX: e.clientX, mouseY: e.clientY, imageX: sketch.x, imageY: sketch.y });
    };

    const handleMouseDownResize = (e, sketch) => {
        if (isExporting) return;
        e.preventDefault(); e.stopPropagation(); 
        
        const targetElement = e.currentTarget.parentElement.querySelector('.resize-target');
        const rect = targetElement ? targetElement.getBoundingClientRect() : { width: 100 };
        const currentScale = sketch.type === 'text' ? 1 : sketch.scale;
        const baseWidth = rect.width / currentScale;

        setResizingImageId(sketch.id);
        setResizeStart({ 
            x: e.clientX, 
            y: e.clientY, 
            scale: currentScale,
            baseWidth: baseWidth > 0 ? baseWidth : 100,
            startX: sketch.x
        });
    };

    useEffect(() => {
        const handleGlobalMouseMove = (e) => {
            if (draggingImageId) {
                const deltaX = e.clientX - dragStart.mouseX;
                const deltaY = e.clientY - dragStart.mouseY;
                let newX = dragStart.imageX + deltaX;
                let newY = dragStart.imageY + deltaY;
                
                if (snapToGrid) {
                    newX = Math.round(newX / GRID_SIZE) * GRID_SIZE;
                    newY = Math.round(newY / GRID_SIZE) * GRID_SIZE;
                }

                newX = Math.max(0, Math.min(newX, canvasWidth - 100));
                newY = Math.max(0, Math.min(newY, canvasMinHeight - 100));

                setSketches(prev => prev.map(s => s.id === draggingImageId ? { ...s, x: newX, y: newY } : s));
            } else if (resizingImageId) {
                const deltaX = e.clientX - resizeStart.x;
                
                setSketches(prev => prev.map(s => {
                    if (s.id === resizingImageId) {
                        if (s.type === 'text') {
                            let newWidth = resizeStart.baseWidth + deltaX;
                            if (snapToGrid) {
                                const expectedRightEdge = resizeStart.startX + newWidth;
                                const snappedRightEdge = Math.round(expectedRightEdge / GRID_SIZE) * GRID_SIZE;
                                newWidth = snappedRightEdge - resizeStart.startX;
                            }
                            newWidth = Math.max(100, newWidth);
                            return { ...s, width: newWidth };
                        } else {
                            let expectedWidth = resizeStart.baseWidth * resizeStart.scale + deltaX;
                            let expectedRightEdge = resizeStart.startX + expectedWidth;
                            
                            let newScale;
                            if (snapToGrid) {
                                let snappedRightEdge = Math.round(expectedRightEdge / GRID_SIZE) * GRID_SIZE;
                                newScale = (snappedRightEdge - resizeStart.startX) / resizeStart.baseWidth;
                            } else {
                                newScale = expectedWidth / resizeStart.baseWidth;
                            }
                            
                            newScale = Math.max(0.1, Math.min(newScale, 5));
                            return { ...s, scale: newScale };
                        }
                    }
                    return s;
                }));
            }
        };

        const handleGlobalMouseUp = () => { setDraggingImageId(null); setResizingImageId(null); };

        if (draggingImageId || resizingImageId) {
            window.addEventListener('mousemove', handleGlobalMouseMove);
            window.addEventListener('mouseup', handleGlobalMouseUp);
        }
        
        return () => {
            window.removeEventListener('mousemove', handleGlobalMouseMove);
            window.removeEventListener('mouseup', handleGlobalMouseUp);
        };
    }, [draggingImageId, resizingImageId, dragStart, resizeStart, snapToGrid, canvasWidth, canvasMinHeight]);

    useEffect(() => {
        const handleGlobalPaste = (e) => {
            if (isExporting || activeTab !== 'canvas') return;

            const items = e.clipboardData?.items;
            if (!items) return;

            const filesToPaste = [];
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.startsWith('image/')) {
                    const file = items[i].getAsFile();
                    if (file) filesToPaste.push(file);
                }
            }

            if (filesToPaste.length > 0) {
                if (document.activeElement && document.activeElement.tagName !== 'TEXTAREA') {
                    e.preventDefault();
                }
                handleAddImages(filesToPaste, 40, 220);
            }
        };

        window.addEventListener('paste', handleGlobalPaste);
        return () => window.removeEventListener('paste', handleGlobalPaste);
    }, [isExporting, activeTab, canvasWidth, canvasMinHeight]);

    const addSection = () => setItems([...items, { id: Date.now(), type: 'section', title: 'НОВЫЙ РАЗДЕЛ' }]);
    const addItem = () => setItems([...items, { id: Date.now(), type: 'item', title: '', price: 0, quantity: 1, finalPrice: 0, link: '' }]);
    const deleteItem = (id) => setItems(items.filter(i => i.id !== id));
    const duplicateItem = (id) => { const idx = items.findIndex(i => i.id === id); if (idx === -1) return; const cp = { ...items[idx], id: Date.now() }; const ni = [...items]; ni.splice(idx + 1, 0, cp); setItems(ni); };
    const moveItem = (idx, dir) => { const ni = [...items]; if (dir === -1 && idx > 0) { [ni[idx], ni[idx - 1]] = [ni[idx - 1], ni[idx]]; } else if (dir === 1 && idx < ni.length - 1) { [ni[idx], ni[idx + 1]] = [ni[idx + 1], ni[idx]]; } setItems(ni); };

    const handleItemChange = (id, field, value) => {
        setItems(prev => prev.map(i => {
            if (i.id === id) {
                const updated = { ...i, [field]: value };
                if (i.type === 'item') {
                    const p = parseFloat(updated.price) || 0;
                    const q = parseFloat(updated.quantity) || 0;
                    updated.finalPrice = window.calcFinal ? window.calcFinal(p, q, false, 'fixed', 0) : (p * q); 
                }
                return updated;
            }
            return i;
        }));
    };

    const formatPriceSafe = (p) => new Intl.NumberFormat('ru-RU').format(Math.round(p || 0));
    
    const totals = useMemo(() => { 
        const baseTotal = items.reduce((acc, i) => i.type === 'item' ? acc + ((parseFloat(i.price)||0) * (parseFloat(i.quantity)||0)) : acc, 0); 
        return { t: baseTotal }; 
    }, [items]);

    const handleLocalSave = () => { 
        const payloadData = { templateType: 'furniture', clientName, clientDate, sketches, orientation, items, showBaseRequisites, showFullRequisites, requisites };
        const data = JSON.stringify(payloadData, null, 2); 
        const blob = new Blob([data], { type: 'application/json' }); 
        const url = URL.createObjectURL(blob); 
        const a = document.createElement('a'); 
        a.href = url; 
        a.download = `Мебель_${clientName || 'Новый'}.json`; 
        a.click(); 
        URL.revokeObjectURL(url); 
        setHasUnsavedChanges(false);
    };
    
    const handleLocalLoad = (e) => { 
        const file = e.target.files[0]; 
        if (!file) return; 
        const reader = new FileReader(); 
        reader.onload = (ev) => { 
            try { 
                const data = JSON.parse(ev.target.result); 
                if (data.clientName !== undefined) setClientName(data.clientName);
                if (data.clientDate !== undefined) setClientDate(data.clientDate);
                if (data.sketches !== undefined) setSketches(data.sketches);
                if (data.orientation !== undefined) setOrientation(data.orientation);
                if (data.items !== undefined) setItems(data.items);
                
                if (data.showBaseRequisites !== undefined) setShowBaseRequisites(data.showBaseRequisites);
                if (data.showFullRequisites !== undefined) setShowFullRequisites(data.showFullRequisites);
                
                if (data.showBaseRequisites === undefined && data.showFullRequisites === undefined && data.showRequisites !== undefined) {
                    const hasData = data.requisites && (data.requisites.seller.inn || data.requisites.buyer.company);
                    if (hasData) setShowFullRequisites(data.showRequisites);
                    else setShowBaseRequisites(data.showRequisites);
                }

                if (data.requisites !== undefined) setRequisites(data.requisites);
                showToast("Проект загружен!"); 
                setHasUnsavedChanges(false); 
            } catch (err) { showToast("Ошибка загрузки", 'error'); } 
        }; 
        reader.readAsText(file); 
        e.target.value = null; 
    };

    const handleCloudSave = async () => {
        if (!user || !user.id) { showToast("Войдите в систему", 'error'); return; }
        setSaving(true);
        const payloadData = { templateType: 'furniture', clientName, clientDate, sketches, orientation, items, showBaseRequisites, showFullRequisites, requisites };
        const pName = clientName ? `Мебель: ${clientName}` : 'Новое Мебельное КП';
        
        let projectIdToSave = currentProjectId;
        try {
            const checkRes = await fetch(`/api/projects/${user.id}?t=${Date.now()}`);
            const checkData = await checkRes.json();
            if (Array.isArray(checkData)) {
                const existingProject = checkData.find(p => p.name === pName);
                if (existingProject) {
                    if (!projectIdToSave || projectIdToSave !== existingProject.id) {
                        const confirmOverwrite = confirm(`Файл "${pName}" уже существует. Перезаписать его?`);
                        if (confirmOverwrite) { projectIdToSave = existingProject.id; } else { setSaving(false); return; }
                    }
                }
            }
        } catch (e) { }

        let sketchesToSave = sketches;
        let hasCompressed = false;

        let projectData = { user_id: user.id, id: projectIdToSave || 0, name: pName, data: JSON.stringify({...payloadData, sketches: sketchesToSave}) };
        let payloadSize = new Blob([JSON.stringify(projectData)]).size;

        if (payloadSize > 900 * 1024) {
            sketchesToSave = await Promise.all(sketchesToSave.map(async (sk) => {
                if (sk.type === 'image' && sk.url && sk.url.startsWith('data:image/')) {
                    try {
                        const compressed = await window.compressImage(sk.url, 800, 0.7);
                        if (compressed !== sk.url) hasCompressed = true;
                        return { ...sk, url: compressed };
                    } catch (e) { return sk; }
                }
                return sk;
            }));
            
            projectData.data = JSON.stringify({...payloadData, sketches: sketchesToSave});
            payloadSize = new Blob([JSON.stringify(projectData)]).size;
        }

        if (hasCompressed) setSketches(sketchesToSave);

        if (payloadSize > 1024 * 1024) {
            const mbSize = (payloadSize / (1024 * 1024)).toFixed(2);
            showToast(`Файл слишком большой (${mbSize} МБ). Сервер принимает до 1 МБ. Уменьшите количество или размер фото.`, 'error');
            setSaving(false);
            return;
        }

        try {
            const res = await fetch('/api/projects', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(projectData) });
            const data = await res.json();
            if (data.status === 'created' || data.status === 'updated') { 
                if (data.id) setCurrentProjectId(data.id); 
                showToast("✅ Проект успешно сохранен в облако!"); 
                setHasUnsavedChanges(false);
            } 
            else { showToast("Ошибка сохранения: " + data.message, 'error'); }
        } catch (e) { showToast("Ошибка соединения", 'error'); } finally { setSaving(false); }
    };

    const handleSendToTelegram = async () => {
        if (!user) return;
        if (!exportCanvas && !exportTable) {
            showToast("Выберите хотя бы один раздел для экспорта!", "error");
            return;
        }
        
        if (window.loadPdfLibrary && !window.html2pdf) {
            try { await window.loadPdfLibrary(); } catch (e) {}
        }
        if (!window.html2pdf) {
            showToast("Ошибка: Библиотека PDF заблокирована браузером. Отключите блокировщик рекламы или обновите страницу.", "error");
            return;
        }

        showToast("Генерация и отправка в Telegram (~30 сек). Можно продолжать работу.", "success");
        setSendingTg(true);
        setIsPdf(true);

        setTimeout(async () => {
            const el = document.getElementById('print-area');

            try {
                const pdfOptions = {
                    margin: 0,
                    image: { type: 'jpeg', quality: 0.98 },
                    html2canvas: { scale: 2, useCORS: true, scrollY: 0, backgroundColor: '#ffffff' },
                    jsPDF: { format: 'a4', orientation: orientation, unit: 'mm' }
                };

                const blob = await window.html2pdf().set(pdfOptions).from(el).output('blob');
                if (blob.size === 0) throw new Error("Generated PDF is empty");

                setIsPdf(false);

                const formData = new FormData();
                formData.append('file', blob, `${clientName ? 'Мебель_'+clientName : 'Мебельное_КП'}.pdf`);
                formData.append('user_id', user.id);

                const res = await fetch('/api/send-pdf', { method: 'POST', body: formData });

                let errData = null;
                if (!res.ok) {
                    try { errData = await res.json(); } 
                    catch (parseError) { throw new Error("Ошибка сервера (возможно файл слишком большой)"); }
                }

                if (res.ok) {
                    showToast("Файл успешно доставлен в Telegram!", "success");
                } else {
                    if (res.status === 400 && errData?.detail && errData.detail.includes("Telegram ID missing")) {
                        showToast("Бот не знает ваш ID. Нажмите /start в боте.", 'error');
                    } else {
                        showToast("Ошибка отправки: " + (errData?.detail || `Код ${res.status}`), 'error');
                    }
                }
            } catch (e) {
                console.error("CRITICAL SEND ERROR:", e);
                showToast(e.message || "Ошибка", 'error');
                setIsPdf(false); 
            } finally {
                setSendingTg(false);
            }
        }, 200);
    };

    const handlePdf = async () => {
        if (!exportCanvas && !exportTable) {
            showToast("Выберите хотя бы один раздел для экспорта (Активно)", "error");
            return;
        }

        if (window.loadPdfLibrary && !window.html2pdf) {
            try { await window.loadPdfLibrary(); } catch (e) {}
        }
        if (!window.html2pdf) {
            showToast("Ошибка: Библиотека PDF заблокирована браузером. Отключите блокировщик рекламы или обновите страницу.", "error");
            return;
        }

        setIsPdf(true);
        await new Promise(r => setTimeout(r, 200)); 

        const el = document.getElementById('print-area');
        
        try {
            await window.html2pdf().set({
                margin: 0, 
                filename: `${clientName ? 'Мебель_'+clientName : 'Мебельное_КП'}.pdf`,
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2, useCORS: true, scrollY: 0, backgroundColor: '#ffffff' },
                jsPDF: { format: 'a4', orientation: orientation, unit: 'mm' },
                pagebreak: { mode: ['css', 'legacy'] }
            }).from(el).save();
            showToast("✅ PDF успешно скачан!");
        } catch (e) {
            console.error(e);
            showToast("Ошибка при генерации PDF", "error");
        } finally {
            setIsPdf(false);
        }
    };

    const canvasGridStyle = (showGrid && !isExporting) ? {
        backgroundImage: `linear-gradient(to right, #e5e7eb 1px, transparent 1px), linear-gradient(to bottom, #e5e7eb 1px, transparent 1px)`,
        backgroundSize: `${GRID_SIZE}px ${GRID_SIZE}px`
    } : {};

    return (
        <div className={`min-h-screen bg-gray-100 flex flex-col pb-20 relative overflow-x-hidden ${isPdf ? 'pdf-mode' : ''}`}>
            
            {toast.show && !isExporting && (
                <div className={`fixed top-20 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-xl shadow-2xl font-bold text-white z-[9999] flex items-center gap-2 animate-fade-in-up ${toast.type === 'error' ? 'bg-red-600' : 'bg-gray-800'}`}>
                    {toast.type === 'success' && <CheckCircle size={20} className="text-green-400" />}
                    {toast.type === 'error' && <AlertTriangle size={20} className="text-red-300" />}
                    {toast.message}
                </div>
            )}

            {!isExporting && (
                <header className="bg-white border-b shadow-sm sticky top-0 z-40">
                    <div className="max-w-7xl mx-auto px-4 py-3 flex justify-between items-center">
                        <div className="flex items-center gap-4">
                            <button onClick={handleBackClick} className="flex items-center gap-2 text-gray-500 hover:text-gray-800 font-medium">
                                <SafeArrowLeft size={20} /> <span className="hidden md:inline">Назад</span>
                            </button>
                            <h1 className="text-xl font-bold text-gray-800 hidden md:block">Мебельное КП</h1>
                        </div>
                        <div className="flex gap-2 flex-wrap justify-end">
                            
                            {isManagerOrHigher && (
                                <>
                                    <button onClick={handleLocalSave} className="hidden sm:flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 font-bold transition"><Save size={16} /> <span className="hidden md:inline">Файл</span></button>
                                    <label className="hidden sm:flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 font-bold transition cursor-pointer"><SafeUploadCloud size={16} /> <span className="hidden md:inline">Загрузить</span><input type="file" onChange={handleLocalLoad} accept=".json" className="hidden" /></label>
                                </>
                            )}
                            
                            <button onClick={handleCloudSave} disabled={saving} className={`flex items-center gap-2 px-4 py-2 font-bold rounded-lg transition ${hasUnsavedChanges ? 'bg-orange-100 text-orange-700 hover:bg-orange-200 shadow-inner' : 'bg-blue-100 text-blue-700 hover:bg-blue-200'}`}>
                                {saving ? <Loader size={16} className="animate-spin" /> : <SafeCloud size={16} />} 
                                <span className="hidden md:inline">{saving ? "..." : (hasUnsavedChanges ? "Сохранить*" : "Облако")}</span>
                            </button>
                            
                            {isSpeedOrVip && (
                                <button onClick={handleSendToTelegram} disabled={sendingTg || isExporting} className="flex items-center gap-2 px-4 py-2 bg-indigo-100 text-indigo-700 rounded-lg hover:bg-indigo-200 font-bold transition shadow-sm active:scale-95">
                                    {sendingTg ? <Loader size={16} className="animate-spin" /> : <SendIcon size={16} />}
                                    <span className="hidden md:inline">{sendingTg ? "Отправка..." : "В Telegram"}</span>
                                </button>
                            )}

                            <button onClick={handlePdf} disabled={isExporting || sendingTg} className="flex items-center gap-2 px-4 py-2 ml-1 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-bold transition shadow-sm active:scale-95">
                                {isExporting ? <Loader size={16} className="animate-spin" /> : <Download size={16} />}
                                <span className="hidden md:inline">{isExporting ? "Генерация..." : "Скачать PDF"}</span>
                            </button>

                        </div>
                    </div>
                </header>
            )}

            <main id="print-area" className={isExporting ? "bg-white mx-auto w-max" : "flex-1 max-w-7xl mx-auto w-full p-4 md:p-6 flex flex-col gap-6"}>
                
                {!isExporting && (
                    <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 shrink-0">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label className="block text-xs font-bold text-gray-500 mb-1">Название / Номер договора</label>
                                <input type="text" value={clientName} onChange={e => setClientName(e.target.value)} className="w-full border border-gray-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 bg-gray-50 p-2 outline-none font-bold text-gray-800" placeholder="МЕБ-02/03-..." />
                            </div>
                            <div>
                                <label className="block text-xs font-bold text-gray-500 mb-1">Дата составления</label>
                                <input type="date" value={clientDate} onChange={e => setClientDate(e.target.value)} className="w-full border border-gray-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 bg-gray-50 p-2 outline-none font-bold text-gray-800" />
                            </div>
                        </div>
                    </div>
                )}

                {/* --- ВЫНЕСЕННЫЕ КНОПКИ ПОКАЗА РЕКВИЗИТОВ --- */}
                {!isPdf && (
                    <div className="w-full flex justify-end gap-3 mb-4 no-print flex-wrap">
                        <label className="flex items-center gap-2 cursor-pointer text-sm font-bold text-gray-600 hover:text-blue-600 transition-colors bg-white px-4 py-2 rounded-xl shadow-sm border border-gray-200 select-none">
                            <input type="checkbox" checked={showBaseRequisites} onChange={e => setShowBaseRequisites(e.target.checked)} className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500 cursor-pointer" />
                            Логотип и реквизиты (базовые)
                        </label>
                        <label className="flex items-center gap-2 cursor-pointer text-sm font-bold text-gray-600 hover:text-blue-600 transition-colors bg-white px-4 py-2 rounded-xl shadow-sm border border-gray-200 select-none">
                            <input type="checkbox" checked={showFullRequisites} onChange={e => setShowFullRequisites(e.target.checked)} className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500 cursor-pointer" />
                            Полная форма (Покупатель/Продавец)
                        </label>
                    </div>
                )}

                {/* --- ФОРМА ВВОДА ПОЛНЫХ РЕКВИЗИТОВ --- */}
                {showFullRequisites && !isPdf && (
                    <div className="w-full mb-2 animate-fade-in">
                        <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 text-sm">
                            <div className="flex justify-between items-center mb-4">
                                <h3 className="font-black text-lg text-gray-800">Информация о продавце</h3>
                                <button onClick={saveSellerToLocal} className="text-xs bg-blue-50 hover:bg-blue-100 text-blue-700 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1 font-bold border border-blue-200 shadow-sm active:scale-95">
                                    <Save size={14} /> Сохранить шаблон
                                </button>
                            </div>
                            
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-8">
                                <div className="md:col-span-3">
                                    <input value={requisites.seller.name} onChange={e => setReqField('seller', 'name', e.target.value)} placeholder="Название компании или ИП" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                                </div>
                                <input value={requisites.seller.inn} onChange={e => setReqField('seller', 'inn', e.target.value)} placeholder="ИНН" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                                <input value={requisites.seller.kpp} onChange={e => setReqField('seller', 'kpp', e.target.value)} placeholder="КПП" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                                <input value={requisites.seller.ogrn} onChange={e => setReqField('seller', 'ogrn', e.target.value)} placeholder="ОГРН" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />

                                <input value={requisites.seller.account} onChange={e => setReqField('seller', 'account', e.target.value)} placeholder="№ расчетного счета" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-1" />
                                <input value={requisites.seller.bank} onChange={e => setReqField('seller', 'bank', e.target.value)} placeholder="Наименование банка" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-2" />

                                <input value={requisites.seller.bik} onChange={e => setReqField('seller', 'bik', e.target.value)} placeholder="БИК Банка" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-1" />
                                <input value={requisites.seller.corr} onChange={e => setReqField('seller', 'corr', e.target.value)} placeholder="№ корреспондентского счета" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-2" />

                                <input value={requisites.seller.phone} onChange={e => setReqField('seller', 'phone', e.target.value)} placeholder="Телефон" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                                <input value={requisites.seller.site} onChange={e => setReqField('seller', 'site', e.target.value)} placeholder="Сайт" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                                <input value={requisites.seller.email} onChange={e => setReqField('seller', 'email', e.target.value)} placeholder="Email" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />

                                <input value={requisites.seller.directorTitle} onChange={e => setReqField('seller', 'directorTitle', e.target.value)} placeholder="Должность руководителя" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-1" />
                                <input value={requisites.seller.directorName} onChange={e => setReqField('seller', 'directorName', e.target.value)} placeholder="ФИО руководителя" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-2" />

                                <input value={requisites.seller.managerName} onChange={e => setReqField('seller', 'managerName', e.target.value)} placeholder="ФИО исполнителя" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-1" />
                                <input value={requisites.seller.managerPhone} onChange={e => setReqField('seller', 'managerPhone', e.target.value)} placeholder="Телефон исполнителя" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors md:col-span-2" />
                            </div>

                            <h3 className="font-black text-lg mb-4 text-gray-800">Информация о покупателе</h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <div className="md:col-span-2">
                                    <input value={requisites.buyer.targetTitle} onChange={e => setReqField('buyer', 'targetTitle', e.target.value)} placeholder="Должность сотрудника для кого адресовано КП" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                                </div>
                                <input value={requisites.buyer.company} onChange={e => setReqField('buyer', 'company', e.target.value)} placeholder="Название компании" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                                <input value={requisites.buyer.targetName} onChange={e => setReqField('buyer', 'targetName', e.target.value)} placeholder="ФИО сотрудника" className="w-full border border-gray-300 focus:border-blue-500 p-2.5 rounded-md outline-none transition-colors" />
                            </div>
                        </div>
                    </div>
                )}

                {!isExporting && (
                    <div className="flex bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden shrink-0">
                        <div className={`flex-1 flex flex-col transition-colors ${activeTab === 'canvas' ? 'bg-blue-50' : 'bg-white hover:bg-gray-50'}`}>
                            <button onClick={() => setActiveTab('canvas')} className={`py-2 pt-3 font-bold text-sm w-full text-center outline-none ${activeTab === 'canvas' ? 'text-blue-700' : 'text-gray-600'}`}>🎨 Визуализация (Холст)</button>
                            <div className="flex items-center justify-center pb-3 pt-1">
                                <label className="flex items-center gap-2 cursor-pointer group" onClick={(e) => e.stopPropagation()}>
                                    <div className="relative flex items-center">
                                        <input type="checkbox" className="sr-only" checked={exportCanvas} onChange={e => setExportCanvas(e.target.checked)} />
                                        <div className={`block w-8 h-4 rounded-full transition-colors ${exportCanvas ? 'bg-blue-500' : 'bg-gray-300'}`}></div>
                                        <div className={`absolute left-0.5 top-0.5 bg-white w-3 h-3 rounded-full transition-transform ${exportCanvas ? 'translate-x-4' : ''}`}></div>
                                    </div>
                                    <span className={`text-[10px] uppercase tracking-wider font-bold ${exportCanvas ? 'text-blue-600' : 'text-gray-400'}`}>{exportCanvas ? 'Активно' : 'Неактивно'}</span>
                                </label>
                            </div>
                        </div>
                        
                        <div className="w-px bg-gray-200"></div>
                        
                        <div className={`flex-1 flex flex-col transition-colors ${activeTab === 'table' ? 'bg-blue-50' : 'bg-white hover:bg-gray-50'}`}>
                            <button onClick={() => setActiveTab('table')} className={`py-2 pt-3 font-bold text-sm w-full text-center outline-none ${activeTab === 'table' ? 'text-blue-700' : 'text-gray-600'}`}>📊 Смета и расчеты</button>
                            <div className="flex items-center justify-center pb-3 pt-1">
                                <label className="flex items-center gap-2 cursor-pointer group" onClick={(e) => e.stopPropagation()}>
                                    <div className="relative flex items-center">
                                        <input type="checkbox" className="sr-only" checked={exportTable} onChange={e => setExportTable(e.target.checked)} />
                                        <div className={`block w-8 h-4 rounded-full transition-colors ${exportTable ? 'bg-blue-500' : 'bg-gray-300'}`}></div>
                                        <div className={`absolute left-0.5 top-0.5 bg-white w-3 h-3 rounded-full transition-transform ${exportTable ? 'translate-x-4' : ''}`}></div>
                                    </div>
                                    <span className={`text-[10px] uppercase tracking-wider font-bold ${exportTable ? 'text-blue-600' : 'text-gray-400'}`}>{exportTable ? 'Активно' : 'Неактивно'}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                )}

                <div className={(!isExporting && activeTab === 'canvas') || (isExporting && exportCanvas) ? (isExporting ? 'bg-white' : 'flex-1 flex flex-col min-h-[600px] bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden') : 'hidden'}>
                    
                    {!isExporting && (
                        <div className="bg-gray-50 border-b border-gray-200 p-3 flex flex-wrap items-center justify-between gap-4 z-20 shrink-0">
                            <div className="flex flex-wrap items-center gap-4 px-2">
                                <div className="flex items-center gap-2 border-r border-gray-300 pr-4">
                                    <span className="text-sm font-bold text-gray-700">Формат:</span>
                                    <select value={orientation} onChange={e => setOrientation(e.target.value)} className="text-sm border border-gray-300 rounded px-2 py-1 outline-none focus:border-blue-50 cursor-pointer bg-white">
                                        <option value="portrait">А4 Вертикальный</option>
                                        <option value="landscape">А4 Горизонтальный</option>
                                    </select>
                                </div>
                                <label className="flex items-center gap-2 cursor-pointer group">
                                    <input type="checkbox" checked={showGrid} onChange={e => setShowGrid(e.target.checked)} className="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500 cursor-pointer" />
                                    <span className="text-sm font-bold text-gray-700 group-hover:text-blue-600 transition-colors">Видимая сетка</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer group pr-4">
                                    <input type="checkbox" checked={snapToGrid} onChange={e => setSnapToGrid(e.target.checked)} className="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500 cursor-pointer" />
                                    <span className="text-sm font-bold text-gray-700 group-hover:text-blue-600 transition-colors">Магнит к сетке</span>
                                </label>
                            </div>
                            
                            <div className="flex items-center gap-2">
                                {FileText && (
                                    <button onClick={handleAddText} className="cursor-pointer bg-green-100 hover:bg-green-200 text-green-700 px-4 py-2 rounded-lg font-bold text-sm transition-colors flex items-center gap-2 shadow-sm active:scale-95">
                                        <FileText size={16} /> Добавить текст
                                    </button>
                                )}
                                <label className="cursor-pointer bg-blue-100 hover:bg-blue-200 text-blue-700 px-4 py-2 rounded-lg font-bold text-sm transition-colors flex items-center gap-2 shadow-sm active:scale-95">
                                    {Plus && <Plus size={16} />} Добавить фото
                                    <input type="file" multiple accept="image/*" onChange={handleFileInput} className="hidden" />
                                </label>
                            </div>
                        </div>
                    )}

                    <div className={isExporting ? "bg-white flex justify-center items-start" : "flex-1 overflow-auto bg-gray-200 p-4 md:p-8 flex justify-center items-start"}>
                        <div 
                            ref={canvasRef} 
                            className={`relative bg-white transition-all duration-300 ${isExporting ? '' : 'shadow-md'}`} 
                            style={{ 
                                ...canvasGridStyle, 
                                width: `${canvasWidth}px`, 
                                height: `${canvasMinHeight}px`, 
                                overflow: isExporting ? 'hidden' : 'visible' 
                            }} 
                            onDragOver={handleDragOver} 
                            onDrop={handleCanvasDrop}
                        >
                            <div className="absolute top-0 left-0 w-full px-12 pt-10 pointer-events-none z-0">
                                
                                {/* --- ФИРМЕННЫЙ СТИЛЬ И РЕКВИЗИТЫ В PDF --- */}
                                {(showBaseRequisites || showFullRequisites) && (
                                    <div className="flex flex-col mb-4 pb-4 border-b border-gray-300 relative z-10 break-inside-avoid text-black print-text-black">
                                        <div className="flex justify-between items-start w-full">
                                            {/* Продавец */}
                                            <div className={`${showFullRequisites ? 'w-1/2 pr-4' : 'w-full'} flex flex-col gap-1`}>
                                                {user?.company_logo && <img src={user.company_logo} className="max-h-16 w-auto object-contain object-left-top pdf-no-border mb-2" alt="Логотип" />}
                                                
                                                {(showFullRequisites && (requisites.seller.inn || requisites.seller.account || requisites.seller.phone || requisites.seller.name)) ? (
                                                    <>
                                                        <div className="text-sm font-bold uppercase">{requisites.seller.name || (user?.company_requisites ? 'Продавец' : '')}</div>
                                                        <div className="text-[10px] space-y-0.5 leading-tight text-gray-800">
                                                            {requisites.seller.inn && <div>ИНН: {requisites.seller.inn}{requisites.seller.kpp ? ` / КПП: ${requisites.seller.kpp}` : ''}</div>}
                                                            {requisites.seller.ogrn && <div>ОГРН: {requisites.seller.ogrn}</div>}
                                                            {requisites.seller.bank && <div className="mt-1">Банк: {requisites.seller.bank}</div>}
                                                            {requisites.seller.account && <div>Р/С: {requisites.seller.account}</div>}
                                                            {requisites.seller.corr && <div>К/С: {requisites.seller.corr}{requisites.seller.bik ? ` / БИК: ${requisites.seller.bik}` : ''}</div>}
                                                            
                                                            {(requisites.seller.phone || requisites.seller.email || requisites.seller.site) && (
                                                                <div className="pt-1 mt-1 border-t border-gray-200">
                                                                    {requisites.seller.phone && <span className="mr-2">Тел: {requisites.seller.phone}</span>}
                                                                    {requisites.seller.email && <span className="mr-2">Email: {requisites.seller.email}</span>}
                                                                    {requisites.seller.site && <span>Web: {requisites.seller.site}</span>}
                                                                </div>
                                                            )}
                                                            
                                                            {(requisites.seller.directorTitle || requisites.seller.directorName || requisites.seller.managerName) && (
                                                                <div className="pt-1 mt-1 border-t border-gray-200">
                                                                    {requisites.seller.directorName && <div>{requisites.seller.directorTitle || 'Руководитель'}: {requisites.seller.directorName}</div>}
                                                                    {requisites.seller.managerName && <div>Менеджер: {requisites.seller.managerName} {requisites.seller.managerPhone}</div>}
                                                                </div>
                                                            )}
                                                        </div>
                                                    </>
                                                ) : (
                                                    <>
                                                        {showFullRequisites && requisites.seller.name && <div className="text-sm font-bold uppercase">{requisites.seller.name}</div>}
                                                        <div className="text-[10px] whitespace-pre-wrap text-gray-800">
                                                            {user?.company_requisites}
                                                        </div>
                                                    </>
                                                )}
                                            </div>

                                            {/* Покупатель */}
                                            {showFullRequisites && (
                                                <div className="w-1/2 pl-6 border-l border-gray-300 flex flex-col gap-1">
                                                    <div className="text-[10px] text-gray-500 font-bold uppercase tracking-wider mb-1">Информация о покупателе</div>
                                                    <div className="text-sm font-bold">{requisites.buyer.company || clientName || 'Организация не указана'}</div>
                                                    <div className="text-[11px] leading-tight text-gray-800 mt-1">
                                                        {requisites.buyer.targetTitle && <div>{requisites.buyer.targetTitle}</div>}
                                                        {requisites.buyer.targetName && <div className="font-bold mt-0.5">{requisites.buyer.targetName}</div>}
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                )}

                                <h1 className="text-4xl font-black italic text-gray-800 uppercase mb-4 opacity-80 print-text-black">Коммерческое Предложение</h1>
                                <div className="flex justify-between items-end border-b-2 border-gray-300 pb-2">
                                    <div className="text-lg text-gray-700 font-bold opacity-80 print-text-black">
                                        {clientName || ''}
                                    </div>
                                    <div className="text-lg text-gray-700 font-bold opacity-80 print-text-black">
                                        {clientDate ? `Дата: ${getFormattedDateForPrint()}` : ''}
                                    </div>
                                </div>
                            </div>

                            {sketches.length === 0 && !isExporting && (
                                <div className="absolute inset-0 flex flex-col items-center justify-center text-gray-400 pointer-events-none">
                                    {Plus && <Plus size={48} className="mb-4 opacity-50" />}
                                    <p className="font-bold text-lg">Холст пуст</p>
                                    <p className="text-sm">Перетащите сюда картинки или нажмите кнопку выше (или Ctrl+V)</p>
                                </div>
                            )}

                            {sketches.map((sketch) => {
                                const isText = sketch.type === 'text';
                                const currentScale = isText ? 1 : sketch.scale;
                                const currentWidth = isText ? (sketch.width || 250) : undefined;
                                const currentFontSize = isText ? (sketch.fontSize || 16) : undefined;

                                return (
                                    <div key={sketch.id} className="absolute group/photo z-10 hover:z-50" 
                                         style={{ 
                                             left: `${sketch.x}px`, 
                                             top: `${sketch.y}px`, 
                                             transform: `scale(${currentScale})`, 
                                             transformOrigin: 'top left', 
                                             transition: (draggingImageId === sketch.id || resizingImageId === sketch.id || isExporting) ? 'none' : 'transform 0.1s ease-out, left 0.1s ease-out, top 0.1s ease-out', 
                                             zIndex: draggingImageId === sketch.id ? 50 : undefined,
                                             width: isText ? `${currentWidth}px` : undefined 
                                         }}>
                                        
                                        {isText ? (
                                            <div className={`resize-target w-full bg-white ${isExporting ? '' : 'border-2 border-dashed border-gray-300 shadow-sm'} rounded p-2`} style={{ minHeight: '50px' }}>
                                                {isExporting ? (
                                                    <div className="w-full text-black font-medium" style={{ fontSize: `${currentFontSize}px`, minHeight: '30px', whiteSpace: 'pre-wrap', wordBreak: 'break-word', lineHeight: '1.2' }}>{sketch.text}</div>
                                                ) : (
                                                    <textarea
                                                        value={sketch.text}
                                                        onChange={(e) => {
                                                            const val = e.target.value;
                                                            setSketches(prev => prev.map(s => s.id === sketch.id ? { ...s, text: val } : s));
                                                        }}
                                                        onFocus={(e) => {
                                                            if (sketch.text === 'Введите текст...') {
                                                                setSketches(prev => prev.map(s => s.id === sketch.id ? { ...s, text: '' } : s));
                                                            }
                                                        }}
                                                        onInput={(e) => { e.target.style.height = 'auto'; e.target.style.height = e.target.scrollHeight + 'px'; }}
                                                        className="w-full bg-transparent outline-none resize-none overflow-hidden text-gray-800 font-medium sketch-textarea"
                                                        style={{ fontSize: `${currentFontSize}px`, minHeight: '30px', lineHeight: '1.2' }}
                                                        placeholder="Введите текст..."
                                                    />
                                                )}
                                            </div>
                                        ) : (
                                            <img src={sketch.url} alt={`Эскиз`} className={`resize-target pointer-events-none border-2 rounded bg-white ${isExporting ? 'border-transparent shadow-none' : 'border-transparent group-hover/photo:border-blue-400/50 shadow-sm'}`} style={{ display: 'block', maxWidth: '800px', maxHeight: '800px' }} draggable={false} />
                                        )}
                                        
                                        {!isExporting && (
                                            <>
                                                <div className="absolute bg-white border border-gray-200 text-gray-700 rounded shadow-md opacity-0 group-hover/photo:opacity-100 cursor-move flex items-center justify-center hover:bg-gray-50 transition-opacity z-30 active:bg-blue-50 active:text-blue-600" style={{ top: '4px', left: '4px', transform: `scale(${1 / currentScale})`, transformOrigin: 'top left', padding: '6px' }} onMouseDown={(e) => handleMouseDownPan(e, sketch)} title="Переместить"><SafeMove size={16} /></div>
                                                
                                                <div className="absolute bg-blue-600 text-white rounded shadow-md opacity-0 group-hover/photo:opacity-100 cursor-nwse-resize flex items-center justify-center hover:bg-blue-700 transition-opacity z-30" style={{ bottom: '4px', right: '4px', transform: `scale(${1 / currentScale})`, transformOrigin: 'bottom right', padding: '6px' }} onMouseDown={(e) => handleMouseDownResize(e, sketch)} title={isText ? "Растянуть блок" : "Масштабировать"}><SafeMaximize2 size={16} /></div>
                                                
                                                <div className="absolute bg-red-500 text-white rounded shadow-md opacity-0 group-hover/photo:opacity-100 cursor-pointer flex items-center justify-center hover:bg-red-600 transition-opacity z-30" style={{ top: '4px', right: '4px', transform: `scale(${1 / currentScale})`, transformOrigin: 'top right', padding: '6px' }} onClick={() => handleRemoveSketch(sketch.id)} title="Удалить">{Trash2 && <Trash2 size={16} />}</div>
                                                
                                                {isText && (
                                                    <>
                                                        <div className="absolute bg-white border border-gray-200 text-gray-700 rounded shadow-md opacity-0 group-hover/photo:opacity-100 cursor-pointer flex items-center justify-center hover:bg-blue-50 hover:text-blue-600 transition-opacity z-30 active:scale-95" style={{ top: '4px', right: '36px', padding: '4px 8px', fontSize: '14px', fontWeight: 'bold' }} onClick={(e) => handleFontSize(e, sketch.id, 1)} title="Увеличить шрифт">А+</div>
                                                        <div className="absolute bg-white border border-gray-200 text-gray-700 rounded shadow-md opacity-0 group-hover/photo:opacity-100 cursor-pointer flex items-center justify-center hover:bg-blue-50 hover:text-blue-600 transition-opacity z-30 active:scale-95" style={{ top: '4px', right: '72px', padding: '4px 8px', fontSize: '12px', fontWeight: 'bold' }} onClick={(e) => handleFontSize(e, sketch.id, -1)} title="Уменьшить шрифт">А-</div>
                                                    </>
                                                )}
                                                
                                                {!isText && sketch.scale !== 1 && (
                                                    <div className="absolute bg-black/60 text-white text-[10px] font-bold px-2 py-1 rounded pointer-events-none z-20 backdrop-blur-sm" style={{ bottom: '4px', left: '4px', transform: `scale(${1 / currentScale})`, transformOrigin: 'bottom left' }}>{Math.round(sketch.scale * 100)}%</div>
                                                )}
                                            </>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>

                {isExporting && exportCanvas && exportTable && <div className="html2pdf__page-break" style={{ height: 0, margin: 0, padding: 0, overflow: 'hidden' }}></div>}

                <div 
                    className={(!isExporting && activeTab === 'table') || (isExporting && exportTable) ? (isExporting ? `bg-white px-12 py-10 mx-auto` : 'flex-1 flex flex-col bg-white rounded-2xl shadow-sm border border-gray-200') : 'hidden'} 
                    style={isExporting ? { width: `${canvasWidth}px` } : {}}
                >
                    
                    {isExporting && (
                        <div className="mb-6 border-b-2 border-gray-800 pb-4">
                            {/* --- ФИРМЕННЫЙ СТИЛЬ И РЕКВИЗИТЫ В PDF --- */}
                            {(showBaseRequisites || showFullRequisites) && (
                                <div className="flex flex-col mb-4 pb-4 border-b border-gray-300 relative z-10 break-inside-avoid text-black print-text-black">
                                    <div className="flex justify-between items-start w-full">
                                        {/* Продавец */}
                                        <div className={`${showFullRequisites ? 'w-1/2 pr-4' : 'w-full'} flex flex-col gap-1`}>
                                            {user?.company_logo && <img src={user.company_logo} className="max-h-16 w-auto object-contain object-left-top pdf-no-border mb-2" alt="Логотип" />}
                                            
                                            {(showFullRequisites && (requisites.seller.inn || requisites.seller.account || requisites.seller.phone || requisites.seller.name)) ? (
                                                <>
                                                    <div className="text-sm font-bold uppercase">{requisites.seller.name || (user?.company_requisites ? 'Продавец' : '')}</div>
                                                    <div className="text-[10px] space-y-0.5 leading-tight text-gray-800">
                                                        {requisites.seller.inn && <div>ИНН: {requisites.seller.inn}{requisites.seller.kpp ? ` / КПП: ${requisites.seller.kpp}` : ''}</div>}
                                                        {requisites.seller.ogrn && <div>ОГРН: {requisites.seller.ogrn}</div>}
                                                        {requisites.seller.bank && <div className="mt-1">Банк: {requisites.seller.bank}</div>}
                                                        {requisites.seller.account && <div>Р/С: {requisites.seller.account}</div>}
                                                        {requisites.seller.corr && <div>К/С: {requisites.seller.corr}{requisites.seller.bik ? ` / БИК: ${requisites.seller.bik}` : ''}</div>}
                                                        
                                                        {(requisites.seller.phone || requisites.seller.email || requisites.seller.site) && (
                                                            <div className="pt-1 mt-1 border-t border-gray-200">
                                                                {requisites.seller.phone && <span className="mr-2">Тел: {requisites.seller.phone}</span>}
                                                                {requisites.seller.email && <span className="mr-2">Email: {requisites.seller.email}</span>}
                                                                {requisites.seller.site && <span>Web: {requisites.seller.site}</span>}
                                                            </div>
                                                        )}
                                                        
                                                        {(requisites.seller.directorTitle || requisites.seller.directorName || requisites.seller.managerName) && (
                                                            <div className="pt-1 mt-1 border-t border-gray-200">
                                                                {requisites.seller.directorName && <div>{requisites.seller.directorTitle || 'Руководитель'}: {requisites.seller.directorName}</div>}
                                                                {requisites.seller.managerName && <div>Менеджер: {requisites.seller.managerName} {requisites.seller.managerPhone}</div>}
                                                            </div>
                                                        )}
                                                    </div>
                                                </>
                                            ) : (
                                                <>
                                                    {showFullRequisites && requisites.seller.name && <div className="text-sm font-bold uppercase">{requisites.seller.name}</div>}
                                                    <div className="text-[10px] whitespace-pre-wrap text-gray-800">
                                                        {user?.company_requisites}
                                                    </div>
                                                </>
                                            )}
                                        </div>

                                        {/* Покупатель */}
                                        {showFullRequisites && (
                                            <div className="w-1/2 pl-6 border-l border-gray-300 flex flex-col gap-1">
                                                <div className="text-[10px] text-gray-500 font-bold uppercase tracking-wider mb-1">Информация о покупателе</div>
                                                <div className="text-sm font-bold">{requisites.buyer.company || clientName || 'Организация не указана'}</div>
                                                <div className="text-[11px] leading-tight text-gray-800 mt-1">
                                                    {requisites.buyer.targetTitle && <div>{requisites.buyer.targetTitle}</div>}
                                                    {requisites.buyer.targetName && <div className="font-bold mt-0.5">{requisites.buyer.targetName}</div>}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}

                            <h1 className="text-3xl font-black uppercase mb-4 text-black">Смета проекта</h1>
                            <div className="text-xl text-black mb-1 font-bold">{clientName || 'Без названия'}</div>
                            <div className="text-lg text-black"><b>Дата составления:</b> {getFormattedDateForPrint()}</div>
                        </div>
                    )}

                    <div className={isExporting ? "" : "p-6 pr-12"}>
                        
                        {!isExporting && (
                            <div className="flex justify-start gap-4 mb-6">
                                <button onClick={addItem} className="flex items-center gap-2 px-6 py-2.5 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 font-bold transition text-sm">{Plus && <Plus size={18} />} Добавить Строку</button>
                                <button onClick={addSection} className="flex items-center gap-2 px-6 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 font-bold transition text-sm">{Layout && <Layout size={18} />} Добавить Раздел</button>
                            </div>
                        )}

                        <div className="space-y-3">
                            {items.map((item, index) => {
                                const isFirstItem = index === 0;
                                const isAfterSection = index > 0 && items[index - 1].type === 'section';
                                const showHeader = item.type === 'item' && (isFirstItem || isAfterSection);

                                if (item.type === 'section') {
                                    return (
                                        <div key={item.id} className="pt-6 pb-2 group relative z-0 hover:z-50">
                                            <div className="flex items-end border-b-2 border-gray-400 pb-1">
                                                {isExporting ? (
                                                    <div className="text-xl font-black italic text-black uppercase w-full">{item.title}</div>
                                                ) : (
                                                    <input value={item.title} onChange={e => handleItemChange(item.id, 'title', e.target.value)} className="text-xl font-black italic text-gray-800 uppercase bg-transparent outline-none w-full placeholder:text-gray-300" placeholder="НАЗВАНИЕ РАЗДЕЛА" />
                                                )}
                                            </div>
                                            {!isExporting && (
                                                <div className="absolute -right-12 top-6 opacity-0 group-hover:opacity-100 transition-opacity z-10 bg-white shadow-md border rounded p-1 flex flex-col gap-1">
                                                    <button onClick={() => moveItem(index, -1)} disabled={index === 0} className="hover:text-blue-600 text-gray-400 p-1">{ChevronUp && <ChevronUp size={14} />}</button>
                                                    <button onClick={() => moveItem(index, 1)} disabled={index === items.length - 1} className="hover:text-blue-600 text-gray-400 p-1">{ChevronDown && <ChevronDown size={14} />}</button>
                                                    <button onClick={() => deleteItem(item.id)} className="text-red-400 hover:text-red-600 p-1">{Trash2 && <Trash2 size={14} />}</button>
                                                </div>
                                            )}
                                        </div>
                                    );
                                }
                                return (
                                    <React.Fragment key={item.id}>
                                        {showHeader && (
                                            <div className="grid grid-cols-[1fr_80px_80px_120px_120px] gap-4 pb-2 mt-4 border-b-2 border-gray-800 text-xs font-bold text-gray-500 uppercase px-2 break-inside-avoid">
                                                <div>Наименование / Описание</div>
                                                <div className="text-center">Ссылка</div>
                                                <div className="text-right">Кол-во</div>
                                                <div className="text-right">Цена</div>
                                                <div className="text-right">Сумма</div>
                                            </div>
                                        )}
                                        <div className="group relative break-inside-avoid z-0 hover:z-50">
                                            <div className={`grid grid-cols-[1fr_80px_80px_120px_120px] gap-4 items-center p-2 rounded-lg transition-colors ${isExporting ? 'border-b border-gray-200 pb-3' : 'hover:bg-gray-50 border border-transparent hover:border-gray-200'}`}>
                                                <div>
                                                    {isExporting ? (
                                                        <div className="font-bold text-black text-sm whitespace-pre-wrap">{item.title}</div>
                                                    ) : (
                                                        <textarea rows={1} value={item.title} onChange={e => handleItemChange(item.id, 'title', e.target.value)} className="w-full font-bold text-gray-800 text-sm bg-transparent border-b border-dashed border-gray-300 focus:border-blue-50 outline-none resize-none overflow-hidden" placeholder="Описание материала или работы..." style={{minHeight: '28px'}} onInput={(e) => { e.target.style.height = 'auto'; e.target.style.height = e.target.scrollHeight + 'px'; }} />
                                                    )}
                                                </div>
                                                
                                                <div className="text-center pt-1">
                                                    {!isExporting ? (
                                                        canUseLinks ? (
                                                            <>
                                                                <input value={item.link || ''} onChange={e => handleItemChange(item.id, 'link', e.target.value)} placeholder="URL" className="bg-[#f0f0f0] px-2 py-1 rounded-md text-[10px] font-bold text-gray-600 w-full text-center outline-none" />
                                                                {item.link && <a href={item.link} target="_blank" className="text-[#5c5cff] block text-center mt-1">{ExternalLink && <ExternalLink size={14} className="inline" />}</a>}
                                                            </>
                                                        ) : (
                                                            <div className="bg-gray-100 text-gray-400 text-[10px] font-bold py-1 px-1 rounded flex flex-col items-center justify-center cursor-not-allowed" title="Доступно на платных тарифах">
                                                                <span>🔒 PRO</span>
                                                            </div>
                                                        )
                                                    ) : (
                                                        <div className="text-center">{item.link && <a href={item.link} style={{ fontSize: '10px', color: 'blue', textDecoration: 'underline' }}>Ссылка</a>}</div>
                                                    )}
                                                </div>

                                                <div className={`text-right ${isExporting ? 'text-black font-bold' : ''}`}>
                                                    {isExporting ? item.quantity : <input type="number" value={item.quantity} onChange={e => handleItemChange(item.id, 'quantity', e.target.value)} className="w-full text-right bg-transparent outline-none font-bold text-gray-800 border-b border-transparent focus:border-gray-300" />}
                                                </div>
                                                <div className={`text-right ${isExporting ? 'text-black' : ''}`}>
                                                    {isExporting ? formatPriceSafe(item.price) : <input type="number" value={item.price} onChange={e => handleItemChange(item.id, 'price', e.target.value)} onFocus={e => e.target.select()} className="w-full text-right bg-transparent outline-none font-medium text-gray-800 border-b border-transparent focus:border-gray-300" />}
                                                </div>
                                                <div className={`text-right font-bold text-base ${isExporting ? 'text-black' : 'text-gray-800'}`}>
                                                    {formatPriceSafe(item.price * item.quantity)}
                                                </div>
                                            </div>
                                            {!isExporting && (
                                                <div className="absolute -right-12 top-2 opacity-0 group-hover:opacity-100 transition-opacity z-10 bg-white shadow-md border rounded p-1 flex flex-col gap-1">
                                                    <button onClick={() => moveItem(index, -1)} disabled={index === 0} className="hover:text-blue-600 text-gray-400 p-1">{ChevronUp && <ChevronUp size={14} />}</button>
                                                    <button onClick={() => duplicateItem(item.id)} className="text-blue-500 hover:text-blue-700 p-1">{Copy && <Copy size={14} />}</button>
                                                    <button onClick={() => moveItem(index, 1)} disabled={index === items.length - 1} className="hover:text-blue-600 text-gray-400 p-1">{ChevronDown && <ChevronDown size={14} />}</button>
                                                    <div className="w-full h-px bg-gray-200 my-0.5"></div>
                                                    <button onClick={() => deleteItem(item.id)} className="text-red-400 hover:text-red-600 p-1">{Trash2 && <Trash2 size={14} />}</button>
                                                </div>
                                            )}
                                        </div>
                                    </React.Fragment>
                                );
                            })}
                        </div>

                        <div className="mt-12 border-t-2 border-gray-800 pt-6 flex flex-col items-end">
                            <div className="w-64">
                                <div className="flex justify-between items-center">
                                    <span className="text-xl font-black uppercase text-gray-800">Итого:</span>
                                    <span className="text-3xl font-black text-gray-800">{formatPriceSafe(totals.t)} ₽</span>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

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