import React, { useState, useEffect, useRef, useCallback } from 'react';
import { initializeApp } from 'firebase/app';
import { 
    getAuth, 
    onAuthStateChanged, 
    GoogleAuthProvider, 
    signInWithPopup, 
    signOut 
} from 'firebase/auth';
import { 
    getFirestore, 
    doc, 
    onSnapshot, 
    setDoc, 
    updateDoc, 
    deleteDoc, 
    collection, 
    addDoc, 
    increment,
    serverTimestamp,
    query,
    orderBy,
    limit,
    writeBatch,
    getDocs
} from 'firebase/firestore';

const firebaseConfig = {
  apiKey: "AIzaSyDJx6_b3JxctCW1RoDE-bm4zp7rrWT9lqA",
  authDomain: "cointube-f7695.firebaseapp.com",
  projectId: "cointube-f7695",
  storageBucket: "cointube-f7695.firebasestorage.app",
  messagingSenderId: "710177637377",
  appId: "1:710177637377:web:10605b43eea6eac446ac00"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

const ADMIN_EMAIL = "dimensionalpulsar@gmail.com";
const VIDEO_COST = 10000; 

// Datos de EmailJS
const EMAILJS_SERVICE_ID = "service_v18p188"; 
const EMAILJS_TEMPLATE_ID = "template_wexg1ww";
const EMAILJS_PUBLIC_KEY = "XK6EoFoAqInBoDjIe";

export default function App() {
    
    const [videos, setVideos] = useState([]); 
    const [leaderboard, setLeaderboard] = useState([]); 
    const [user, setUser] = useState(null);
    const [userId, setUserId] = useState(null);
    const [authReady, setAuthReady] = useState(false);
    const [userProfile, setUserProfile] = useState(null);
    const [currentTab, setCurrentTab] = useState('ganar');
    
    const [currentVideoId, setCurrentVideoId] = useState(null);
    const [currentVideoTitle, setCurrentVideoTitle] = useState(null);
    
    const [ytApiReady, setYtApiReady] = useState(false);
    
    const playerRef = useRef(null);
    const coinIntervalRef = useRef(null);
    const localCoinBufferRef = useRef(0);
    const initialLoadRef = useRef(true);

    useEffect(() => {
        const unsubscribeAuth = onAuthStateChanged(auth, (user) => {
            if (user) {
                setUser(user);
                setUserId(user.uid);
            } else {
                setUser(null);
                setUserId(null);
                setUserProfile(null);
            }
            setAuthReady(true);
        });
        return () => unsubscribeAuth();
    }, []);

    useEffect(() => {
        if (!userId) return;
        const profileRef = doc(db, 'users', userId);
        const unsubscribeProfile = onSnapshot(profileRef, (docSnap) => {
            if (docSnap.exists()) {
                setUserProfile(docSnap.data());
            } else {
                const newProfile = { 
                    email: user.email, 
                    coins: 0
                };
                setDoc(profileRef, newProfile).catch(e => console.error(e));
                setUserProfile(newProfile);
            }
        }, (error) => console.error(error));
        return () => unsubscribeProfile();
    }, [userId, user]);

    // Lógica de Reseteo Diario (Para el admin)
    useEffect(() => {
        if (user?.email !== ADMIN_EMAIL) return;
        
        const checkReset = async () => {
            const settingsRef = doc(db, 'settings', 'stats');
            const snap = await getDocs(query(collection(db, 'settings')));
            if (snap.empty) return;
            
            const data = snap.docs[0].data();
            const lastReset = data.lastReset.toDate();
            const now = new Date();
            
            // 86,400,000 ms = 1 Día (Reseteo Diario)
            if (now - lastReset >= 86400000) {
                const batch = writeBatch(db);
                const usersSnap = await getDocs(collection(db, 'users'));
                
                usersSnap.forEach((userDoc) => {
                    if (userDoc.data().email !== ADMIN_EMAIL) {
                        batch.update(userDoc.ref, { coins: 0 });
                    }
                });

                batch.update(settingsRef, { lastReset: serverTimestamp() });
                await batch.commit();
                alert("Reseteo Diario Completado: Las monedas de los usuarios se reiniciaron a 0.");
            }
        };
        checkReset();
    }, [user]);

    // Lista de videos (Randomizada y sin video por defecto)
    useEffect(() => {
        const q = query(collection(db, 'videos'), orderBy('createdAt', 'desc'), limit(50));
        const unsubscribe = onSnapshot(q, (snapshot) => {
            let fetchedVideos = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
            
            if (fetchedVideos.length > 0) {
                // Randomizar la lista de videos
                fetchedVideos = fetchedVideos.sort(() => Math.random() - 0.5);

                setVideos(fetchedVideos);
                if (initialLoadRef.current || !currentVideoId) {
                    const latestVideo = fetchedVideos[0];
                    setCurrentVideoId(latestVideo.videoId);
                    setCurrentVideoTitle(latestVideo.title);
                    initialLoadRef.current = false;
                }
            } else {
                setVideos([]);
                if (initialLoadRef.current || !currentVideoId) {
                    setCurrentVideoId(null);
                    setCurrentVideoTitle("Sin videos disponibles");
                    initialLoadRef.current = false;
                }
            }
        });
        return () => unsubscribe();
    }, [currentVideoId]); 

    useEffect(() => {
        const q = query(collection(db, 'users'), orderBy('coins', 'desc'), limit(100));
        const unsubscribe = onSnapshot(q, (snapshot) => {
            let usersList = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
            
            usersList = usersList.filter(u => 
                u.email && 
                u.email.endsWith('@gmail.com')
            );

            setLeaderboard(usersList.slice(0, 20));
        });
        return () => unsubscribe();
    }, []);

    useEffect(() => {
        if (!window.YT) {
            const tag = document.createElement('script');
            tag.src = "https://www.youtube.com/iframe_api";
            const firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            window.onYouTubeIframeAPIReady = () => setYtApiReady(true);
        } else {
            setYtApiReady(true);
        }
    }, []);

    const saveCoinBuffer = useCallback(() => {
        if (localCoinBufferRef.current > 0 && userId) {
            const coinsToSave = localCoinBufferRef.current;
            localCoinBufferRef.current = 0;
            const profileRef = doc(db, 'users', userId);
            updateDoc(profileRef, { coins: increment(coinsToSave) })
                .catch(e => { localCoinBufferRef.current += coinsToSave; });
        }
    }, [userId]);
    
    const startCoinInterval = useCallback(() => {
        if (coinIntervalRef.current) return;
        coinIntervalRef.current = setInterval(() => {
            localCoinBufferRef.current++;
            if (localCoinBufferRef.current >= 5) saveCoinBuffer();
        }, 1000);
    }, [saveCoinBuffer]);

    const stopCoinInterval = useCallback(() => {
        if (coinIntervalRef.current) {
            clearInterval(coinIntervalRef.current);
            coinIntervalRef.current = null;
            saveCoinBuffer();
        }
    }, [saveCoinBuffer]);

    const onPlayerReady = useCallback((event) => {
        playerRef.current = event.target;
        playerRef.current.playVideo();
    }, []);

    const onPlayerStateChange = useCallback((event) => {
        const state = event.data;
        if (state === window.YT.PlayerState.PLAYING) startCoinInterval();
        else stopCoinInterval();
    }, [startCoinInterval, stopCoinInterval]);

    useEffect(() => {
        if (ytApiReady && userId && !playerRef.current && currentVideoId) {
            playerRef.current = new window.YT.Player('player', {
                height: '100%',
                width: '100%',
                videoId: currentVideoId,
                playerVars: { 'playsinline': 1, 'autoplay': 1, 'controls': 1, 'modestbranding': 1, 'rel': 0 },
                events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange }
            });
        }
        if (!userId && playerRef.current) {
            stopCoinInterval();
            playerRef.current = null;
        }
    }, [ytApiReady, userId, currentVideoId, onPlayerReady, onPlayerStateChange]);

    const loadVideo = (video) => {
        stopCoinInterval();
        setCurrentVideoId(video.videoId);
        setCurrentVideoTitle(video.title);
        if (playerRef.current) playerRef.current.loadVideoById(video.videoId);
    };

    const handleDeleteVideo = async (e, videoId) => {
        e.stopPropagation();
        if (!confirm("¿Eliminar video?")) return;
        try { await deleteDoc(doc(db, "videos", videoId)); } catch (error) { console.error(error); }
    };

    const handleGiveCoins = async (targetUserId, currentCoins) => {
        const amountStr = prompt("Cantidad de monedas a sumar (usa negativo para restar):", "1000");
        if (!amountStr) return;
        const amount = parseInt(amountStr);
        if (isNaN(amount)) return;

        try {
            const userRef = doc(db, 'users', targetUserId);
            await updateDoc(userRef, { coins: increment(amount) });
            alert("Monedas actualizadas.");
        } catch (error) {
            console.error("Error:", error);
            alert("Error al dar monedas. Revisa las reglas de Firebase.");
        }
    };

    // Función para Email Masivo
    const handleMassEmail = async () => {
        if (!window.emailjs) return alert("EmailJS no está cargado. Revisa tu index.html.");
        if (!confirm("¿Enviar notificación de reseteo a todos los usuarios?")) return;

        const usersSnap = await getDocs(collection(db, 'users'));
        let count = 0;

        usersSnap.forEach((uDoc) => {
            const userData = uDoc.data();
            if (userData.email) {
                window.emailjs.send(EMAILJS_SERVICE_ID, EMAILJS_TEMPLATE_ID, {
                    to_email: userData.email,
                    message: "¡Hola! Los puntos se han reseteado para una nueva ronda. ¡Vuelve a CoinTube y suma monedas viendo videos!"
                }, EMAILJS_PUBLIC_KEY);
                count++;
            }
        });
        alert(`Correos en proceso de envío para ${count} usuarios.`);
    };

    // Uso de Popup original restaurado
    const handleGoogleLogin = async () => {
        const provider = new GoogleAuthProvider();
        try {
            await signInWithPopup(auth, provider);
        } catch (error) {
            console.error("Error Google:", error);
        }
    };

    const handleLogout = async () => {
        stopCoinInterval();
        await signOut(auth);
    };

    if (!authReady) {
        return (
            <div className="flex flex-col items-center justify-center h-full w-full">
                <div className="spinner mb-4"></div>
                <p className="text-lg text-gray-400">Cargando...</p>
            </div>
        );
    }

    if (authReady && !user) {
        return (
            <div className="flex flex-col items-center justify-center h-full w-full bg-gray-900 p-4">
                <div className="max-w-md w-full bg-gray-800 rounded-2xl shadow-2xl p-8 text-center border border-gray-700">
                    <div className="flex justify-center mb-6">
                        <div className="bg-blue-600 p-4 rounded-full shadow-lg">
                            <svg className="w-12 h-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                    </div>
                    <h1 className="text-3xl font-bold text-white mb-2 tracking-tight">Bienvenido a CoinTube</h1>
                    <p className="text-gray-400 mb-8 text-sm leading-relaxed">
                        Descubre contenido increíble, gana monedas virtuales por cada minuto que ves y promociona tus propios videos.<br/><br/>
                        <span className="text-yellow-400 font-bold text-base">¡Junta 10,000 monedas para subir tu video!</span>
                    </p>
                    <div className="space-y-3">
                        <button onClick={handleGoogleLogin} className="w-full flex items-center justify-center px-4 py-3 bg-white text-gray-800 font-bold rounded-lg hover:bg-gray-100 transition-all duration-200 shadow-md">
                            <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
                                <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                                <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                                <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                                <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                            </svg>
                            Continuar con Google
                        </button>
                    </div>
                    <p className="mt-6 text-xs text-gray-500">Al continuar, aceptas nuestros términos.</p>
                </div>
            </div>
        );
    }

    return (
        <div className="h-full w-full max-w-7xl mx-auto flex flex-col p-4 md:p-6">
            
            <header className="flex justify-between items-center pb-4 mb-4 border-b border-gray-700">
                <h1 className="text-2xl md:text-3xl font-bold text-white">
                    Coin<span className="text-blue-500">Tube</span>
                </h1>

                <div className="flex items-center gap-4">
                    <div className="text-right">
                        <div className="text-xs text-gray-400">{user.email}</div>
                        <div className="text-lg font-bold text-yellow-400">
                            {Math.floor(userProfile?.coins || 0)} 🪙
                        </div>
                    </div>

                    <button 
                        onClick={handleLogout} 
                        className="px-3 py-1 bg-gray-700 text-white text-sm rounded hover:bg-gray-600"
                    >
                        Salir
                    </button>
                </div>

            </header>
            <a 
                href="https://wa.me/+2286051539" 
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-2 bg-green-600 hover:bg-green-500 text-white px-4 py-2 rounded-lg shadow-md w-fit mx-auto mb-4"
            >
                <svg 
                    xmlns="http://www.w3.org/2000/svg" 
                    fill="currentColor" 
                    viewBox="0 0 24 24" 
                    className="w-6 h-6"
                >
                    <path d="M.057 24l1.687-6.163a11.867 11.867 0 01-1.587-5.96C.159 5.3 5.41 0 12.084 0c3.184 0 6.167 1.24 8.413 3.488a11.8 11.8 0 013.5 8.404c-.003 6.673-5.312 11.92-11.987 11.92a11.95 11.95 0 01-5.93-1.575L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.593 5.448 0 9.886-4.415 9.889-9.848.003-5.46-4.415-9.89-9.881-9.893-5.466 0-9.887 4.42-9.889 9.878a9.86 9.86 0 001.733 5.57l-.999 3.648 3.755-.948zm11.387-5.464c-.074-.123-.272-.198-.57-.347s-1.758-.868-2.03-.967c-.272-.099-.47-.148-.669.148-.198.297-.768.966-.94 1.164-.173.198-.347.223-.644.074-.297-.148-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.52.149-.173.198-.297.297-.495.099-.198.05-.371-.025-.52-.074-.148-.669-1.611-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.148.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.718 2.006-1.413.248-.694.248-1.289.173-1.413z"/>
                </svg>

                <span className="font-bold">Grupo WhatsApp 4000 horas</span>
            </a>

            <nav className="flex justify-center gap-2 mb-6 bg-gray-800 p-1 rounded-lg w-fit mx-auto">
                <button 
                    onClick={() => setCurrentTab('ganar')} 
                    className={`w-[200px] py-2 rounded ${currentTab === 'ganar' ? 'bg-blue-600 text-white' : 'text-gray-400'}`}
                >
                    Ver Videos
                </button>
                
                <button 
                    onClick={() => setCurrentTab('promocionar')} 
                    className={`w-[200px] py-2 rounded ${currentTab === 'promocionar' ? 'bg-blue-600 text-white' : 'text-gray-400'}`}
                >
                    Subir Video
                </button>

                {user.email === ADMIN_EMAIL && (
                    <button 
                        onClick={handleMassEmail} 
                        className="w-[150px] py-2 rounded bg-indigo-600 hover:bg-indigo-500 text-white font-bold ml-2 shadow"
                    >
                        📧 Enviar Correo
                    </button>
                )}
            </nav>

            <main className={`${currentTab === 'ganar' ? 'flex' : 'hidden'} flex-1 flex-col lg:flex-row gap-6`}>
                <div className="lg:w-2/3">
                    <div className="aspect-video bg-black rounded-lg overflow-hidden shadow-xl flex items-center justify-center">
                        {currentVideoId ? (
                            <div id="player" className="w-full h-full"></div>
                        ) : (
                            <div className="text-gray-500 animate-pulse">Esperando videos... ¡Sube el tuyo!</div>
                        )}
                    </div>
                    <div className="mt-3 p-3 bg-gray-800 rounded">
                        <h3 className="text-white font-medium">{currentVideoTitle || "Aún no hay videos"}</h3>
                    </div>
                </div>
                <aside className="lg:w-1/3 flex flex-col gap-4 h-full overflow-hidden">
                    <div className="bg-gray-800 rounded p-4 flex-1 flex flex-col min-h-[200px]">
                        <h3 className="text-gray-400 text-sm uppercase font-bold mb-2">Lista de Reproducción</h3>
                        <div className="overflow-y-auto flex-1 pr-2 custom-scrollbar space-y-2">
                            {videos.length > 0 ? videos.map((video) => (
                                <button key={video.id} onClick={() => loadVideo(video)} className={`w-full text-left p-2 rounded flex justify-between items-center group ${video.videoId === currentVideoId ? 'bg-blue-900 border-l-2 border-blue-500' : 'bg-gray-700 hover:bg-gray-600'}`}>
                                    <div className="text-sm text-white truncate flex-1">{video.title}</div>
                                    {user?.email === ADMIN_EMAIL && (
                                        <span onClick={(e) => handleDeleteVideo(e, video.id)} className="ml-2 text-red-500 hover:text-red-300 font-bold px-2 py-1 rounded bg-red-900/50 hover:bg-red-900 cursor-pointer" title="Borrar Video">X</span>
                                    )}
                                </button>
                            )) : (
                                <div className="text-center text-gray-500 text-sm py-4">No hay videos en la red.</div>
                            )}
                        </div>
                    </div>
                    
                    <div className="bg-gray-800 rounded p-4 flex-1 flex flex-col min-h-[200px]">
                        <h3 className="text-yellow-500 text-sm uppercase font-bold mb-2">Ranking Global</h3>
                        <div className="overflow-y-auto flex-1 pr-2 custom-scrollbar space-y-2">
                            {leaderboard.length > 0 ? (
                                leaderboard.map((u, i) => (
                                    <div key={u.id || i} className="flex justify-between items-center p-2 bg-gray-700 rounded">
                                        <div className="flex items-center truncate">
                                            <span className="text-xs text-gray-300 truncate mr-2" title={u.email}>
                                                {u.email ? u.email.split('@')[0] : 'Usuario'}
                                            </span>
                                        </div>
                                        
                                        <div className="flex items-center gap-2">
                                            <span className="text-yellow-400 font-mono text-sm whitespace-nowrap">{Math.floor(u.coins || 0)}</span>
                                            {user?.email === ADMIN_EMAIL && (
                                                <button 
                                                    onClick={() => handleGiveCoins(u.id, u.coins)}
                                                    className="bg-green-600 hover:bg-green-500 text-white text-xs font-bold px-2 py-0.5 rounded shadow"
                                                    title="Dar Monedas"
                                                >
                                                    +
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                ))
                            ) : (
                                <div className="text-center text-gray-500 text-sm py-4">Esperando usuarios...</div>
                            )}
                        </div>
                    </div>
                </aside>
            </main>

            <main className={`${currentTab === 'promocionar' ? 'flex' : 'hidden'} flex-1 items-center justify-center`}>
                <PromoCheck user={user} userProfile={userProfile} userId={userId} adminEmail={ADMIN_EMAIL} videoCost={VIDEO_COST} db={db} />
            </main>
        </div>
    );
}

function PromoCheck({ user, userProfile, userId, adminEmail, videoCost, db }) {
    const isAdmin = user?.email === adminEmail;
    const coins = userProfile?.coins || 0;
    const hasEnoughCoins = coins >= videoCost;

    if (isAdmin) return <PromoUnlocked userId={userId} isAdmin={true} db={db} />;
    if (hasEnoughCoins) return <PromoUnlocked userId={userId} isAdmin={false} videoCost={videoCost} db={db} />;

    return (
        <div className="text-center p-8 bg-gray-800 rounded-lg shadow-xl max-w-lg border border-gray-700">
            <h2 className="text-2xl font-bold text-white mb-2">Insuficientes Monedas</h2>
            <p className="text-gray-400 mb-4">Necesitas {videoCost} monedas para subir un video.</p>
            
            <div className="w-full bg-gray-700 rounded-full h-3 mb-4">
                <div className="bg-yellow-400 h-3 rounded-full" style={{ width: `${Math.min((coins / videoCost) * 100, 100)}%` }}></div>
            </div>
            <p className="text-sm text-gray-500 mb-6">{Math.floor(coins)} / {videoCost}</p>

            <div className="mt-6 border-t border-gray-600 pt-6">
                <h3 className="text-yellow-400 font-bold text-xl mb-2">¿Quieres subir tu video ya?</h3>
                <p className="text-white mb-4 text-sm">Deposita USDT para recargar al instante.</p>
                <div className="bg-gray-900 p-4 rounded-lg">
                    <p className="text-green-400 font-bold mb-4 bg-green-900/30 py-2 rounded">1 USD = 3000 Monedas</p>
                    
                    <div className="flex justify-center mb-4">
                        <img src="/qr.png" alt="QR Deposito" className="w-32 h-32 rounded-lg border-2 border-white"/>
                    </div>
                    
                    <p className="text-xs text-gray-400 mb-1 uppercase font-bold">Dirección USDT (BEP20/TRC20):</p>
                    <div className="break-all bg-black p-3 rounded text-xs font-mono text-gray-300 select-all border border-gray-700">
                        0x64531cafffbbc7ab1212d27cbafb4fa58111c84128804edec9d17c49c787e512
                    </div>
                    <p className="text-xs text-gray-500 mt-3">
                        Envía tu comprobante a: <a href={`mailto:${adminEmail}`} className="text-blue-400 hover:underline">{adminEmail}</a>
                    </p>
                </div>
            </div>
        </div>
    );
}

function PromoUnlocked({ userId, isAdmin, videoCost, db }) {
    const [url, setUrl] = useState('');
    const [title, setTitle] = useState('');
    const [message, setMessage] = useState({ text: '', type: '' });
    const [loading, setLoading] = useState(false);

    const extractYouTubeID = (url) => {
        const regex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
        const match = url.match(regex);
        return match ? match[1] : null;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        const videoId = extractYouTubeID(url);
        
        if (!videoId) {
            setMessage({ text: "Enlace de YouTube no válido", type: 'error' });
            return;
        }
        if (!title.trim()) {
            setMessage({ text: "Por favor escribe un título", type: 'error' });
            return;
        }
        if (!db) {
            setMessage({ text: "Error: Base de datos no conectada", type: 'error' });
            return;
        }

        setLoading(true);

        try {
            if (!isAdmin) {
                const userRef = doc(db, 'users', userId);
                await updateDoc(userRef, { coins: increment(-videoCost) });
            }

            const videosRef = collection(db, 'videos');
            await addDoc(videosRef, {
                title: title,
                videoId: videoId,
                addedBy: userId,
                createdAt: serverTimestamp(),
                isPromoted: !isAdmin
            });

            setMessage({ text: "¡Video agregado con éxito!", type: 'success' });
            setUrl('');
            setTitle('');
        } catch (error) {
            console.error("Error al subir:", error);
            setMessage({ text: "Error al procesar. Intenta de nuevo.", type: 'error' });
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="bg-gray-800 p-8 rounded-lg shadow-xl max-w-md w-full border border-green-900">
            <h2 className="text-2xl font-bold text-white mb-4 text-center">{isAdmin ? "Panel Admin" : "¡Meta Alcanzada!"}</h2>
            <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                    <label className="block text-sm text-gray-400 mb-1">Enlace del Video</label>
                    <input 
                        type="url" 
                        placeholder="https://youtube.com/watch?v=..." 
                        className="w-full p-3 bg-gray-700 text-white rounded border border-gray-600 focus:border-blue-500 outline-none"
                        value={url}
                        onChange={(e) => setUrl(e.target.value)}
                        required
                    />
                </div>
                <div>
                    <label className="block text-sm text-gray-400 mb-1">Título del Video</label>
                    <input 
                        type="text" 
                        placeholder="Ej: Mi Gameplay Épico" 
                        className="w-full p-3 bg-gray-700 text-white rounded border border-gray-600 focus:border-blue-500 outline-none"
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                        required
                        maxLength={50}
                    />
                </div>
                <button disabled={loading} className="w-full py-3 bg-green-600 hover:bg-green-700 text-white font-bold rounded transition-colors disabled:opacity-50">
                    {loading ? 'Procesando...' : (isAdmin ? 'Subir Gratis' : `Pagar ${videoCost} y Subir`)}
                </button>
                {message.text && (
                    <p className={`text-center font-medium ${message.type === 'error' ? 'text-red-400' : 'text-green-400'}`}>
                        {message.text}
                    </p>
                )}
            </form>
        </div>
    );
}