// Version: 2.11.31 (Removed obsolete AdminPanel)
// --- GLOBAL SHARED COMPONENTS ---

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

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

// ИСПРАВЛЕНИЕ: Теперь SafeIcon честно ищет иконку, а не возвращает текст
window.SafeIcon = window.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}>[{name}]</span>;
    return <Icon {...props} />;
});
var SafeIcon = window.SafeIcon;

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"><SafeIcon name="Zap" size={16} className="fill-current" /></div>
                        <h3 className="font-bold text-lg">{isVip ? "Пригласить коллегу" : "Бонусная программа"}</h3>
                    </div>
                    <div className={"transform transition-transform " + (expanded ? 'rotate-180' : '')}><SafeIcon name="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 месяца тарифа Speed при регистрации!" :
                                <span>Пригласите коллегу или друга! Вы получите <span className="font-bold text-yellow-300">7 дней тарифа Speed</span> сразу после его регистрации, и еще <span className="font-bold text-yellow-300">2 месяца</span>, когда он совершит первую оплату. Ваш друг получит <span className="font-bold text-yellow-300">2 месяца тарифа Speed</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"><SafeIcon name="Zap" size={200} className="absolute -right-10 -top-10 transform rotate-12" /></div>}
        </div>
    );
};

window.TariffModal = ({ isOpen, onClose, botLink, prices, user, onPaymentSuccess }) => {
    useEffect(() => {
        if (!isOpen || !user) return;
        const pollInterval = setInterval(async () => {
            try {
                const res = await fetch(`/api/user/status/${user.id}`);
                if (!res.ok) return;
                const status = await res.json();
                
                const currentTierVal = getTierValue(user.tier);
                const newTierVal = getTierValue(status.tier);
                
                if (newTierVal > currentTierVal || (status.is_premium && !user.is_premium) || (status.is_premium && status.sub_end !== user.sub_end)) {
                    if (onPaymentSuccess) onPaymentSuccess(status);
                }
            } catch (e) { console.error("Polling error", e); }
        }, 3000); 
        return () => clearInterval(pollInterval);
    }, [isOpen, user, onPaymentSuccess]);

    const getTierValue = (t) => {
        if (t === 'vip') return 3;
        if (t === 'speed') return 2;
        if (t === 'manager') return 1;
        return 0; 
    };

    const getSafeBotLink = () => {
        if (botLink && botLink.startsWith('http')) return botLink;
        const fallbackName = window.BOT_USERNAME || 'kp_gen_my_bot';
        return `https://t.me/${fallbackName}`;
    };

    const safeLink = getSafeBotLink();

    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}><SafeIcon name="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"><SafeIcon name="CheckCircle" size={16} className="text-green-500" /> 5 документов</li>
                                <li className="flex gap-2"><SafeIcon name="CheckCircle" size={16} className="text-green-500" /> Без водяного знака</li>
                                <li className="flex gap-2"><SafeIcon name="CheckCircle" size={16} className="text-green-500" /> Сохранение в облако</li>
                                <li className="flex gap-2 opacity-50"><SafeIcon name="X" size={16} className="text-gray-400" /> Без интеграции 1С</li>
                            </ul>
                        </div>
                        <a href={`${safeLink}?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"><SafeIcon name="CheckCircle" size={16} className="text-yellow-400" /> Безлимит документов</li>
                                <li className="flex gap-2"><SafeIcon name="CheckCircle" size={16} className="text-yellow-400" /> Без водяного знака</li>
                                <li className="flex gap-2"><SafeIcon name="CheckCircle" size={16} className="text-yellow-400" /> Интеграция 1С</li>
                                <li className="flex gap-2"><SafeIcon name="CheckCircle" size={16} className="text-yellow-400" /> Приоритетная поддержка</li>
                            </ul>
                        </div>
                        <a href={`${safeLink}?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>
    );
};
