
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { createRoot } from 'react-dom/client';
import { GoogleGenAI } from "@google/genai";
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.10.0/firebase-app.js";
import { 
  getAuth, signInWithEmailAndPassword, onAuthStateChanged, signOut, setPersistence, 
  browserLocalPersistence, sendPasswordResetEmail 
} from "https://www.gstatic.com/firebasejs/11.10.0/firebase-auth.js";
import { 
  getFirestore, doc, getDoc, updateDoc, arrayUnion, arrayRemove, setDoc 
} from "https://www.gstatic.com/firebasejs/11.10.0/firebase-firestore.js";
import { 
  Play, Info, Search, ChevronRight, ChevronLeft, X, 
  Loader2, LogOut, Check, Star, SlidersHorizontal,
  Home, Bookmark, CheckCircle, PlayCircle, Eye, EyeOff
} from 'lucide-react';

// --- Firebase Configuration ---
const firebaseConfig = {
  apiKey: "AIzaSyDECpHC2RJw5yf0soUdLdBjFAGHidlEoB8",
  authDomain: "army-tv-408b0.firebaseapp.com",
  projectId: "army-tv-408b0"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

const CONTENT_API = 'https://sheet2api.com/v1/hM8tf8qUS2Wj/conteudos-bts-bangtannow';

const AVATARS: Record<string, string> = {
  rm:"https://bangtannow.com/wp-content/uploads/2025/01/Kim-Namjoon-2.jpg",
  jin:"https://bangtannow.com/wp-content/uploads/2025/01/Kim-Seokjin-1.jpg",
  suga:"https://bangtannow.com/wp-content/uploads/2025/01/Min-Yoongi.jpg",
  "j-hope":"https://bangtannow.com/wp-content/uploads/2025/01/Jung-Hoseok.jpg",
  jimin:"https://bangtannow.com/wp-content/uploads/2025/01/Park-Jimin.jpg",
  v:"https://bangtannow.com/wp-content/uploads/2025/01/Kim-Taehyung.jpg",
  jungkook:"https://bangtannow.com/wp-content/uploads/2025/01/Jeon-Jungkook.jpg",
  bts:"https://i.imgur.com/brTJR6X.png",
  koya: "https://i.imgur.com/8eTGXzV.png",
  rj: "https://i.imgur.com/5N8Sm6v.png",
  shooky: "https://i.imgur.com/OcvNgyg.png",
  mang: "https://i.imgur.com/gPU6T75.png",
  chimmy: "https://i.imgur.com/SUO4HlP.png",
  tata: "https://i.imgur.com/kE02Emw.png",
  cooky: "https://i.imgur.com/ofR4Znl.png",
  bt21: "https://i.imgur.com/CtTegOi.png",
  van: "https://i.imgur.com/rcSYbNG.png",
  wootteo: "https://i.imgur.com/a2S7P3D.png",
  whamii: "https://i.imgur.com/R0ZOhpM.png",
};

const CATEGORIES_CONFIG = [
  { id: 'bastidores', title: 'Bastidores' },
  { id: 'dance practice', title: 'Dance Practice' },
  { id: 'entrevista', title: 'Entrevistas' },
  { id: 'fanmeeting', title: 'Fanmeeting e Autógrafos' },
  { id: 'documentário', title: 'Filmes e Documentários' },
  { id: 'live', title: 'Live e Vlogs' },
  { id: 'muster', title: 'Muster' },
  { id: 'mv', title: 'MVs' },
  { id: 'premiacao', title: 'Premiações' },
  { id: 'programa', title: 'Programas' },
  { id: 'performance', title: 'Performance' },
  { id: 'reality', title: 'Reality Shows e Variedades' },
  { id: 'fotos', title: 'Sessão de Fotos' },
  { id: 'show', title: 'Shows e Turnês' },
  { id: 'outros', title: 'Outros' }
];

const MEMBERS_LIST = ['RM', 'Jin', 'SUGA', 'j-hope', 'Jimin', 'V', 'Jung Kook', 'BTS'];

interface ContentItem {
  TITULO: string;
  DESCRIÇÃO: string;
  IMAGEM: string;
  LINK: string;
  DATA: string;
  CATEGORIAS: string;
  MEMBROS: string;
  ANOS: string | number;
}

const parseDate = (dateStr: string) => {
  if (!dateStr) return new Date(0);
  const [day, month, year] = dateStr.split('/').map(Number);
  return new Date(year, month - 1, day);
};

const NetflixCard = ({ item, onOpen, isFavorite, isWatched, onToggleFavorite, onToggleWatched }: any) => {
  return (
    <div className="flex-none w-44 md:w-64 group relative transition-all duration-300 hover:scale-105 md:hover:scale-110 hover:z-30">
      <div className="aspect-video rounded-md overflow-hidden bg-gray-900 shadow-lg relative">
        <img src={item.IMAGEM} alt={item.TITULO} className="w-full h-full object-cover" loading="lazy" />
        <div className="absolute top-1.5 right-1.5 flex gap-1 z-10">
          {isFavorite && (
            <div className="bg-yellow-500 p-0.5 md:p-1 rounded-full shadow-lg">
              <Star size={8} fill="black" className="text-black md:w-2.5 md:h-2.5" />
            </div>
          )}
          {isWatched && (
            <div className="bg-purple-600 p-0.5 md:p-1 rounded-full shadow-lg">
              <Check size={8} className="text-white md:w-2.5 md:h-2.5" />
            </div>
          )}
        </div>
      </div>
      <div className="absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition flex flex-col justify-end p-2 md:p-3 rounded-md">
        <div className="flex gap-1.5 md:gap-2 mb-1.5 md:mb-2">
          <button onClick={() => window.open(item.LINK, '_blank')} className="bg-white p-1.5 md:p-2 rounded-full text-black hover:bg-gray-200">
            <Play size={12} fill="black" className="md:w-3.5 md:h-3.5" />
          </button>
          <button onClick={(e) => { e.stopPropagation(); onToggleFavorite(item.LINK); }} className={`p-1.5 md:p-2 rounded-full border transition ${isFavorite ? 'bg-yellow-500 border-yellow-500 text-black' : 'bg-black/60 border-gray-400 text-white hover:border-white'}`}>
            <Star size={12} fill={isFavorite ? "currentColor" : "none"} className="md:w-3.5 md:h-3.5" />
          </button>
          <button onClick={(e) => { e.stopPropagation(); onToggleWatched(item.LINK); }} className={`p-1.5 md:p-2 rounded-full border transition ${isWatched ? 'bg-purple-600 border-purple-600 text-white' : 'bg-black/60 border-gray-400 text-white hover:border-white'}`}>
            <Check size={12} className="md:w-3.5 md:h-3.5" />
          </button>
          <button onClick={() => onOpen(item)} className="ml-auto p-1.5 md:p-2 rounded-full bg-black/60 border border-gray-400 hover:border-white text-white">
            <Info size={12} className="md:w-3.5 md:h-3.5" />
          </button>
        </div>
        <p className="text-[10px] md:text-xs font-bold truncate text-white">{item.TITULO}</p>
      </div>
    </div>
  );
};

const Row = ({ title, items, ...cardProps }: any) => {
  const scrollRef = useRef<HTMLDivElement>(null);
  const scroll = (dir: 'L' | 'R') => {
    if (scrollRef.current) {
      const offset = dir === 'L' ? -400 : 400;
      scrollRef.current.scrollBy({ left: offset, behavior: 'smooth' });
    }
  };
  if (items.length === 0) return null;
  return (
    <div className="py-2 md:py-4 px-6 md:px-12 relative group/row overflow-visible">
      <h3 className="text-lg md:text-xl font-bold mb-4 text-gray-100 tracking-wide">{title}</h3>
      <div className="relative">
        <button onClick={() => scroll('L')} className="hidden md:block absolute left-0 top-0 bottom-0 z-20 bg-black/60 opacity-0 group-hover/row:opacity-100 transition px-2"><ChevronLeft /></button>
        <div ref={scrollRef} className="flex gap-4 md:gap-5 overflow-x-auto no-scrollbar pb-6 scroll-smooth">
          {items.map((item: any, idx: number) => (
            <NetflixCard key={idx} item={item} {...cardProps} isFavorite={cardProps.favorites.includes(item.LINK)} isWatched={cardProps.watched.includes(item.LINK)} />
          ))}
        </div>
        <button onClick={() => scroll('R')} className="hidden md:block absolute right-0 top-0 bottom-0 z-20 bg-black/60 opacity-0 group-hover/row:opacity-100 transition px-2"><ChevronRight /></button>
      </div>
    </div>
  );
};

const HeroSlider = ({ items, onOpenModal }: { items: ContentItem[], onOpenModal: (item: ContentItem) => void }) => {
  const [current, setCurrent] = useState(0);
  useEffect(() => {
    const timer = setInterval(() => setCurrent(prev => (prev + 1) % items.length), 8000);
    return () => clearInterval(timer);
  }, [items.length]);
  if (items.length === 0) return null;
  return (
    <div className="relative h-[80vh] md:h-[95vh] w-full overflow-hidden bg-black z-10">
      {items.map((item, idx) => (
        <div key={idx} className={`absolute inset-0 transition-opacity duration-1000 ease-in-out ${idx === current ? 'opacity-100 z-10' : 'opacity-0 z-0'}`}>
          <div className={`absolute inset-0 transition-transform duration-[10000ms] ease-linear ${idx === current ? 'scale-110' : 'scale-100'}`}>
            <img src={item.IMAGEM} className="w-full h-full object-cover object-center" alt={item.TITULO} />
          </div>
          <div className="absolute inset-0 bg-gradient-to-r from-black/95 via-black/30 to-transparent" />
          <div className="absolute inset-0 bg-gradient-to-t from-[#141414] via-transparent to-transparent" />
          <div className="absolute inset-0 flex items-center px-6 md:px-12 pt-20">
            <div className="max-w-3xl animate-in fade-in slide-in-from-left-8 duration-1000 relative z-40 pb-20 md:pb-32">
              <div className="flex items-center gap-2 mb-4">
                <span className="bg-purple-600 text-white text-[10px] md:text-xs font-bold px-2 py-1 rounded uppercase tracking-wider shadow-lg">Lançamento</span>
                <span className="text-gray-300 text-xs font-semibold drop-shadow-md">{item.DATA}</span>
              </div>
              <h1 className="text-2xl md:text-4xl lg:text-5xl font-black mb-6 uppercase drop-shadow-2xl leading-[1.2] max-w-sm md:max-w-2xl">{item.TITULO}</h1>
              <p className="text-sm md:text-lg text-gray-200 mb-8 line-clamp-2 md:line-clamp-3 max-w-xs md:max-w-xl font-medium drop-shadow-lg opacity-90">{item.DESCRIÇÃO}</p>
              <div className="flex gap-4 relative z-50">
                <button onClick={(e) => { e.stopPropagation(); window.open(item.LINK, '_blank'); }} className="flex items-center gap-2 bg-white text-black px-6 md:px-10 py-3 rounded font-bold hover:bg-gray-200 transition text-sm md:text-lg shadow-2xl pointer-events-auto">
                  <Play fill="black" size={20}/> Assistir
                </button>
                <button onClick={(e) => { e.stopPropagation(); onOpenModal(item); }} className="flex items-center gap-2 bg-gray-500/50 text-white px-6 md:px-10 py-3 rounded font-bold hover:bg-gray-500/70 transition backdrop-blur-md border border-white/10 text-sm md:text-lg pointer-events-auto">
                  <Info size={20}/> Mais Informações
                </button>
              </div>
            </div>
          </div>
        </div>
      ))}
      <div className="absolute bottom-32 right-12 z-20 hidden md:flex gap-3">
        {items.map((_, idx) => (
          <button key={idx} onClick={() => setCurrent(idx)} className={`h-1.5 transition-all duration-500 rounded-full shadow-lg ${idx === current ? 'w-10 bg-purple-500' : 'w-5 bg-gray-600/50'}`} />
        ))}
      </div>
    </div>
  );
};

function App() {
  const [user, setUser] = useState<any>(null);
  const [profile, setProfile] = useState<string | null>(localStorage.getItem('selectedProfile'));
  const [authLoading, setAuthLoading] = useState(true);
  const [isFetching, setIsFetching] = useState(false);
  const [content, setContent] = useState<ContentItem[]>([]);
  const [favorites, setFavorites] = useState<string[]>([]);
  const [watched, setWatched] = useState<string[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedItem, setSelectedItem] = useState<ContentItem | null>(null);
  const [activeTab, setActiveTab] = useState('home');
  const [showFilters, setShowFilters] = useState(false);
  const [filterMember, setFilterMember] = useState('');
  const [filterYear, setFilterYear] = useState('');
  const [filterCat, setFilterCat] = useState('');
  const [showPassword, setShowPassword] = useState(false);

  useEffect(() => {
    return onAuthStateChanged(auth, async (u) => {
      if (u) {
        setUser(u);
        const docSnap = await getDoc(doc(db, "usuarios", u.uid));
        if (docSnap.exists()) {
          setFavorites(docSnap.data().favorites || []);
          setWatched(docSnap.data().watched || []);
        }
      } else {
        setUser(null);
        setProfile(null);
      }
      setAuthLoading(false);
    });
  }, []);

  useEffect(() => {
    if (user && profile) {
      setIsFetching(true);
      fetch(CONTENT_API)
        .then(r => r.json())
        .then(data => {
          const sorted = data.sort((a: any, b: any) => parseDate(b.DATA).getTime() - parseDate(a.DATA).getTime());
          setContent(sorted);
        })
        .finally(() => setIsFetching(false));
    }
  }, [user, profile]);

  const toggleFavorite = async (link: string) => {
    if (!user) return;
    const userRef = doc(db, "usuarios", user.uid);
    if (favorites.includes(link)) {
      await updateDoc(userRef, { favorites: arrayRemove(link) });
      setFavorites(f => f.filter(i => i !== link));
    } else {
      await updateDoc(userRef, { favorites: arrayUnion(link) });
      setFavorites(f => [...f, link]);
    }
  };

  const toggleWatched = async (link: string) => {
    if (!user) return;
    const userRef = doc(db, "usuarios", user.uid);
    if (watched.includes(link)) {
      await updateDoc(userRef, { watched: arrayRemove(link) });
      setWatched(w => w.filter(i => i !== link));
    } else {
      await updateDoc(userRef, { watched: arrayUnion(link) });
      setWatched(w => [...w, link]);
    }
  };

  const yearsList = useMemo(() => {
    const years = content.map(i => String(i.ANOS || '')).filter(Boolean);
    return Array.from(new Set(years)).sort((a, b) => b.localeCompare(a));
  }, [content]);

  const filteredContent = useMemo(() => {
    let result = content;
    if (searchTerm) {
      const q = searchTerm.toLowerCase();
      result = result.filter(i => i.TITULO.toLowerCase().includes(q) || i.DESCRIÇÃO?.toLowerCase().includes(q));
    }
    if (activeTab === 'fav') result = result.filter(i => favorites.includes(i.LINK));
    if (activeTab === 'watched') result = result.filter(i => watched.includes(i.LINK));
    if (activeTab === 'not-watched') result = result.filter(i => !watched.includes(i.LINK));

    if (filterMember) result = result.filter(i => i.MEMBROS?.toLowerCase().includes(filterMember.toLowerCase()));
    if (filterYear) result = result.filter(i => String(i.ANOS) === filterYear);
    if (filterCat) result = result.filter(i => i.CATEGORIAS?.toLowerCase().includes(filterCat.toLowerCase()));

    return result;
  }, [content, searchTerm, activeTab, favorites, watched, filterMember, filterYear, filterCat]);

  const heroItems = useMemo(() => content.slice(0, 5), [content]);

  const resetFilters = () => {
    setFilterMember('');
    setFilterYear('');
    setFilterCat('');
    setSearchTerm('');
  };

  if (authLoading) return <div className="h-screen bg-black flex items-center justify-center"><Loader2 className="animate-spin text-purple-600" size={50} /></div>;

  if (!user) {
    return (
      <div className="h-screen w-full flex flex-col items-center justify-center bg-[#141414] px-6">
        <div className="bg-black/90 p-10 rounded-2xl w-full max-w-md border border-white/5 shadow-[0_0_80px_rgba(0,0,0,0.9)] text-center">
          <img src="https://bangtannow.com/wp-content/uploads/2025/07/ARMYTVPLUS-LOGO.png" className="w-48 mx-auto mb-10" />
          <form onSubmit={async (e: any) => {
            e.preventDefault();
            try {
              await setPersistence(auth, browserLocalPersistence);
              await signInWithEmailAndPassword(auth, e.target.email.value, e.target.password.value);
            } catch (err: any) { alert("Erro de login. Verifique seus dados."); }
          }} className="space-y-6">
            <input name="email" type="email" placeholder="Email" className="w-full p-4 bg-white/90 rounded-lg outline-none text-black font-medium" required />
            <div className="relative">
              <input name="password" type={showPassword ? "text" : "password"} placeholder="Senha" className="w-full p-4 bg-white/90 rounded-lg outline-none text-black font-medium" required />
              <button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500">{showPassword ? <EyeOff size={20} /> : <Eye size={20} />}</button>
            </div>
            <button type="submit" className="w-full p-4 bg-[#D1A0FF] text-black font-bold rounded-lg hover:bg-purple-300 transition-all uppercase tracking-widest shadow-xl">Entrar</button>
            <div className="mt-6 flex flex-col gap-4">
              <button type="button" onClick={() => { /* logic */ }} className="text-yellow-400 text-sm font-semibold hover:underline">Esqueci minha senha</button>
              <p className="text-sm text-gray-300">Não tem conta? <a href="https://bangtannow.com/assinar-armytv/" target="_blank" className="text-white underline font-bold">Assinar ARMY TV+</a></p>
            </div>
          </form>
        </div>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="min-h-screen bg-[#141414] flex flex-col items-center justify-center animate-in fade-in duration-700 py-16 px-10 overflow-y-auto">
        <h1 className="text-3xl md:text-5xl font-medium mb-12 text-white">Quem está assistindo?</h1>
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-7 gap-8 max-w-7xl">
          {Object.entries(AVATARS).map(([id, url]) => (
            <div key={id} onClick={() => { localStorage.setItem('selectedProfile', id); setProfile(id); }} className="text-center group cursor-pointer">
              <div className="aspect-square rounded-lg overflow-hidden border-[4px] border-transparent group-hover:border-white transition-all shadow-2xl">
                <img src={url} className="w-full h-full object-cover" />
              </div>
              <p className="text-gray-400 group-hover:text-white capitalize text-sm mt-3 font-semibold tracking-wide transition-colors">{id}</p>
            </div>
          ))}
        </div>
        <button onClick={() => { signOut(auth); localStorage.removeItem('selectedProfile'); }} className="mt-16 border border-gray-600 text-gray-500 px-10 py-3 hover:border-white hover:text-white transition-all uppercase text-xs tracking-[0.3em] font-black">Sair da Conta</button>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#141414] text-white">
      <nav className="fixed top-0 w-full z-[110] flex items-center justify-between px-6 md:px-12 py-5 bg-gradient-to-b from-black/90 via-black/40 to-transparent transition-all">
        <div className="flex items-center gap-10">
          <img src="https://bangtannow.com/wp-content/uploads/2025/07/ARMYTVPLUS-LOGO.png" className="h-6 md:h-9 cursor-pointer" onClick={() => { setActiveTab('home'); resetFilters(); }} />
          <ul className="hidden lg:flex gap-8 text-sm font-semibold tracking-wide">
            {['home', 'fav', 'watched', 'not-watched'].map(tab => (
              <li key={tab} className={`cursor-pointer transition-all ${activeTab === tab ? 'text-white' : 'text-gray-400'}`} onClick={() => setActiveTab(tab)}>
                {tab === 'home' ? 'Início' : tab === 'fav' ? 'Minha Lista' : tab === 'watched' ? 'Assistidos' : 'Não Assistidos'}
              </li>
            ))}
          </ul>
        </div>
        <div className="flex items-center gap-4 md:gap-6">
          <div className="relative group hidden md:block">
            <Search className="absolute left-3 top-2.5 text-gray-400" size={16} />
            <input type="text" value={searchTerm} onChange={e => setSearchTerm(e.target.value)} placeholder="Títulos, membros..." className="bg-black/60 border border-white/10 rounded-full py-2 pl-10 pr-4 text-xs w-48 focus:w-72 transition-all outline-none" />
          </div>
          <button onClick={() => setShowFilters(!showFilters)} className={`p-2.5 rounded-full transition-all flex items-center gap-2 ${showFilters ? 'bg-purple-600' : 'text-gray-400'}`}><SlidersHorizontal size={20} /></button>
          <div className="flex items-center gap-3 cursor-pointer" onClick={() => setProfile(null)}>
            <img src={AVATARS[profile] || AVATARS.bts} className="w-8 h-8 md:w-10 md:h-10 rounded border border-white/10" />
          </div>
          <button onClick={() => signOut(auth)} className="text-gray-500 hover:text-white"><LogOut size={20}/></button>
        </div>
      </nav>

      <div className="lg:hidden fixed bottom-0 left-0 right-0 z-[110] bg-black/80 backdrop-blur-2xl border-t border-white/5 flex items-center justify-around py-4">
        <button onClick={() => {setActiveTab('home'); resetFilters();}} className={activeTab === 'home' ? 'text-purple-500' : 'text-gray-500'}><Home size={22} /></button>
        <button onClick={() => setActiveTab('fav')} className={activeTab === 'fav' ? 'text-purple-500' : 'text-gray-500'}><Bookmark size={22} /></button>
        <button onClick={() => setActiveTab('watched')} className={activeTab === 'watched' ? 'text-purple-500' : 'text-gray-500'}><CheckCircle size={22} /></button>
        <button onClick={() => setActiveTab('not-watched')} className={activeTab === 'not-watched' ? 'text-purple-500' : 'text-gray-500'}><PlayCircle size={22} /></button>
      </div>

      <div className={`fixed top-[70px] w-full z-[100] transition-all origin-top ${showFilters ? 'scale-y-100 opacity-100' : 'scale-y-0 opacity-0 pointer-events-none'}`}>
         <div className="px-6 md:px-12 py-6 bg-[#141414]/95 border-b border-white/5 flex flex-wrap gap-8 shadow-2xl">
            <select value={filterMember} onChange={e => setFilterMember(e.target.value)} className="bg-white/5 text-sm rounded px-4 py-2">
              <option value="">Todos os Membros</option>
              {MEMBERS_LIST.map(m => <option key={m} value={m} className="bg-gray-900">{m}</option>)}
            </select>
            <select value={filterYear} onChange={e => setFilterYear(e.target.value)} className="bg-white/5 text-sm rounded px-4 py-2">
              <option value="">Todos os Anos</option>
              {yearsList.map(y => <option key={y} value={y} className="bg-gray-900">{y}</option>)}
            </select>
            <select value={filterCat} onChange={e => setFilterCat(e.target.value)} className="bg-white/5 text-sm rounded px-4 py-2">
              <option value="">Todas as Categorias</option>
              {CATEGORIES_CONFIG.map(c => <option key={c.id} value={c.id} className="bg-gray-900">{c.title}</option>)}
            </select>
         </div>
      </div>

      {activeTab === 'home' && !searchTerm && !filterMember && !filterYear && !filterCat && (
        <HeroSlider items={heroItems} onOpenModal={setSelectedItem} />
      )}

      <div className={`relative z-20 pb-32 ${activeTab === 'home' && !searchTerm && !filterMember && !filterYear && !filterCat ? 'mt-[-80px]' : 'pt-28'}`}>
        {activeTab !== 'home' && (
          <div className="px-6 md:px-12 mb-6">
            <h2 className="text-2xl md:text-3xl font-black text-white uppercase tracking-tight">
              {activeTab === 'fav' ? 'Seus Favoritos' : activeTab === 'watched' ? 'Seus Assistidos' : 'Ainda não assistidos'}
            </h2>
          </div>
        )}
        
        <div className="space-y-2">
          {isFetching ? (
            <div className="flex flex-col items-center justify-center py-40 gap-6">
              <div className="w-16 h-16 border-4 border-purple-600 border-t-transparent rounded-full animate-spin"></div>
            </div>
          ) : filteredContent.length > 0 ? (
            CATEGORIES_CONFIG.map(cat => (
              <Row 
                key={cat.id} title={cat.title} 
                items={filteredContent.filter(i => i.CATEGORIAS?.toLowerCase().includes(cat.id.toLowerCase()))}
                onOpen={setSelectedItem}
                onToggleFavorite={toggleFavorite}
                onToggleWatched={toggleWatched}
                favorites={favorites} 
                watched={watched}
              />
            ))
          ) : (
            <div className="text-center py-48 text-gray-500">Nenhum conteúdo encontrado.</div>
          )}
        </div>
      </div>

      {selectedItem && (
        <div className="fixed inset-0 z-[200] flex justify-center items-start md:items-center bg-black/95 backdrop-blur-xl overflow-y-auto pt-0 md:pt-0">
          <div className="bg-[#181818] w-full max-w-4xl min-h-screen md:min-h-0 md:max-h-[90vh] md:rounded-2xl relative shadow-2xl animate-in slide-in-from-bottom md:zoom-in-95 duration-300">
            {/* Botão de Fechar fixo para Mobile e Absoluto para Desktop */}
            <button 
              onClick={() => setSelectedItem(null)} 
              className="fixed md:absolute top-4 right-4 z-[250] bg-black/70 p-2.5 rounded-full hover:bg-black transition-colors border border-white/20 shadow-xl"
            >
              <X size={24} className="text-white"/>
            </button>
            
            <div className="relative h-64 md:h-[450px]">
              <img src={selectedItem.IMAGEM} className="w-full h-full object-cover" />
              <div className="absolute inset-0 bg-gradient-to-t from-[#181818] via-transparent to-transparent" />
              <div className="absolute bottom-6 left-6 md:left-10 right-6">
                <h2 className="text-xl md:text-4xl font-black mb-6 uppercase leading-tight drop-shadow-lg">{selectedItem.TITULO}</h2>
                <div className="flex gap-4">
                  <button onClick={() => window.open(selectedItem.LINK, '_blank')} className="flex items-center gap-2 bg-white text-black px-8 py-3 rounded-lg font-black hover:bg-gray-200 transition text-sm md:text-base">
                    <Play fill="black" size={18} /> Assistir
                  </button>
                  <button onClick={() => toggleFavorite(selectedItem.LINK)} className={`p-3 rounded-lg border border-white/20 transition ${favorites.includes(selectedItem.LINK) ? 'bg-yellow-500 text-black border-yellow-500' : 'bg-black/40 text-white hover:bg-black/60'}`}>
                    <Star size={20} fill={favorites.includes(selectedItem.LINK) ? "currentColor" : "none"} />
                  </button>
                  <button onClick={() => toggleWatched(selectedItem.LINK)} className={`p-3 rounded-lg border border-white/20 transition ${watched.includes(selectedItem.LINK) ? 'bg-purple-600 text-white border-purple-600 shadow-lg shadow-purple-600/20' : 'bg-black/40 text-white hover:bg-black/60'}`}>
                    <Check size={20} />
                  </button>
                </div>
              </div>
            </div>
            
            <div className="p-6 md:p-10 grid md:grid-cols-3 gap-10">
              <div className="md:col-span-2 space-y-6 pb-12 md:pb-0">
                <div className="flex items-center gap-3 text-sm font-bold">
                  <span className="text-green-500">98% Relevante</span>
                  <span className="text-gray-400 border border-gray-600 px-1 rounded">10+</span>
                  <span className="text-gray-300">{selectedItem.ANOS}</span>
                </div>
                <p className="text-sm md:text-lg text-gray-300 leading-relaxed font-normal">
                  {selectedItem.DESCRIÇÃO || 'Conteúdo exclusivo do BTS! Explore os bastidores, shows e momentos inesquecíveis. 💜'}
                </p>
              </div>
              <div className="space-y-6 text-xs md:text-sm border-t md:border-t-0 md:border-l border-white/5 pt-6 md:pt-0 md:pl-8 pb-10 md:pb-0">
                <div>
                  <span className="text-gray-500 block uppercase font-bold text-[10px] tracking-widest mb-1">Membros</span>
                  <span className="text-gray-100 font-medium">{selectedItem.MEMBROS || 'Todos os membros'}</span>
                </div>
                <div>
                  <span className="text-gray-500 block uppercase font-bold text-[10px] tracking-widest mb-1">Categoria</span>
                  <span className="text-gray-100 font-medium">{selectedItem.CATEGORIAS}</span>
                </div>
                <div>
                  <span className="text-gray-500 block uppercase font-bold text-[10px] tracking-widest mb-1">Lançamento</span>
                  <span className="text-gray-100 font-medium">{selectedItem.DATA}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      <style>{`
        .no-scrollbar::-webkit-scrollbar { display: none; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #141414; }
        ::-webkit-scrollbar-thumb { background: #333; border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: #444; }
        .scrollbar-thin::-webkit-scrollbar { width: 4px; }
      `}</style>
    </div>
  );
}

const rootElement = document.getElementById('root');
if (rootElement) { createRoot(rootElement).render(<App />); }
