// Version: 2.02.00
// --- GLOBAL SHARED COMPONENTS   ---

const { useState, useEffect, useMemo, useRef } = React;

const ADMIN_VERSION = "2.02.00"; 
const API_BASE = (window.location.protocol === 'blob:' || window.location.protocol === 'file:') ? 'https://kp-generator-b4fb.onrender.com' : '';

window.TelegramLogin = ({ onAuth, botUsername }) => {
    const ref = useRef(null);
    const onAuthRef = useRef(onAuth);
    useEffect(() => { onAuthRef.current = onAuth; }, [onAuth]);
    useEffect(() => {
        window.onTelegramAuth = (user) => {
            if (onAuthRef.current) onAuthRef.current(user);
        };
        if (ref.current) {
            ref.current.innerHTML = "";
            const script = document.createElement("script");
            script.src = "https://telegram.org/js/telegram-widget.js?22";
            script.setAttribute("data-telegram-login", botUsername);
            script.setAttribute("data-size", "large");
            script.setAttribute("data-radius", "10");
            script.setAttribute("data-request-access", "write");
            script.setAttribute("data-userpic", "false");
            script.setAttribute("data-onauth", "onTelegramAuth(user)");
            script.async = true;
            ref.current.appendChild(script);
        }
    }, [botUsername]);
    return <div ref={ref} className="flex justify-center mt-6"></div>;
};

window.ApiTestButton = () => {
    const [status, setStatus] = useState('idle');
    const test = async () => {
        setStatus('loading');
        try {
            const res = await fetch(`/api/proxy/search?article=102529M`);
            if (!res.ok) throw new Error(res.statusText);
            const json = await res.json();
            if (json.found !== undefined) { setStatus('success'); setTimeout(() => setStatus('idle'), 3000); }
            else { throw new Error("Некорректный ответ"); }
        } catch (e) { console.error(e); setStatus('error'); setTimeout(() => setStatus('idle'), 3000); }
    };
    if (status === 'loading') return <span className="text-xs font-bold text-gray-500 animate-pulse">Проверка...</span>;
    if (status === 'success') return <span className="text-xs font-bold text-green-600">✅ OK</span>;
    if (status === 'error') return <span className="text-xs font-bold text-red-500">❌ Ошибка</span>;
    return <button onClick={test} className="px-3 py-1 bg-gray-200 hover:bg-gray-300 rounded text-xs font-bold text-gray-700 transition-colors">Тест</button>;
};

window.BonusBanner = ({ refLink, isVip }) => {
    const [expanded, setExpanded] = useState(false);
    const copyRef = (e) => {
        e.stopPropagation();
        navigator.clipboard.writeText(refLink).then(() => alert("Ссылка скопирована!"));
    };
    const shareTelegram = (e) => {
        e.stopPropagation();
        const text = encodeURIComponent("Привет! Рекомендую этот конструктор КП. Регистрируйся по ссылке и получи бонусы:");
        window.open(`https://t.me/share/url?url=${refLink}&text=${text}`, '_blank');
    };
    return (
        <div onClick={() => setExpanded(!expanded)} className={`bg-gradient-to-r from-blue-600 to-indigo-600 rounded-xl p-4 shadow-lg text-white mb-8 relative overflow-hidden cursor-pointer transition-all ${expanded ? 'h-auto' : 'h-16 flex items-center'}`}>
            <div className="relative z-10 w-full">
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                        <div className="bg-yellow-400 text-blue-800 p-1 rounded-full"><Zap size={16} className="fill-current" /></div>
                        <h3 className="font-bold text-lg">{isVip ? "Пригласить коллегу" : "Бонусная программа"}</h3>
                    </div>
                    <div className={`transform transition-transform ${expanded ? 'rotate-180' : ''}`}><ChevronDown size={20} /></div>
                </div>
                {expanded && (
                    <div className="mt-4 animate-fade-in">
                        <p className="text-sm opacity-90 mb-4 max-w-xl">
                            {isVip ?
                                "У вас уже максимальный статус VIP. Поделитесь ссылкой с коллегами, чтобы они получили 2 месяца VIP при регистрации!" :
                                <span>Пригласите коллегу или друга! Вы получите <span className="font-bold text-yellow-300">3 месяца VIP (Speed)</span>, а он — <span className="font-bold text-yellow-300">2 месяца VIP</span> сразу после регистрации.</span>
                            }
                        </p>
                        <div className="bg-white/10 p-1 pl-3 rounded-lg flex flex-wrap gap-2 justify-between items-center max-w-xl border border-white/20">
                            <span className="text-sm font-mono truncate mr-2 flex-grow">{refLink || "Loading..."}</span>
                            <div className="flex gap-2">
                                <button onClick={copyRef} className="bg-white text-blue-600 px-3 py-1.5 rounded-md font-bold text-xs hover:bg-gray-100 transition shadow-sm">Копировать</button>
                                <button onClick={shareTelegram} className="bg-blue-500 text-white px-3 py-1.5 rounded-md font-bold text-xs hover:bg-blue-400 transition shadow-sm flex items-center gap-1"><span className="text-lg">✈️</span> Поделиться</button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
            {expanded && <div className="absolute right-0 top-0 h-full w-1/3 opacity-10 pointer-events-none"><Zap size={200} className="absolute -right-10 -top-10 transform rotate-12" /></div>}
        </div>
    );
};

window.TariffModal = ({ isOpen, onClose, botLink, prices }) => {
    if (!isOpen) return null;
    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content !max-w-2xl 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}><X size={24} className="text-gray-400 hover:text-gray-600" /></button>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="bg-white p-6 rounded-xl border-2 border-blue-100 hover:border-blue-300 transition-colors shadow-sm flex flex-col">
                        <div className="flex-grow">
                            <h3 className="text-xl font-bold text-blue-600 mb-2">Manager</h3>
                            <div className="text-3xl font-black text-gray-800 mb-4">{prices.manager} ⭐️</div>
                            <ul className="space-y-2 text-sm text-gray-600 mb-6">
                                <li className="flex gap-2"><CheckCircle size={16} className="text-green-500" /> 5 документов</li>
                                <li className="flex gap-2"><CheckCircle size={16} className="text-green-500" /> Без водяного знака</li>
                                <li className="flex gap-2"><CheckCircle size={16} className="text-green-500" /> Сохранение в облако</li>
                                <li className="flex gap-2 opacity-50"><X size={16} className="text-gray-400" /> Без интеграции 1С</li>
                            </ul>
                        </div>
                        <a href={`${botLink}?start=buy_manager`} target="_blank" className="block text-center bg-blue-100 text-blue-700 py-3 rounded-lg font-bold hover:bg-blue-200 transition">Выбрать Manager</a>
                    </div>
                    <div className="bg-gradient-to-br from-purple-600 to-indigo-700 p-6 rounded-xl text-white shadow-xl transform md:-translate-y-2 flex flex-col">
                        <div className="flex-grow">
                            <div className="flex justify-between items-start">
                                <h3 className="text-xl font-bold mb-2">Speed</h3>
                                <span className="bg-yellow-400 text-purple-900 text-[10px] px-2 py-0.5 rounded font-bold uppercase">HIT</span>
                            </div>
                            <div className="text-3xl font-black mb-4">{prices.speed} ⭐️</div>
                            <ul className="space-y-2 text-sm opacity-90 mb-6">
                                <li className="flex gap-2"><CheckCircle size={16} className="text-yellow-400" /> Безлимит документов</li>
                                <li className="flex gap-2"><CheckCircle size={16} className="text-yellow-400" /> Без водяного знака</li>
                                <li className="flex gap-2"><CheckCircle size={16} className="text-yellow-400" /> Интеграция 1С</li>
                                <li className="flex gap-2"><CheckCircle size={16} className="text-yellow-400" /> Приоритетная поддержка</li>
                            </ul>
                        </div>
                        <a href={`${botLink}?start=buy_speed`} target="_blank" className="block text-center bg-white text-purple-700 py-3 rounded-lg font-bold hover:bg-gray-100 transition shadow-md">Выбрать Speed</a>
                    </div>
                </div>
            </div>
        </div>
    );
};

window.AdminPanel = ({ onBack, adminVersion = ADMIN_VERSION }) => {
    const [users, setUsers] = useState([]);
    const [tab, setTab] = useState('users');
    const [search, setSearch] = useState('');
    const [sort, setSort] = useState({ key: 'id', dir: 'desc' });
    const [config, setConfig] = useState({ trial_days: 0, price_2_weeks: 0, price_1_month: 0, price_manager_month: 0 });
    const [loading, setLoading] = useState(false);
    const [userFiles, setUserFiles] = useState(null);

    useEffect(() => { loadUsers(); }, []);

    const loadUsers = async () => {
        setLoading(true);
        try {
            const res = await fetch('/api/admin/users');
            const data = await res.json();
            if (!res.ok) { alert(`Error: ${data.message}`); setLoading(false); return; }
            if (Array.isArray(data)) setUsers(data);
        } catch (e) { console.error(e); }
        setLoading(false);
    };

    const loadConfig = async () => { try { const res = await fetch('/api/admin/config'); if (res.ok) setConfig(await res.json()); } catch (e) { } };
    const saveConfig = async () => { try { await fetch('/api/admin/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config) }); alert("Настройки сохранены"); } catch (e) { alert("Ошибка сохранения"); } };
    const toggleBlock = async (id) => { if (!confirm("Изменить блокировку?")) return; await fetch(`/api/admin/users/${id}/toggle_block`, { method: 'POST' }); loadUsers(); };
    const toggleVip = async (id) => { if (!confirm("Переключить VIP?")) return; await fetch(`/api/admin/users/${id}/toggle_vip`, { method: 'POST' }); loadUsers(); };
    const cycleTier = async (id) => { if (!confirm("Изменить тариф (Free -> Manager -> Speed)?")) return; await fetch(`/api/admin/users/${id}/cycle_tier`, { method: 'POST' }); loadUsers(); };

    const setSubDays = async (id) => {
        const daysStr = prompt("Введите количество дней Speed (0 - чтобы отключить):", "30");
        if (daysStr === null) return;
        const days = parseInt(daysStr);
        if (isNaN(days) || days < 0) { alert("Введите корректное число"); return; }
        try {
            await fetch(`/api/admin/users/${id}/set_sub`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ days }) });
            loadUsers();
        } catch (e) { alert("Ошибка обновления"); }
    };

    const openFiles = async (u) => { setUserFiles({ userId: u.id, name: u.name, files: [] }); try { const res = await fetch(`/api/projects/${u.id}`); if (res.ok) setUserFiles({ userId: u.id, name: u.name, files: await res.json() }); } catch (e) { } };
    const downloadFile = async (fid, fname) => { const res = await fetch(`/api/project/${fid}`); const data = await res.json(); const blob = new Blob([data.data], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = (fname || "project") + ".json"; a.click(); };
    const deleteFile = async (fid) => { if (!confirm("Удалить файл?")) return; await fetch(`/api/projects/${fid}`, { method: 'DELETE' }); openFiles({ id: userFiles.userId, name: userFiles.name }); loadUsers(); };
    const uploadFile = async (e) => { const file = e.target.files[0]; if (!file || !userFiles) return; const reader = new FileReader(); reader.onload = async (ev) => { await fetch(`/api/projects`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: userFiles.userId, id: 0, name: file.name.replace('.json', '') + " (Upload)", data: e.target.result }) }); alert("Загружено"); openFiles({ id: userFiles.userId, name: userFiles.name }); loadUsers(); }; reader.readAsText(file); e.target.value = ''; };
    const sortedUsers = useMemo(() => {
        let res = users.filter(u => (u.name && u.name.toLowerCase().includes(search.toLowerCase())) || (u.username && u.username.toLowerCase().includes(search.toLowerCase())) || String(u.telegram_id).includes(search));
        return res.sort((a, b) => {
            let valA = a[sort.key], valB = b[sort.key];
            if (sort.key === 'created_at' || sort.key === 'last_active') { const parse = (s) => { if (!s) return 0; const [d, t] = s.split(' '); const [dd, mm, yy] = d.split('.'); return new Date(yy, mm - 1, dd).getTime(); }; valA = parse(valA); valB = parse(valB); }
            if (valA < valB) return sort.dir === 'asc' ? -1 : 1; if (valA > valB) return sort.dir === 'asc' ? 1 : -1; return 0;
        });
    }, [users, search, sort]);
    const handleSort = (key) => setSort({ key, dir: sort.key === key && sort.dir === 'asc' ? 'desc' : 'asc' });

    return (
        <div className="min-h-screen bg-gray-100 p-8 font-sans relative">
            <div className="max-w-7xl mx-auto">
                <div className="flex justify-between items-center mb-8">
                    <div className="flex flex-col">
                        <h1 className="text-3xl font-bold text-gray-800 flex items-center gap-2"><Shield className="text-blue-600" /> Админ-панель</h1>
                        <div className="text-xs text-gray-400 mt-1 space-y-0.5">
                            <div>Frontend: v{adminVersion}</div>
                        </div>
                    </div>
                    <button onClick={onBack} className="text-gray-500 hover:text-blue-600 flex items-center gap-1 font-bold"><ArrowLeft size={18} /> На сайт</button>
                </div>

                <div className="flex justify-between items-start mb-6">
                    <div className="flex space-x-2 bg-gray-200 p-1 rounded-lg">
                        <button onClick={() => { setTab('users'); loadUsers() }} className={`px-4 py-2 rounded-md font-bold text-sm ${tab === 'users' ? 'bg-white text-blue-600 shadow' : 'text-gray-500'}`}>Пользователи</button>
                        <button onClick={() => { setTab('settings'); loadConfig() }} className={`px-4 py-2 rounded-md font-bold text-sm ${tab === 'settings' ? 'bg-white text-blue-600 shadow' : 'text-gray-500'}`}>Настройки</button>
                    </div>
                    {tab === 'users' && (
                        <div className="flex items-center gap-2">
                            <button onClick={loadUsers} className="flex items-center gap-1 px-3 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-700 font-bold text-sm transition shadow-sm">
                                <RefreshCw size={14} /> Обновить
                            </button>
                            <div className="relative"><input type="text" placeholder="Поиск..." value={search} onChange={e => setSearch(e.target.value)} className="pl-9 pr-4 py-2 rounded-lg border focus:outline-none focus:ring-2 focus:ring-blue-400" /><Search className="absolute left-3 top-2.5 text-gray-400" size={16} /></div>
                        </div>
                    )}
                </div>

                {tab === 'users' && (
                    <div className="bg-white rounded-xl shadow overflow-hidden">
                        <table className="w-full text-left text-sm">
                            <thead className="bg-gray-50 text-gray-500 uppercase text-xs">
                                <tr>
                                    <th className="px-6 py-4 cursor-pointer hover:bg-gray-100 admin-th" onClick={() => handleSort('name')}>Пользователь {sort.key === 'name' && (sort.dir === 'asc' ? '↑' : '↓')}</th>
                                    <th className="px-6 py-4 text-center">Тариф</th>
                                    <th className="px-6 py-4 text-center cursor-pointer hover:bg-gray-100 admin-th" onClick={() => handleSort('projects_count')}>Проекты {sort.key === 'projects_count' && (sort.dir === 'asc' ? '↑' : '↓')}</th>
                                    <th className="px-6 py-4 text-center cursor-pointer hover:bg-gray-100 admin-th" onClick={() => handleSort('storage_kb')}>Объем {sort.key === 'storage_kb' && (sort.dir === 'asc' ? '↑' : '↓')}</th>
                                    <th className="px-6 py-4 cursor-pointer hover:bg-gray-100 admin-th" onClick={() => handleSort('last_active')}>Активность {sort.key === 'last_active' && (sort.dir === 'asc' ? '↑' : '↓')}</th>
                                    <th className="px-6 py-4 cursor-pointer hover:bg-gray-100 admin-th" onClick={() => handleSort('created_at')}>Регистрация {sort.key === 'created_at' && (sort.dir === 'asc' ? '↑' : '↓')}</th>
                                    <th className="px-6 py-4 text-center">Файлы</th>
                                    <th className="px-6 py-4 text-center">Действия</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {loading ? <tr><td colSpan="8" className="text-center py-8">Загрузка...</td></tr> :
                                    sortedUsers.map(u => {
                                        const tierStyle = u.is_vip ? 'bg-yellow-100 text-yellow-700 border-yellow-200' :
                                            u.tier === 'speed' ? 'bg-purple-100 text-purple-700 border-purple-200' :
                                                u.tier === 'manager' ? 'bg-blue-50 text-blue-600 border-blue-200' :
                                                    'bg-gray-100 text-gray-500';
                                        return (
                                            <tr key={u.id} className={`hover:bg-blue-50/50 ${u.is_blocked ? 'bg-red-50' : ''}`}>
                                                <td className="px-6 py-4 flex items-center gap-3">
                                                    {u.photo ? <img src={u.photo} className="w-8 h-8 rounded-full" /> : <div className="w-8 h-8 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center font-bold">{u.name?.[0]}</div>}
                                                    <div><div className={`font-bold ${u.is_blocked ? 'line-through text-red-600' : ''}`}>{u.name}</div><div className="text-xs text-blue-500">@{u.username}</div></div>
                                                </td>
                                                <td className="px-6 py-4 text-center">
                                                    <div className="flex items-center justify-center gap-2">
                                                        <button onClick={() => cycleTier(u.id)} className={`px-2 py-1 rounded text-xs font-bold border ${tierStyle}`} title="Переключить тариф">{u.sub_status}</button>
                                                        <button onClick={() => setSubDays(u.id)} className="text-gray-400 hover:text-blue-600" title="Изменить дни Speed"><Plus size={14} /></button>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4 text-center font-bold">{u.projects_count}</td>
                                                <td className="px-6 py-4 text-center font-mono text-xs text-gray-500">{u.storage_kb} KB</td>
                                                <td className="px-6 py-4 text-xs text-gray-600">{u.last_active}</td>
                                                <td className="px-6 py-4 text-xs text-gray-500">{u.created_at}</td>
                                                <td className="px-6 py-4 text-center"><button onClick={() => openFiles(u)} className="text-blue-600 hover:underline text-xs font-bold">Открыть</button></td>
                                                <td className="px-6 py-4 text-center flex justify-center gap-2">
                                                    <button onClick={() => toggleVip(u.id)} className={`p-1 rounded ${u.is_vip ? 'text-yellow-500 bg-yellow-50' : 'text-gray-300 hover:bg-gray-100'}`} title="VIP"><Crown size={16} /></button>
                                                    <button onClick={() => toggleBlock(u.id)} className={`px-2 py-1 rounded text-xs font-bold border ${u.is_blocked ? 'border-green-200 text-green-600' : 'border-red-200 text-red-500'}`}>{u.is_blocked ? 'Разблок' : 'Блок'}</button>
                                                </td>
                                            </tr>
                                        )
                                    })}
                            </tbody>
                        </table>
                    </div>
                )}

                {tab === 'settings' && (<div className="bg-white rounded-xl shadow p-8 max-w-lg"><h3 className="text-xl font-bold mb-6">Настройки тарифов</h3><div className="space-y-4"><div><label className="block text-sm font-bold text-gray-700 mb-1">Пробный период (дней)</label><input type="number" value={config.trial_days} onChange={e => setConfig({ ...config, trial_days: +e.target.value })} className="w-full border rounded p-2" /></div><div className="grid grid-cols-2 gap-4"><div><label className="block text-sm font-bold text-gray-700 mb-1">Цена Manager (Месяц)</label><input type="number" value={config.price_manager_month} onChange={e => setConfig({ ...config, price_manager_month: +e.target.value })} className="w-full border rounded p-2" /></div><div><label className="block text-sm font-bold text-gray-700 mb-1">Цена Speed (Месяц)</label><input type="number" value={config.price_1_month} onChange={e => setConfig({ ...config, price_1_month: +e.target.value })} className="w-full border rounded p-2" /></div></div><button onClick={saveConfig} className="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 mt-4">Сохранить</button></div></div>)}

                {userFiles && (
                    <div className="fixed inset-0 bg-black/50 z-[6000] flex items-center justify-center" onClick={() => setUserFiles(null)}>
                        <div className="bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[80vh] flex flex-col" onClick={e => e.stopPropagation()}>
                            <div className="p-4 border-b flex justify-between items-center bg-gray-50">
                                <h3 className="font-bold">Файлы: {userFiles.name}</h3>
                                <button onClick={() => setUserFiles(null)}><X size={20} /></button>
                            </div>
                            <div className="p-4 overflow-y-auto flex-grow space-y-2">
                                {userFiles.files.length === 0 ? (
                                    <div className="text-center text-gray-400 py-8">Нет файлов</div>
                                ) : (
                                    userFiles.files.map(f => (
                                        <div key={f.id} className="flex justify-between items-center p-3 border rounded hover:bg-gray-50">
                                            <div>
                                                <div className="font-bold text-sm">{f.name}</div>
                                                <div className="text-xs text-gray-400">{new Date(f.updated_at).toLocaleString()}</div>
                                            </div>
                                            <div className="flex gap-2">
                                                <button onClick={() => downloadFile(f.id, f.name)} className="p-1.5 text-blue-600 hover:bg-blue-100 rounded"><Download size={18} /></button>
                                                <button onClick={() => deleteFile(f.id)} className="p-1.5 text-red-500 hover:bg-red-100 rounded"><Trash2 size={18} /></button>
                                            </div>
                                        </div>
                                    ))
                                )}
                            </div>
                            <div className="p-4 border-t bg-gray-50 flex justify-between items-center">
                                <div className="text-xs text-gray-500">Загрузить файл пользователю:</div>
                                <label className="cursor-pointer bg-blue-600 text-white px-3 py-1.5 rounded-lg text-sm font-bold flex items-center gap-2 hover:bg-blue-700">
                                    <UploadCloud size={16} /> Выбрать JSON
                                    <input type="file" className="hidden" onChange={uploadFile} />
                                </label>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};
