// Version: 2.02.01
// --- GLOBAL APP COMPONENT  ---
const { useState, useEffect } = React;
const { createRoot } = ReactDOM;

// Using global components
const Editor = window.Editor;
const AdminPanel = window.AdminPanel;
const BonusBanner = window.BonusBanner;
const TariffModal = window.TariffModal;
const ApiTestButton = window.ApiTestButton;
const TelegramLogin = window.TelegramLogin;
const LandingPage = window.LandingPage; // New Landing Component

// Using global Icons
const { FileText, Star, Settings, Shield, LogOut, Plus, Trash2, AlertTriangle } = window;
const { formatDate } = window;

const 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 [showIntegrations, setShowIntegrations] = useState(false);
    const [showTariffModal, setShowTariffModal] = useState(false);
    const [useAquaPlaza, setUseAquaPlaza] = useState(true);
    const [prices, setPrices] = useState({ manager: 0, speed: 0 });

    const BOT_USERNAME = window.BOT_USERNAME || "REPLACE_ME_ON_SERVER"; 

    useEffect(() => {
        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;

        // Check URL parameters for direct access
        const urlParams = new URLSearchParams(window.location.search);
        const mode = urlParams.get('mode'); // e.g. ?mode=login
        const startParam = urlParams.get('start'); // Telegram deep linking param

        if (savedUser && savedAuthDate && (now - parseInt(savedAuthDate) < oneDay)) {
            try {
                const u = JSON.parse(savedUser);
                setUser(u); setView('dashboard'); fetchProjects(u.id);
                 fetch('/api/config/public').then(r => r.json()).then(d => {
                     if(d) setPrices({ manager: d.price_manager, speed: d.price_speed });
                 }).catch(e => console.error("Price fetch error", e));
            } catch (e) { 
                localStorage.removeItem('kp_user'); 
                // If token invalid, decide where to go based on URL
                if (mode === 'login' || startParam) setView('auth');
                else setView('landing');
            }
        } else {
            localStorage.removeItem('kp_user'); localStorage.removeItem('kp_auth_date'); 
            // If not logged in, check URL to decide between Landing and Auth
            if (mode === 'login' || startParam) {
                setView('auth');
            } else {
                setView('landing');
            }
        }
    }, []);

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

    const handleAuth = async (tgUser) => {
        try {
            const res = await fetch('/api/auth/telegram', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(tgUser) });
            const data = await res.json();
            if (!res.ok) throw new Error(data.message || "Error");
            if (data.status === 'ok') {
                const userWithUsername = { ...data.user, username: tgUser.username };
                setUser(userWithUsername);
                if (data.bot_link) setBotLink(data.bot_link);
                if (data.config) setPrices({ manager: data.config.price_manager, speed: data.config.price_speed });
                localStorage.setItem('kp_user', JSON.stringify(userWithUsername));
                localStorage.setItem('kp_auth_date', Date.now().toString());
                await fetchProjects(data.user.id);
                setView('dashboard');
            } else { alert("Ошибка: " + data.message); }
        } catch (e) { alert("Ошибка входа: " + e.message); }
    };

    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 handleCreateNew = () => { setCurrentProject({ id: null, name: "Новое КП", data: null }); setView('editor'); };
    const handleOpenProject = async (pid) => { try { const res = await fetch(`/api/project/${pid}`); const data = await res.json(); setCurrentProject({ id: data.id, name: data.name, data: JSON.parse(data.data) }); setView('editor'); } catch (e) { alert("Ошибка открытия"); } };
    const handleDeleteProject = async (pid, e) => { e.stopPropagation(); if (!confirm("Удалить?")) return; await fetch(`/api/projects/${pid}`, { method: 'DELETE' }); fetchProjects(user.id); };
    const handleLogout = () => { localStorage.removeItem('kp_user'); localStorage.removeItem('kp_auth_date'); setUser(null); setView('landing'); };
    
    // Determine privileges
    const getTierLabel = () => {
        if (user?.is_vip) return "VIP (Безлимит)";
        if (user?.tier === 'speed') return `Speed (до ${user.sub_end})`;
        if (user?.tier === 'manager') return `Manager (до ${user.sub_end})`;
        return "Free (1 док)";
    }

    const isSpeedOrVip = user?.tier === 'speed' || user?.is_vip;
    const daysLeft = user?.days_left || 0;
    const showWarning = (user?.tier === 'speed' || user?.tier === 'manager') && daysLeft <= 2 && daysLeft >= 0;

    if (view === 'landing') {
        return <LandingPage onStart={() => 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-2xl shadow-xl max-w-md w-full text-center">
                    <div className="mb-6 flex justify-center text-blue-600"><FileText size={64} /></div>
                    <h1 className="text-3xl font-bold text-gray-800 mb-2">Конструктор КП</h1>
                    <p className="text-gray-500 mb-8">Авторизуйтесь через Telegram, чтобы создавать, сохранять и управлять коммерческими предложениями.</p>
                    <TelegramLogin onAuth={handleAuth} botUsername={BOT_USERNAME} />
                    <button onClick={() => setView('landing')} className="mt-6 text-sm text-gray-400 hover:text-gray-600 underline">Назад на главную</button>
                </div>
            </div>
        );
    }
    if (view === 'admin') { return <AdminPanel onBack={() => setView('dashboard')} />; }
    if (view === 'dashboard') {
        return (
            <div className="min-h-screen bg-gray-50 p-4 md:p-10 relative">
                <TariffModal isOpen={showTariffModal} onClose={() => setShowTariffModal(false)} botLink={botLink} prices={prices} />
                {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"><span className="text-2xl">×</span></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">
                                        <ApiTestButton />
                                        <button onClick={toggleAquaPlaza} 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>
                )}
                <div className="max-w-5xl mx-auto">

                    <BonusBanner refLink={user?.ref_link} isVip={user?.is_vip} />

                    {showWarning && (
                        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl mb-6 flex items-center gap-3 animate-pulse">
                            <AlertTriangle size={20} />
                            <div><span className="font-bold">Внимание!</span> Ваша подписка истекает через {daysLeft} дн. Скоро вы будете переведены на Free тариф.</div>
                        </div>
                    )}

                    <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
                        <h2 className="text-3xl font-bold text-gray-800">Мои Проекты</h2>
                        <div className="flex items-center gap-4">
                            <div className={`flex items-center gap-1 px-3 py-1 rounded-full text-xs font-bold border ${isSpeedOrVip ? 'bg-purple-100 text-purple-700 border-purple-200' : 'bg-gray-100 text-gray-700 border-gray-200'}`}>
                                <Star size={14} className={isSpeedOrVip ? "fill-purple-500 text-purple-500" : "text-gray-500"} />
                                {getTierLabel()}
                            </div>

                            {!user.is_vip && (
                                <button onClick={() => setShowTariffModal(true)} className="flex items-center gap-2 bg-gradient-to-r from-blue-600 to-purple-600 text-white px-4 py-2 rounded-lg font-bold text-sm hover:shadow-lg transition transform hover:-translate-y-0.5"><Star size={16} className="fill-white" /> Улучшить тариф</button>
                            )}

                            {(isSpeedOrVip || user?.role === 'admin') && (<button onClick={() => setShowIntegrations(true)} className="flex items-center gap-2 text-gray-600 hover:bg-white hover:text-blue-600 hover:shadow-sm px-3 py-1.5 rounded-lg transition-all border border-transparent hover:border-gray-200"><Settings size={18} /> Интеграции</button>)}
                            {user?.role === "admin" && (<button onClick={() => setView('admin')} className="text-blue-600 hover:bg-blue-50 px-3 py-1 rounded font-bold flex items-center gap-2 border border-transparent hover:border-blue-200 transition-colors"><Shield size={18} /> Админка</button>)}
                            <span className="text-gray-600 font-medium hidden md:inline">{user?.name}</span>
                            <button onClick={handleLogout} className="text-red-500 hover:bg-red-50 p-2 rounded"><LogOut size={20} /></button>
                        </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div onClick={handleCreateNew} className="bg-white border-2 border-dashed border-blue-300 rounded-xl p-8 flex flex-col items-center justify-center cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition min-h-[200px]"><div className="bg-blue-100 p-4 rounded-full mb-4 text-blue-600"><Plus size={32} /></div><span className="font-bold text-lg text-blue-700">Создать новое КП</span></div>
                        {Array.isArray(projects) && projects.map(p => (
                            <div key={p.id} onClick={() => handleOpenProject(p.id)} className="bg-white rounded-xl shadow-sm hover:shadow-md border border-gray-100 p-6 cursor-pointer transition relative group flex flex-col justify-between min-h-[200px]">
                                <div><div className="flex justify-between items-start mb-2"><div className="bg-orange-100 text-orange-600 p-2 rounded-lg"><FileText size={24} /></div><button onClick={(e) => handleDeleteProject(p.id, e)} className="text-gray-300 hover:text-red-500 p-1"><Trash2 size={18} /></button></div><h3 className="font-bold text-lg text-gray-800 mb-1 line-clamp-2">{p.name || "Без названия"}</h3><p className="text-sm text-gray-400">Обновлено: {formatDate(p.updated_at)}</p></div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        );
    }
    return <Editor user={user} initialProject={currentProject} useAquaPlaza={useAquaPlaza} onBack={() => { setView('dashboard'); fetchProjects(user.id); }} />;
};

const root = createRoot(document.getElementById('kp-app-root'));
root.render(<App />);
