import { Plus, Settings, Layers, User, Copy } from 'lucide-react'; import { useState, useEffect, useMemo } from 'react'; import { HDComicViewer } from './components/HDComicViewer'; import { NewMangaModal } from './components/NewMangaModal'; import { SettingsModal } from './components/SettingsModal'; import { AnnouncementBanner } from './components/AnnouncementBanner'; import { ComicDetail } from './components/ComicDetail'; import { ChapterReader } from './components/ChapterReader'; import { InfoPage } from './components/InfoPage'; import { BulkCategoryModal } from './components/BulkCategoryModal'; import { CategoryFilterModal } from './components/CategoryFilterModal'; import { Category } from './types/manga'; import { SearchBar } from './components/SearchBar'; import { SearchResults } from './components/SearchResults'; import { Toaster, toast } from 'sonner'; import { getAllMangas, deleteManga } from './services/manga'; import { Manga, Chapter } from './types/manga'; import { searchItems } from './utils/searchUtils'; import { GlobalFooter } from './components/GlobalFooter'; type SortType = 'random' | 'name' | 'date' | 'pages' | 'modified' | 'views'; type SortDirection = 'asc' | 'desc'; function App() { const [showModal, setShowModal] = useState(false); const [showSettingsModal, setShowSettingsModal] = useState(false); const [showFilterModal, setShowFilterModal] = useState(false); const [isAdmin, setIsAdmin] = useState(false); const [editingManga, setEditingManga] = useState(null); const [isCategoryPlusEnabled, setIsCategoryPlusEnabled] = useState(false); const [isCopyIdsEnabled, setIsCopyIdsEnabled] = useState(false); const [selectedMangaIds, setSelectedMangaIds] = useState([]); const [showBulkModal, setShowBulkModal] = useState(false); const [selectedComicId, setSelectedComicId] = useState(null); const [navigationHistory, setNavigationHistory] = useState([]); const [selectedChapter, setSelectedChapter] = useState<{ manga: Manga; chapter: Chapter } | null>(null); const [mangas, setMangas] = useState([]); const [showHD, setShowHD] = useState(false); const [showInfo, setShowInfo] = useState(false); const [loading, setLoading] = useState(true); const [searchTerm, setSearchTerm] = useState(''); const [selectedCategories, setSelectedCategories] = useState([]); const [selectedAuthors, setSelectedAuthors] = useState([]); const [sortType, setSortType] = useState(() => (localStorage.getItem('sortType') as SortType) || 'modified' ); const [sortDirection, setSortDirection] = useState(() => (localStorage.getItem('sortDirection') as SortDirection) || 'desc' ); useEffect(() => { // Check for admin mode via URL query parameter const searchParams = new URLSearchParams(window.location.search); const isAdminMode = searchParams.get('admin') === 'true'; setIsAdmin(isAdminMode); }, []); useEffect(() => { localStorage.setItem('sortType', sortType); }, [sortType]); useEffect(() => { localStorage.setItem('sortDirection', sortDirection); }, [sortDirection]); useEffect(() => { // Initialize Telegram Web App // @ts-expect-error Window interface is extended in vite-env.d.ts if (window.Telegram?.WebApp) { // @ts-expect-error Window interface is extended in vite-env.d.ts window.Telegram.WebApp.ready(); } loadMangas(); const hash = window.location.hash.slice(1); if (hash && hash.startsWith('manga/')) { if (hash.endsWith('/hd')) { const mangaId = hash.replace('manga/', '').replace('/hd', ''); setSelectedComicId(mangaId); setShowHD(true); } else { const mangaId = hash.replace('manga/', ''); setSelectedComicId(mangaId); setShowHD(false); } } else if (hash === 'info') { setShowInfo(true); } const handleHashChange = () => { const hash = window.location.hash.slice(1); if (!hash) { setSelectedComicId(null); setSelectedChapter(null); setShowInfo(false); setShowHD(false); } else if (hash.startsWith('manga/')) { if (hash.endsWith('/hd')) { const mangaId = hash.replace('manga/', '').replace('/hd', ''); setSelectedComicId(mangaId); setShowHD(true); } else { const mangaId = hash.replace('manga/', ''); setSelectedComicId(mangaId); setShowHD(false); } setSelectedChapter(null); setShowInfo(false); } else if (hash === 'info') { setShowInfo(true); setSelectedComicId(null); setSelectedChapter(null); } }; window.addEventListener('hashchange', handleHashChange); return () => window.removeEventListener('hashchange', handleHashChange); }, []); useEffect(() => { if (!isCategoryPlusEnabled && !isCopyIdsEnabled) { setSelectedMangaIds([]); } }, [isCategoryPlusEnabled, isCopyIdsEnabled]); async function loadMangas() { try { setLoading(true); const data = await getAllMangas(); setMangas(data); } catch (error) { console.error('Error loading mangas:', error); } finally { setLoading(false); } } const allCategories = useMemo(() => { const categoriesMap = new Map(); mangas.forEach(manga => { manga.categories?.forEach(cat => { if (!categoriesMap.has(cat.id)) { categoriesMap.set(cat.id, cat); } }); }); return Array.from(categoriesMap.values()); }, [mangas]); const searchResult = useMemo(() => { if (!searchTerm.trim()) { return { items: mangas, query: '', resultCount: mangas.length }; } return searchItems( mangas.map(m => ({ id: m.id, title: m.title, author: m.author, categories: m.categories ? m.categories.map(c => c.name) : [] })), searchTerm, { fuzzyMatch: true, minChars: 1 } ); }, [mangas, searchTerm]); const filteredMangas = useMemo(() => { let items = searchResult.items.length > 0 ? searchResult.items.map(item => mangas.find(m => m.id === item.id)).filter(Boolean) as Manga[] : []; if (selectedCategories.length > 0) { items = items.filter(m => selectedCategories.some(selCat => m.categories?.some(c => c.name === selCat)) ); } if (selectedAuthors.length > 0) { items = items.filter(m => selectedAuthors.includes(m.author) ); } const sorted = [...items]; if (sortType === 'random') { return sorted.sort(() => Math.random() - 0.5); } sorted.sort((a, b) => { let compareValue = 0; if (sortType === 'name') { compareValue = a.title.localeCompare(b.title); } else if (sortType === 'date') { const dateA = new Date(a.created_at || 0).getTime(); const dateB = new Date(b.created_at || 0).getTime(); compareValue = dateA - dateB; } else if (sortType === 'modified') { const dateA = new Date(a.updated_at || a.created_at || 0).getTime(); const dateB = new Date(b.updated_at || b.created_at || 0).getTime(); compareValue = dateA - dateB; } else if (sortType === 'pages') { const pagesA = a.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0; const pagesB = b.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0; compareValue = pagesA - pagesB; } else if (sortType === 'views') { compareValue = (a.views || 0) - (b.views || 0); } return sortDirection === 'asc' ? compareValue : -compareValue; }); return sorted; }, [mangas, searchTerm, searchResult.items, sortType, sortDirection, selectedCategories, selectedAuthors]); const handleEditManga = (manga: Manga) => { setEditingManga(manga); setShowModal(true); }; const handleDeleteManga = async (mangaId: string) => { try { await deleteManga(mangaId); await loadMangas(); } catch (error) { console.error('Error deleting manga:', error); alert('Error al eliminar el manga. Por favor intenta de nuevo.'); } }; const toggleSelectManga = (id: string, forceSelect?: boolean) => { setSelectedMangaIds(prev => { const isSelected = prev.includes(id); const shouldSelect = forceSelect !== undefined ? forceSelect : !isSelected; if (shouldSelect) { return isSelected ? prev : [...prev, id]; } else { return prev.filter(mId => mId !== id); } }); }; const handleSelectComic = (mangaId: string) => { if (isCategoryPlusEnabled || isCopyIdsEnabled) { toggleSelectManga(mangaId); return; } window.location.hash = `manga/${mangaId}`; setSelectedComicId(mangaId); setShowHD(false); }; const handleBackToHome = () => { window.location.hash = ''; setSelectedComicId(null); setShowInfo(false); }; const handleNavigateToManga = (newMangaId: string) => { if (selectedComicId) { setNavigationHistory([...navigationHistory, selectedComicId]); } window.location.hash = `manga / ${newMangaId} `; setSelectedComicId(newMangaId); }; const handleSelectCategory = (category: string) => { setSelectedCategories(prev => { if (prev.includes(category)) { return prev.filter(c => c !== category); } return [...prev, category]; }); handleBackToHome(); }; const handleRemoveCategory = (category: string) => { setSelectedCategories(prev => prev.filter(c => c !== category)); }; const handleSelectAuthor = (author: string) => { setSelectedAuthors(prev => { if (prev.includes(author)) { return prev.filter(c => c !== author); } return [...prev, author]; }); handleBackToHome(); }; const handleRemoveAuthor = (author: string) => { setSelectedAuthors(prev => prev.filter(c => c !== author)); }; const mangaItems = useMemo(() => filteredMangas.map(manga => { const chapterCount = manga.chapters?.length || 0; const totalPages = manga.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0; return { id: manga.id, title: manga.title, author: manga.author, chapterCount, pageCount: totalPages, thumbnail: manga.cover_url || manga.thumbnail_url || undefined, manga, }; }), [filteredMangas]); if (selectedChapter) { return ( setSelectedChapter(null)} /> ); } if (showInfo) { return ; } if (selectedComicId !== null) { let currentManga = mangas.find(m => m.id === selectedComicId); if (showHD && currentManga) { return ( { window.history.back(); // Fallback if history back doesn't work or we want explicit control: // window.location.hash = `manga / ${ selectedComicId } `; }} /> ); } return ( { if (navigationHistory.length > 0) { const previousId = navigationHistory[navigationHistory.length - 1]; setNavigationHistory(navigationHistory.slice(0, -1)); window.location.hash = `manga / ${previousId} `; setSelectedComicId(previousId); } else { handleBackToHome(); } }} onReadChapter={(chapter) => { if (currentManga) { setSelectedChapter({ manga: currentManga, chapter }); } }} onMangaLoaded={(loadedManga) => { if (!currentManga) { currentManga = loadedManga; } }} onNavigateToManga={handleNavigateToManga} onSelectCategory={handleSelectCategory} onSelectAuthor={handleSelectAuthor} isAdmin={isAdmin} /> ); } return (
Twisted Brody Logo

Twisted Brody MangaFlow

{(isCategoryPlusEnabled || isCopyIdsEnabled) && (
{isCopyIdsEnabled ? 'Modo Copiar Activo' : 'Modo Plus Activo'} {selectedMangaIds.length}
)} {isAdmin && ( <> )}
setShowFilterModal(true)} /> {searchTerm && (
{searchResult.resultCount} resultado{searchResult.resultCount !== 1 ? 's' : ''} encontrado{searchResult.resultCount !== 1 ? 's' : ''}
)} {(selectedCategories.length > 0 || selectedAuthors.length > 0) && (
Filtrado por: {selectedCategories.map(cat => ( ))} {selectedAuthors.map(auth => ( ))} {(selectedCategories.length > 0 || selectedAuthors.length > 0) && ( )}
)}
{false ? (
) : ( <> )}
{/* Bulk Action Bar */} {(isCategoryPlusEnabled || isCopyIdsEnabled) && selectedMangaIds.length > 0 && (
{selectedMangaIds.length} seleccionados Listos para acción
{isCategoryPlusEnabled && ( )} {isCopyIdsEnabled && ( )}
)} { setShowModal(false); setEditingManga(null); }} editingManga={editingManga} onMangaCreated={(mangaId) => { loadMangas(); setEditingManga(null); if (mangaId && !editingManga) { setTimeout(() => { handleSelectComic(mangaId); }, 500); } }} onDelete={isAdmin ? handleDeleteManga : undefined} /> setShowBulkModal(false)} selectedMangaIds={selectedMangaIds} onSaveComplete={() => { loadMangas(); setSelectedMangaIds([]); }} /> setShowSettingsModal(false)} isAdmin={isAdmin} onAdminChange={setIsAdmin} isCategoryPlusEnabled={isCategoryPlusEnabled} onCategoryPlusChange={setIsCategoryPlusEnabled} isCopyIdsEnabled={isCopyIdsEnabled} onCopyIdsChange={setIsCopyIdsEnabled} /> setShowFilterModal(false)} categories={allCategories} selectedCategories={selectedCategories} onToggleCategory={handleSelectCategory} onClearFilters={() => setSelectedCategories([])} />
); } export default App;