dimensionalpulsar commited on
Commit
f4c480a
·
verified ·
1 Parent(s): e18d8f3

Update cointube.jsx

Browse files
Files changed (1) hide show
  1. cointube.jsx +126 -281
cointube.jsx CHANGED
@@ -20,7 +20,9 @@ import {
20
  serverTimestamp,
21
  query,
22
  orderBy,
23
- limit
 
 
24
  } from 'firebase/firestore';
25
 
26
  const firebaseConfig = {
@@ -41,8 +43,10 @@ const VIDEO_COST = 10000;
41
  const DEFAULT_VIDEO_ID = "1rghd2zPhFo";
42
  const DEFAULT_VIDEO_TITLE = "Cuentos de Terror";
43
 
 
 
 
44
  export default function App() {
45
-
46
  const [videos, setVideos] = useState([]);
47
  const [leaderboard, setLeaderboard] = useState([]);
48
  const [user, setUser] = useState(null);
@@ -50,10 +54,8 @@ export default function App() {
50
  const [authReady, setAuthReady] = useState(false);
51
  const [userProfile, setUserProfile] = useState(null);
52
  const [currentTab, setCurrentTab] = useState('ganar');
53
-
54
  const [currentVideoId, setCurrentVideoId] = useState(null);
55
  const [currentVideoTitle, setCurrentVideoTitle] = useState(null);
56
-
57
  const [ytApiReady, setYtApiReady] = useState(false);
58
 
59
  const playerRef = useRef(null);
@@ -91,16 +93,44 @@ export default function App() {
91
  setDoc(profileRef, newProfile).catch(e => console.error(e));
92
  setUserProfile(newProfile);
93
  }
94
- }, (error) => console.error(error));
95
  return () => unsubscribeProfile();
96
  }, [userId, user]);
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  useEffect(() => {
99
  const q = query(collection(db, 'videos'), orderBy('createdAt', 'desc'), limit(50));
100
  const unsubscribe = onSnapshot(q, (snapshot) => {
101
- const fetchedVideos = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
102
 
103
  if (fetchedVideos.length > 0) {
 
104
  setVideos(fetchedVideos);
105
  if (initialLoadRef.current || !currentVideoId) {
106
  const latestVideo = fetchedVideos[0];
@@ -109,7 +139,8 @@ export default function App() {
109
  initialLoadRef.current = false;
110
  }
111
  } else {
112
- setVideos([{ id: '1', title: DEFAULT_VIDEO_TITLE, videoId: DEFAULT_VIDEO_ID }]);
 
113
  if (initialLoadRef.current || !currentVideoId) {
114
  setCurrentVideoId(DEFAULT_VIDEO_ID);
115
  setCurrentVideoTitle(DEFAULT_VIDEO_TITLE);
@@ -124,12 +155,7 @@ export default function App() {
124
  const q = query(collection(db, 'users'), orderBy('coins', 'desc'), limit(100));
125
  const unsubscribe = onSnapshot(q, (snapshot) => {
126
  let usersList = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
127
-
128
- usersList = usersList.filter(u =>
129
- u.email &&
130
- u.email.endsWith('@gmail.com')
131
- );
132
-
133
  setLeaderboard(usersList.slice(0, 20));
134
  });
135
  return () => unsubscribe();
@@ -182,21 +208,15 @@ export default function App() {
182
  const state = event.data;
183
  if (state === window.YT.PlayerState.PLAYING) startCoinInterval();
184
  else stopCoinInterval();
185
-
186
- if (state === window.YT.PlayerState.ENDED) {
187
- if (currentVideoId === DEFAULT_VIDEO_ID && userId) {
188
- const profileRef = doc(db, 'users', userId);
189
- updateDoc(profileRef, { watchedDefaultVideo: true });
190
- }
191
  }
192
  }, [startCoinInterval, stopCoinInterval, currentVideoId, userId]);
193
 
194
  useEffect(() => {
195
  if (ytApiReady && userId && !playerRef.current && currentVideoId) {
196
  playerRef.current = new window.YT.Player('player', {
197
- height: '100%',
198
- width: '100%',
199
- videoId: currentVideoId,
200
  playerVars: { 'playsinline': 1, 'autoplay': 1, 'controls': 1, 'modestbranding': 1, 'rel': 0 },
201
  events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange }
202
  });
@@ -214,35 +234,23 @@ export default function App() {
214
  if (playerRef.current) playerRef.current.loadVideoById(video.videoId);
215
  };
216
 
217
- const handleDeleteVideo = async (e, videoId) => {
218
  e.stopPropagation();
219
  if (!confirm("¿Eliminar video?")) return;
220
- try { await deleteDoc(doc(db, "videos", videoId)); } catch (error) { console.error(error); }
221
  };
222
 
223
- const handleGiveCoins = async (targetUserId, currentCoins) => {
224
- const amountStr = prompt("Cantidad de monedas a sumar (usa negativo para restar):", "1000");
225
- if (!amountStr) return;
226
- const amount = parseInt(amountStr);
227
- if (isNaN(amount)) return;
228
-
229
- try {
230
- const userRef = doc(db, 'users', targetUserId);
231
- await updateDoc(userRef, { coins: increment(amount) });
232
- alert("Monedas actualizadas.");
233
- } catch (error) {
234
- console.error("Error:", error);
235
- alert("Error al dar monedas. Revisa las reglas de Firebase.");
236
- }
237
  };
238
 
239
  const handleGoogleLogin = async () => {
240
- const provider = new GoogleAuthProvider();
241
- try {
242
- await signInWithPopup(auth, provider);
243
- } catch (error) {
244
- console.error("Error Google:", error);
245
- }
246
  };
247
 
248
  const handleLogout = async () => {
@@ -250,165 +258,92 @@ export default function App() {
250
  await signOut(auth);
251
  };
252
 
253
- if (!authReady) {
254
- return (
255
- <div className="flex flex-col items-center justify-center h-full w-full">
256
- <div className="spinner mb-4"></div>
257
- <p className="text-lg text-gray-400">Cargando...</p>
258
- </div>
259
- );
260
- }
261
-
262
- if (authReady && !user) {
263
- return (
264
- <div className="flex flex-col items-center justify-center h-full w-full bg-gray-900 p-4">
265
- <div className="max-w-md w-full bg-gray-800 rounded-2xl shadow-2xl p-8 text-center border border-gray-700">
266
- <div className="flex justify-center mb-6">
267
- <div className="bg-blue-600 p-4 rounded-full shadow-lg">
268
- <svg className="w-12 h-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
269
- <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>
270
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
271
- </svg>
272
- </div>
273
- </div>
274
- <h1 className="text-3xl font-bold text-white mb-2 tracking-tight">Bienvenido a CoinTube</h1>
275
- <p className="text-gray-400 mb-8 text-sm leading-relaxed">
276
- Descubre contenido increíble, gana monedas virtuales por cada minuto que ves y promociona tus propios videos.<br/><br/>
277
- <span className="text-yellow-400 font-bold text-base">¡Junta 10,000 monedas para subir tu video!</span>
278
- </p>
279
- <div className="space-y-3">
280
- <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">
281
- <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
282
- <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"/>
283
- <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"/>
284
- <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"/>
285
- <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"/>
286
- </svg>
287
- Continuar con Google
288
- </button>
289
- </div>
290
- <p className="mt-6 text-xs text-gray-500">Al continuar, aceptas nuestros términos.</p>
291
- </div>
292
  </div>
293
- );
294
- }
295
 
296
  return (
297
  <div className="h-full w-full max-w-7xl mx-auto flex flex-col p-4 md:p-6">
298
-
299
  <header className="flex justify-between items-center pb-4 mb-4 border-b border-gray-700">
300
- <h1 className="text-2xl md:text-3xl font-bold text-white">
301
- Coin<span className="text-blue-500">Tube</span>
302
- </h1>
303
-
304
  <div className="flex items-center gap-4">
305
  <div className="text-right">
306
  <div className="text-xs text-gray-400">{user.email}</div>
307
- <div className="text-lg font-bold text-yellow-400">
308
- {Math.floor(userProfile?.coins || 0)} 🪙
309
- </div>
310
  </div>
311
-
312
- <button
313
- onClick={handleLogout}
314
- className="px-3 py-1 bg-gray-700 text-white text-sm rounded hover:bg-gray-600"
315
- >
316
- Salir
317
- </button>
318
  </div>
319
-
320
  </header>
321
- <a
322
- href="https://wa.me/+2286051539"
323
- target="_blank"
324
- rel="noopener noreferrer"
325
- 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"
326
- >
327
- <svg
328
- xmlns="http://www.w3.org/2000/svg"
329
- fill="currentColor"
330
- viewBox="0 0 24 24"
331
- className="w-6 h-6"
332
- >
333
- <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"/>
334
- </svg>
335
-
336
- <span className="font-bold">Grupo WhatsApp 4000 horas</span>
337
- </a>
338
 
339
  <nav className="flex justify-center gap-2 mb-6 bg-gray-800 p-1 rounded-lg w-fit mx-auto">
340
- <button
341
- onClick={() => setCurrentTab('ganar')}
342
- className={`w-[250px] py-2 rounded ${currentTab === 'ganar' ? 'bg-blue-600 text-white' : 'text-gray-400'}`}
343
- >
344
- Ver Videos
345
- </button>
346
-
347
- <button
348
- onClick={() => setCurrentTab('promocionar')}
349
- className={`w-[250px] py-2 rounded ${currentTab === 'promocionar' ? 'bg-blue-600 text-white' : 'text-gray-400'}`}
350
- >
351
- Subir Video
352
- </button>
353
  </nav>
354
 
355
  <main className={`${currentTab === 'ganar' ? 'flex' : 'hidden'} flex-1 flex-col lg:flex-row gap-6`}>
356
  <div className="lg:w-2/3">
357
  <div className="aspect-video bg-black rounded-lg overflow-hidden shadow-xl flex items-center justify-center">
358
- {currentVideoId ? (
359
- <div id="player" className="w-full h-full"></div>
360
- ) : (
361
- <div className="text-gray-500 animate-pulse">Cargando último video...</div>
362
- )}
363
  </div>
364
  <div className="mt-3 p-3 bg-gray-800 rounded">
365
- <h3 className="text-white font-medium">{currentVideoTitle || "Cargando..."}</h3>
366
  </div>
367
  </div>
368
  <aside className="lg:w-1/3 flex flex-col gap-4 h-full overflow-hidden">
369
  <div className="bg-gray-800 rounded p-4 flex-1 flex flex-col min-h-[200px]">
370
- <h3 className="text-gray-400 text-sm uppercase font-bold mb-2">Lista de Reproducción</h3>
371
- <div className="overflow-y-auto flex-1 pr-2 custom-scrollbar space-y-2">
372
- {videos.map((video) => (
373
- <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'}`}>
374
- <div className="text-sm text-white truncate flex-1">{video.title}</div>
375
  {user?.email === ADMIN_EMAIL && (
376
- <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>
377
  )}
378
  </button>
379
  ))}
380
  </div>
381
  </div>
382
-
383
  <div className="bg-gray-800 rounded p-4 flex-1 flex flex-col min-h-[200px]">
384
- <h3 className="text-yellow-500 text-sm uppercase font-bold mb-2">Ranking Global</h3>
385
- <div className="overflow-y-auto flex-1 pr-2 custom-scrollbar space-y-2">
386
- {leaderboard.length > 0 ? (
387
- leaderboard.map((u, i) => (
388
- <div key={u.id || i} className="flex justify-between items-center p-2 bg-gray-700 rounded">
389
- <div className="flex items-center truncate">
390
- <span className="text-xs text-gray-300 truncate mr-2" title={u.email}>
391
- {u.email ? u.email.split('@')[0] : 'Usuario'}
392
- </span>
393
- </div>
394
-
395
- <div className="flex items-center gap-2">
396
- <span className="text-yellow-400 font-mono text-sm whitespace-nowrap">{Math.floor(u.coins || 0)}</span>
397
- {user?.email === ADMIN_EMAIL && (
398
- <button
399
- onClick={() => handleGiveCoins(u.id, u.coins)}
400
- className="bg-green-600 hover:bg-green-500 text-white text-xs font-bold px-2 py-0.5 rounded shadow"
401
- title="Dar Monedas"
402
- >
403
- +
404
- </button>
405
- )}
406
- </div>
407
  </div>
408
- ))
409
- ) : (
410
- <div className="text-center text-gray-500 text-sm py-4">Esperando usuarios...</div>
411
- )}
412
  </div>
413
  </div>
414
  </aside>
@@ -425,39 +360,14 @@ function PromoCheck({ user, userProfile, userId, adminEmail, videoCost, db }) {
425
  const isAdmin = user?.email === adminEmail;
426
  const coins = userProfile?.coins || 0;
427
  const hasEnoughCoins = coins >= videoCost;
428
-
429
- if (isAdmin) return <PromoUnlocked userId={userId} isAdmin={true} db={db} />;
430
- if (hasEnoughCoins) return <PromoUnlocked userId={userId} isAdmin={false} videoCost={videoCost} db={db} />;
431
-
432
  return (
433
- <div className="text-center p-8 bg-gray-800 rounded-lg shadow-xl max-w-lg border border-gray-700">
434
- <h2 className="text-2xl font-bold text-white mb-2">Insuficientes Monedas</h2>
435
- <p className="text-gray-400 mb-4">Necesitas {videoCost} monedas para subir un video.</p>
436
-
437
  <div className="w-full bg-gray-700 rounded-full h-3 mb-4">
438
  <div className="bg-yellow-400 h-3 rounded-full" style={{ width: `${Math.min((coins / videoCost) * 100, 100)}%` }}></div>
439
  </div>
440
- <p className="text-sm text-gray-500 mb-6">{Math.floor(coins)} / {videoCost}</p>
441
-
442
- <div className="mt-6 border-t border-gray-600 pt-6">
443
- <h3 className="text-yellow-400 font-bold text-xl mb-2">¿Quieres subir tu video ya?</h3>
444
- <p className="text-white mb-4 text-sm">Deposita USDT para recargar al instante.</p>
445
- <div className="bg-gray-900 p-4 rounded-lg">
446
- <p className="text-green-400 font-bold mb-4 bg-green-900/30 py-2 rounded">1 USD = 3000 Monedas</p>
447
-
448
- <div className="flex justify-center mb-4">
449
- <img src="/qr.png" alt="QR Deposito" className="w-32 h-32 rounded-lg border-2 border-white"/>
450
- </div>
451
-
452
- <p className="text-xs text-gray-400 mb-1 uppercase font-bold">Dirección USDT (BEP20/TRC20):</p>
453
- <div className="break-all bg-black p-3 rounded text-xs font-mono text-gray-300 select-all border border-gray-700">
454
- 0x64531cafffbbc7ab1212d27cbafb4fa58111c84128804edec9d17c49c787e512
455
- </div>
456
- <p className="text-xs text-gray-500 mt-3">
457
- Envía tu comprobante a: <a href={`mailto:${adminEmail}`} className="text-blue-400 hover:underline">{adminEmail}</a>
458
- </p>
459
- </div>
460
- </div>
461
  </div>
462
  );
463
  }
@@ -465,96 +375,31 @@ function PromoCheck({ user, userProfile, userId, adminEmail, videoCost, db }) {
465
  function PromoUnlocked({ userId, isAdmin, videoCost, db }) {
466
  const [url, setUrl] = useState('');
467
  const [title, setTitle] = useState('');
468
- const [message, setMessage] = useState({ text: '', type: '' });
469
  const [loading, setLoading] = useState(false);
470
 
471
- const extractYouTubeID = (url) => {
472
- const regex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
473
- const match = url.match(regex);
474
- return match ? match[1] : null;
475
- };
476
-
477
  const handleSubmit = async (e) => {
478
  e.preventDefault();
479
- const videoId = extractYouTubeID(url);
480
-
481
- if (!videoId) {
482
- setMessage({ text: "Enlace de YouTube no válido", type: 'error' });
483
- return;
484
- }
485
- if (!title.trim()) {
486
- setMessage({ text: "Por favor escribe un título", type: 'error' });
487
- return;
488
- }
489
- if (!db) {
490
- setMessage({ text: "Error: Base de datos no conectada", type: 'error' });
491
- return;
492
- }
493
-
494
  setLoading(true);
495
-
496
  try {
497
- if (!isAdmin) {
498
- const userRef = doc(db, 'users', userId);
499
- await updateDoc(userRef, { coins: increment(-videoCost) });
500
- }
501
-
502
- const videosRef = collection(db, 'videos');
503
- await addDoc(videosRef, {
504
- title: title,
505
- videoId: videoId,
506
- addedBy: userId,
507
- createdAt: serverTimestamp(),
508
- isPromoted: !isAdmin
509
  });
510
-
511
- setMessage({ text: "¡Video agregado con éxito!", type: 'success' });
512
- setUrl('');
513
- setTitle('');
514
- } catch (error) {
515
- console.error("Error al subir:", error);
516
- setMessage({ text: "Error al procesar. Intenta de nuevo.", type: 'error' });
517
- } finally {
518
- setLoading(false);
519
- }
520
  };
521
 
522
  return (
523
- <div className="bg-gray-800 p-8 rounded-lg shadow-xl max-w-md w-full border border-green-900">
524
- <h2 className="text-2xl font-bold text-white mb-4 text-center">{isAdmin ? "Panel Admin" : "¡Meta Alcanzada!"}</h2>
525
- <form onSubmit={handleSubmit} className="space-y-4">
526
- <div>
527
- <label className="block text-sm text-gray-400 mb-1">Enlace del Video</label>
528
- <input
529
- type="url"
530
- placeholder="https://youtube.com/watch?v=..."
531
- className="w-full p-3 bg-gray-700 text-white rounded border border-gray-600 focus:border-blue-500 outline-none"
532
- value={url}
533
- onChange={(e) => setUrl(e.target.value)}
534
- required
535
- />
536
- </div>
537
- <div>
538
- <label className="block text-sm text-gray-400 mb-1">Título del Video</label>
539
- <input
540
- type="text"
541
- placeholder="Ej: Mi Gameplay Épico"
542
- className="w-full p-3 bg-gray-700 text-white rounded border border-gray-600 focus:border-blue-500 outline-none"
543
- value={title}
544
- onChange={(e) => setTitle(e.target.value)}
545
- required
546
- maxLength={50}
547
- />
548
- </div>
549
- <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">
550
- {loading ? 'Procesando...' : (isAdmin ? 'Subir Gratis' : `Pagar ${videoCost} y Subir`)}
551
- </button>
552
- {message.text && (
553
- <p className={`text-center font-medium ${message.type === 'error' ? 'text-red-400' : 'text-green-400'}`}>
554
- {message.text}
555
- </p>
556
- )}
557
- </form>
558
- </div>
559
  );
560
  }
 
20
  serverTimestamp,
21
  query,
22
  orderBy,
23
+ limit,
24
+ writeBatch,
25
+ getDocs
26
  } from 'firebase/firestore';
27
 
28
  const firebaseConfig = {
 
43
  const DEFAULT_VIDEO_ID = "1rghd2zPhFo";
44
  const DEFAULT_VIDEO_TITLE = "Cuentos de Terror";
45
 
46
+ const EMAILJS_SERVICE_ID = "service_v18p188";
47
+ const EMAILJS_TEMPLATE_ID = "template_wexg1ww";
48
+
49
  export default function App() {
 
50
  const [videos, setVideos] = useState([]);
51
  const [leaderboard, setLeaderboard] = useState([]);
52
  const [user, setUser] = useState(null);
 
54
  const [authReady, setAuthReady] = useState(false);
55
  const [userProfile, setUserProfile] = useState(null);
56
  const [currentTab, setCurrentTab] = useState('ganar');
 
57
  const [currentVideoId, setCurrentVideoId] = useState(null);
58
  const [currentVideoTitle, setCurrentVideoTitle] = useState(null);
 
59
  const [ytApiReady, setYtApiReady] = useState(false);
60
 
61
  const playerRef = useRef(null);
 
93
  setDoc(profileRef, newProfile).catch(e => console.error(e));
94
  setUserProfile(newProfile);
95
  }
96
+ });
97
  return () => unsubscribeProfile();
98
  }, [userId, user]);
99
 
100
+ useEffect(() => {
101
+ if (user?.email !== ADMIN_EMAIL) return;
102
+ const checkReset = async () => {
103
+ const settingsRef = doc(db, 'settings', 'stats');
104
+ const snap = await getDocs(query(collection(db, 'settings')));
105
+ if (snap.empty) return;
106
+
107
+ const data = snap.docs[0].data();
108
+ const lastReset = data.lastReset.toDate();
109
+ const now = new Date();
110
+
111
+ if (now - lastReset >= 432000000) {
112
+ const batch = writeBatch(db);
113
+ const usersSnap = await getDocs(collection(db, 'users'));
114
+ usersSnap.forEach((uDoc) => {
115
+ if (uDoc.data().email !== ADMIN_EMAIL) {
116
+ batch.update(uDoc.ref, { coins: 0 });
117
+ }
118
+ });
119
+ batch.update(settingsRef, { lastReset: serverTimestamp() });
120
+ await batch.commit();
121
+ alert("Ciclo de 5 días completado: Puntos reseteados.");
122
+ }
123
+ };
124
+ checkReset();
125
+ }, [user]);
126
+
127
  useEffect(() => {
128
  const q = query(collection(db, 'videos'), orderBy('createdAt', 'desc'), limit(50));
129
  const unsubscribe = onSnapshot(q, (snapshot) => {
130
+ let fetchedVideos = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
131
 
132
  if (fetchedVideos.length > 0) {
133
+ fetchedVideos = fetchedVideos.sort(() => Math.random() - 0.5);
134
  setVideos(fetchedVideos);
135
  if (initialLoadRef.current || !currentVideoId) {
136
  const latestVideo = fetchedVideos[0];
 
139
  initialLoadRef.current = false;
140
  }
141
  } else {
142
+ const def = [{ id: '1', title: DEFAULT_VIDEO_TITLE, videoId: DEFAULT_VIDEO_ID }];
143
+ setVideos(def);
144
  if (initialLoadRef.current || !currentVideoId) {
145
  setCurrentVideoId(DEFAULT_VIDEO_ID);
146
  setCurrentVideoTitle(DEFAULT_VIDEO_TITLE);
 
155
  const q = query(collection(db, 'users'), orderBy('coins', 'desc'), limit(100));
156
  const unsubscribe = onSnapshot(q, (snapshot) => {
157
  let usersList = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
158
+ usersList = usersList.filter(u => u.email && u.email.endsWith('@gmail.com'));
 
 
 
 
 
159
  setLeaderboard(usersList.slice(0, 20));
160
  });
161
  return () => unsubscribe();
 
208
  const state = event.data;
209
  if (state === window.YT.PlayerState.PLAYING) startCoinInterval();
210
  else stopCoinInterval();
211
+ if (state === window.YT.PlayerState.ENDED && currentVideoId === DEFAULT_VIDEO_ID && userId) {
212
+ updateDoc(doc(db, 'users', userId), { watchedDefaultVideo: true });
 
 
 
 
213
  }
214
  }, [startCoinInterval, stopCoinInterval, currentVideoId, userId]);
215
 
216
  useEffect(() => {
217
  if (ytApiReady && userId && !playerRef.current && currentVideoId) {
218
  playerRef.current = new window.YT.Player('player', {
219
+ height: '100%', width: '100%', videoId: currentVideoId,
 
 
220
  playerVars: { 'playsinline': 1, 'autoplay': 1, 'controls': 1, 'modestbranding': 1, 'rel': 0 },
221
  events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange }
222
  });
 
234
  if (playerRef.current) playerRef.current.loadVideoById(video.videoId);
235
  };
236
 
237
+ const handleDeleteVideo = async (e, vId) => {
238
  e.stopPropagation();
239
  if (!confirm("¿Eliminar video?")) return;
240
+ try { await deleteDoc(doc(db, "videos", vId)); } catch (e) { console.error(e); }
241
  };
242
 
243
+ const handleGiveCoins = async (tId, cC) => {
244
+ const amtStr = prompt("Monedas a sumar/restar:", "1000");
245
+ if (!amtStr) return;
246
+ const amt = parseInt(amtStr);
247
+ if (isNaN(amt)) return;
248
+ try { await updateDoc(doc(db, 'users', tId), { coins: increment(amt) }); } catch (e) { console.error(e); }
 
 
 
 
 
 
 
 
249
  };
250
 
251
  const handleGoogleLogin = async () => {
252
+ const p = new GoogleAuthProvider();
253
+ try { await signInWithPopup(auth, p); } catch (e) { console.error(e); }
 
 
 
 
254
  };
255
 
256
  const handleLogout = async () => {
 
258
  await signOut(auth);
259
  };
260
 
261
+ const handleMassEmail = async () => {
262
+ if (!window.emailjs) return alert("EmailJS no detectado");
263
+ if (!confirm("¿Enviar notificación de reseteo a todos?")) return;
264
+ const snap = await getDocs(collection(db, 'users'));
265
+ snap.forEach((uDoc) => {
266
+ const data = uDoc.data();
267
+ if (data.email) {
268
+ window.emailjs.send(EMAILJS_SERVICE_ID, EMAILJS_TEMPLATE_ID, {
269
+ to_email: data.email,
270
+ subject: "¡Reseteo de Puntos!",
271
+ message: "Los puntos se han reseteado. ¡Ven a ver videos para ganar más!"
272
+ });
273
+ }
274
+ });
275
+ alert("Envíos iniciados.");
276
+ };
277
+
278
+ 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-gray-400">Cargando...</p></div>;
279
+
280
+ if (!user) return (
281
+ <div className="flex flex-col items-center justify-center h-full w-full bg-gray-900 p-4">
282
+ <div className="max-w-md w-full bg-gray-800 rounded-2xl p-8 text-center border border-gray-700">
283
+ <h1 className="text-3xl font-bold text-white mb-8">Bienvenido a CoinTube</h1>
284
+ <button onClick={handleGoogleLogin} className="w-full py-3 bg-white text-gray-800 font-bold rounded-lg">Continuar con Google</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  </div>
286
+ </div>
287
+ );
288
 
289
  return (
290
  <div className="h-full w-full max-w-7xl mx-auto flex flex-col p-4 md:p-6">
 
291
  <header className="flex justify-between items-center pb-4 mb-4 border-b border-gray-700">
292
+ <h1 className="text-2xl md:text-3xl font-bold text-white">Coin<span className="text-blue-500">Tube</span></h1>
 
 
 
293
  <div className="flex items-center gap-4">
294
  <div className="text-right">
295
  <div className="text-xs text-gray-400">{user.email}</div>
296
+ <div className="text-lg font-bold text-yellow-400">{Math.floor(userProfile?.coins || 0)} 🪙</div>
 
 
297
  </div>
298
+ <button onClick={handleLogout} className="px-3 py-1 bg-gray-700 text-white text-sm rounded">Salir</button>
 
 
 
 
 
 
299
  </div>
 
300
  </header>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
 
302
  <nav className="flex justify-center gap-2 mb-6 bg-gray-800 p-1 rounded-lg w-fit mx-auto">
303
+ <button onClick={() => setCurrentTab('ganar')} className={`w-[120px] md:w-[250px] py-2 rounded ${currentTab === 'ganar' ? 'bg-blue-600 text-white' : 'text-gray-400'}`}>Ver Videos</button>
304
+ <button onClick={() => setCurrentTab('promocionar')} className={`w-[120px] md:w-[250px] py-2 rounded ${currentTab === 'promocionar' ? 'bg-blue-600 text-white' : 'text-gray-400'}`}>Subir Video</button>
305
+ {user.email === ADMIN_EMAIL && (
306
+ <button onClick={handleMassEmail} className="px-4 py-2 bg-indigo-600 text-white rounded text-xs font-bold">📧 Notificar</button>
307
+ )}
 
 
 
 
 
 
 
 
308
  </nav>
309
 
310
  <main className={`${currentTab === 'ganar' ? 'flex' : 'hidden'} flex-1 flex-col lg:flex-row gap-6`}>
311
  <div className="lg:w-2/3">
312
  <div className="aspect-video bg-black rounded-lg overflow-hidden shadow-xl flex items-center justify-center">
313
+ <div id="player" className="w-full h-full"></div>
 
 
 
 
314
  </div>
315
  <div className="mt-3 p-3 bg-gray-800 rounded">
316
+ <h3 className="text-white font-medium">{currentVideoTitle}</h3>
317
  </div>
318
  </div>
319
  <aside className="lg:w-1/3 flex flex-col gap-4 h-full overflow-hidden">
320
  <div className="bg-gray-800 rounded p-4 flex-1 flex flex-col min-h-[200px]">
321
+ <h3 className="text-gray-400 text-sm font-bold mb-2">Lista Aleatoria</h3>
322
+ <div className="overflow-y-auto flex-1 space-y-2 custom-scrollbar">
323
+ {videos.map((v) => (
324
+ <button key={v.id} onClick={() => loadVideo(v)} className={`w-full text-left p-2 rounded flex justify-between items-center ${v.videoId === currentVideoId ? 'bg-blue-900 border-l-2 border-blue-500' : 'bg-gray-700 hover:bg-gray-600'}`}>
325
+ <div className="text-sm text-white truncate flex-1">{v.title}</div>
326
  {user?.email === ADMIN_EMAIL && (
327
+ <span onClick={(e) => handleDeleteVideo(e, v.id)} className="ml-2 text-red-500 font-bold px-2 py-1 rounded bg-red-900/50">X</span>
328
  )}
329
  </button>
330
  ))}
331
  </div>
332
  </div>
 
333
  <div className="bg-gray-800 rounded p-4 flex-1 flex flex-col min-h-[200px]">
334
+ <h3 className="text-yellow-500 text-sm font-bold mb-2">Ranking</h3>
335
+ <div className="overflow-y-auto flex-1 space-y-2 custom-scrollbar">
336
+ {leaderboard.map((u, i) => (
337
+ <div key={u.id || i} className="flex justify-between items-center p-2 bg-gray-700 rounded">
338
+ <span className="text-xs text-gray-300 truncate">{u.email?.split('@')[0]}</span>
339
+ <div className="flex items-center gap-2">
340
+ <span className="text-yellow-400 font-mono text-sm">{Math.floor(u.coins || 0)}</span>
341
+ {user?.email === ADMIN_EMAIL && (
342
+ <button onClick={() => handleGiveCoins(u.id, u.coins)} className="bg-green-600 text-white text-xs px-2 rounded">+</button>
343
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  </div>
345
+ </div>
346
+ ))}
 
 
347
  </div>
348
  </div>
349
  </aside>
 
360
  const isAdmin = user?.email === adminEmail;
361
  const coins = userProfile?.coins || 0;
362
  const hasEnoughCoins = coins >= videoCost;
363
+ if (isAdmin || hasEnoughCoins) return <PromoUnlocked userId={userId} isAdmin={isAdmin} videoCost={videoCost} db={db} />;
 
 
 
364
  return (
365
+ <div className="text-center p-8 bg-gray-800 rounded-lg max-w-lg border border-gray-700">
366
+ <h2 className="text-2xl font-bold text-white mb-2">Faltan Monedas</h2>
 
 
367
  <div className="w-full bg-gray-700 rounded-full h-3 mb-4">
368
  <div className="bg-yellow-400 h-3 rounded-full" style={{ width: `${Math.min((coins / videoCost) * 100, 100)}%` }}></div>
369
  </div>
370
+ <p className="text-gray-500">{Math.floor(coins)} / {videoCost}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  </div>
372
  );
373
  }
 
375
  function PromoUnlocked({ userId, isAdmin, videoCost, db }) {
376
  const [url, setUrl] = useState('');
377
  const [title, setTitle] = useState('');
 
378
  const [loading, setLoading] = useState(false);
379
 
 
 
 
 
 
 
380
  const handleSubmit = async (e) => {
381
  e.preventDefault();
382
+ const vId = url.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/)?.[1];
383
+ if (!vId || !title.trim()) return alert("Enlace no válido");
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  setLoading(true);
 
385
  try {
386
+ if (!isAdmin) await updateDoc(doc(db, 'users', userId), { coins: increment(-videoCost) });
387
+ await addDoc(collection(db, 'videos'), {
388
+ title, videoId: vId, addedBy: userId, createdAt: serverTimestamp(), isPromoted: !isAdmin
 
 
 
 
 
 
 
 
 
389
  });
390
+ alert("¡Video subido!");
391
+ setUrl(''); setTitle('');
392
+ } catch (err) { console.error(err); } finally { setLoading(false); }
 
 
 
 
 
 
 
393
  };
394
 
395
  return (
396
+ <form onSubmit={handleSubmit} className="bg-gray-800 p-8 rounded-lg max-w-md w-full space-y-4 border border-green-900">
397
+ <h2 className="text-2xl font-bold text-white text-center">{isAdmin ? "Panel Admin" : "Subir Video"}</h2>
398
+ <input type="url" placeholder="URL de YouTube" className="w-full p-3 bg-gray-700 text-white rounded border border-gray-600" value={url} onChange={e => setUrl(e.target.value)} required />
399
+ <input type="text" placeholder="Título" className="w-full p-3 bg-gray-700 text-white rounded border border-gray-600" value={title} onChange={e => setTitle(e.target.value)} required maxLength={50} />
400
+ <button disabled={loading} className="w-full py-3 bg-green-600 text-white font-bold rounded">
401
+ {loading ? 'Subiendo...' : 'Publicar'}
402
+ </button>
403
+ </form>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  );
405
  }