// Version: 2.11.67 (QR Proxy & Link Copy Failsafe)
var { useState, useEffect, useRef } = React;

const SafePage = ({ name, ...props }) => {
    const Component = window[name];
    if (!Component) {
        return (
            <div className="flex items-center justify-center p-3 bg-red-50 text-red-500 text-xs border border-red-100 rounded-lg m-2 shadow-sm">
                <span>⏳ Ожидание загрузки <b>{name}</b>...</span> 
                <button onClick={() => window.location.reload(true)} className="ml-3 font-bold underline hover:text-red-700">Обновить страницу</button>
            </div>
        );
    }
    return <Component {...props} />;
};

var SafeIcon = ({ name, fallback = 'LayoutTemplate', ...props }) => {
    let Icon = window[name];
    if (!Icon) Icon = window[fallback];
    if (!Icon) return <span className="text-red-500 text-[10px] font-bold" title={name}>[X]</span>;
    return <Icon {...props} />;
};
window.SafeIcon = SafeIcon;

// --- МОБИЛЬНЫЙ ЭКРАН ПОДТВЕРЖДЕНИЯ ---
window.MobileAuth = ({ sessionId }) => {
    const [code, setCode] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        const getCode = async () => {
            try {
                // Создаем простой слепок браузера
                const fingerprint = navigator.userAgent + window.screen.width + window.screen.height;
                const res = await fetch('/api/auth/mobile_confirm', {
                    method: 'POST', 
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ session_id: sessionId, fingerprint })
                });
                
                if (res.ok) {
                    const data = await res.json();
                    setCode(data.code);
                } else {
                    setError("Сессия устарела или сканирование не удалось.");
                }
            } catch(e) { 
                setError("Ошибка сети. Проверьте подключение к интернету."); 
            }
        };
        getCode();
    }, [sessionId]);

    if (error) {
        return (
            <div className="min-h-screen bg-gray-50 flex items-center justify-center p-6">
                <div className="bg-white p-8 rounded-2xl shadow-xl w-full text-center">
                    <div className="text-red-500 mb-4 flex justify-center"><SafeIcon name="AlertTriangle" size={48}/></div>
                    <h2 className="text-xl font-bold text-gray-800 mb-2">Ошибка</h2>
                    <p className="text-gray-500">{error}</p>
                </div>
            </div>
        );
    }

    if (!code) {
        return (
            <div className="min-h-screen bg-blue-50 flex items-center justify-center p-6">
                <div className="flex flex-col items-center justify-center">
                    <SafeIcon name="Loader" className="animate-spin text-blue-600 mb-4" size={48} />
                    <p className="font-bold text-blue-800">Проверка устройства...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gradient-to-br from-blue-600 to-indigo-800 flex items-center justify-center p-6">
            <div className="bg-white p-8 rounded-3xl shadow-2xl w-full text-center transform transition-all">
                <div className="mb-6 flex justify-center text-blue-600"><SafeIcon name="Shield" size={56} /></div>
                <h1 className="text-2xl font-black text-gray-800 mb-2">Ваш код для входа</h1>
                <p className="text-gray-500 mb-8 text-sm">Введите эти 4 цифры на компьютере, чтобы подтвердить авторизацию.</p>
                
                <div className="bg-gray-50 rounded-2xl p-6 mb-8 border-2 border-dashed border-gray-300">
                    <span className="text-6xl font-mono font-black text-blue-600 tracking-[0.5em]">{code}</span>
                </div>
                
                <div className="text-xs text-gray-400">
                    <SafeIcon name="CheckCircle" size={14} className="inline mr-1 text-green-500"/> Устройство проверено
                </div>
            </div>
        </div>
    );
};

// ... existing RequisitesModal, SupportModal components ...
window.RequisitesModal = ({ isOpen, onClose, user, onUpdateUser }) => {
    const [logo, setLogo] = useState('');
    const [reqs, setReqs] = useState('');
    const [loading, setLoading] = useState(false);
    const [isDragging, setIsDragging] = useState(false);

    useEffect(() => {
        if (isOpen && user) {
            setLogo(user.company_logo || '');
            setReqs(user.company_requisites || '');
        }
    }, [isOpen, user]); 

    const uploadFile = async (file) => {
        if (!file) return;
        const formData = new FormData();
        formData.append('file', file);
        setLoading(true);
        try {
            const res = await fetch('/api/upload/image', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.url) setLogo(data.url);
        } catch (err) { alert('Ошибка загрузки'); }
        setLoading(false);
    };

    const handleUpload = (e) => uploadFile(e.target.files[0]);

    const handleDragOver = (e) => { e.preventDefault(); setIsDragging(true); };
    const handleDragLeave = (e) => { e.preventDefault(); setIsDragging(false); };
    const handleDrop = (e) => {
        e.preventDefault();
        setIsDragging(false);
        const file = e.dataTransfer.files[0];
        if (file && file.type.startsWith('image/')) {
            uploadFile(file);
        }
    };

    const handleSave = async () => {
        setLoading(true);
        try {
            await fetch(`/api/user/${user.id}/requisites`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ logo: logo, requisites: reqs })
            });
            onUpdateUser({ ...user, company_logo: logo, company_requisites: reqs });
            onClose();
        } catch (e) { alert("Ошибка сохранения"); }
        setLoading(false);
    };

    if (!isOpen) return null;
    return (
        <div className="modal-overlay z-[6000]" onClick={onClose}>
            <div className="modal-content !max-w-xl bg-gray-50" onClick={e => e.stopPropagation()}>
                <div className="flex justify-between items-center mb-6">
                    <h2 className="text-2xl font-bold text-gray-800">Мои реквизиты</h2>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><SafeIcon name="X" size={24} /></button>
                </div>
                
                <div className="bg-white p-6 rounded-xl border border-gray-200 shadow-sm space-y-6">
                    <div>
                        <label className="block text-sm font-bold text-gray-700 mb-3">Логотип компании</label>
                        <div 
                            className={`flex items-center gap-4 transition-all ${isDragging ? 'ring-2 ring-blue-500 bg-blue-50 rounded-xl' : ''}`}
                            onDragOver={handleDragOver}
                            onDragLeave={handleDragLeave}
                            onDrop={handleDrop}
                        >
                            {logo ? (
                                <div className="relative inline-block border border-gray-200 rounded-lg p-3 bg-gray-50 shadow-inner w-full">
                                    <img src={logo} className="h-24 mx-auto object-contain rounded" alt="Логотип" />
                                    <button onClick={()=>setLogo('')} className="absolute -top-3 -right-3 bg-red-500 hover:bg-red-600 text-white rounded-full p-1.5 shadow-md transition-colors"><SafeIcon name="Trash2" size={14} /></button>
                                </div>
                            ) : (
                                <label className="inline-flex flex-col items-center justify-center gap-2 w-full py-8 bg-gray-50 text-gray-500 rounded-xl cursor-pointer hover:bg-gray-100 hover:text-blue-600 transition-colors font-bold text-sm border-2 border-dashed border-gray-300 hover:border-blue-400 relative">
                                    <SafeIcon name="UploadCloud" size={32} />
                                    <span>Загрузить изображение</span>
                                    <span className="text-xs font-normal text-gray-400">или перетащите сюда (Drag & Drop)</span>
                                    <input type="file" className="hidden" accept="image/*" onChange={handleUpload} disabled={loading} />
                                    {isDragging && <div className="absolute inset-0 bg-blue-500/10 rounded-xl pointer-events-none"></div>}
                                </label>
                            )}
                        </div>
                    </div>
                    
                    <div>
                        <label className="block text-sm font-bold text-gray-700 mb-3">Текст реквизитов (контакты, адрес, ИНН и т.д.)</label>
                        <textarea rows="6" value={reqs} onChange={e=>setReqs(e.target.value)} placeholder="ООО «Ромашка»&#10;ИНН 1234567890&#10;г. Москва, ул. Ленина, д. 1&#10;Телефон: +7 (999) 000-00-00&#10;Email: info@romashka.ru" className="w-full border border-gray-300 rounded-lg p-4 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 resize-y text-sm bg-gray-50 focus:bg-white transition-colors"></textarea>
                    </div>
                </div>

                <div className="mt-6 flex justify-end gap-3">
                    <button onClick={onClose} className="px-6 py-2.5 text-gray-500 hover:bg-gray-200 rounded-lg font-bold transition-colors">Отмена</button>
                    <button onClick={handleSave} disabled={loading} className="px-8 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-bold transition flex items-center gap-2 shadow-sm active:scale-95 disabled:opacity-50">
                        {loading ? <SafeIcon name="Loader" size={16} className="animate-spin" /> : <SafeIcon name="Save" size={16} />}
                        Сохранить
                    </button>
                </div>
            </div>
        </div>
    );
};

window.SupportModal = ({ isOpen, onClose, user }) => {
    const [tab, setTab] = useState('new'); 
    const [tickets, setTickets] = useState([]);
    const [activeTicket, setActiveTicket] = useState(null);
    const [chatData, setChatData] = useState(null);
    
    const [type, setType] = useState('tech'); 
    const [text, setText] = useState('');
    const [imageUrl, setImageUrl] = useState('');
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        if (isOpen && user) loadTickets();
    }, [isOpen, user]);

    useEffect(() => {
        let interval;
        if (isOpen && tab === 'chat' && activeTicket) {
            interval = setInterval(() => loadChat(activeTicket), 5000);
        }
        return () => clearInterval(interval);
    }, [isOpen, tab, activeTicket]);

    const loadTickets = async () => {
        try {
            const res = await fetch(`/api/support/tickets/${user.id}`);
            const data = await res.json();
            setTickets(data);
            if (data.length > 0 && tab === 'new' && !text) setTab('list');
        } catch (e) { console.error(e); }
    };

    const loadChat = async (id) => {
        try {
            const res = await fetch(`/api/support/tickets/${user.id}/${id}`);
            const data = await res.json();
            setChatData(data);
        } catch (e) { console.error(e); }
    };

    const openChat = (id) => {
        setActiveTicket(id);
        setTab('chat');
        setChatData(null);
        loadChat(id);
    };

    const handleImageUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const formData = new FormData();
        formData.append('file', file);
        setLoading(true);
        try {
            const res = await fetch('/api/upload/image', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.url) setImageUrl(data.url);
        } catch (err) { alert('Ошибка загрузки фото'); }
        setLoading(false);
    };

    const submitNewTicket = async () => {
        if (!text.trim()) { alert("Введите текст"); return; }
        setLoading(true);
        try {
            const res = await fetch('/api/support/tickets', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ user_id: user.id, type, text, image_url: imageUrl })
            });
            const data = await res.json();
            if (data.status === 'ok') {
                setText(''); setImageUrl('');
                await loadTickets();
                openChat(data.ticket_id);
            }
        } catch (e) { alert("Ошибка отправки"); }
        setLoading(false);
    };

    const submitMessage = async () => {
        if (!text.trim() && !imageUrl) return;
        setLoading(true);
        try {
            await fetch(`/api/support/tickets/${activeTicket}/messages`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ sender: 'user', text, image_url: imageUrl })
            });
            setText(''); setImageUrl('');
            await loadChat(activeTicket);
        } catch (e) { alert("Ошибка отправки"); }
        setLoading(false);
    };

    if (!isOpen) return null;

    return (
        <div className="modal-overlay z-[6000]" onClick={onClose}>
            <div className="modal-content !p-0 !max-w-3xl overflow-hidden flex flex-col h-[80vh]" onClick={e => e.stopPropagation()}>
                <div className="bg-gray-50 border-b p-4 flex justify-between items-center shrink-0">
                    <h2 className="text-xl font-bold flex items-center gap-2 text-gray-800"><SafeIcon name="LifeBuoy" className="text-blue-600" /> Поддержка</h2>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><SafeIcon name="X" size={24} /></button>
                </div>
                
                <div className="flex bg-gray-100 border-b shrink-0">
                    <button onClick={() => setTab('new')} className={`flex-1 py-3 text-sm font-bold transition ${tab==='new'?'bg-white text-blue-600 border-b-2 border-blue-600':'text-gray-500 hover:bg-gray-50'}`}>Новое обращение</button>
                    <button onClick={() => {setTab('list'); loadTickets()}} className={`flex-1 py-3 text-sm font-bold transition flex items-center justify-center gap-2 ${tab==='list'?'bg-white text-blue-600 border-b-2 border-blue-600':'text-gray-500 hover:bg-gray-50'}`}>Мои обращения {tickets.filter(t=>t.has_unread).length > 0 && <span className="bg-red-500 text-white text-[10px] px-1.5 rounded-full">{tickets.filter(t=>t.has_unread).length}</span>}</button>
                </div>

                <div className="flex-1 overflow-y-auto bg-white p-6">
                    {tab === 'new' && (
                        <div className="max-w-xl mx-auto space-y-4">
                            <div>
                                <label className="block text-sm font-bold text-gray-700 mb-2">Тема обращения</label>
                                <div className="flex gap-2">
                                    <button onClick={()=>setType('tech')} className={`flex-1 py-2 rounded-lg font-bold text-sm border transition ${type==='tech'?'bg-blue-50 border-blue-400 text-blue-700':'bg-white border-gray-200 text-gray-500'}`}>Вопрос / Проблема</button>
                                    <button onClick={()=>setType('idea')} className={`flex-1 py-2 rounded-lg font-bold text-sm border transition ${type==='idea'?'bg-yellow-50 border-yellow-400 text-yellow-700':'bg-white border-gray-200 text-gray-500'}`}>Предложить улучшение</button>
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-gray-700 mb-2">Подробное описание</label>
                                <textarea rows="6" value={text} onChange={e=>setText(e.target.value)} placeholder="Опишите ситуацию..." className="w-full border border-gray-300 rounded-lg p-3 outline-none focus:border-blue-500 resize-none"></textarea>
                            </div>
                            <div>
                                {imageUrl ? (
                                    <div className="relative inline-block border rounded-lg p-1">
                                        <img src={imageUrl} className="h-20 object-contain rounded" />
                                        <button onClick={()=>setImageUrl('')} className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1"><SafeIcon name="X" size={12} /></button>
                                    </div>
                                ) : (
                                    <label className="inline-flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg cursor-pointer hover:bg-gray-200 transition text-sm font-bold">
                                        <SafeIcon name="ImageIcon" size={16} /> Прикрепить фото
                                        <input type="file" className="hidden" accept="image/*" onChange={handleImageUpload} />
                                    </label>
                                )}
                            </div>
                            <button onClick={submitNewTicket} disabled={loading || !text.trim()} className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold hover:bg-blue-700 disabled:opacity-50 transition mt-4">Отправить</button>
                        </div>
                    )}

                    {tab === 'list' && (
                        <div className="space-y-3">
                            {tickets.length === 0 ? <div className="text-center text-gray-400 py-10">У вас пока нет обращений</div> : 
                                tickets.map(t => (
                                    <div key={t.id} onClick={()=>openChat(t.id)} className="border border-gray-200 rounded-xl p-4 cursor-pointer hover:bg-gray-50 transition relative">
                                        <div className="flex justify-between items-start mb-2">
                                            <span className={`text-xs font-bold px-2 py-1 rounded ${t.type==='tech'?'bg-blue-100 text-blue-700':'bg-yellow-100 text-yellow-700'}`}>{t.type==='tech'?'Вопрос':'Идея'} #{t.id}</span>
                                            <span className={`text-xs font-bold ${t.status==='closed'?'text-gray-400':'text-green-500'}`}>{t.status==='closed'?'Закрыт':'Открыт'}</span>
                                        </div>
                                        <div className="text-sm text-gray-800 line-clamp-1">{t.last_message || '...'}</div>
                                        <div className="text-xs text-gray-400 mt-2">{t.updated_at}</div>
                                        {t.has_unread && <div className="absolute top-4 right-4 w-3 h-3 bg-red-500 rounded-full animate-pulse"></div>}
                                    </div>
                                ))
                            }
                        </div>
                    )}

                    {tab === 'chat' && chatData && (
                        <div className="flex flex-col h-full">
                            <div className="flex items-center gap-2 mb-4 pb-2 border-b shrink-0">
                                <button onClick={()=>setTab('list')} className="text-blue-600 hover:underline text-sm font-bold flex items-center gap-1">← К списку</button>
                                <span className="ml-auto text-xs font-bold text-gray-400">Статус: {chatData.status === 'closed' ? 'Закрыт' : 'Открыт'}</span>
                            </div>
                            <div className="flex-1 overflow-y-auto space-y-4 mb-4 pr-2">
                                {chatData.messages.map(m => (
                                    <div key={m.id} className={`flex flex-col ${m.sender === 'user' ? 'items-end' : 'items-start'}`}>
                                        <div className={`max-w-[80%] rounded-2xl p-3 ${m.sender === 'user' ? 'bg-blue-600 text-white rounded-br-none' : 'bg-gray-100 text-gray-800 rounded-bl-none'}`}>
                                            {m.image && <img src={m.image} className="max-w-full rounded mb-2" />}
                                            <div className="text-sm whitespace-pre-wrap">{m.text}</div>
                                        </div>
                                        <span className="text-[10px] text-gray-400 mt-1">{m.sender==='admin'?'Служба поддержки':user.name} • {m.time}</span>
                                    </div>
                                ))}
                            </div>
                            {chatData.status === 'open' ? (
                                <div className="shrink-0 bg-gray-50 rounded-xl p-2 border flex items-end gap-2">
                                     <label className="p-2 text-gray-400 hover:text-blue-600 cursor-pointer transition shrink-0">
                                        <SafeIcon name="ImageIcon" size={20} />
                                        <input type="file" className="hidden" accept="image/*" onChange={handleImageUpload} />
                                    </label>
                                    <div className="flex-1 flex flex-col gap-2">
                                        {imageUrl && (
                                            <div className="relative inline-block w-max mt-2 ml-2">
                                                <img src={imageUrl} className="h-12 object-contain rounded border" />
                                                <button onClick={()=>setImageUrl('')} className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-0.5"><SafeIcon name="X" size={10} /></button>
                                            </div>
                                        )}
                                        <textarea rows={imageUrl ? "2" : "1"} value={text} onChange={e=>setText(e.target.value)} onKeyDown={e=>{if(e.key==='Enter' && !e.shiftKey){e.preventDefault(); submitMessage()}}} placeholder="Ваш ответ..." className="w-full bg-transparent p-2 outline-none resize-none text-sm"></textarea>
                                    </div>
                                    <button onClick={submitMessage} disabled={loading || (!text.trim() && !imageUrl)} className="p-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition disabled:opacity-50 shrink-0"><SafeIcon name="Send" size={18} /></button>
                                </div>
                            ) : (
                                <div className="text-center text-sm text-gray-500 bg-gray-50 p-3 rounded-lg border border-gray-200">Обращение закрыто. Для новых вопросов создайте новую заявку.</div>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};


window.App = () => {
    const [view, setView] = useState('loading');
    const [user, setUser] = useState(null);
    const [botLink, setBotLink] = useState('');
    const [projects, setProjects] = useState([]);
    const [currentProject, setCurrentProject] = useState(null);
    const [prices, setPrices] = useState({ manager: 150, speed: 250, enable_furniture: false, global_announcement: '', announcement_exclude_vip: true });
    const [useAquaPlaza, setUseAquaPlaza] = useState(true);
    
    const [sessionToken, setSessionToken] = useState(localStorage.getItem('kp_session_token') || '');
    
    // Auth State (PC)
    const [authStep, setAuthStep] = useState(1); // 1: phone, 2: qr, 3: code
    const [phoneInput, setPhoneInput] = useState('');
    const [authSessionId, setAuthSessionId] = useState('');
    const [authCode, setAuthCode] = useState('');
    const [qrUrl, setQrUrl] = useState('');
    const [qrImageBase64, setQrImageBase64] = useState(''); // NEW: Хранит саму картинку QR
    const [authError, setAuthError] = useState('');

    // Admin backdoor
    const [showAdminLogin, setShowAdminLogin] = useState(false);
    const [adminUser, setAdminUser] = useState('');
    const [adminPass, setAdminPass] = useState('');
    const [adminLoading, setAdminLoading] = useState(false);

    const handleLogout = () => { 
        localStorage.removeItem('kp_user'); 
        localStorage.removeItem('kp_auth_date'); 
        localStorage.removeItem('kp_session_token');
        setSessionToken(''); 
        setUser(null); 
        setAuthStep(1);
        setPhoneInput('');
        setAuthCode('');
        setQrImageBase64('');
        setView('landing'); 
    };

    // Восстановление сессии
    const refreshUserStatus = async (currentUser, currentToken) => {
        if (!currentUser) return null;
        try {
            const res = await fetch(`/api/user/status/${currentUser.id}?token=${currentToken || 'INVALID'}&t=${Date.now()}`);
            
            if (res.status === 401) {
                const err = await res.json();
                if (err.status === 'session_expired') {
                    alert("Выполнен вход с другого устройства. Ваша сессия завершена.");
                    handleLogout();
                    return null;
                }
            }
            if (res.ok) {
                const status = await res.json();
                const updatedUser = { 
                    ...currentUser, 
                    is_premium: status.is_premium,
                    is_vip: status.is_vip,
                    tier: status.tier,
                    sub_end: status.sub_end,
                    days_left: status.days_left,
                    total_invites: status.total_invites,
                    paid_invites: status.paid_invites,
                    unread_support: status.unread_support,
                    company_logo: status.company_logo !== undefined ? status.company_logo : currentUser.company_logo,
                    company_requisites: status.company_requisites !== undefined ? status.company_requisites : currentUser.company_requisites
                };
                setUser(updatedUser);
                localStorage.setItem('kp_user', JSON.stringify(updatedUser));
                return updatedUser;
            }
        } catch (e) {
            console.error("Failed to refresh user status", e);
        }
        return currentUser;
    };

    // Инициализация при загрузке приложения (проверка URL и восстановление сессии)
    useEffect(() => {
        const urlParams = new URLSearchParams(window.location.search);
        const mode = urlParams.get('mode');
        const sessId = urlParams.get('session_id');
        const startParam = urlParams.get('start'); 
        
        // 1. Проверяем, не открыт ли сайт с мобилки по ссылке из QR-кода
        if (mode === 'mobile_auth' && sessId) {
            setView('mobile_auth');
            setAuthSessionId(sessId);
            return; // Прерываем проверку сессии, чтобы не сбросить мобильный экран
        }

        // 2. Обычный режим (ПК или прямой заход). Проверяем сохраненную сессию
        const savedUser = localStorage.getItem('kp_user');
        const savedAuthDate = localStorage.getItem('kp_auth_date');
        const savedSetting = localStorage.getItem('use_aquaplaza');
        if (savedSetting === 'false') setUseAquaPlaza(false);

        const now = Date.now();
        const oneDay = 24 * 60 * 60 * 1000;

        if (savedUser && savedAuthDate && (now - parseInt(savedAuthDate) < oneDay)) {
            try {
                const u = JSON.parse(savedUser);
                refreshUserStatus(u, sessionToken).then((freshUser) => {
                    if (freshUser) {
                        setUser(freshUser); 
                        setView('dashboard'); 
                        fetchProjects(freshUser.id);
                    }
                });
                
                 fetch('/api/config/public').then(r => r.json()).then(d => {
                     if(d) setPrices(prev => ({ ...prev, manager: d.price_manager, speed: d.price_speed, enable_furniture: d.enable_furniture, global_announcement: d.global_announcement || '', announcement_exclude_vip: d.announcement_exclude_vip !== undefined ? d.announcement_exclude_vip : true }));
                 }).catch(e => console.error("Price fetch error", e));
            } catch (e) { 
                localStorage.removeItem('kp_user'); 
                if (startParam) setView('auth');
                else setView('landing');
            }
        } else {
            localStorage.removeItem('kp_user'); localStorage.removeItem('kp_auth_date'); 
            if (startParam) {
                setView('auth');
            } else {
                setView('landing');
            }
        }
    }, []); // <-- Пустой массив зависимостей, срабатывает 1 раз!

    // Polling для ПК во время шага QR
    useEffect(() => {
        let interval;
        if (view === 'auth' && authStep === 2 && authSessionId) {
            interval = setInterval(async () => {
                try {
                    const res = await fetch(`/api/auth/qr_poll/${authSessionId}`);
                    if (res.ok) {
                        const data = await res.json();
                        if (data.status === 'scanned') {
                            setAuthStep(3); // Переключаем на ввод 4-значного кода
                        }
                    }
                } catch (e) { console.error("Poll err", e); }
            }, 2000);
        }
        return () => clearInterval(interval);
    }, [view, authStep, authSessionId]);

    useEffect(() => {
        let interval;
        if (view === 'dashboard' && user) {
            interval = setInterval(() => refreshUserStatus(user, sessionToken), 10000);
        }
        return () => clearInterval(interval);
    }, [view, user, sessionToken]);

    const toggleAquaPlaza = () => {
        const newValue = !useAquaPlaza;
        setUseAquaPlaza(newValue);
        localStorage.setItem('use_aquaplaza', newValue.toString());
    };

    const fetchProjects = async (uid) => { try { const res = await fetch(`/api/projects/${uid}?t=${Date.now()}`); const data = await res.json(); setProjects(Array.isArray(data) ? data : []); } catch (e) { setProjects([]); } };
    const loadProject = async (pid) => {
        try {
            const res = await fetch(`/api/project/${pid}`);
            if (res.ok) {
                const data = await res.json();
                const parsedData = JSON.parse(data.data);
                setCurrentProject({ id: data.id, data: parsedData, name: data.name });
                if (parsedData.templateType === 'furniture') setView('furniture_editor');
                else setView('editor');
            }
        } catch (e) { alert("Ошибка загрузки"); }
    };

    const deleteProject = async (e, pid) => {
        e.stopPropagation();
        if (!confirm("Удалить проект?")) return;
        try { await fetch(`/api/projects/${pid}`, { method: 'DELETE' }); fetchProjects(user.id); } catch (e) { alert("Ошибка удаления"); }
    };

    // === ФУНКЦИИ НОВОГО ЛОГИНА (PC) ===
    const handlePhoneSubmit = async () => {
        const cleanPhone = phoneInput.replace(/\D/g, '');
        
        // Скрытый вход для админа по номеру
        if (cleanPhone === '79253115397') {
            setShowAdminLogin(true);
            setPhoneInput(''); // очистим поле ввода
            return;
        }

        if (cleanPhone.length < 10) {
            setAuthError('Введите корректный номер телефона');
            return;
        }
        setAuthError('');
        
        try {
            const res = await fetch('/api/auth/qr_init', {
                method: 'POST', headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ phone: cleanPhone })
            });
            if (res.ok) {
                const data = await res.json();
                setAuthSessionId(data.session_id);
                // Формируем ссылку для QR кода (ведет на наш же сайт с параметрами)
                const currentDomain = window.location.origin;
                const link = `${currentDomain}/?mode=mobile_auth&session_id=${data.session_id}`;
                setQrUrl(link);
                setAuthStep(2);
                setQrImageBase64(''); // Очищаем старую картинку, если была
                
                // Запрашиваем саму картинку QR-кода через наш бэкенд прокси, чтобы обойти AdBlock
                const qrApiUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(link)}`;
                if (window.urlToBase64) {
                    const b64 = await window.urlToBase64(qrApiUrl);
                    if (b64) setQrImageBase64(b64);
                }
            } else {
                setAuthError('Ошибка инициализации сессии');
            }
        } catch (e) { setAuthError('Ошибка сети'); }
    };

    const handleCodeSubmit = async () => {
        if (authCode.length !== 4) {
            setAuthError('Код должен состоять из 4 цифр');
            return;
        }
        setAuthError('');

        try {
            const res = await fetch('/api/auth/qr_verify', {
                method: 'POST', headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ session_id: authSessionId, code: authCode })
            });
            const data = await res.json();
            
            if (res.ok && data.status === 'ok') {
                setUser(data.user);
                if (data.bot_link) setBotLink(data.bot_link);
                if (data.config) setPrices({ manager: data.config.price_manager, speed: data.config.price_speed, enable_furniture: data.config.enable_furniture, global_announcement: data.config.global_announcement || '', announcement_exclude_vip: data.config.announcement_exclude_vip !== undefined ? data.config.announcement_exclude_vip : true });
                
                localStorage.setItem('kp_user', JSON.stringify(data.user));
                localStorage.setItem('kp_auth_date', Date.now().toString());
                localStorage.setItem('kp_session_token', data.token);
                setSessionToken(data.token); 
                
                await fetchProjects(data.user.id);
                setView('dashboard');
            } else {
                setAuthError(data.detail || 'Неверный код. Попробуйте еще раз.');
            }
        } catch (e) { setAuthError('Ошибка проверки кода'); }
    };

    const handleAdminLogin = async () => {
        if(!adminUser || !adminPass) return;
        setAdminLoading(true);
        try {
            const res = await fetch('/api/auth/admin_login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username: adminUser, password: adminPass })
            });
            const data = await res.json();
            if(res.ok && data.status === 'ok') {
                setUser(data.user);
                if (data.bot_link) setBotLink(data.bot_link);
                if (data.config) setPrices({ manager: data.config.price_manager, speed: data.config.price_speed, enable_furniture: data.config.enable_furniture, global_announcement: data.config.global_announcement || '', announcement_exclude_vip: data.config.announcement_exclude_vip !== undefined ? data.config.announcement_exclude_vip : true });
                
                localStorage.setItem('kp_user', JSON.stringify(data.user));
                localStorage.setItem('kp_auth_date', Date.now().toString());
                localStorage.setItem('kp_session_token', data.token);
                setSessionToken(data.token); 
                
                await fetchProjects(data.user.id);
                setShowAdminLogin(false);
                setView('dashboard');
            } else {
                alert("Ошибка входа: " + (data.detail || "Неверный логин или пароль"));
            }
        } catch (e) {
            alert("Сетевая ошибка");
        }
        setAdminLoading(false);
    };

    const renderAppContent = () => {
        if (view === 'loading') return <div className="min-h-screen flex items-center justify-center"><SafeIcon name="Loader" className="animate-spin text-blue-600" size={48} /></div>;
        
        // Экран подтверждения на смартфоне
        if (view === 'mobile_auth') return <SafePage name="MobileAuth" sessionId={authSessionId} />;
        
        if (view === 'editor') return <SafePage name="Editor" user={user} initialProject={currentProject} useAquaPlaza={useAquaPlaza} onBack={() => { setView('dashboard'); fetchProjects(user.id); }} />;
        if (view === 'furniture_editor') return <SafePage name="FurnitureEditor" user={user} initialProject={currentProject} onBack={() => { setView('dashboard'); fetchProjects(user.id); }} />;
        
        if (view === 'landing') {
            return <SafePage name="LandingPage" onStart={() => {setAuthStep(1); setView('auth');}} />;
        }

        if (view === 'auth') {
            return (
                <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
                    <div className="bg-white p-8 rounded-3xl shadow-2xl max-w-md w-full relative overflow-hidden text-center transform transition-all">
                        <div className="mb-6 flex justify-center text-blue-600"><SafeIcon name="Shield" size={56} /></div>
                        <h1 className="text-3xl font-black text-gray-800 mb-2">Безопасный Вход</h1>
                        
                        {/* ШАГ 1: ВВОД ТЕЛЕФОНА */}
                        {authStep === 1 && (
                            <div className="w-full">
                                <p className="text-gray-500 mb-6">Введите номер телефона для безопасной идентификации (Identification-First).</p>
                                <input 
                                    type="tel" 
                                    placeholder="+7 (999) 000-00-00" 
                                    value={phoneInput} 
                                    onChange={(e) => {
                                        let val = e.target.value;
                                        if (val === '8') val = '+7 ';
                                        else if (val === '7') val = '+7 ';
                                        else if (val === '9') val = '+7 9';
                                        else if (val.length > 1 && !val.startsWith('+')) {
                                            if (val.startsWith('8')) val = '+7 ' + val.slice(1);
                                            else if (val.startsWith('7')) val = '+7 ' + val.slice(1);
                                            else if (val.startsWith('9')) val = '+7 ' + val;
                                        }
                                        setPhoneInput(val);
                                    }}
                                    onKeyDown={(e) => e.key === 'Enter' && handlePhoneSubmit()}
                                    className="w-full bg-gray-50 border-2 border-gray-200 rounded-xl px-4 py-4 text-xl font-bold text-center text-gray-800 focus:border-blue-500 focus:bg-white outline-none transition-colors mb-4"
                                />
                                {authError && <div className="text-red-500 text-sm font-bold mb-4">{authError}</div>}
                                <button onClick={handlePhoneSubmit} disabled={phoneInput.length < 5} className="w-full bg-blue-600 text-white rounded-xl py-4 font-bold text-lg hover:bg-blue-700 transition active:scale-95 disabled:opacity-50">
                                    Далее
                                </button>
                            </div>
                        )}

                        {/* ШАГ 2: ПОКАЗ QR */}
                        {authStep === 2 && (
                            <div className="w-full">
                                <p className="text-gray-500 mb-6 font-medium">Наведите камеру смартфона на QR-код для подтверждения входа.</p>
                                <div className="bg-white p-4 rounded-2xl shadow-inner border-2 border-dashed border-gray-300 inline-block mb-4 relative">
                                    {qrImageBase64 ? (
                                        <img src={qrImageBase64} alt="QR Code" className="w-48 h-48 animate-fade-in" />
                                    ) : (
                                        <div className="w-48 h-48 flex flex-col items-center justify-center text-blue-500">
                                            <SafeIcon name="Loader" size={32} className="animate-spin mb-2" />
                                            <span className="text-xs font-bold">Генерация QR...</span>
                                        </div>
                                    )}
                                    <div className="absolute inset-0 bg-blue-500/5 rounded-2xl pointer-events-none"></div>
                                </div>
                                
                                <div className="flex flex-col items-center gap-2 text-sm text-blue-600 font-bold bg-blue-50 py-3 px-4 rounded-xl border border-blue-100 mb-4">
                                    <div className="flex items-center gap-2">
                                        <SafeIcon name="Loader" size={18} className="animate-spin" /> Ожидаем сканирования...
                                    </div>
                                </div>

                                {/* Дополнительная подстраховка, если QR заблокирован вообще всем чем можно */}
                                <button 
                                    onClick={() => {
                                        navigator.clipboard.writeText(qrUrl).then(() => alert("Ссылка скопирована! Отправьте её себе на телефон (например, в 'Избранное' Telegram) и откройте там."));
                                    }} 
                                    className="text-xs font-bold text-blue-500 hover:text-blue-700 underline block w-full mb-4 transition-colors"
                                >
                                    Не грузится QR? Скопировать ссылку
                                </button>

                                <button onClick={() => setAuthStep(1)} className="text-sm text-gray-400 hover:text-gray-600 underline font-medium">Отмена</button>
                            </div>
                        )}

                        {/* ШАГ 3: ВВОД КОДА ИЗ ТЕЛЕФОНА */}
                        {authStep === 3 && (
                            <div className="w-full">
                                <p className="text-gray-500 mb-6 font-medium">Устройство проверено. Введите <span className="font-bold text-gray-800">4-значный код</span>, который появился на экране смартфона.</p>
                                <input 
                                    type="text" 
                                    maxLength="4"
                                    placeholder="0000" 
                                    value={authCode} 
                                    onChange={(e) => {
                                        const val = e.target.value.replace(/\D/g, '');
                                        setAuthCode(val);
                                        if (val.length === 4) {
                                            // Небольшой хак, чтобы дать state обновиться перед вызовом
                                            setTimeout(() => document.getElementById('verify-btn').click(), 50);
                                        }
                                    }}
                                    className="w-full bg-gray-50 border-2 border-blue-200 rounded-xl px-4 py-4 text-4xl tracking-[0.5em] font-black text-center text-blue-600 focus:border-blue-500 focus:bg-white outline-none transition-colors mb-4 font-mono"
                                    autoFocus
                                />
                                {authError && <div className="text-red-500 text-sm font-bold mb-4 bg-red-50 py-2 rounded-lg">{authError}</div>}
                                <button id="verify-btn" onClick={handleCodeSubmit} disabled={authCode.length < 4} className="w-full bg-blue-600 text-white rounded-xl py-4 font-bold text-lg hover:bg-blue-700 transition active:scale-95 disabled:opacity-50">
                                    Войти
                                </button>
                                <button onClick={() => setAuthStep(1)} className="mt-4 text-sm text-gray-400 hover:text-gray-600 underline font-medium">Вернуться в начало</button>
                            </div>
                        )}

                        <div className="mt-8 pt-4 border-t border-gray-100 text-[10px] text-gray-300 font-mono text-center">
                            <span onClick={() => setShowAdminLogin(true)} className="cursor-pointer hover:text-gray-400 transition-colors">v2.11.67</span> | Хост: {window.location.hostname}
                        </div>
                        
                        {/* Скрытая модалка для логина админа (Backdoor) */}
                        {showAdminLogin && (
                            <div className="absolute inset-0 bg-white/95 backdrop-blur z-[100] flex flex-col justify-center items-center p-8">
                                <h2 className="text-2xl font-black mb-6 text-gray-800"><SafeIcon name="Shield" size={28} className="inline mr-2 text-blue-600"/>Admin Backdoor</h2>
                                <input type="text" placeholder="Username" value={adminUser} onChange={e => setAdminUser(e.target.value)} className="w-full mb-3 p-4 border-2 border-gray-200 rounded-xl focus:border-blue-500 outline-none font-bold" />
                                <input type="password" placeholder="Password" value={adminPass} onChange={e => setAdminPass(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleAdminLogin()} className="w-full mb-6 p-4 border-2 border-gray-200 rounded-xl focus:border-blue-500 outline-none font-bold" />
                                <div className="flex w-full gap-3">
                                    <button onClick={() => setShowAdminLogin(false)} className="flex-1 py-4 text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold transition">Отмена</button>
                                    <button onClick={handleAdminLogin} disabled={adminLoading} className="flex-1 py-4 bg-blue-600 text-white rounded-xl font-bold shadow hover:bg-blue-700 transition flex justify-center items-center gap-2">
                                        {adminLoading ? <SafeIcon name="Loader" size={20} className="animate-spin" /> : "Вход"}
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            );
        }

        return (
            <Dashboard 
                user={user} 
                projects={projects} 
                botLink={botLink}
                prices={prices}
                sessionToken={sessionToken}
                useAquaPlaza={useAquaPlaza}
                onToggleAquaPlaza={toggleAquaPlaza}
                onRefreshUser={() => refreshUserStatus(user, sessionToken)}
                onCreateStandard={() => { setCurrentProject(null); setView('editor'); }}
                onCreateFurniture={() => { setCurrentProject(null); setView('furniture_editor'); }}
                onLoadProject={loadProject}
                onDeleteProject={deleteProject}
                onLogout={handleLogout}
                onUpdateUser={(newUser) => setUser(newUser)}
            />
        );
    };

    return (
        <>
            {renderAppContent()}
        </>
    );
};

const Dashboard = ({ user, projects, botLink, prices, sessionToken, useAquaPlaza, onToggleAquaPlaza, onRefreshUser, onCreateStandard, onCreateFurniture, onLoadProject, onDeleteProject, onLogout, onUpdateUser }) => {
    const [showTariffModal, setShowTariffModal] = useState(false);
    const [showSupportModal, setShowSupportModal] = useState(false);
    const [showIntegrations, setShowIntegrations] = useState(false);
    const [showReqModal, setShowReqModal] = useState(false);
    
    const [dismissedAnnouncement, setDismissedAnnouncement] = useState(localStorage.getItem('kp_dismissed_announcement') || '');
    
    const handleDismissAnnouncement = () => {
        if (prices?.global_announcement) {
            setDismissedAnnouncement(prices.global_announcement);
            localStorage.setItem('kp_dismissed_announcement', prices.global_announcement);
        }
    };
    
    return (
        <div className="min-h-screen bg-gray-50 pb-20 relative">
            <header className="bg-white shadow-sm border-b sticky top-0 z-40">
                <div className="max-w-7xl mx-auto px-4 md:px-8 py-4 flex justify-between items-center">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-blue-600 rounded-xl flex items-center justify-center text-white font-black text-xl shadow-lg">КП</div>
                        <h1 className="text-xl font-bold hidden md:block text-gray-800">Конструктор КП</h1>
                    </div>
                    <div className="flex items-center gap-2 md:gap-4 overflow-x-auto no-scrollbar pb-1 md:pb-0">
                        {user.is_vip ? (
                            <span className="bg-yellow-100 text-yellow-800 px-3 py-1.5 rounded-lg text-sm font-bold border border-yellow-200 shadow-sm flex items-center gap-1 whitespace-nowrap"><SafeIcon name="Crown" size={14}/> VIP (Для своих)</span>
                        ) : (
                            <div className="flex items-center gap-2">
                                <span className="bg-purple-100 text-purple-800 px-3 py-1.5 rounded-lg text-sm font-bold border border-purple-200 shadow-sm flex items-center gap-1 whitespace-nowrap">
                                    <SafeIcon name="Star" size={14}/> {user.tier.toUpperCase()} {user.sub_end ? `(до ${user.sub_end})` : ''}
                                </span>
                                {user.tier !== 'speed' && (
                                    <button onClick={() => setShowTariffModal(true)} className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-1.5 rounded-lg text-sm font-bold transition shadow-sm whitespace-nowrap flex items-center gap-1"><SafeIcon name="Star" size={14} className="fill-current text-yellow-300"/> Улучшить тариф</button>
                                )}
                            </div>
                        )}
                        
                        <button onClick={() => setShowSupportModal(true)} className={`flex items-center gap-2 px-4 py-1.5 rounded-lg font-bold text-sm shadow-sm transition-all border ${user?.unread_support ? 'bg-red-100 text-red-600 border-red-300 animate-pulse' : 'bg-gray-100 text-gray-600 border-gray-200 hover:bg-gray-200'}`}>
                            <SafeIcon name="LifeBuoy" size={16} /> Поддержка {user?.unread_support > 0 && <div className="w-2 h-2 bg-red-500 rounded-full ml-1"></div>}
                        </button>
                        
                        <button onClick={() => setShowIntegrations(true)} className="flex items-center gap-2 px-4 py-1.5 text-sm font-bold text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition whitespace-nowrap"><SafeIcon name="Settings" size={16}/> Интеграции</button>
                        
                        {user.role === 'admin' && (
                            <button onClick={() => window.location.href = '/admin'} className="flex items-center gap-2 px-4 py-1.5 text-sm font-bold text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg border border-blue-200 transition whitespace-nowrap">
                                <SafeIcon name="Shield" size={16}/> Админка
                            </button>
                        )}

                        <div className="h-8 w-px bg-gray-200 mx-2 hidden md:block"></div>
                        <div className="flex items-center gap-3 bg-white border px-3 py-1 rounded-full shadow-sm">
                            <span className="text-sm font-bold text-gray-700 max-w-[100px] truncate">{user.name}</span>
                            <button onClick={onLogout} className="text-red-500 hover:bg-red-50 p-1.5 rounded-full transition"><SafeIcon name="LogOut" size={16} /></button>
                        </div>
                    </div>
                </div>
            </header>

            {showIntegrations && (
                <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center" onClick={() => setShowIntegrations(false)}>
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-md overflow-hidden" onClick={e => e.stopPropagation()}>
                        <div className="p-4 border-b bg-gray-50 flex justify-between items-center">
                            <h3 className="text-lg font-bold">Интеграции</h3>
                            <button onClick={() => setShowIntegrations(false)} className="text-gray-400 hover:text-gray-600">
                                <SafeIcon name="X" size={24} />
                            </button>
                        </div>
                        <div className="p-6 border-b border-gray-100">
                            <div className="flex items-center justify-between">
                                <div>
                                    <div className="font-bold text-gray-800">Aquaplaza-online.ru</div>
                                    <div className="text-sm text-gray-500 mt-1">Поиск товаров по артикулу</div>
                                </div>
                                <div className="flex items-center gap-4">
                                    <SafePage name="ApiTestButton" />
                                    <button onClick={onToggleAquaPlaza} className={`w-12 h-6 rounded-full p-1 transition-colors ${useAquaPlaza ? 'bg-green-500' : 'bg-gray-300'}`}>
                                        <div className={`w-4 h-4 bg-white rounded-full shadow-md transform transition-transform ${useAquaPlaza ? 'translate-x-6' : ''}`}></div>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div className="p-4 bg-gray-50 text-right">
                            <button onClick={() => setShowIntegrations(false)} className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-bold">Готово</button>
                        </div>
                    </div>
                </div>
            )}

            <main className="max-w-7xl mx-auto px-4 md:px-8 py-8 w-full">
                
                {prices?.global_announcement && prices.global_announcement !== dismissedAnnouncement && (!user?.is_vip || !prices?.announcement_exclude_vip) && (
                    <div className="bg-blue-50 border border-blue-200 p-4 sm:p-5 rounded-xl mb-6 shadow-sm relative w-full box-border">
                        <div className="flex items-start gap-3 pr-8 min-w-0 w-full">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-blue-600 mt-0.5 shrink-0">
                                <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"></path>
                                <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"></path>
                            </svg>
                            <div className="min-w-0 flex-1">
                                <div className="text-sm font-medium text-blue-900 whitespace-pre-wrap break-words">
                                    {prices.global_announcement}
                                </div>
                            </div>
                        </div>
                        <button onClick={handleDismissAnnouncement} className="absolute top-3 right-3 text-blue-400 hover:text-blue-700 hover:bg-blue-100 rounded-full p-1.5 transition-colors z-10 shrink-0 cursor-pointer" title="Закрыть уведомление">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <line x1="18" y1="6" x2="6" y2="18"></line>
                                <line x1="6" y1="6" x2="18" y2="18"></line>
                            </svg>
                        </button>
                    </div>
                )}
                
                <SafePage name="BonusBanner" refLink={user?.ref_link} isVip={user?.is_vip} />

                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 mb-10">
                    <div onClick={onCreateStandard} className="bg-white border-2 border-dashed border-blue-300 rounded-2xl flex flex-col items-center justify-center cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-all h-48 group shadow-sm">
                        <div className="w-16 h-16 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mb-4 group-hover:scale-110 transition-transform"><SafeIcon name="Plus" size={32} /></div>
                        <span className="font-bold text-blue-600">Создать Товарное КП</span>
                        <span className="text-xs text-gray-400 mt-1">Классическая таблица</span>
                    </div>

                    {(user?.role === 'admin' || prices?.enable_furniture) && (
                        <div onClick={onCreateFurniture} className="bg-white border-2 border-dashed border-purple-300 rounded-2xl flex flex-col items-center justify-center cursor-pointer hover:border-purple-500 hover:bg-purple-50 transition-all h-48 group shadow-sm relative">
                            {user?.role === 'admin' && !prices?.enable_furniture && (
                                <div className="absolute top-3 right-3 bg-gray-800/80 backdrop-blur-sm text-white text-[10px] font-bold px-2 py-1 rounded">Скрыто от юзеров</div>
                            )}
                            <div className="w-16 h-16 bg-purple-100 text-purple-600 rounded-full flex items-center justify-center mb-4 group-hover:scale-110 transition-transform"><SafeIcon name="Sofa" fallback="LayoutTemplate" size={32} /></div>
                            <span className="font-bold text-purple-600">Создать Мебельное КП</span>
                            <span className="text-xs text-gray-400 mt-1">Визуал + расчет (ЛДСП и т.д.)</span>
                        </div>
                    )}
                </div>

                <div className="flex flex-col md:flex-row items-start md:items-center justify-between mb-6 gap-4 border-t border-gray-200 pt-8">
                    <h2 className="text-3xl font-black text-gray-800">Мои Проекты</h2>
                    <button onClick={() => setShowReqModal(true)} className="text-red-500 hover:bg-red-50 border border-red-200 bg-white px-4 py-2 rounded-lg font-bold transition flex items-center gap-2 shadow-sm">
                        <SafeIcon name="ImageIcon" size={18} /> Мои реквизиты и логотип
                    </button>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                    {projects.map(p => (
                        <div key={p.id} onClick={() => onLoadProject(p.id)} className="kp-card cursor-pointer group bg-white border border-gray-100 rounded-xl p-4 flex items-start gap-3 relative shadow-sm hover:shadow-md transition-all hover:border-blue-200">
                            <div className="p-2.5 bg-orange-50 text-orange-500 rounded-lg shrink-0 group-hover:bg-orange-100 transition-colors">
                                <SafeIcon name="FileText" size={24} />
                            </div>
                            <div className="flex-1 min-w-0 pr-6 flex flex-col justify-center">
                                <h3 className="font-bold text-gray-800 text-sm mb-1 line-clamp-2 leading-tight" title={p.name}>{p.name}</h3>
                                <div className="text-[11px] text-gray-500">
                                    Обновлено: {new Date(p.updated_at).toLocaleString('ru-RU', {day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute:'2-digit'})}
                                </div>
                            </div>
                            <button onClick={(e) => { e.stopPropagation(); onDeleteProject(e, p.id); }} className="absolute top-4 right-4 text-gray-400 hover:text-red-500 p-1.5 bg-white rounded-md hover:bg-red-50 transition-colors opacity-0 group-hover:opacity-100 shadow-sm border border-gray-100">
                                <SafeIcon name="Trash2" size={14} />
                            </button>
                        </div>
                    ))}
                </div>
            </main>

            <SafePage 
                name="RequisitesModal" 
                isOpen={showReqModal} 
                onClose={() => setShowReqModal(false)} 
                user={user} 
                onUpdateUser={onUpdateUser} 
            />

            <SafePage 
                name="SupportModal" 
                isOpen={showSupportModal} 
                onClose={() => {setShowSupportModal(false); onRefreshUser();}} 
                user={user} 
            />

            <SafePage 
                name="TariffModal"
                isOpen={showTariffModal} 
                onClose={() => setShowTariffModal(false)} 
                botLink={botLink} 
                prices={prices} 
                user={user}
                onPaymentSuccess={(updatedUser) => {
                    onUpdateUser(updatedUser);
                    setShowTariffModal(false);
                }}
            />
        </div>
    );
};

const rootElement = document.getElementById('kp-app-root');
if (rootElement) {
    const root = ReactDOM.createRoot(rootElement);
    root.render(<window.App />);
}
