import React, { useState, useEffect, useRef } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from 'firebase/auth';
import { getFirestore, collection, doc, setDoc, getDocs, onSnapshot, addDoc, updateDoc, deleteDoc } from 'firebase/firestore';
import { 
  BookOpen, Home, Info, MessageCircle, HelpCircle, 
  Send, Plus, Palette, Shield, X, ChevronLeft, ChevronRight, 
  Flame, Sparkles, Star, Layers, Compass
} from 'lucide-react';

// ==========================================
// CONFIGURACIÓN DE FIREBASE Y ESTADO GLOBAL
// ==========================================
// @ts-ignore
const appId = typeof __app_id !== 'undefined' ? __app_id : 'manga-app-default';
// @ts-ignore
const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {};

let app: any, auth: any, db: any;
try {
  app = initializeApp(firebaseConfig);
  auth = getAuth(app);
  db = getFirestore(app);
} catch (error) {
  console.error("Error inicializando Firebase:", error);
}

// Helpers para colecciones de Firestore
const getPublicPath = (colName: string) => collection(db, 'artifacts', appId, 'public', 'data', colName);
const getPublicDoc = (colName: string, docId: string) => doc(db, 'artifacts', appId, 'public', 'data', colName, docId);

// ==========================================
// TIPOS E INTERFACES
// ==========================================
interface Manga {
  id: string;
  title: string;
  romajiTitle?: string;
  category: string;
  demography?: 'Shonen' | 'Seinen' | 'Shojo' | 'Josei' | 'Isekai' | 'General';
  status?: 'En Emisión' | 'Finalizado';
  author?: string;
  description: string;
  coverUrl: string;
  pages: string[];
  score?: number;
  createdAt: number;
}

interface MangaComment {
  id: string;
  mangaId: string;
  userId: string;
  userName: string;
  text: string;
  rating?: number;
  timestamp: number;
}

interface ChatMessage {
  id: string;
  userId: string;
  userName: string;
  text: string;
  timestamp: number;
}

interface ThemeSettings {
  themeColor: string;
  backgroundStyle: string;
  readingDirectionDefault?: 'vertical' | 'rtl';
}

// ==========================================
// COMPONENTES DE UI
// ==========================================
const Modal = ({ isOpen, onClose, title, children }: { isOpen: boolean; onClose: () => void; title: string; children: React.ReactNode }) => {
  if (!isOpen) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md p-4">
      <div className="bg-zinc-900 border border-zinc-700 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in-95 duration-200">
        <div className="flex justify-between items-center p-4 border-b border-zinc-800 bg-zinc-950/50">
          <h3 className="text-xl font-black text-white tracking-wide">{title}</h3>
          <button onClick={onClose} className="text-zinc-400 hover:text-white p-1 rounded-lg hover:bg-zinc-800 transition-colors">
            <X size={20} />
          </button>
        </div>
        <div className="p-5 text-zinc-300">
          {children}
        </div>
      </div>
    </div>
  );
};

const CustomAlert = ({ message, type = 'info', onClose }: { message: string; type?: 'info' | 'success' | 'error'; onClose: () => void }) => {
  if (!message) return null;
  const colors = {
    info: 'bg-zinc-900/90 border-cyan-500/50 text-cyan-200 shadow-cyan-950/50',
    success: 'bg-zinc-900/90 border-emerald-500/50 text-emerald-200 shadow-emerald-950/50',
    error: 'bg-zinc-900/90 border-rose-500/50 text-rose-200 shadow-rose-950/50'
  };
  return (
    <div className={`fixed bottom-5 right-5 p-4 rounded-xl border backdrop-blur-md shadow-2xl z-50 flex items-center gap-3 animate-in slide-in-from-bottom-5 duration-300 ${colors[type]}`}>
      <span className="font-medium text-sm">{message}</span>
      <button onClick={onClose} className="opacity-70 hover:opacity-100 transition-opacity">
        <X size={16}/>
      </button>
    </div>
  );
};

// ==========================================
// NAVEGACIÓN
// ==========================================
const Navbar = ({ currentView, setCurrentView, themeColor }: { currentView: string; setCurrentView: (v: string) => void; themeColor: string }) => {
  const navItems = [
    { id: 'home', icon: Home, label: 'Biblioteca' },
    { id: 'chat', icon: MessageCircle, label: 'Dojo Otaku (Chat)' },
    { id: 'info', icon: Info, label: 'Arquitectura & API' },
    { id: 'guide', icon: HelpCircle, label: 'Guía de Lectura' },
    { id: 'admin', icon: Shield, label: 'Panel Mangaka' },
  ];

  return (
    <nav className="sticky top-0 z-40 backdrop-blur-md bg-opacity-90 border-b border-white/10" style={{ backgroundColor: `${themeColor}EE` }}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          <div className="flex items-center gap-3 cursor-pointer group" onClick={() => setCurrentView('home')}>
            <div className="p-2 bg-gradient-to-tr from-rose-600 to-amber-500 rounded-xl shadow-lg shadow-rose-600/30 group-hover:scale-105 transition-transform">
              <BookOpen className="text-white h-6 w-6" />
            </div>
            <div>
              <span className="font-black text-2xl tracking-tight text-white uppercase">
                Manga<span className="text-rose-500">Verse</span>
              </span>
              <span className="hidden sm:inline-block ml-2 text-[10px] uppercase font-bold tracking-widest text-zinc-400 bg-zinc-800/80 px-2 py-0.5 rounded-full border border-zinc-700">
                漫画ポータル
              </span>
            </div>
          </div>
          
          <div className="hidden md:flex items-center space-x-1">
            {navItems.map((item) => (
              <button
                key={item.id}
                onClick={() => setCurrentView(item.id)}
                className={`flex items-center gap-2 px-3.5 py-2 rounded-xl text-sm font-semibold transition-all ${
                  currentView === item.id 
                    ? 'bg-rose-500/20 text-rose-300 border border-rose-500/30 shadow-[0_0_15px_rgba(244,63,94,0.15)]' 
                    : 'text-zinc-300 hover:bg-white/10 hover:text-white'
                }`}
              >
                <item.icon size={17} />
                {item.label}
              </button>
            ))}
          </div>

          {/* Navegación móvil */}
          <div className="md:hidden flex items-center gap-1 overflow-x-auto py-1">
            {navItems.map((item) => (
              <button
                key={item.id}
                onClick={() => setCurrentView(item.id)}
                className={`p-2.5 rounded-lg text-xs font-semibold ${
                  currentView === item.id ? 'bg-rose-600 text-white' : 'text-zinc-400 hover:text-white hover:bg-white/10'
                }`}
                title={item.label}
              >
                <item.icon size={19} />
              </button>
            ))}
          </div>
        </div>
      </div>
    </nav>
  );
};

// ==========================================
// VISTAS DE LA APLICACIÓN
// ==========================================

const HomeView = ({ mangas, setViewDetail }: { mangas: Manga[]; setViewDetail: (m: Manga) => void }) => {
  const [selectedCategory, setSelectedCategory] = useState('Todas');
  const [searchQuery, setSearchQuery] = useState('');
  
  const categories = ['Todas', 'Shonen', 'Seinen', 'Shojo', 'Isekai', 'Fantasía', 'Acción', 'Sobrenatural'];

  const filteredMangas = mangas.filter(m => {
    const matchesCat = selectedCategory === 'Todas' || m.category === selectedCategory || m.demography === selectedCategory;
    const matchesSearch = m.title.toLowerCase().includes(searchQuery.toLowerCase()) || 
                          (m.romajiTitle && m.romajiTitle.toLowerCase().includes(searchQuery.toLowerCase()));
    return matchesCat && matchesSearch;
  });

  return (
    <div className="p-4 sm:p-6 max-w-7xl mx-auto min-h-screen">
      {/* Hero Header */}
      <div className="mb-10 text-center relative py-6">
        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs font-bold uppercase tracking-wider mb-3">
          <Sparkles size={14} /> El Santuario del Lector Otaku
        </div>
        <h1 className="text-4xl sm:text-6xl font-black text-transparent bg-clip-text bg-gradient-to-r from-white via-zinc-200 to-rose-400 mb-4 tracking-tight drop-shadow-md">
          DESCUBRE EL UNIVERSO MANGA
        </h1>
        <p className="text-base sm:text-lg text-zinc-400 max-w-2xl mx-auto">
          Lee historias legendarias, capítulos en alta definición, comparte tus teorías en el Dojo y personaliza tu experiencia de lectura.
        </p>

        {/* Buscador Rápido */}
        <div className="mt-6 max-w-md mx-auto">
          <input
            type="text"
            placeholder="Buscar por título, rōmaji o mangaka..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full bg-zinc-900/90 border border-zinc-700 focus:border-rose-500 rounded-full px-5 py-3 text-sm text-white placeholder-zinc-500 outline-none transition-all shadow-inner"
          />
        </div>
      </div>

      {/* Selector de Categorías / Demografía */}
      <div className="flex flex-wrap justify-center gap-2 mb-10">
        {categories.map(cat => (
          <button
            key={cat}
            onClick={() => setSelectedCategory(cat)}
            className={`px-4 py-2 rounded-full font-bold text-xs uppercase tracking-wider transition-all transform hover:scale-105 ${
              selectedCategory === cat 
                ? 'bg-rose-600 text-white shadow-[0_0_20px_rgba(244,63,94,0.4)]' 
                : 'bg-zinc-900/90 text-zinc-400 border border-zinc-800 hover:border-zinc-600 hover:text-white'
            }`}
          >
            {cat}
          </button>
        ))}
      </div>

      {/* Grid de Mangas */}
      {filteredMangas.length === 0 ? (
        <div className="text-center p-16 bg-zinc-900/50 rounded-3xl border border-zinc-800/80 backdrop-blur-sm max-w-xl mx-auto">
          <Compass className="mx-auto h-14 w-14 text-rose-500/60 mb-4 animate-pulse" />
          <h3 className="text-xl font-bold text-white mb-2">No se encontraron mangas en esta sección</h3>
          <p className="text-zinc-400 text-sm">Intenta con otra categoría o accede al Panel Mangaka para publicar un nuevo título.</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 sm:gap-6">
          {filteredMangas.map(manga => (
            <div 
              key={manga.id} 
              className="group bg-zinc-900 rounded-2xl overflow-hidden border border-zinc-800 hover:border-rose-500/50 shadow-lg hover:shadow-[0_10px_30px_rgba(244,63,94,0.2)] transition-all duration-300 cursor-pointer flex flex-col transform hover:-translate-y-1.5"
              onClick={() => setViewDetail(manga)}
            >
              <div className="relative aspect-[3/4] overflow-hidden bg-zinc-950">
                <img 
                  src={manga.coverUrl || `https://placehold.co/400x600/18181b/ffffff?text=${encodeURIComponent(manga.title)}`} 
                  alt={manga.title}
                  className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
                  onError={(e: any) => { e.target.src = 'https://placehold.co/400x600/18181b/ffffff?text=Manga+Cover'; }}
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black via-black/30 to-transparent opacity-90 group-hover:opacity-75 transition-opacity"></div>
                
                {/* Etiquetas superiores */}
                <div className="absolute top-2 left-2 flex flex-col gap-1">
                  <span className="text-[10px] font-black px-2 py-0.5 bg-rose-600/90 backdrop-blur-md text-white rounded-md uppercase tracking-wider">
                    {manga.category}
                  </span>
                  {manga.status && (
                    <span className="text-[9px] font-bold px-1.5 py-0.5 bg-zinc-900/80 backdrop-blur-md text-zinc-300 rounded border border-zinc-700">
                      {manga.status}
                    </span>
                  )}
                </div>

                {/* Score */}
                <div className="absolute top-2 right-2 flex items-center gap-1 bg-black/70 backdrop-blur-md px-2 py-0.5 rounded-md text-amber-400 text-xs font-bold">
                  <Star size={12} className="fill-amber-400" />
                  <span>{manga.score || '9.4'}</span>
                </div>

                {/* Información inferior */}
                <div className="absolute bottom-0 left-0 p-3 sm:p-4 w-full">
                  {manga.romajiTitle && (
                    <p className="text-[11px] font-medium text-rose-400 line-clamp-1 italic">{manga.romajiTitle}</p>
                  )}
                  <h3 className="text-base sm:text-lg font-black text-white leading-snug line-clamp-2 drop-shadow">
                    {manga.title}
                  </h3>
                  <div className="mt-2 flex items-center justify-between text-[11px] text-zinc-400">
                    <span>{manga.pages ? `${manga.pages.length} págs` : '0 págs'}</span>
                    <span className="text-rose-400 font-semibold group-hover:underline">Leer →</span>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// Lector de Manga con modo Cascada y Modo Página por Página (Tradicional)
const MangaDetailView = ({ manga, goBack, user }: { manga: Manga; goBack: () => void; user: any }) => {
  const [comments, setComments] = useState<MangaComment[]>([]);
  const [newComment, setNewComment] = useState('');
  const [newRating, setNewRating] = useState(5);
  const [readingMode, setReadingMode] = useState(false);
  const [readerType, setReaderType] = useState<'cascade' | 'single'>('cascade'); // Cascada (Webtoon) o Tradicional
  const [currentPage, setCurrentPage] = useState(0);

  useEffect(() => {
    if (!manga) return;
    const q = getPublicPath('manga_comments');
    const unsubscribe = onSnapshot(q, (snapshot) => {
      const allComments = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })) as MangaComment[];
      const mangaComments = allComments
        .filter(c => c.mangaId === manga.id)
        .sort((a, b) => b.timestamp - a.timestamp);
      setComments(mangaComments);
    }, (error) => console.error("Error comentarios manga:", error));
    return () => unsubscribe();
  }, [manga]);

  const handleAddComment = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newComment.trim() || !user) return;
    try {
      await addDoc(getPublicPath('manga_comments'), {
        mangaId: manga.id,
        userId: user.uid,
        userName: `Lector-${user.uid.substring(0, 4)}`,
        text: newComment,
        rating: newRating,
        timestamp: Date.now()
      });
      setNewComment('');
    } catch (err) {
      console.error("Error agregando reseña:", err);
    }
  };

  if (!manga) return null;

  return (
    <div className="max-w-5xl mx-auto p-4 sm:p-6 bg-zinc-950/90 min-h-screen rounded-t-3xl shadow-2xl border-t border-zinc-800">
      <button 
        onClick={goBack} 
        className="flex items-center gap-2 text-zinc-400 hover:text-white mb-6 bg-zinc-900 border border-zinc-800 px-4 py-2 rounded-xl transition-all"
      >
        <ChevronLeft size={18} /> Volver a la Biblioteca
      </button>

      {!readingMode ? (
        /* Vista de Detalle y Sinopsis */
        <div className="flex flex-col md:flex-row gap-8 mb-12">
          <div className="w-full md:w-1/3 flex-shrink-0">
            <div className="relative rounded-2xl overflow-hidden shadow-[0_0_35px_rgba(244,63,94,0.2)] border border-zinc-800">
              <img 
                src={manga.coverUrl || `https://placehold.co/400x600/18181b/ffffff?text=${encodeURIComponent(manga.title)}`} 
                alt={manga.title}
                className="w-full h-auto object-cover"
              />
            </div>
            {manga.author && (
              <p className="mt-3 text-xs text-center text-zinc-400">
                Mangaka / Autor: <strong className="text-zinc-200">{manga.author}</strong>
              </p>
            )}
          </div>

          <div className="flex-1 text-zinc-300">
            <div className="flex flex-wrap items-center gap-2 mb-3">
              <span className="bg-rose-600 text-white px-3 py-1 rounded-full text-xs font-black uppercase tracking-wider">
                {manga.category}
              </span>
              {manga.demography && (
                <span className="bg-zinc-800 text-zinc-300 px-3 py-1 rounded-full text-xs font-bold border border-zinc-700">
                  {manga.demography}
                </span>
              )}
              {manga.status && (
                <span className="bg-emerald-950 text-emerald-300 px-3 py-1 rounded-full text-xs font-bold border border-emerald-800">
                  {manga.status}
                </span>
              )}
            </div>

            {manga.romajiTitle && (
              <p className="text-rose-400 text-sm font-semibold tracking-wide">{manga.romajiTitle}</p>
            )}
            <h1 className="text-3xl sm:text-5xl font-black text-white mt-1 mb-4 leading-tight">{manga.title}</h1>
            
            <p className="text-zinc-300 text-base leading-relaxed mb-8 bg-zinc-900/60 p-5 rounded-2xl border border-zinc-800/80">
              {manga.description || 'Sin sinopsis disponible para este título.'}
            </p>

            <div className="flex flex-col sm:flex-row gap-4">
              <button 
                onClick={() => { setReadingMode(true); setReaderType('cascade'); }}
                className="flex-1 bg-gradient-to-r from-rose-600 to-rose-500 hover:from-rose-500 hover:to-rose-400 text-white font-bold py-4 px-6 rounded-2xl text-lg shadow-lg shadow-rose-600/30 transition-all transform hover:-translate-y-0.5 flex justify-center items-center gap-2"
              >
                <BookOpen size={20} /> Leer en Cascada (Webtoon)
              </button>
              <button 
                onClick={() => { setReadingMode(true); setReaderType('single'); setCurrentPage(0); }}
                className="bg-zinc-800 hover:bg-zinc-700 text-zinc-200 border border-zinc-700 font-bold py-4 px-6 rounded-2xl text-base transition-all flex justify-center items-center gap-2"
              >
                <Layers size={18} /> Modo Tradicional (Página a Página)
              </button>
            </div>
          </div>
        </div>
      ) : (
        /* Lector de Manga */
        <div className="mb-12 bg-black rounded-2xl overflow-hidden border border-zinc-800 p-2 sm:p-4 shadow-2xl">
          {/* Header del Lector */}
          <div className="flex flex-wrap justify-between items-center p-3 sm:p-4 bg-zinc-900 rounded-xl mb-4 gap-3 border border-zinc-800">
            <div>
              <h2 className="text-lg font-bold text-white flex items-center gap-2">
                <BookOpen className="text-rose-500" size={18} /> {manga.title}
              </h2>
              <p className="text-xs text-zinc-400">
                Modo: {readerType === 'cascade' ? 'Cascada vertical' : `Página ${currentPage + 1} de ${manga.pages ? manga.pages.length : 0}`}
              </p>
            </div>

            <div className="flex items-center gap-2">
              <button 
                onClick={() => setReaderType(readerType === 'cascade' ? 'single' : 'cascade')}
                className="text-xs font-semibold px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-200 border border-zinc-700 transition-colors"
              >
                Cambiar a {readerType === 'cascade' ? 'Paginado' : 'Cascada'}
              </button>
              <button 
                onClick={() => setReadingMode(false)} 
                className="text-xs font-bold px-3 py-1.5 rounded-lg bg-rose-600 hover:bg-rose-500 text-white transition-colors"
              >
                Cerrar Lector
              </button>
            </div>
          </div>

          {/* Contenido de lectura */}
          {manga.pages && manga.pages.length > 0 ? (
            readerType === 'cascade' ? (
              /* Modo Cascada (Vertical) */
              <div className="flex flex-col items-center gap-4 bg-zinc-950 p-2 sm:p-6 rounded-xl max-h-[80vh] overflow-y-auto custom-scrollbar">
                {manga.pages.map((page, idx) => (
                  <div key={idx} className="relative w-full max-w-3xl flex flex-col items-center">
                    <img 
                      src={page} 
                      alt={`Página ${idx + 1}`} 
                      className="w-full h-auto rounded-lg shadow-xl border border-zinc-800" 
                      loading="lazy"
                    />
                    <span className="text-[11px] text-zinc-500 mt-1 mb-4 font-mono">Página {idx + 1} / {manga.pages.length}</span>
                  </div>
                ))}
              </div>
            ) : (
              /* Modo Tradicional (Página individual) */
              <div className="flex flex-col items-center bg-zinc-950 p-4 rounded-xl min-h-[600px] justify-between">
                <div className="w-full max-w-2xl flex justify-center items-center py-4">
                  <img 
                    src={manga.pages[currentPage]} 
                    alt={`Página ${currentPage + 1}`} 
                    className="max-h-[70vh] w-auto rounded-lg shadow-2xl border border-zinc-800" 
                  />
                </div>
                
                {/* Controles de paginación */}
                <div className="flex items-center gap-4 py-4">
                  <button 
                    disabled={currentPage === 0}
                    onClick={() => setCurrentPage(prev => Math.max(0, prev - 1))}
                    className="flex items-center gap-1 bg-zinc-900 border border-zinc-700 hover:bg-zinc-800 text-white px-4 py-2 rounded-xl text-sm font-bold disabled:opacity-30 disabled:cursor-not-allowed transition-all"
                  >
                    <ChevronLeft size={18} /> Anterior
                  </button>
                  <span className="text-sm font-mono text-zinc-300">
                    {currentPage + 1} / {manga.pages.length}
                  </span>
                  <button 
                    disabled={currentPage >= manga.pages.length - 1}
                    onClick={() => setCurrentPage(prev => Math.min(manga.pages.length - 1, prev + 1))}
                    className="flex items-center gap-1 bg-rose-600 hover:bg-rose-500 text-white px-4 py-2 rounded-xl text-sm font-bold disabled:opacity-30 disabled:cursor-not-allowed transition-all"
                  >
                    Siguiente <ChevronRight size={18} />
                  </button>
                </div>
              </div>
            )
          ) : (
            <div className="flex flex-col items-center justify-center h-72 bg-zinc-950 rounded-xl text-zinc-400">
              <BookOpen size={50} className="mb-4 opacity-40 text-rose-500" />
              <p className="font-bold text-lg text-white">Este manga aún no tiene páginas cargadas.</p>
              <p className="text-sm text-zinc-500 mt-1">El mangaka o administrador debe agregar los enlaces a las páginas en el panel de control.</p>
            </div>
          )}
        </div>
      )}

      {/* Reseñas y Comentarios de la Comunidad */}
      <div className="mt-12 bg-zinc-900/60 p-6 sm:p-8 rounded-3xl border border-zinc-800">
        <h3 className="text-2xl font-black text-white mb-6 flex items-center gap-3">
          <MessageCircle className="text-rose-500"/> Reseñas de Lectores ({comments.length})
        </h3>
        
        <form onSubmit={handleAddComment} className="mb-8 flex flex-col gap-4">
          <div className="flex items-center gap-3">
            <span className="text-xs text-zinc-400 font-bold uppercase tracking-wider">Tu Puntuación:</span>
            <div className="flex gap-1">
              {[1, 2, 3, 4, 5].map((star) => (
                <button
                  type="button"
                  key={star}
                  onClick={() => setNewRating(star)}
                  className={`p-1 rounded transition-colors ${newRating >= star ? 'text-amber-400' : 'text-zinc-600'}`}
                >
                  <Star size={18} className={newRating >= star ? 'fill-amber-400' : ''} />
                </button>
              ))}
            </div>
          </div>

          <div className="flex gap-3">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-tr from-rose-600 to-amber-500 flex items-center justify-center font-black text-white text-sm flex-shrink-0 shadow-md">
              {user ? user.uid.substring(0,2).toUpperCase() : 'OT'}
            </div>
            <div className="flex-1 flex flex-col gap-2">
              <textarea 
                value={newComment}
                onChange={(e) => setNewComment(e.target.value)}
                placeholder="¿Qué te pareció este capítulo o volumen? Comparte tus teorías..."
                className="w-full bg-zinc-950 text-white rounded-2xl p-4 border border-zinc-800 focus:border-rose-500 focus:ring-1 focus:ring-rose-500 outline-none resize-none h-24 text-sm transition-all"
              />
              <button 
                type="submit" 
                disabled={!newComment.trim()} 
                className="self-end bg-rose-600 hover:bg-rose-500 text-white font-bold text-sm py-2.5 px-6 rounded-xl disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-md shadow-rose-600/20"
              >
                Publicar Reseña
              </button>
            </div>
          </div>
        </form>

        <div className="space-y-3 max-h-96 overflow-y-auto pr-2 custom-scrollbar">
          {comments.map(c => (
            <div key={c.id} className="bg-zinc-950/70 p-4 rounded-2xl border border-zinc-800/80">
              <div className="flex justify-between items-start mb-2">
                <div className="flex items-center gap-2">
                  <span className="font-bold text-rose-400 text-sm">{c.userName}</span>
                  {c.rating && (
                    <div className="flex items-center text-amber-400 text-xs">
                      <Star size={12} className="fill-amber-400 mr-1" />
                      {c.rating}/5
                    </div>
                  )}
                </div>
                <span className="text-[11px] text-zinc-500 font-mono">
                  {new Date(c.timestamp).toLocaleDateString()}
                </span>
              </div>
              <p className="text-zinc-300 text-sm whitespace-pre-wrap leading-relaxed">{c.text}</p>
            </div>
          ))}
          {comments.length === 0 && (
            <p className="text-center text-zinc-500 py-8 text-sm">Aún no hay reseñas para este manga. ¡Sé el primero en opinar!</p>
          )}
        </div>
      </div>
    </div>
  );
};

// Chat Global Otaku
const CommunityChat = ({ user }: { user: any }) => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const q = getPublicPath('manga_chat');
    const unsubscribe = onSnapshot(q, (snapshot) => {
      const allMsgs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })) as ChatMessage[];
      allMsgs.sort((a, b) => a.timestamp - b.timestamp);
      setMessages(allMsgs);
    }, (error) => console.error("Error chat:", error));
    return () => unsubscribe();
  }, []);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newMessage.trim() || !user) return;
    try {
      await addDoc(getPublicPath('manga_chat'), {
        userId: user.uid,
        userName: `Shinobi-${user.uid.substring(0, 4)}`,
        text: newMessage,
        timestamp: Date.now()
      });
      setNewMessage('');
    } catch (err) {
      console.error("Error enviando mensaje:", err);
    }
  };

  return (
    <div className="max-w-4xl mx-auto p-4 h-[calc(100vh-5rem)] flex flex-col">
      <div className="bg-zinc-900 rounded-t-2xl p-4 border border-zinc-800 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="bg-rose-500 w-3 h-3 rounded-full animate-ping"></div>
          <div>
            <h2 className="text-lg font-black text-white tracking-wide uppercase">Dojo Otaku (Chat en Vivo)</h2>
            <p className="text-xs text-zinc-400">Canal global de discusión sobre spoilers, mangas y noticias</p>
          </div>
        </div>
        <span className="text-xs font-mono text-zinc-500">{messages.length} mensajes</span>
      </div>
      
      <div className="flex-1 bg-zinc-950/90 backdrop-blur-md p-4 overflow-y-auto custom-scrollbar flex flex-col gap-3 border-x border-zinc-800">
        {messages.map(msg => {
          const isMe = user && msg.userId === user.uid;
          return (
            <div key={msg.id} className={`flex flex-col ${isMe ? 'items-end' : 'items-start'} max-w-[85%] ${isMe ? 'self-end' : 'self-start'}`}>
              <span className={`text-[11px] mb-1 font-semibold ${isMe ? 'text-rose-400 mr-2' : 'text-zinc-400 ml-2'}`}>
                {msg.userName}
              </span>
              <div className={`p-3 rounded-2xl text-sm leading-relaxed ${isMe ? 'bg-rose-600 text-white rounded-tr-none' : 'bg-zinc-800 text-zinc-200 rounded-tl-none border border-zinc-700'}`}>
                {msg.text}
              </div>
            </div>
          );
        })}
        <div ref={messagesEndRef} />
      </div>

      <form onSubmit={handleSend} className="bg-zinc-900 p-3 sm:p-4 rounded-b-2xl flex gap-2 border border-zinc-800 shadow-xl">
        <input 
          type="text" 
          value={newMessage}
          onChange={(e) => setNewMessage(e.target.value)}
          placeholder="Escribe tu mensaje para el Dojo..."
          className="flex-1 bg-zinc-950 text-white rounded-xl px-4 py-3 outline-none border border-zinc-800 focus:border-rose-500 text-sm transition-colors"
        />
        <button 
          type="submit" 
          disabled={!newMessage.trim()} 
          className="bg-rose-600 hover:bg-rose-500 text-white rounded-xl px-5 flex items-center justify-center disabled:opacity-40 transition-all font-bold text-sm shadow-md shadow-rose-600/20"
        >
          <Send size={18} />
        </button>
      </form>
    </div>
  );
};

// Panel de Administración Mangaka
const AdminPanel = ({ mangas, setAlert }: { mangas: Manga[]; setAlert: (msg: string, type?: 'info' | 'success' | 'error') => void }) => {
  const [activeTab, setActiveTab] = useState<'mangas' | 'theme'>('mangas');
  const [newManga, setNewManga] = useState({ 
    title: '', 
    romajiTitle: '',
    category: 'Shonen', 
    demography: 'Shonen',
    status: 'En Emisión',
    author: '',
    description: '', 
    coverUrl: '', 
    pagesStr: '',
    score: 9.2
  });
  const [themeSettings, setThemeSettings] = useState<ThemeSettings>({ 
    themeColor: '#09090b', 
    backgroundStyle: 'neo-tokyo' 
  });

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const docSnap = await getDocs(getPublicPath('manga_settings'));
        if (!docSnap.empty) {
          const data = docSnap.docs[0].data() as ThemeSettings;
          setThemeSettings(data);
        }
      } catch(e) { console.error(e); }
    };
    fetchSettings();
  }, []);

  const handleAddManga = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const pages = newManga.pagesStr.split(',').map(s => s.trim()).filter(Boolean);
      await addDoc(getPublicPath('mangas'), {
        title: newManga.title,
        romajiTitle: newManga.romajiTitle,
        category: newManga.category,
        demography: newManga.demography,
        status: newManga.status,
        author: newManga.author,
        description: newManga.description,
        coverUrl: newManga.coverUrl,
        pages: pages,
        score: Number(newManga.score) || 9.0,
        createdAt: Date.now()
      });
      setAlert("Manga publicado exitosamente en la biblioteca.", "success");
      setNewManga({ 
        title: '', 
        romajiTitle: '',
        category: 'Shonen', 
        demography: 'Shonen',
        status: 'En Emisión',
        author: '',
        description: '', 
        coverUrl: '', 
        pagesStr: '',
        score: 9.2
      });
    } catch (err) {
      setAlert("Error al publicar el manga.", "error");
    }
  };

  const handleDeleteManga = async (id: string) => {
    try {
      await deleteDoc(getPublicDoc('mangas', id));
      setAlert("Manga eliminado de la colección.", "info");
    } catch (err) {
      setAlert("Error al eliminar.", "error");
    }
  };

  const handleUpdateTheme = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const snap = await getDocs(getPublicPath('manga_settings'));
      if (snap.empty) {
        await addDoc(getPublicPath('manga_settings'), themeSettings);
      } else {
        await updateDoc(getPublicDoc('manga_settings', snap.docs[0].id), { ...themeSettings });
      }
      setAlert("Tema visual actualizado en tiempo real.", "success");
    } catch (err) {
      setAlert("Error actualizando estilo.", "error");
    }
  };

  return (
    <div className="max-w-6xl mx-auto p-4 sm:p-6">
      <div className="bg-zinc-900 rounded-3xl border border-zinc-800 overflow-hidden shadow-2xl">
        <div className="flex border-b border-zinc-800 bg-zinc-950">
          <button 
            className={`flex-1 py-4 font-bold text-base flex justify-center items-center gap-2 transition-all ${
              activeTab === 'mangas' ? 'text-rose-400 border-b-2 border-rose-500 bg-zinc-900/50' : 'text-zinc-400 hover:bg-zinc-900/30'
            }`}
            onClick={() => setActiveTab('mangas')}
          >
            <BookOpen size={18} /> Publicación de Mangas
          </button>
          <button 
            className={`flex-1 py-4 font-bold text-base flex justify-center items-center gap-2 transition-all ${
              activeTab === 'theme' ? 'text-rose-400 border-b-2 border-rose-500 bg-zinc-900/50' : 'text-zinc-400 hover:bg-zinc-900/30'
            }`}
            onClick={() => setActiveTab('theme')}
          >
            <Palette size={18} /> Estilos & Ambientación
          </button>
        </div>

        <div className="p-6 sm:p-8">
          {activeTab === 'mangas' && (
            <div className="grid md:grid-cols-2 gap-10">
              <div>
                <h3 className="text-xl font-black text-white mb-6 flex items-center gap-2">
                  <Plus className="text-rose-500"/> Nuevo Manga / Manhwa
                </h3>
                <form onSubmit={handleAddManga} className="space-y-4">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-zinc-400 mb-1 text-xs font-semibold">Título en Español / Inglés</label>
                      <input required type="text" value={newManga.title} onChange={e => setNewManga({...newManga, title: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 text-sm" placeholder="Ej: Cazador de Sombras" />
                    </div>
                    <div>
                      <label className="block text-zinc-400 mb-1 text-xs font-semibold">Título en Japonés / Rōmaji</label>
                      <input type="text" value={newManga.romajiTitle} onChange={e => setNewManga({...newManga, romajiTitle: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 text-sm" placeholder="Ej: Kage no Ryoushi" />
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-3">
                    <div>
                      <label className="block text-zinc-400 mb-1 text-xs font-semibold">Demografía / Categoría</label>
                      <select value={newManga.category} onChange={e => setNewManga({...newManga, category: e.target.value, demography: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 text-sm">
                        <option>Shonen</option><option>Seinen</option><option>Shojo</option><option>Josei</option><option>Isekai</option><option>Fantasía</option><option>Acción</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-zinc-400 mb-1 text-xs font-semibold">Estado</label>
                      <select value={newManga.status} onChange={e => setNewManga({...newManga, status: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 text-sm">
                        <option>En Emisión</option><option>Finalizado</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-zinc-400 mb-1 text-xs font-semibold">Puntuación</label>
                      <input type="number" step="0.1" min="1" max="10" value={newManga.score} onChange={e => setNewManga({...newManga, score: parseFloat(e.target.value)})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 text-sm" />
                    </div>
                  </div>

                  <div>
                    <label className="block text-zinc-400 mb-1 text-xs font-semibold">Mangaka / Autor</label>
                    <input type="text" value={newManga.author} onChange={e => setNewManga({...newManga, author: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 text-sm" placeholder="Ej: Eiichiro Oda, Kentaro Miura..." />
                  </div>

                  <div>
                    <label className="block text-zinc-400 mb-1 text-xs font-semibold">URL de la Portada</label>
                    <input required type="url" value={newManga.coverUrl} onChange={e => setNewManga({...newManga, coverUrl: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 text-sm" placeholder="https://..." />
                  </div>

                  <div>
                    <label className="block text-zinc-400 mb-1 text-xs font-semibold">Sinopsis</label>
                    <textarea required value={newManga.description} onChange={e => setNewManga({...newManga, description: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 h-24 text-sm" placeholder="Describe la trama del manga..." />
                  </div>

                  <div>
                    <label className="block text-zinc-400 mb-1 text-xs font-semibold">URLs de las Páginas (Separadas por comas)</label>
                    <textarea value={newManga.pagesStr} onChange={e => setNewManga({...newManga, pagesStr: e.target.value})} className="w-full bg-zinc-950 text-white rounded-xl p-3 border border-zinc-800 h-24 font-mono text-xs" placeholder="https://pagina1.jpg, https://pagina2.jpg..." />
                  </div>

                  <button type="submit" className="w-full bg-rose-600 hover:bg-rose-500 text-white font-bold py-3.5 rounded-xl shadow-lg shadow-rose-600/30 transition-all text-sm">
                    Publicar Manga en la Plataforma
                  </button>
                </form>
              </div>
              
              <div>
                <h3 className="text-xl font-black text-white mb-6">Mangas Registrados ({mangas.length})</h3>
                <div className="space-y-3 max-h-[600px] overflow-y-auto pr-2 custom-scrollbar">
                  {mangas.map(m => (
                    <div key={m.id} className="flex items-center justify-between bg-zinc-950 p-3 rounded-2xl border border-zinc-800">
                      <div className="flex items-center gap-3">
                        <img src={m.coverUrl} className="w-12 h-16 object-cover rounded-lg bg-zinc-900" alt="" onError={(e: any)=>e.target.style.display='none'}/>
                        <div>
                          <div className="font-bold text-white text-sm">{m.title}</div>
                          <div className="text-xs text-rose-400">{m.category} • {m.pages ? m.pages.length : 0} págs</div>
                        </div>
                      </div>
                      <button onClick={() => handleDeleteManga(m.id)} className="text-rose-400 hover:text-rose-300 text-xs font-bold px-3 py-1.5 bg-rose-950/40 border border-rose-900/50 rounded-xl transition-colors">
                        Eliminar
                      </button>
                    </div>
                  ))}
                  {mangas.length === 0 && <p className="text-zinc-500 text-sm">Aún no hay mangas registrados.</p>}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'theme' && (
            <div className="max-w-2xl mx-auto">
              <h3 className="text-2xl font-black text-white mb-2">Ambientación Visual (Global)</h3>
              <p className="text-zinc-400 text-sm mb-8">Personaliza la atmósfera del sitio para todos los lectores en tiempo real mediante Firestore.</p>
              
              <form onSubmit={handleUpdateTheme} className="space-y-6">
                <div className="bg-zinc-950 p-6 rounded-2xl border border-zinc-800">
                  <label className="block text-white font-bold text-sm mb-2">Tono Base de la Barra de Navegación</label>
                  <div className="flex items-center gap-4">
                    <input type="color" value={themeSettings.themeColor} onChange={e => setThemeSettings({...themeSettings, themeColor: e.target.value})} className="w-14 h-14 rounded-xl cursor-pointer bg-transparent border-0" />
                    <div className="flex-1 text-zinc-400 text-xs">Selecciona un color base oscuro para mantener el contraste estético de lectura. Actualmente: {themeSettings.themeColor}</div>
                  </div>
                </div>

                <div className="bg-zinc-950 p-6 rounded-2xl border border-zinc-800">
                  <label className="block text-white font-bold text-sm mb-4">Estilo de Fondo y Atmósfera</label>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {[
                      { id: 'neo-tokyo', label: 'Neo Tokyo (Cyberpunk Noche)', classes: 'bg-gradient-to-br from-zinc-950 via-purple-950 to-zinc-950 border-purple-500/30' },
                      { id: 'ink', label: 'Tinta & Papel (Manga Clásico B/N)', classes: 'bg-zinc-950 border-zinc-700' },
                      { id: 'shonen-fire', label: 'Llama Shonen (Rojo Ardiente)', classes: 'bg-gradient-to-br from-zinc-950 via-rose-950 to-amber-950 border-rose-500/30' },
                      { id: 'dark-abyss', label: 'Abismo Seinen (Azul Profundo)', classes: 'bg-gradient-to-br from-slate-950 via-indigo-950 to-zinc-950 border-indigo-500/30' }
                    ].map(style => (
                      <div 
                        key={style.id}
                        onClick={() => setThemeSettings({...themeSettings, backgroundStyle: style.id})}
                        className={`p-4 rounded-xl cursor-pointer border-2 transition-all ${
                          themeSettings.backgroundStyle === style.id 
                            ? 'border-rose-500 shadow-[0_0_15px_rgba(244,63,94,0.3)] bg-zinc-900' 
                            : 'border-zinc-800 hover:border-zinc-700 bg-zinc-950'
                        }`}
                      >
                        <div className={`w-full h-14 rounded-lg mb-2 ${style.classes}`}></div>
                        <div className="text-center text-white font-bold text-xs">{style.label}</div>
                      </div>
                    ))}
                  </div>
                </div>
                
                <button type="submit" className="w-full bg-rose-600 hover:bg-rose-500 text-white font-bold py-4 rounded-2xl shadow-xl shadow-rose-600/20 transition-all text-base">
                  Guardar y Aplicar Atmósfera a Todo el Sitio
                </button>
              </form>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// Vistas Informativas y Guías
const InfoView = () => (
  <div className="max-w-4xl mx-auto p-4 sm:p-6 text-zinc-300">
    <div className="bg-zinc-900 p-6 sm:p-8 rounded-3xl border border-zinc-800 shadow-xl">
      <h2 className="text-3xl font-black text-white mb-6 border-b border-zinc-800 pb-4 flex items-center gap-3">
        <Layers className="text-rose-500" /> Arquitectura Técnica & Base de Datos
      </h2>
      <p className="mb-6 leading-relaxed text-sm">
        MangaVerse implementa un modelo <strong>JAMstack Serverless</strong> con sincronización en tiempo real gracias a <strong>Firebase Firestore</strong> y <strong>Firebase Auth</strong>. No requiere servidores backend dedicados; los clientes interactúan mediante listeners reactivos de WebSockets nativos.
      </p>
      
      <h3 className="text-lg font-bold text-rose-400 mt-8 mb-4">Estructura del Esquema de Datos (JSON)</h3>
      <div className="bg-zinc-950 p-5 rounded-2xl font-mono text-xs overflow-x-auto border border-zinc-800">
        <pre className="text-rose-300">
{`{
  "coleccion_mangas": [
    {
      "id": "string (Auto-generado)",
      "title": "string (Ej: Jujutsu Kaisen)",
      "romajiTitle": "string",
      "category": "Shonen | Seinen | Shojo | Isekai | ...",
      "demography": "Shonen | Seinen | ...",
      "status": "En Emisión | Finalizado",
      "author": "string",
      "description": "string",
      "coverUrl": "string (URL)",
      "pages": ["https://img1.jpg", "https://img2.jpg", "..."],
      "score": 9.5,
      "createdAt": 1727650000000
    }
  ],
  "coleccion_manga_comments": [
    {
      "id": "string",
      "mangaId": "string (Referencia)",
      "userId": "string",
      "userName": "string",
      "text": "string",
      "rating": 5,
      "timestamp": 1727650000000
    }
  ],
  "coleccion_manga_chat": [
    {
      "id": "string",
      "userId": "string",
      "userName": "string",
      "text": "string",
      "timestamp": 1727650000000
    }
  ],
  "coleccion_manga_settings": [
    {
      "themeColor": "#09090b",
      "backgroundStyle": "neo-tokyo | ink | shonen-fire | dark-abyss"
    }
  ]
}`}
        </pre>
      </div>
    </div>
  </div>
);

const GuideView = () => (
  <div className="max-w-4xl mx-auto p-4 sm:p-6 text-zinc-300">
    <div className="bg-zinc-900 p-6 sm:p-8 rounded-3xl border border-zinc-800 shadow-xl">
      <h2 className="text-3xl font-black text-white mb-6 flex items-center gap-3">
        <HelpCircle className="text-rose-500" /> Guía para Lectores y Otakus
      </h2>
      
      <div className="space-y-6">
        <div className="flex gap-4 items-start bg-zinc-950/50 p-5 rounded-2xl border border-zinc-800">
          <div className="bg-rose-900/40 p-3 rounded-xl text-rose-400"><BookOpen size={28}/></div>
          <div>
            <h3 className="text-lg font-bold text-white mb-1">1. Modos de Lectura Versátiles</h3>
            <p className="text-sm text-zinc-400">Puedes alternar entre el <strong>Modo Cascada (Webtoon)</strong> para desplazarte verticalmente con scroll continuo, o el <strong>Modo Tradicional</strong> para avanzar página por página con los controles táctiles o botones de navegación.</p>
          </div>
        </div>
        
        <div className="flex gap-4 items-start bg-zinc-950/50 p-5 rounded-2xl border border-zinc-800">
          <div className="bg-amber-900/40 p-3 rounded-xl text-amber-400"><MessageCircle size={28}/></div>
          <div>
            <h3 className="text-lg font-bold text-white mb-1">2. Dojo Otaku & Sistema de Reseñas</h3>
            <p className="text-sm text-zinc-400">Califica cada título con estrellas y comparte tus opiniones en la pestaña de cada manga. Si prefieres conversar en vivo, únete al <strong>Dojo Otaku</strong> para debatir con lectores de todo el mundo.</p>
          </div>
        </div>

        <div className="flex gap-4 items-start bg-zinc-950/50 p-5 rounded-2xl border border-zinc-800">
          <div className="bg-purple-900/40 p-3 rounded-xl text-purple-400"><Shield size={28}/></div>
          <div>
            <h3 className="text-lg font-bold text-white mb-1">3. Panel Mangaka (Administración)</h3>
            <p className="text-sm text-zinc-400">Registra nuevos títulos, define autores, agrega enlaces de páginas y modifica la ambientación estética (Cyberpunk Neo-Tokyo, Shonen Fire o Tinta & Papel) que se sincroniza automáticamente para todos los visitantes.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
);

// ==========================================
// APLICACIÓN PRINCIPAL
// ==========================================
export default function App() {
  const [user, setUser] = useState<any>(null);
  const [currentView, setCurrentView] = useState('home');
  const [selectedManga, setSelectedManga] = useState<Manga | null>(null);
  const [mangas, setMangas] = useState<Manga[]>([]);
  const [theme, setTheme] = useState<ThemeSettings>({ 
    themeColor: '#09090b', 
    backgroundStyle: 'neo-tokyo' 
  });
  const [alertConfig, setAlertConfig] = useState<{ message: string; type: 'info' | 'success' | 'error' } | null>(null);

  const showAlert = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
    setAlertConfig({ message, type });
    setTimeout(() => setAlertConfig(null), 4000);
  };

  // Autenticación inicial anónima o con token
  useEffect(() => {
    if (!auth) return;
    const initAuth = async () => {
      try {
        // @ts-ignore
        if (typeof __initial_auth_token !== 'undefined' && __initial_auth_token) {
          // @ts-ignore
          await signInWithCustomToken(auth, __initial_auth_token);
        } else {
          await signInAnonymously(auth);
        }
      } catch (error) {
        console.error("Error Auth:", error);
        showAlert("Error de conexión con el servidor", "error");
      }
    };

    const unsubscribe = onAuthStateChanged(auth, (u) => {
      if (u) setUser(u);
    });

    initAuth();
    return () => unsubscribe();
  }, []);

  // Suscripción reactiva a Mangas y Configuración
  useEffect(() => {
    if (!user || !db) return;

    // Escuchar colección de mangas
    const unsubMangas = onSnapshot(getPublicPath('mangas'), (snap) => {
      const docs = snap.docs.map(d => ({ id: d.id, ...d.data() })) as Manga[];
      docs.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
      
      // Datos de ejemplo iniciales orientados al Manga
      if (snap.empty && docs.length === 0) {
        const mockMangas: Omit<Manga, 'id'>[] = [
          { 
            title: "Sombra Carmesí: El Despertar", 
            romajiTitle: "Shinku no Kage: Kakusei",
            category: "Shonen", 
            demography: "Shonen",
            status: "En Emisión",
            author: "Kenji Sato",
            score: 9.6,
            description: "En un mundo donde los cazadores sellan demonios a través de runas de sangre, un joven sin afinidad mágica despierta el grimorio proscrito.", 
            coverUrl: "https://images.unsplash.com/photo-1607604276583-eef5d076aa5f?auto=format&fit=crop&w=600&q=80", 
            pages: [
              "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=80",
              "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=80"
            ], 
            createdAt: Date.now() 
          },
          { 
            title: "Reencarnado como Alquimista Legendario", 
            romajiTitle: "Densetsu no Renkinjutsushi",
            category: "Isekai", 
            demography: "Seinen",
            status: "En Emisión",
            author: "Yuki Tanaka",
            score: 9.3,
            description: "Tras un accidente en su laboratorio de química moderna, despierta en un imperio fantástico donde domina las fórmulas que desafían las leyes divinas.", 
            coverUrl: "https://images.unsplash.com/photo-1578632767115-351597cf2477?auto=format&fit=crop&w=600&q=80", 
            pages: [], 
            createdAt: Date.now() - 2000 
          },
          { 
            title: "El Filo de Neo-Tokyo", 
            romajiTitle: "Neo-Tokyo no Yaiba",
            category: "Seinen", 
            demography: "Seinen",
            status: "Finalizado",
            author: "Ryu Takahashi",
            score: 9.8,
            description: "Año 2099. Los samuráis cibernéticos defienden los callejones iluminados por neón de sindicatos sintéticos.", 
            coverUrl: "https://images.unsplash.com/photo-1563089145-599997674d42?auto=format&fit=crop&w=600&q=80", 
            pages: [], 
            createdAt: Date.now() - 4000 
          }
        ];
        mockMangas.forEach(m => addDoc(getPublicPath('mangas'), m).catch(console.error));
      } else {
        setMangas(docs);
      }
    }, (err) => console.error(err));

    // Escuchar configuraciones de estilo
    const unsubSettings = onSnapshot(getPublicPath('manga_settings'), (snap) => {
      if (!snap.empty) {
        setTheme(snap.docs[0].data() as ThemeSettings);
      }
    }, (err) => console.error(err));

    return () => {
      unsubMangas();
      unsubSettings();
    };
  }, [user]);

  // Manejo del render de vistas
  const renderView = () => {
    if (selectedManga) {
      return <MangaDetailView manga={selectedManga} goBack={() => setSelectedManga(null)} user={user} />;
    }
    
    switch (currentView) {
      case 'home': return <HomeView mangas={mangas} setViewDetail={setSelectedManga} />;
      case 'chat': return <CommunityChat user={user} />;
      case 'info': return <InfoView />;
      case 'guide': return <GuideView />;
      case 'admin': return <AdminPanel mangas={mangas} setAlert={showAlert} />;
      default: return <HomeView mangas={mangas} setViewDetail={setSelectedManga} />;
    }
  };

  // Clases dinámicas de fondo basadas en los temas de manga
  const getBackgroundClass = () => {
    switch (theme.backgroundStyle) {
      case 'shonen-fire': return 'bg-gradient-to-br from-zinc-950 via-rose-950/70 to-amber-950/60';
      case 'dark-abyss': return 'bg-gradient-to-br from-slate-950 via-indigo-950/70 to-zinc-950';
      case 'ink': return 'bg-zinc-950 bg-[radial-gradient(circle_at_top,_rgba(255,255,255,0.03)_1px,_transparent_1px)] bg-[size:24px_24px]';
      case 'neo-tokyo':
      default: return 'bg-zinc-950 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-purple-950/40 via-zinc-950 to-black';
    }
  };

  return (
    <div className={`min-h-screen text-zinc-100 font-sans transition-all duration-700 ease-in-out ${getBackgroundClass()}`}>
      <style dangerouslySetInnerHTML={{__html: `
        .custom-scrollbar::-webkit-scrollbar { width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: rgba(0,0,0,0.3); border-radius: 8px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(244,63,94,0.3); border-radius: 8px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(244,63,94,0.6); }
      `}} />
      
      <Navbar 
        currentView={selectedManga ? 'manga' : currentView} 
        setCurrentView={(view) => { setSelectedManga(null); setCurrentView(view); }} 
        themeColor={theme.themeColor}
      />
      
      <main className="relative z-10 pt-2 pb-14">
        {!user ? (
          <div className="flex flex-col justify-center items-center h-72 gap-4">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-rose-500"></div>
            <p className="text-zinc-400 text-sm font-semibold animate-pulse">Sintonizando con el Santuario Manga...</p>
          </div>
        ) : (
          renderView()
        )}
      </main>

      {alertConfig && (
        <CustomAlert 
          message={alertConfig.message} 
          type={alertConfig.type} 
          onClose={() => setAlertConfig(null)} 
        />
      )}
    </div>
  );
}
