salomonsky commited on
Commit
ddf0dad
·
verified ·
1 Parent(s): db0b331

Update cointube.jsx

Browse files
Files changed (1) hide show
  1. cointube.jsx +219 -61
cointube.jsx CHANGED
@@ -23,7 +23,7 @@ import {
23
  setLogLevel
24
  } from 'firebase/firestore';
25
 
26
- // --- Configuración de Firebase ---
27
  const firebaseConfig = {
28
  apiKey: "AIzaSyCwJjVJGuOmA_PKRbaTnQDrK-Q07NI_utc",
29
  authDomain: "insights-5c2d6.firebaseapp.com",
@@ -38,7 +38,6 @@ try {
38
  app = initializeApp(firebaseConfig);
39
  auth = getAuth(app);
40
  db = getFirestore(app);
41
- // setLogLevel('debug'); // Descomentar si necesitas ver logs de firebase en consola
42
  } catch (error) {
43
  console.error("Error inicializando Firebase:", error);
44
  }
@@ -49,17 +48,11 @@ const COIN_GOAL = 10000;
49
 
50
  export default function App() {
51
 
 
52
  const [videos, setVideos] = useState([
53
- { id: '1', title: 'Pelicula Completa', videoId: 'UtEhewStfMA' },
54
  { id: '2', title: 'Documental Comida', videoId: 'lwiNN7WUw50' },
55
  { id: '3', title: 'Cine de Arte', videoId: 'GxEx6Kgo6Es' },
56
- { id: '4', title: 'Celos Infieles', videoId: '8nqtOYAN9Lo' },
57
- { id: '5', title: 'Rescatando Perros', videoId: 'KzyQttgzu1Q' },
58
- { id: '6', title: 'Feminismo', videoId: 'YGf2DMGoiiE' },
59
- { id: '7', title: 'Recetas Cocina', videoId: 'M6rL0SkFyGo' },
60
- { id: '8', title: 'Titeres', videoId: 'pb12nP7Ples' },
61
- { id: '9', title: 'Comedia', videoId: 'yUUUY0GVMeU' },
62
- { id: '10', title: 'Experimento', videoId: '0KefumC4bY8' },
63
  ]);
64
 
65
  const [user, setUser] = useState(null);
@@ -95,7 +88,7 @@ export default function App() {
95
  return () => unsubscribeAuth();
96
  }, []);
97
 
98
- // 2. Perfil
99
  useEffect(() => {
100
  if (!userId || !db) return;
101
  const profileRef = doc(db, 'users', userId);
@@ -116,6 +109,32 @@ export default function App() {
116
  return () => unsubscribeProfile();
117
  }, [userId, user]);
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  // 4. API YouTube
120
  useEffect(() => {
121
  if (!window.YT) {
@@ -129,6 +148,7 @@ export default function App() {
129
  }
130
  }, []);
131
 
 
132
  const saveCoinBuffer = useCallback(() => {
133
  if (localCoinBufferRef.current > 0 && userId) {
134
  const coinsToSave = localCoinBufferRef.current;
@@ -155,6 +175,7 @@ export default function App() {
155
  }
156
  }, [saveCoinBuffer]);
157
 
 
158
  const onPlayerReady = useCallback((event) => {
159
  playerRef.current = event.target;
160
  playerRef.current.playVideo();
@@ -173,6 +194,7 @@ export default function App() {
173
  }
174
  }, [startCoinInterval, stopCoinInterval, currentVideoId, userId]);
175
 
 
176
  useEffect(() => {
177
  if (ytApiReady && userId && !playerRef.current) {
178
  try {
@@ -202,6 +224,7 @@ export default function App() {
202
  }
203
  };
204
 
 
205
  const handleGoogleLogin = async () => {
206
  const provider = new GoogleAuthProvider();
207
  try {
@@ -219,22 +242,46 @@ export default function App() {
219
 
220
  if (!authReady) {
221
  return (
222
- <div className="flex flex-col items-center justify-center h-full w-full text-white">
223
  <div className="spinner mb-4"></div>
224
- <p>Cargando CoinTube...</p>
225
  </div>
226
  );
227
  }
228
 
 
229
  if (authReady && !user) {
230
  return (
231
  <div className="flex flex-col items-center justify-center h-full w-full bg-gray-900 p-4">
232
  <div className="max-w-md w-full bg-gray-800 rounded-2xl shadow-2xl p-8 text-center border border-gray-700">
233
- <h1 className="text-3xl font-bold text-white mb-2">Bienvenido a CoinTube</h1>
234
- <p className="text-gray-400 mb-8 text-sm">Gana monedas viendo videos.</p>
235
- <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">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  Continuar con Google
237
  </button>
 
 
 
 
238
  </div>
239
  </div>
240
  );
@@ -252,10 +299,11 @@ export default function App() {
252
  PromoComponent = <PromoUnlocked userId={userId} />;
253
  }
254
 
 
255
  return (
256
- <div className="h-full w-full max-w-7xl mx-auto flex flex-col p-4 md:p-6 text-white">
257
  <header className="flex flex-col md:flex-row justify-between items-center pb-4 mb-4 border-b border-gray-700">
258
- <h1 className="text-3xl font-bold">Coin<span className="text-blue-500">Tube</span></h1>
259
  <div className="flex items-center space-x-4 mt-4 md:mt-0">
260
  <div className="flex flex-col items-end">
261
  <span className="text-sm text-gray-400">{userProfile?.name || user?.email || 'Usuario'}</span>
@@ -263,46 +311,71 @@ export default function App() {
263
  {(userProfile?.coins || 0).toLocaleString()} Monedas
264
  </span>
265
  </div>
266
- <button onClick={handleLogout} className="px-4 py-2 bg-gray-700 text-sm font-medium rounded-lg hover:bg-gray-600">Salir</button>
 
 
 
 
 
267
  </div>
268
  </header>
269
 
270
  <nav className="flex space-x-1 mb-6 rounded-lg bg-gray-800 p-1 max-w-lg mx-auto">
271
- <button onClick={() => setCurrentTab('ganar')} className={`flex-1 py-2 px-4 rounded-lg text-sm ${currentTab === 'ganar' ? 'bg-blue-600 text-white' : 'text-gray-300 hover:bg-gray-700'}`}>Ganar</button>
272
- <button onClick={() => setCurrentTab('promocionar')} className={`flex-1 py-2 px-4 rounded-lg text-sm ${currentTab === 'promocionar' ? 'bg-blue-600 text-white' : 'text-gray-300 hover:bg-gray-700'}`}>Promocionar</button>
273
- <button onClick={() => setCurrentTab('ranking')} className={`flex-1 py-2 px-4 rounded-lg text-sm ${currentTab === 'ranking' ? 'bg-blue-600 text-white' : 'text-gray-300 hover:bg-gray-700'}`}>Ranking</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  </nav>
275
 
276
- <main className={`${currentTab === 'ganar' ? 'flex' : 'hidden'} flex-1 flex-col lg:flex-row gap-6`}>
 
277
  <div className="lg:w-2/3 flex flex-col">
278
- <div className="w-full bg-black rounded-lg shadow-2xl overflow-hidden aspect-video">
279
- <div id="player" className="w-full h-full"></div>
 
 
280
  </div>
281
  <div className="mt-4 p-4 bg-gray-800 rounded-lg">
282
- <h3 className="text-lg font-semibold">{currentVideoTitle}</h3>
283
  </div>
284
  </div>
285
- <aside className="lg:w-1/3 flex flex-col bg-gray-800 rounded-lg shadow-lg p-4 max-h-[500px]">
286
- <h2 className="text-xl font-semibold mb-4 pb-2 border-b border-gray-700">Videos</h2>
287
  <div className="flex-1 overflow-y-auto space-y-2 pr-2">
288
  {videos.map((video) => (
289
  <button
290
  key={video.id}
291
  onClick={() => loadVideo(video)}
292
- className="w-full text-left px-4 py-3 bg-gray-700 rounded-lg hover:bg-gray-600 disabled:opacity-50"
293
  disabled={video.videoId === currentVideoId}
294
  >
295
- {video.title}
296
  </button>
297
  ))}
298
  </div>
299
  </aside>
300
  </main>
301
 
 
302
  <main className={`${currentTab === 'promocionar' ? 'flex' : 'hidden'} flex-1 flex-col items-center justify-center`}>
303
  {PromoComponent}
304
  </main>
305
 
 
306
  <main className={`${currentTab === 'ranking' ? 'flex' : 'hidden'} flex-1 flex-col items-center justify-start py-4 overflow-auto`}>
307
  <Leaderboard db={db} currentUserId={userId} />
308
  </main>
@@ -310,7 +383,8 @@ export default function App() {
310
  );
311
  }
312
 
313
- // --- Sub-Componentes (Sin Cambios, lógica protegida) ---
 
314
  function Leaderboard({ db, currentUserId }) {
315
  const [ranking, setRanking] = useState([]);
316
  const [loading, setLoading] = useState(true);
@@ -319,8 +393,15 @@ function Leaderboard({ db, currentUserId }) {
319
  useEffect(() => {
320
  if (!db) return;
321
  setLoading(true);
 
322
  try {
323
- const q = query(collection(db, 'users'), orderBy('coins', 'desc'), limit(10));
 
 
 
 
 
 
324
  const unsubscribe = onSnapshot(q, (snapshot) => {
325
  const users = [];
326
  snapshot.forEach((doc) => {
@@ -333,75 +414,152 @@ function Leaderboard({ db, currentUserId }) {
333
  });
334
  setRanking(users);
335
  setLoading(false);
 
336
  }, (err) => {
337
  console.error("Error ranking:", err);
338
- setError("Requiere índice en Firebase o permiso insuficiente.");
339
  setLoading(false);
340
  });
341
  return () => unsubscribe();
342
  } catch (e) {
343
- setError(e.message);
 
344
  setLoading(false);
345
  }
346
  }, [db]);
347
 
348
- if (loading) return <div className="p-8">Cargando ranking...</div>;
349
- if (error) return <div className="p-8 text-red-400">Error: {error} (Revisa la consola F12 para crear el índice)</div>;
350
 
351
  return (
352
  <div className="w-full max-w-lg bg-gray-800 rounded-xl shadow-2xl p-6">
353
- <h2 className="text-3xl font-bold mb-6 text-center">🏆 Ranking 🏆</h2>
354
- <ul className="space-y-3">
355
- {ranking.map((user, index) => (
356
- <li key={user.id} className={`flex justify-between p-4 rounded-lg ${user.id === currentUserId ? 'bg-blue-600' : 'bg-gray-700'}`}>
357
- <span>#{index + 1} {user.name}</span>
358
- <span>{(user.coins || 0).toLocaleString()} 💰</span>
359
- </li>
360
- ))}
361
- </ul>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  </div>
363
  );
364
  }
365
 
366
  function GoalLocked({ coinGoal, currentCoins }) {
367
  return (
368
- <div className="text-center p-8 bg-gray-800 rounded-lg max-w-lg">
 
369
  <h2 className="text-2xl font-bold mb-2 text-yellow-400">¡Meta de Monedas!</h2>
370
- <p className="text-gray-300">Acumulado: {(currentCoins || 0).toLocaleString()} / {coinGoal.toLocaleString()}</p>
371
- <p className="text-blue-400 text-sm mt-2">Sigue viendo videos.</p>
 
 
 
 
 
 
 
372
  </div>
373
  );
374
  }
375
 
376
  function PromoLocked({ defaultTitle }) {
377
  return (
378
- <div className="text-center p-8 bg-gray-800 rounded-lg max-w-lg">
 
379
  <h2 className="text-2xl font-bold mb-2">Sección Bloqueada</h2>
380
- <p className="text-gray-300">Debes ver el video: "{defaultTitle}"</p>
 
 
 
381
  </div>
382
  );
383
  }
384
 
385
  function PromoUnlocked({ userId }) {
386
- // (El código de PromoUnlocked que ya tenías, sin cambios lógicos)
387
  const [url, setUrl] = useState('');
388
- const [message, setMessage] = useState({ text: '', type: '' });
 
 
 
 
 
 
389
 
390
  const handleSubmit = async (e) => {
391
  e.preventDefault();
392
- // ... lógica de envío ...
393
- // Para simplificar en esta respuesta, asumo que la lógica es la misma de antes
394
- // Si necesitas que te la repita completa, avísame, pero el error de pantalla blanca no estaba aquí.
395
- setMessage({text: "Función lista (Simulada para brevedad)", type: 'success'});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  };
397
 
398
  return (
399
- <div className="text-center p-8 bg-gray-800 rounded-lg max-w-lg">
400
- <h2 className="text-2xl font-bold mb-2">¡Desbloqueado!</h2>
 
 
 
 
401
  <form onSubmit={handleSubmit} className="flex flex-col space-y-4">
402
- <input type="url" placeholder="URL de YouTube..." className="p-2 bg-gray-700 rounded text-white" value={url} onChange={e=>setUrl(e.target.value)} />
403
- <button type="submit" className="bg-blue-600 p-2 rounded font-bold">Promocionar</button>
404
- {message.text && <p>{message.text}</p>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  </form>
406
  </div>
407
  );
 
23
  setLogLevel
24
  } from 'firebase/firestore';
25
 
26
+ // --- Constantes de Firebase ---
27
  const firebaseConfig = {
28
  apiKey: "AIzaSyCwJjVJGuOmA_PKRbaTnQDrK-Q07NI_utc",
29
  authDomain: "insights-5c2d6.firebaseapp.com",
 
38
  app = initializeApp(firebaseConfig);
39
  auth = getAuth(app);
40
  db = getFirestore(app);
 
41
  } catch (error) {
42
  console.error("Error inicializando Firebase:", error);
43
  }
 
48
 
49
  export default function App() {
50
 
51
+ // Lista de videos inicializada con datos fijos para el primer render
52
  const [videos, setVideos] = useState([
53
+ { id: '1', title: DEFAULT_VIDEO_TITLE, videoId: DEFAULT_VIDEO_ID },
54
  { id: '2', title: 'Documental Comida', videoId: 'lwiNN7WUw50' },
55
  { id: '3', title: 'Cine de Arte', videoId: 'GxEx6Kgo6Es' },
 
 
 
 
 
 
 
56
  ]);
57
 
58
  const [user, setUser] = useState(null);
 
88
  return () => unsubscribeAuth();
89
  }, []);
90
 
91
+ // 2. Perfil de Usuario
92
  useEffect(() => {
93
  if (!userId || !db) return;
94
  const profileRef = doc(db, 'users', userId);
 
109
  return () => unsubscribeProfile();
110
  }, [userId, user]);
111
 
112
+ // 3. Videos de Firebase (RESTAURADO: Carga dinámica)
113
+ useEffect(() => {
114
+ if (!db) return;
115
+ const videosRef = collection(db, 'videos');
116
+ const q = query(videosRef, orderBy('createdAt', 'desc'), limit(100)); // Límite para evitar sobrecarga
117
+
118
+ const unsubscribeVideos = onSnapshot(q, (snapshot) => {
119
+ if (snapshot.empty) {
120
+ // Si no hay videos, se añade el por defecto solo en la base de datos
121
+ addDoc(videosRef, {
122
+ title: DEFAULT_VIDEO_TITLE,
123
+ videoId: DEFAULT_VIDEO_ID,
124
+ addedBy: "system",
125
+ createdAt: serverTimestamp()
126
+ }).catch(e => console.error(e));
127
+ } else {
128
+ const videoList = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
129
+ setVideos(videoList);
130
+ }
131
+ }, (error) => {
132
+ console.error("Error listening to videos:", error);
133
+ });
134
+
135
+ return () => unsubscribeVideos();
136
+ }, []);
137
+
138
  // 4. API YouTube
139
  useEffect(() => {
140
  if (!window.YT) {
 
148
  }
149
  }, []);
150
 
151
+ // --- Lógica de Monedas ---
152
  const saveCoinBuffer = useCallback(() => {
153
  if (localCoinBufferRef.current > 0 && userId) {
154
  const coinsToSave = localCoinBufferRef.current;
 
175
  }
176
  }, [saveCoinBuffer]);
177
 
178
+ // --- Player Events ---
179
  const onPlayerReady = useCallback((event) => {
180
  playerRef.current = event.target;
181
  playerRef.current.playVideo();
 
194
  }
195
  }, [startCoinInterval, stopCoinInterval, currentVideoId, userId]);
196
 
197
+ // 5. Inicializar Player
198
  useEffect(() => {
199
  if (ytApiReady && userId && !playerRef.current) {
200
  try {
 
224
  }
225
  };
226
 
227
+ // --- FUNCIONES DE LOGIN (SIN ANÓNIMO) ---
228
  const handleGoogleLogin = async () => {
229
  const provider = new GoogleAuthProvider();
230
  try {
 
242
 
243
  if (!authReady) {
244
  return (
245
+ <div className="flex flex-col items-center justify-center h-full w-full">
246
  <div className="spinner mb-4"></div>
247
+ <p className="text-lg text-gray-400">Conectando...</p>
248
  </div>
249
  );
250
  }
251
 
252
+ // --- Renderizado de Login (SIN BOTÓN ANÓNIMO) ---
253
  if (authReady && !user) {
254
  return (
255
  <div className="flex flex-col items-center justify-center h-full w-full bg-gray-900 p-4">
256
  <div className="max-w-md w-full bg-gray-800 rounded-2xl shadow-2xl p-8 text-center border border-gray-700">
257
+ <div className="flex justify-center mb-6">
258
+ <div className="bg-blue-600 p-4 rounded-full shadow-lg">
259
+ <svg className="w-12 h-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
260
+ <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>
261
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
262
+ </svg>
263
+ </div>
264
+ </div>
265
+ <h1 className="text-3xl font-bold text-white mb-2 tracking-tight">Bienvenido a CoinTube</h1>
266
+ <p className="text-gray-400 mb-8 text-sm leading-relaxed">
267
+ Descubre contenido increíble, gana monedas virtuales por cada minuto que ves y promociona tus propios videos.
268
+ </p>
269
+ <button
270
+ onClick={handleGoogleLogin}
271
+ 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"
272
+ >
273
+ <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
274
+ <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"/>
275
+ <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"/>
276
+ <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"/>
277
+ <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"/>
278
+ </svg>
279
  Continuar con Google
280
  </button>
281
+
282
+ <p className="mt-6 text-xs text-gray-500">
283
+ Al continuar, aceptas nuestros términos de servicio.
284
+ </p>
285
  </div>
286
  </div>
287
  );
 
299
  PromoComponent = <PromoUnlocked userId={userId} />;
300
  }
301
 
302
+ // --- App Principal ---
303
  return (
304
+ <div className="h-full w-full max-w-7xl mx-auto flex flex-col p-4 md:p-6">
305
  <header className="flex flex-col md:flex-row justify-between items-center pb-4 mb-4 border-b border-gray-700">
306
+ <h1 className="text-3xl font-bold text-white">Coin<span className="text-blue-500">Tube</span></h1>
307
  <div className="flex items-center space-x-4 mt-4 md:mt-0">
308
  <div className="flex flex-col items-end">
309
  <span className="text-sm text-gray-400">{userProfile?.name || user?.email || 'Usuario'}</span>
 
311
  {(userProfile?.coins || 0).toLocaleString()} Monedas
312
  </span>
313
  </div>
314
+ <button
315
+ onClick={handleLogout}
316
+ className="px-4 py-2 bg-gray-700 text-white text-sm font-medium rounded-lg hover:bg-gray-600 transition-colors"
317
+ >
318
+ Salir
319
+ </button>
320
  </div>
321
  </header>
322
 
323
  <nav className="flex space-x-1 mb-6 rounded-lg bg-gray-800 p-1 max-w-lg mx-auto">
324
+ <button
325
+ onClick={() => setCurrentTab('ganar')}
326
+ className={`flex-1 py-2 px-4 rounded-lg text-center font-medium text-sm transition-colors ${currentTab === 'ganar' ? 'bg-blue-600 text-white' : 'text-gray-300 hover:bg-gray-700'}`}
327
+ >
328
+ Ganar Monedas
329
+ </button>
330
+ <button
331
+ onClick={() => setCurrentTab('promocionar')}
332
+ className={`flex-1 py-2 px-4 rounded-lg text-center font-medium text-sm transition-colors ${currentTab === 'promocionar' ? 'bg-blue-600 text-white' : 'text-gray-300 hover:bg-gray-700'}`}
333
+ >
334
+ Promocionar Video
335
+ </button>
336
+ <button
337
+ onClick={() => setCurrentTab('ranking')}
338
+ className={`flex-1 py-2 px-4 rounded-lg text-center font-medium text-sm transition-colors ${currentTab === 'ranking' ? 'bg-blue-600 text-white' : 'text-gray-300 hover:bg-gray-700'}`}
339
+ >
340
+ Ranking
341
+ </button>
342
  </nav>
343
 
344
+ {/* SECCIÓN GANAR MONEDAS */}
345
+ <main className={`${currentTab === 'ganar' ? 'flex' : 'hidden'} flex-1 flex-col lg:flex-row gap-6 overflow-hidden`}>
346
  <div className="lg:w-2/3 flex flex-col">
347
+ <div className="w-full bg-black rounded-lg shadow-2xl overflow-hidden">
348
+ <div className="aspect-video w-full">
349
+ <div id="player" className="w-full h-full"></div>
350
+ </div>
351
  </div>
352
  <div className="mt-4 p-4 bg-gray-800 rounded-lg">
353
+ <h3 className="text-lg font-semibold text-white">{currentVideoTitle}</h3>
354
  </div>
355
  </div>
356
+ <aside className="lg:w-1/3 flex flex-col bg-gray-800 rounded-lg shadow-lg p-4">
357
+ <h2 className="text-xl font-semibold mb-4 pb-2 border-b border-gray-700">Videos Disponibles</h2>
358
  <div className="flex-1 overflow-y-auto space-y-2 pr-2">
359
  {videos.map((video) => (
360
  <button
361
  key={video.id}
362
  onClick={() => loadVideo(video)}
363
+ className="w-full text-left px-4 py-3 bg-gray-700 rounded-lg hover:bg-gray-600 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
364
  disabled={video.videoId === currentVideoId}
365
  >
366
+ {video.title || `Video ID: ${video.videoId}`}
367
  </button>
368
  ))}
369
  </div>
370
  </aside>
371
  </main>
372
 
373
+ {/* SECCIÓN PROMOCIONAR VIDEO */}
374
  <main className={`${currentTab === 'promocionar' ? 'flex' : 'hidden'} flex-1 flex-col items-center justify-center`}>
375
  {PromoComponent}
376
  </main>
377
 
378
+ {/* SECCIÓN RANKING */}
379
  <main className={`${currentTab === 'ranking' ? 'flex' : 'hidden'} flex-1 flex-col items-center justify-start py-4 overflow-auto`}>
380
  <Leaderboard db={db} currentUserId={userId} />
381
  </main>
 
383
  );
384
  }
385
 
386
+ // --- Sub-Componentes ---
387
+
388
  function Leaderboard({ db, currentUserId }) {
389
  const [ranking, setRanking] = useState([]);
390
  const [loading, setLoading] = useState(true);
 
393
  useEffect(() => {
394
  if (!db) return;
395
  setLoading(true);
396
+
397
  try {
398
+ // Consulta: top 10 usuarios ordenados por monedas
399
+ const q = query(
400
+ collection(db, 'users'),
401
+ orderBy('coins', 'desc'),
402
+ limit(10)
403
+ );
404
+
405
  const unsubscribe = onSnapshot(q, (snapshot) => {
406
  const users = [];
407
  snapshot.forEach((doc) => {
 
414
  });
415
  setRanking(users);
416
  setLoading(false);
417
+ setError(null);
418
  }, (err) => {
419
  console.error("Error ranking:", err);
420
+ setError("No se pudo cargar el ranking. (Revisar consola y reglas de Firebase)");
421
  setLoading(false);
422
  });
423
  return () => unsubscribe();
424
  } catch (e) {
425
+ console.error("Error al iniciar consulta de ranking:", e);
426
+ setError("Error interno al iniciar el ranking.");
427
  setLoading(false);
428
  }
429
  }, [db]);
430
 
431
+ if (loading) return <div className="text-center p-8 text-gray-400">Cargando ranking...</div>;
432
+ if (error) return <div className="text-center p-8 text-red-400">{error}</div>;
433
 
434
  return (
435
  <div className="w-full max-w-lg bg-gray-800 rounded-xl shadow-2xl p-6">
436
+ <h2 className="text-3xl font-bold text-white mb-6 pb-2 border-b border-gray-700 text-center">🏆 Ranking de Monedas 🏆</h2>
437
+
438
+ {ranking.length === 0 ? (
439
+ <div className="text-center p-8 text-gray-400">Aún no hay usuarios en el ranking.</div>
440
+ ) : (
441
+ <ul className="space-y-3">
442
+ {ranking.map((user, index) => (
443
+ <li
444
+ key={user.id}
445
+ className={`flex items-center justify-between p-4 rounded-lg transition-all duration-200 ${user.id === currentUserId
446
+ ? 'bg-blue-600 shadow-lg ring-2 ring-blue-400'
447
+ : 'bg-gray-700 hover:bg-gray-600'
448
+ }`}
449
+ >
450
+ <div className="flex items-center space-x-4">
451
+ <span className={`text-xl font-extrabold w-6 text-center ${index < 3 ? 'text-yellow-400' : 'text-gray-400'}`}>
452
+ {index + 1}.
453
+ </span>
454
+ <span className={`text-lg font-medium truncate ${user.id === currentUserId ? 'text-white' : 'text-gray-200'}`}>
455
+ {user.id === currentUserId ? `${user.name} (Tú)` : user.name}
456
+ </span>
457
+ </div>
458
+ <span className={`text-xl font-bold ${user.id === currentUserId ? 'text-yellow-200' : 'text-yellow-400'}`}>
459
+ {(user.coins || 0).toLocaleString()} 💰
460
+ </span>
461
+ </li>
462
+ ))}
463
+ </ul>
464
+ )}
465
  </div>
466
  );
467
  }
468
 
469
  function GoalLocked({ coinGoal, currentCoins }) {
470
  return (
471
+ <div className="text-center p-8 bg-gray-800 rounded-lg shadow-xl max-w-lg">
472
+ <svg className="w-16 h-16 text-yellow-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8c1.657 0 3 1.343 3 3s-1.343 3-3 3-1.343-3-3-3 3 1.343 3 3v4m-6 0h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"></path></svg>
473
  <h2 className="text-2xl font-bold mb-2 text-yellow-400">¡Meta de Monedas!</h2>
474
+ <p className="text-gray-300">
475
+ ¡Felicidades! Desbloqueaste la promoción por ver el video, pero el servicio requiere un mínimo de monedas.
476
+ </p>
477
+ <p className="text-gray-100 text-lg mt-4 font-semibold">
478
+ Acumulado: {(currentCoins || 0).toLocaleString()} / {coinGoal.toLocaleString()} Monedas
479
+ </p>
480
+ <p className="text-blue-400 text-sm mt-2 font-bold">
481
+ ¡Debes seguir viendo videos hasta juntar {coinGoal.toLocaleString()} monedas!
482
+ </p>
483
  </div>
484
  );
485
  }
486
 
487
  function PromoLocked({ defaultTitle }) {
488
  return (
489
+ <div className="text-center p-8 bg-gray-800 rounded-lg shadow-xl max-w-lg">
490
+ <svg className="w-16 h-16 text-yellow-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
491
  <h2 className="text-2xl font-bold mb-2">Sección Bloqueada</h2>
492
+ <p className="text-gray-300">
493
+ Para poder promocionar tu propio video, primero debes ver el video predeterminado ("{defaultTitle}") por completo.
494
+ </p>
495
+ <p className="text-gray-400 text-sm mt-4">¡Ve a "Ganar Monedas", búscalo en la lista y míralo hasta el final!</p>
496
  </div>
497
  );
498
  }
499
 
500
  function PromoUnlocked({ userId }) {
 
501
  const [url, setUrl] = useState('');
502
+ const [message, setMessage] = useState({ text: '', type: 'success' });
503
+
504
+ const extractYouTubeID = (url) => {
505
+ const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
506
+ const match = url.match(regex);
507
+ return match ? match[1] : null;
508
+ };
509
 
510
  const handleSubmit = async (e) => {
511
  e.preventDefault();
512
+ const videoId = extractYouTubeID(url);
513
+
514
+ if (!videoId) {
515
+ setMessage({ text: "URL de YouTube no válida.", type: 'error' });
516
+ return;
517
+ }
518
+ const title = `Video de usuario (${videoId.substring(0, 5)}...)`;
519
+
520
+ try {
521
+ const videosRef = collection(db, 'videos');
522
+ await addDoc(videosRef, {
523
+ title: title,
524
+ videoId: videoId,
525
+ addedBy: userId,
526
+ createdAt: serverTimestamp()
527
+ });
528
+ setMessage({ text: "¡Video agregado con éxito!", type: 'success' });
529
+ setUrl('');
530
+ } catch (error) {
531
+ console.error(error);
532
+ setMessage({ text: "Error al agregar el video.", type: 'error' });
533
+ }
534
  };
535
 
536
  return (
537
+ <div className="text-center p-8 bg-gray-800 rounded-lg shadow-xl max-w-lg w-full">
538
+ <svg className="w-16 h-16 text-green-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"></path></svg>
539
+ <h2 className="text-2xl font-bold mb-2">¡Sección Desbloqueada!</h2>
540
+ <p className="text-gray-300 mb-6">
541
+ Pega el enlace de un video de YouTube para agregarlo a la lista pública.
542
+ </p>
543
  <form onSubmit={handleSubmit} className="flex flex-col space-y-4">
544
+ <input
545
+ type="url"
546
+ placeholder="https://www.youtube.com/watch?v=..."
547
+ className="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
548
+ required
549
+ value={url}
550
+ onChange={(e) => setUrl(e.target.value)}
551
+ />
552
+ <button
553
+ type="submit"
554
+ className="w-full px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors"
555
+ >
556
+ Promocionar Video
557
+ </button>
558
+ {message.text && (
559
+ <p className={`text-sm ${message.type === 'success' ? 'text-green-500' : 'text-red-500'}`}>
560
+ {message.text}
561
+ </p>
562
+ )}
563
  </form>
564
  </div>
565
  );