dante commited on
Commit
98ddda2
·
verified ·
1 Parent(s): e440f71

Upload 32 files

Browse files
src/App.tsx CHANGED
@@ -1,353 +1,353 @@
1
- import { Plus, Settings } from 'lucide-react';
2
- import { useState, useEffect, useMemo } from 'react';
3
- import { NewMangaModal } from './components/NewMangaModal';
4
- import { SettingsModal } from './components/SettingsModal';
5
- import { AnnouncementBanner } from './components/AnnouncementBanner';
6
- import { ComicDetail } from './components/ComicDetail';
7
- import { ChapterReader } from './components/ChapterReader';
8
- import { InfoPage } from './components/InfoPage';
9
-
10
- import { SearchBar } from './components/SearchBar';
11
- import { SearchResults } from './components/SearchResults';
12
- import { getAllMangas, deleteManga } from './services/manga';
13
- import { Manga, Chapter } from './types/manga';
14
- import { searchItems } from './utils/searchUtils';
15
- import { GlobalFooter } from './components/GlobalFooter';
16
-
17
- type SortType = 'random' | 'name' | 'date' | 'pages' | 'modified' | 'views';
18
- type SortDirection = 'asc' | 'desc';
19
-
20
- function App() {
21
- const [showModal, setShowModal] = useState(false);
22
- const [showSettingsModal, setShowSettingsModal] = useState(false);
23
- const [isAdmin, setIsAdmin] = useState(() => {
24
- return localStorage.getItem('isAdmin') === 'true';
25
- });
26
- const [editingManga, setEditingManga] = useState<Manga | null>(null);
27
- const [selectedComicId, setSelectedComicId] = useState<string | null>(null);
28
- const [navigationHistory, setNavigationHistory] = useState<string[]>([]);
29
- const [selectedChapter, setSelectedChapter] = useState<{ manga: Manga; chapter: Chapter } | null>(null);
30
- const [mangas, setMangas] = useState<Manga[]>([]);
31
- const [showInfo, setShowInfo] = useState(false);
32
- const [loading, setLoading] = useState(true);
33
- const [searchTerm, setSearchTerm] = useState('');
34
- const [sortType, setSortType] = useState<SortType>(() =>
35
- (localStorage.getItem('sortType') as SortType) || 'modified'
36
- );
37
- const [sortDirection, setSortDirection] = useState<SortDirection>(() =>
38
- (localStorage.getItem('sortDirection') as SortDirection) || 'desc'
39
- );
40
-
41
- useEffect(() => {
42
- localStorage.setItem('isAdmin', String(isAdmin));
43
- }, [isAdmin]);
44
-
45
- useEffect(() => {
46
- localStorage.setItem('sortType', sortType);
47
- }, [sortType]);
48
-
49
- useEffect(() => {
50
- localStorage.setItem('sortDirection', sortDirection);
51
- }, [sortDirection]);
52
-
53
- useEffect(() => {
54
- // Initialize Telegram Web App
55
- // @ts-expect-error Window interface is extended in vite-env.d.ts
56
- if (window.Telegram?.WebApp) {
57
- // @ts-expect-error Window interface is extended in vite-env.d.ts
58
- window.Telegram.WebApp.ready();
59
- }
60
- loadMangas();
61
-
62
- const hash = window.location.hash.slice(1);
63
- if (hash && hash.startsWith('manga/')) {
64
- const mangaId = hash.replace('manga/', '');
65
- setSelectedComicId(mangaId);
66
- } else if (hash === 'info') {
67
- setShowInfo(true);
68
- }
69
-
70
- const handleHashChange = () => {
71
- const hash = window.location.hash.slice(1);
72
- if (!hash) {
73
- setSelectedComicId(null);
74
- setSelectedChapter(null);
75
- setShowInfo(false);
76
- } else if (hash.startsWith('manga/')) {
77
- const mangaId = hash.replace('manga/', '');
78
- setSelectedComicId(mangaId);
79
- setSelectedChapter(null);
80
- setShowInfo(false);
81
- } else if (hash === 'info') {
82
- setShowInfo(true);
83
- setSelectedComicId(null);
84
- setSelectedChapter(null);
85
- }
86
- };
87
-
88
- window.addEventListener('hashchange', handleHashChange);
89
- return () => window.removeEventListener('hashchange', handleHashChange);
90
- }, []);
91
-
92
- async function loadMangas() {
93
- try {
94
- setLoading(true);
95
- const data = await getAllMangas();
96
- setMangas(data);
97
- } catch (error) {
98
- console.error('Error loading mangas:', error);
99
- } finally {
100
- setLoading(false);
101
- }
102
- }
103
-
104
- const searchResult = useMemo(() => {
105
- if (!searchTerm.trim()) {
106
- return { items: mangas, query: '', resultCount: mangas.length };
107
- }
108
- return searchItems(
109
- mangas.map(m => ({ id: m.id, title: m.title, author: m.author })),
110
- searchTerm,
111
- { fuzzyMatch: true, minChars: 1 }
112
- );
113
- }, [mangas, searchTerm]);
114
-
115
- const filteredMangas = useMemo(() => {
116
- let items = searchResult.items.length > 0
117
- ? searchResult.items.map(item => mangas.find(m => m.id === item.id)).filter(Boolean) as Manga[]
118
- : [];
119
-
120
- const sorted = [...items];
121
-
122
- if (sortType === 'random') {
123
- return sorted.sort(() => Math.random() - 0.5);
124
- }
125
-
126
- sorted.sort((a, b) => {
127
- let compareValue = 0;
128
-
129
- if (sortType === 'name') {
130
- compareValue = a.title.localeCompare(b.title);
131
- } else if (sortType === 'date') {
132
- const dateA = new Date(a.created_at || 0).getTime();
133
- const dateB = new Date(b.created_at || 0).getTime();
134
- compareValue = dateA - dateB;
135
- } else if (sortType === 'modified') {
136
- const dateA = new Date(a.updated_at || a.created_at || 0).getTime();
137
- const dateB = new Date(b.updated_at || b.created_at || 0).getTime();
138
- compareValue = dateA - dateB;
139
- } else if (sortType === 'pages') {
140
- const pagesA = a.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0;
141
- const pagesB = b.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0;
142
- compareValue = pagesA - pagesB;
143
- } else if (sortType === 'views') {
144
- compareValue = (a.views || 0) - (b.views || 0);
145
- }
146
-
147
- return sortDirection === 'asc' ? compareValue : -compareValue;
148
- });
149
-
150
- return sorted;
151
- }, [mangas, searchTerm, searchResult.items, sortType, sortDirection]);
152
-
153
- const handleEditManga = (manga: Manga) => {
154
- setEditingManga(manga);
155
- setShowModal(true);
156
- };
157
-
158
- const handleDeleteManga = async (mangaId: string) => {
159
- try {
160
- await deleteManga(mangaId);
161
- await loadMangas();
162
- } catch (error) {
163
- console.error('Error deleting manga:', error);
164
- alert('Error al eliminar el manga. Por favor intenta de nuevo.');
165
- }
166
- };
167
-
168
- const handleSelectComic = (mangaId: string) => {
169
- window.location.hash = `manga/${mangaId}`;
170
- setSelectedComicId(mangaId);
171
- };
172
-
173
- const handleBackToHome = () => {
174
- window.location.hash = '';
175
- setSelectedComicId(null);
176
- setShowInfo(false);
177
- };
178
-
179
- const handleNavigateToManga = (newMangaId: string) => {
180
- if (selectedComicId) {
181
- setNavigationHistory([...navigationHistory, selectedComicId]);
182
- }
183
- window.location.hash = `manga/${newMangaId}`;
184
- setSelectedComicId(newMangaId);
185
- };
186
-
187
- const mangaItems = useMemo(() => filteredMangas.map(manga => {
188
- const chapterCount = manga.chapters?.length || 0;
189
- const totalPages = manga.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0;
190
- return {
191
- id: manga.id,
192
- title: manga.title,
193
- author: manga.author,
194
- chapterCount,
195
- pageCount: totalPages,
196
- thumbnail: manga.cover_url || manga.thumbnail_url || undefined,
197
- manga,
198
- };
199
- }), [filteredMangas]);
200
-
201
- if (selectedChapter) {
202
- return (
203
- <ChapterReader
204
- manga={selectedChapter.manga}
205
- chapter={selectedChapter.chapter}
206
- onBack={() => setSelectedChapter(null)}
207
- />
208
- );
209
- }
210
-
211
- if (showInfo) {
212
- return <InfoPage onBack={handleBackToHome} isAdmin={isAdmin} />;
213
- }
214
-
215
- if (selectedComicId !== null) {
216
- let currentManga = mangas.find(m => m.id === selectedComicId);
217
- return (
218
- <ComicDetail
219
- id={selectedComicId}
220
- onBack={() => {
221
- if (navigationHistory.length > 0) {
222
- const previousId = navigationHistory[navigationHistory.length - 1];
223
- setNavigationHistory(navigationHistory.slice(0, -1));
224
- window.location.hash = `manga/${previousId}`;
225
- setSelectedComicId(previousId);
226
- } else {
227
- handleBackToHome();
228
- }
229
- }}
230
- onReadChapter={(chapter) => {
231
- if (currentManga) {
232
- setSelectedChapter({ manga: currentManga, chapter });
233
- }
234
- }}
235
- onMangaLoaded={(loadedManga) => {
236
- if (!currentManga) {
237
- currentManga = loadedManga;
238
- }
239
- }}
240
- onNavigateToManga={handleNavigateToManga}
241
- isAdmin={isAdmin}
242
- />
243
- );
244
- }
245
-
246
- return (
247
- <div className="min-h-screen bg-[#121212] text-white flex flex-col">
248
- <header className="border-b border-gray-800/50 px-3 sm:px-6 md:px-12 py-4 sm:py-6 flex-shrink-0 transition-all duration-300">
249
- <div className="max-w-[1800px] mx-auto flex items-center justify-between gap-2 sm:gap-0">
250
- <div className="flex items-center gap-1 sm:gap-1.5 group cursor-pointer">
251
- <img
252
- src="/icons/icones.png"
253
- alt="Twisted Brody Logo"
254
- className="w-10 h-10 sm:w-14 sm:h-14 object-contain transition-all duration-300 group-hover:rotate-12 group-hover:scale-110"
255
- />
256
- <h1 className="text-lg sm:text-2xl font-bold text-white transition-colors duration-300 group-hover:text-[#bb86fc]">
257
- Twisted Brody MangaFlow
258
- </h1>
259
- </div>
260
- <div className="flex items-center gap-1.5 sm:gap-3">
261
- <button
262
- onClick={() => setShowSettingsModal(true)}
263
- className="bg-gray-800 hover:bg-gray-700 active:scale-95 text-white px-2 py-2 sm:px-4 sm:py-2.5 rounded-lg flex items-center gap-1.5 sm:gap-2 font-semibold transition-all duration-300 border border-gray-700/50 hover:border-gray-600 text-xs sm:text-sm hover:scale-110 hover:shadow-lg hover:shadow-gray-700/50"
264
- title="Ajustes y Admin"
265
- >
266
- <Settings className="w-4 h-4 sm:w-5 sm:h-5 transition-transform duration-300 hover:rotate-180" />
267
- <span className="hidden sm:inline">Ajustes</span>
268
- </button>
269
- <button
270
- onClick={() => setShowModal(true)}
271
- className="bg-purple-600 hover:bg-purple-700 active:scale-95 text-white px-2 py-2 sm:px-4 sm:py-2.5 rounded-lg flex items-center gap-1.5 sm:gap-2 font-semibold transition-all duration-300 shadow-lg shadow-purple-600/30 hover:shadow-purple-600/50 text-xs sm:text-sm hover:scale-110"
272
- >
273
- <Plus className="w-4 h-4 sm:w-5 sm:h-5 transition-transform duration-300 hover:rotate-180" />
274
- <span className="hidden sm:inline">Nuevo Manga</span>
275
- </button>
276
- </div>
277
- </div>
278
- </header>
279
-
280
- <main className="flex-1 px-4 sm:px-6 md:px-12 py-8">
281
- <AnnouncementBanner isAdmin={isAdmin} />
282
-
283
- <div className="max-w-[1800px] mx-auto mb-8 flex-shrink-0">
284
- <SearchBar
285
- value={searchTerm}
286
- onChange={setSearchTerm}
287
- placeholder="Buscar por título, autor..."
288
- sortType={sortType}
289
- onSortTypeChange={setSortType}
290
- sortDirection={sortDirection}
291
- onSortDirectionChange={setSortDirection}
292
- />
293
- {searchTerm && (
294
- <div className="mt-2 text-sm text-gray-400">
295
- {searchResult.resultCount} resultado{searchResult.resultCount !== 1 ? 's' : ''} encontrado{searchResult.resultCount !== 1 ? 's' : ''}
296
- </div>
297
- )}
298
- </div>
299
-
300
- <div className="max-w-[1800px] mx-auto">
301
- {false ? (
302
- <div className="hidden"></div>
303
- ) : (
304
- <>
305
- <link rel="preconnect" href="https://i.ibb.co" />
306
- <SearchResults
307
- items={mangaItems}
308
- searchTerm={searchTerm}
309
- isSearching={false}
310
- isLoading={loading}
311
- onSelectComic={handleSelectComic}
312
- onEditManga={isAdmin ? handleEditManga : undefined}
313
- onDeleteManga={isAdmin ? handleDeleteManga : undefined}
314
- />
315
- </>
316
- )}
317
- </div>
318
- </main>
319
-
320
- <GlobalFooter />
321
-
322
- <NewMangaModal
323
- isOpen={showModal}
324
- onClose={() => {
325
- setShowModal(false);
326
- setEditingManga(null);
327
- }}
328
- editingManga={editingManga}
329
- onMangaCreated={(mangaId) => {
330
- loadMangas();
331
- setEditingManga(null);
332
- if (mangaId && !editingManga) {
333
- setTimeout(() => {
334
- handleSelectComic(mangaId);
335
- }, 500);
336
- }
337
- }}
338
- onDelete={isAdmin ? handleDeleteManga : undefined}
339
- />
340
-
341
- <SettingsModal
342
- isOpen={showSettingsModal}
343
- onClose={() => setShowSettingsModal(false)}
344
- isAdmin={isAdmin}
345
- onAdminChange={setIsAdmin}
346
- />
347
-
348
-
349
- </div>
350
- );
351
- }
352
-
353
- export default App;
 
1
+ import { Plus, Settings } from 'lucide-react';
2
+ import { useState, useEffect, useMemo } from 'react';
3
+ import { NewMangaModal } from './components/NewMangaModal';
4
+ import { SettingsModal } from './components/SettingsModal';
5
+ import { AnnouncementBanner } from './components/AnnouncementBanner';
6
+ import { ComicDetail } from './components/ComicDetail';
7
+ import { ChapterReader } from './components/ChapterReader';
8
+ import { InfoPage } from './components/InfoPage';
9
+
10
+ import { SearchBar } from './components/SearchBar';
11
+ import { SearchResults } from './components/SearchResults';
12
+ import { getAllMangas, deleteManga } from './services/manga';
13
+ import { Manga, Chapter } from './types/manga';
14
+ import { searchItems } from './utils/searchUtils';
15
+ import { GlobalFooter } from './components/GlobalFooter';
16
+
17
+ type SortType = 'random' | 'name' | 'date' | 'pages' | 'modified' | 'views';
18
+ type SortDirection = 'asc' | 'desc';
19
+
20
+ function App() {
21
+ const [showModal, setShowModal] = useState(false);
22
+ const [showSettingsModal, setShowSettingsModal] = useState(false);
23
+ const [isAdmin, setIsAdmin] = useState(() => {
24
+ return localStorage.getItem('isAdmin') === 'true';
25
+ });
26
+ const [editingManga, setEditingManga] = useState<Manga | null>(null);
27
+ const [selectedComicId, setSelectedComicId] = useState<string | null>(null);
28
+ const [navigationHistory, setNavigationHistory] = useState<string[]>([]);
29
+ const [selectedChapter, setSelectedChapter] = useState<{ manga: Manga; chapter: Chapter } | null>(null);
30
+ const [mangas, setMangas] = useState<Manga[]>([]);
31
+ const [showInfo, setShowInfo] = useState(false);
32
+ const [loading, setLoading] = useState(true);
33
+ const [searchTerm, setSearchTerm] = useState('');
34
+ const [sortType, setSortType] = useState<SortType>(() =>
35
+ (localStorage.getItem('sortType') as SortType) || 'modified'
36
+ );
37
+ const [sortDirection, setSortDirection] = useState<SortDirection>(() =>
38
+ (localStorage.getItem('sortDirection') as SortDirection) || 'desc'
39
+ );
40
+
41
+ useEffect(() => {
42
+ localStorage.setItem('isAdmin', String(isAdmin));
43
+ }, [isAdmin]);
44
+
45
+ useEffect(() => {
46
+ localStorage.setItem('sortType', sortType);
47
+ }, [sortType]);
48
+
49
+ useEffect(() => {
50
+ localStorage.setItem('sortDirection', sortDirection);
51
+ }, [sortDirection]);
52
+
53
+ useEffect(() => {
54
+ // Initialize Telegram Web App
55
+ // @ts-expect-error Window interface is extended in vite-env.d.ts
56
+ if (window.Telegram?.WebApp) {
57
+ // @ts-expect-error Window interface is extended in vite-env.d.ts
58
+ window.Telegram.WebApp.ready();
59
+ }
60
+ loadMangas();
61
+
62
+ const hash = window.location.hash.slice(1);
63
+ if (hash && hash.startsWith('manga/')) {
64
+ const mangaId = hash.replace('manga/', '');
65
+ setSelectedComicId(mangaId);
66
+ } else if (hash === 'info') {
67
+ setShowInfo(true);
68
+ }
69
+
70
+ const handleHashChange = () => {
71
+ const hash = window.location.hash.slice(1);
72
+ if (!hash) {
73
+ setSelectedComicId(null);
74
+ setSelectedChapter(null);
75
+ setShowInfo(false);
76
+ } else if (hash.startsWith('manga/')) {
77
+ const mangaId = hash.replace('manga/', '');
78
+ setSelectedComicId(mangaId);
79
+ setSelectedChapter(null);
80
+ setShowInfo(false);
81
+ } else if (hash === 'info') {
82
+ setShowInfo(true);
83
+ setSelectedComicId(null);
84
+ setSelectedChapter(null);
85
+ }
86
+ };
87
+
88
+ window.addEventListener('hashchange', handleHashChange);
89
+ return () => window.removeEventListener('hashchange', handleHashChange);
90
+ }, []);
91
+
92
+ async function loadMangas() {
93
+ try {
94
+ setLoading(true);
95
+ const data = await getAllMangas();
96
+ setMangas(data);
97
+ } catch (error) {
98
+ console.error('Error loading mangas:', error);
99
+ } finally {
100
+ setLoading(false);
101
+ }
102
+ }
103
+
104
+ const searchResult = useMemo(() => {
105
+ if (!searchTerm.trim()) {
106
+ return { items: mangas, query: '', resultCount: mangas.length };
107
+ }
108
+ return searchItems(
109
+ mangas.map(m => ({ id: m.id, title: m.title, author: m.author })),
110
+ searchTerm,
111
+ { fuzzyMatch: true, minChars: 1 }
112
+ );
113
+ }, [mangas, searchTerm]);
114
+
115
+ const filteredMangas = useMemo(() => {
116
+ let items = searchResult.items.length > 0
117
+ ? searchResult.items.map(item => mangas.find(m => m.id === item.id)).filter(Boolean) as Manga[]
118
+ : [];
119
+
120
+ const sorted = [...items];
121
+
122
+ if (sortType === 'random') {
123
+ return sorted.sort(() => Math.random() - 0.5);
124
+ }
125
+
126
+ sorted.sort((a, b) => {
127
+ let compareValue = 0;
128
+
129
+ if (sortType === 'name') {
130
+ compareValue = a.title.localeCompare(b.title);
131
+ } else if (sortType === 'date') {
132
+ const dateA = new Date(a.created_at || 0).getTime();
133
+ const dateB = new Date(b.created_at || 0).getTime();
134
+ compareValue = dateA - dateB;
135
+ } else if (sortType === 'modified') {
136
+ const dateA = new Date(a.updated_at || a.created_at || 0).getTime();
137
+ const dateB = new Date(b.updated_at || b.created_at || 0).getTime();
138
+ compareValue = dateA - dateB;
139
+ } else if (sortType === 'pages') {
140
+ const pagesA = a.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0;
141
+ const pagesB = b.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0;
142
+ compareValue = pagesA - pagesB;
143
+ } else if (sortType === 'views') {
144
+ compareValue = (a.views || 0) - (b.views || 0);
145
+ }
146
+
147
+ return sortDirection === 'asc' ? compareValue : -compareValue;
148
+ });
149
+
150
+ return sorted;
151
+ }, [mangas, searchTerm, searchResult.items, sortType, sortDirection]);
152
+
153
+ const handleEditManga = (manga: Manga) => {
154
+ setEditingManga(manga);
155
+ setShowModal(true);
156
+ };
157
+
158
+ const handleDeleteManga = async (mangaId: string) => {
159
+ try {
160
+ await deleteManga(mangaId);
161
+ await loadMangas();
162
+ } catch (error) {
163
+ console.error('Error deleting manga:', error);
164
+ alert('Error al eliminar el manga. Por favor intenta de nuevo.');
165
+ }
166
+ };
167
+
168
+ const handleSelectComic = (mangaId: string) => {
169
+ window.location.hash = `manga/${mangaId}`;
170
+ setSelectedComicId(mangaId);
171
+ };
172
+
173
+ const handleBackToHome = () => {
174
+ window.location.hash = '';
175
+ setSelectedComicId(null);
176
+ setShowInfo(false);
177
+ };
178
+
179
+ const handleNavigateToManga = (newMangaId: string) => {
180
+ if (selectedComicId) {
181
+ setNavigationHistory([...navigationHistory, selectedComicId]);
182
+ }
183
+ window.location.hash = `manga/${newMangaId}`;
184
+ setSelectedComicId(newMangaId);
185
+ };
186
+
187
+ const mangaItems = useMemo(() => filteredMangas.map(manga => {
188
+ const chapterCount = manga.chapters?.length || 0;
189
+ const totalPages = manga.chapters?.reduce((sum: number, ch: any) => sum + (ch.pages?.length || 0), 0) || 0;
190
+ return {
191
+ id: manga.id,
192
+ title: manga.title,
193
+ author: manga.author,
194
+ chapterCount,
195
+ pageCount: totalPages,
196
+ thumbnail: manga.cover_url || manga.thumbnail_url || undefined,
197
+ manga,
198
+ };
199
+ }), [filteredMangas]);
200
+
201
+ if (selectedChapter) {
202
+ return (
203
+ <ChapterReader
204
+ manga={selectedChapter.manga}
205
+ chapter={selectedChapter.chapter}
206
+ onBack={() => setSelectedChapter(null)}
207
+ />
208
+ );
209
+ }
210
+
211
+ if (showInfo) {
212
+ return <InfoPage onBack={handleBackToHome} isAdmin={isAdmin} />;
213
+ }
214
+
215
+ if (selectedComicId !== null) {
216
+ let currentManga = mangas.find(m => m.id === selectedComicId);
217
+ return (
218
+ <ComicDetail
219
+ id={selectedComicId}
220
+ onBack={() => {
221
+ if (navigationHistory.length > 0) {
222
+ const previousId = navigationHistory[navigationHistory.length - 1];
223
+ setNavigationHistory(navigationHistory.slice(0, -1));
224
+ window.location.hash = `manga/${previousId}`;
225
+ setSelectedComicId(previousId);
226
+ } else {
227
+ handleBackToHome();
228
+ }
229
+ }}
230
+ onReadChapter={(chapter) => {
231
+ if (currentManga) {
232
+ setSelectedChapter({ manga: currentManga, chapter });
233
+ }
234
+ }}
235
+ onMangaLoaded={(loadedManga) => {
236
+ if (!currentManga) {
237
+ currentManga = loadedManga;
238
+ }
239
+ }}
240
+ onNavigateToManga={handleNavigateToManga}
241
+ isAdmin={isAdmin}
242
+ />
243
+ );
244
+ }
245
+
246
+ return (
247
+ <div className="min-h-screen bg-[#121212] text-white flex flex-col">
248
+ <header className="border-b border-gray-800/50 px-3 sm:px-6 md:px-12 py-4 sm:py-6 flex-shrink-0 transition-all duration-300">
249
+ <div className="max-w-[1800px] mx-auto flex items-center justify-between gap-2 sm:gap-0">
250
+ <div className="flex items-center gap-1 sm:gap-1.5 group cursor-pointer">
251
+ <img
252
+ src="/icons/icones.png"
253
+ alt="Twisted Brody Logo"
254
+ className="w-10 h-10 sm:w-14 sm:h-14 object-contain transition-all duration-300 group-hover:rotate-12 group-hover:scale-110"
255
+ />
256
+ <h1 className="text-lg sm:text-2xl font-bold text-white transition-colors duration-300 group-hover:text-[#bb86fc]">
257
+ Twisted Brody MangaFlow
258
+ </h1>
259
+ </div>
260
+ <div className="flex items-center gap-1.5 sm:gap-3">
261
+ <button
262
+ onClick={() => setShowSettingsModal(true)}
263
+ className="bg-gray-800 hover:bg-gray-700 active:scale-95 text-white px-2 py-2 sm:px-4 sm:py-2.5 rounded-lg flex items-center gap-1.5 sm:gap-2 font-semibold transition-all duration-300 border border-gray-700/50 hover:border-gray-600 text-xs sm:text-sm hover:scale-110 hover:shadow-lg hover:shadow-gray-700/50"
264
+ title="Ajustes y Admin"
265
+ >
266
+ <Settings className="w-4 h-4 sm:w-5 sm:h-5 transition-transform duration-300 hover:rotate-180" />
267
+ <span className="hidden sm:inline">Ajustes</span>
268
+ </button>
269
+ <button
270
+ onClick={() => setShowModal(true)}
271
+ className="bg-purple-600 hover:bg-purple-700 active:scale-95 text-white px-2 py-2 sm:px-4 sm:py-2.5 rounded-lg flex items-center gap-1.5 sm:gap-2 font-semibold transition-all duration-300 shadow-lg shadow-purple-600/30 hover:shadow-purple-600/50 text-xs sm:text-sm hover:scale-110"
272
+ >
273
+ <Plus className="w-4 h-4 sm:w-5 sm:h-5 transition-transform duration-300 hover:rotate-180" />
274
+ <span className="hidden sm:inline">Nuevo Manga</span>
275
+ </button>
276
+ </div>
277
+ </div>
278
+ </header>
279
+
280
+ <main className="flex-1 px-4 sm:px-6 md:px-12 py-8">
281
+ <AnnouncementBanner isAdmin={isAdmin} />
282
+
283
+ <div className="max-w-[1800px] mx-auto mb-8 flex-shrink-0">
284
+ <SearchBar
285
+ value={searchTerm}
286
+ onChange={setSearchTerm}
287
+ placeholder="Buscar por título, autor..."
288
+ sortType={sortType}
289
+ onSortTypeChange={setSortType}
290
+ sortDirection={sortDirection}
291
+ onSortDirectionChange={setSortDirection}
292
+ />
293
+ {searchTerm && (
294
+ <div className="mt-2 text-sm text-gray-400">
295
+ {searchResult.resultCount} resultado{searchResult.resultCount !== 1 ? 's' : ''} encontrado{searchResult.resultCount !== 1 ? 's' : ''}
296
+ </div>
297
+ )}
298
+ </div>
299
+
300
+ <div className="max-w-[1800px] mx-auto">
301
+ {false ? (
302
+ <div className="hidden"></div>
303
+ ) : (
304
+ <>
305
+ <link rel="preconnect" href="https://i.ibb.co" />
306
+ <SearchResults
307
+ items={mangaItems}
308
+ searchTerm={searchTerm}
309
+ isSearching={false}
310
+ isLoading={loading}
311
+ onSelectComic={handleSelectComic}
312
+ onEditManga={isAdmin ? handleEditManga : undefined}
313
+ onDeleteManga={isAdmin ? handleDeleteManga : undefined}
314
+ />
315
+ </>
316
+ )}
317
+ </div>
318
+ </main>
319
+
320
+ <GlobalFooter />
321
+
322
+ <NewMangaModal
323
+ isOpen={showModal}
324
+ onClose={() => {
325
+ setShowModal(false);
326
+ setEditingManga(null);
327
+ }}
328
+ editingManga={editingManga}
329
+ onMangaCreated={(mangaId) => {
330
+ loadMangas();
331
+ setEditingManga(null);
332
+ if (mangaId && !editingManga) {
333
+ setTimeout(() => {
334
+ handleSelectComic(mangaId);
335
+ }, 500);
336
+ }
337
+ }}
338
+ onDelete={isAdmin ? handleDeleteManga : undefined}
339
+ />
340
+
341
+ <SettingsModal
342
+ isOpen={showSettingsModal}
343
+ onClose={() => setShowSettingsModal(false)}
344
+ isAdmin={isAdmin}
345
+ onAdminChange={setIsAdmin}
346
+ />
347
+
348
+
349
+ </div>
350
+ );
351
+ }
352
+
353
+ export default App;
src/components/AnnouncementBanner.tsx CHANGED
@@ -1,91 +1,91 @@
1
- import { useState, useEffect } from 'react';
2
- import { Megaphone, Timer } from 'lucide-react';
3
- import { subscribeToAnnouncement } from '../services/announcement';
4
-
5
- interface AnnouncementBannerProps {
6
- isAdmin?: boolean;
7
- }
8
-
9
- export function AnnouncementBanner({ isAdmin }: AnnouncementBannerProps) {
10
- const [announcement, setAnnouncement] = useState<string>('');
11
- const [expiresAt, setExpiresAt] = useState<string | null>(null);
12
- const [timeLeft, setTimeLeft] = useState<string>('');
13
- const [isLoading, setIsLoading] = useState(true);
14
-
15
- useEffect(() => {
16
- const unsubscribe = subscribeToAnnouncement((data) => {
17
- if (data) {
18
- setAnnouncement(data.text);
19
- setExpiresAt(data.expiresAt);
20
- } else {
21
- setAnnouncement('');
22
- setExpiresAt(null);
23
- }
24
- setIsLoading(false);
25
- });
26
-
27
- return () => unsubscribe();
28
- }, []);
29
-
30
- useEffect(() => {
31
- if (!expiresAt) {
32
- setTimeLeft('');
33
- return;
34
- }
35
-
36
- const interval = setInterval(() => {
37
- const now = new Date().getTime();
38
- const expiration = new Date(expiresAt).getTime();
39
- const difference = expiration - now;
40
-
41
- if (difference <= 0) {
42
- setAnnouncement('');
43
- setExpiresAt(null);
44
- clearInterval(interval);
45
- } else {
46
- const days = Math.floor(difference / (1000 * 60 * 60 * 24));
47
- const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
48
- const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
49
- const seconds = Math.floor((difference % (1000 * 60)) / 1000);
50
-
51
- let timeString = '';
52
- if (days > 0) timeString += `${days}d `;
53
- timeString += `${hours.toString().padStart(2, '0')}h ${minutes.toString().padStart(2, '0')}m ${seconds.toString().padStart(2, '0')}s`;
54
- setTimeLeft(timeString);
55
- }
56
- }, 1000);
57
-
58
- return () => clearInterval(interval);
59
- }, [expiresAt]);
60
-
61
- if (!announcement && !isLoading) return null;
62
- if (!announcement) return null;
63
-
64
- return (
65
- <div className="w-full max-w-[1800px] mx-auto px-4 sm:px-6 md:px-12 mt-6 mb-8 animate-in fade-in slide-in-from-top-4 duration-500 flex justify-center">
66
- <div className="bg-gradient-to-r from-[#bb86fc]/20 to-[#121212] border border-[#bb86fc]/30 rounded-xl p-6 flex flex-col items-center gap-4 shadow-lg shadow-[#bb86fc]/10 relative group backdrop-blur-sm max-w-2xl w-full text-center">
67
-
68
- <div className="flex items-center gap-3">
69
- <div className="p-2.5 bg-[#bb86fc]/20 rounded-lg animate-pulse">
70
- <Megaphone className="w-6 h-6 text-[#bb86fc]" />
71
- </div>
72
- <h3 className="text-sm font-bold text-[#bb86fc] uppercase tracking-wider flex items-center gap-2">
73
- Información Importante
74
- <span className="w-2 h-2 rounded-full bg-[#bb86fc] animate-ping" />
75
- </h3>
76
- </div>
77
-
78
- <div className="text-base text-gray-200 leading-relaxed whitespace-pre-wrap font-medium max-w-lg">
79
- {announcement}
80
- </div>
81
-
82
- {timeLeft && (
83
- <div className="flex items-center gap-2 text-xs font-mono text-gray-400 bg-black/30 px-3 py-1.5 rounded-full border border-gray-800">
84
- <Timer className="w-3.5 h-3.5" />
85
- <span>Expira en: {timeLeft}</span>
86
- </div>
87
- )}
88
- </div>
89
- </div>
90
- );
91
- }
 
1
+ import { useState, useEffect } from 'react';
2
+ import { Megaphone, Timer } from 'lucide-react';
3
+ import { subscribeToAnnouncement } from '../services/announcement';
4
+
5
+ interface AnnouncementBannerProps {
6
+ isAdmin?: boolean;
7
+ }
8
+
9
+ export function AnnouncementBanner({ isAdmin }: AnnouncementBannerProps) {
10
+ const [announcement, setAnnouncement] = useState<string>('');
11
+ const [expiresAt, setExpiresAt] = useState<string | null>(null);
12
+ const [timeLeft, setTimeLeft] = useState<string>('');
13
+ const [isLoading, setIsLoading] = useState(true);
14
+
15
+ useEffect(() => {
16
+ const unsubscribe = subscribeToAnnouncement((data) => {
17
+ if (data) {
18
+ setAnnouncement(data.text);
19
+ setExpiresAt(data.expiresAt);
20
+ } else {
21
+ setAnnouncement('');
22
+ setExpiresAt(null);
23
+ }
24
+ setIsLoading(false);
25
+ });
26
+
27
+ return () => unsubscribe();
28
+ }, []);
29
+
30
+ useEffect(() => {
31
+ if (!expiresAt) {
32
+ setTimeLeft('');
33
+ return;
34
+ }
35
+
36
+ const interval = setInterval(() => {
37
+ const now = new Date().getTime();
38
+ const expiration = new Date(expiresAt).getTime();
39
+ const difference = expiration - now;
40
+
41
+ if (difference <= 0) {
42
+ setAnnouncement('');
43
+ setExpiresAt(null);
44
+ clearInterval(interval);
45
+ } else {
46
+ const days = Math.floor(difference / (1000 * 60 * 60 * 24));
47
+ const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
48
+ const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
49
+ const seconds = Math.floor((difference % (1000 * 60)) / 1000);
50
+
51
+ let timeString = '';
52
+ if (days > 0) timeString += `${days}d `;
53
+ timeString += `${hours.toString().padStart(2, '0')}h ${minutes.toString().padStart(2, '0')}m ${seconds.toString().padStart(2, '0')}s`;
54
+ setTimeLeft(timeString);
55
+ }
56
+ }, 1000);
57
+
58
+ return () => clearInterval(interval);
59
+ }, [expiresAt]);
60
+
61
+ if (!announcement && !isLoading) return null;
62
+ if (!announcement) return null;
63
+
64
+ return (
65
+ <div className="w-full max-w-[1800px] mx-auto px-4 sm:px-6 md:px-12 mt-6 mb-8 animate-in fade-in slide-in-from-top-4 duration-500 flex justify-center">
66
+ <div className="bg-gradient-to-r from-[#bb86fc]/20 to-[#121212] border border-[#bb86fc]/30 rounded-xl p-6 flex flex-col items-center gap-4 shadow-lg shadow-[#bb86fc]/10 relative group backdrop-blur-sm max-w-2xl w-full text-center">
67
+
68
+ <div className="flex items-center gap-3">
69
+ <div className="p-2.5 bg-[#bb86fc]/20 rounded-lg animate-pulse">
70
+ <Megaphone className="w-6 h-6 text-[#bb86fc]" />
71
+ </div>
72
+ <h3 className="text-sm font-bold text-[#bb86fc] uppercase tracking-wider flex items-center gap-2">
73
+ Información Importante
74
+ <span className="w-2 h-2 rounded-full bg-[#bb86fc] animate-ping" />
75
+ </h3>
76
+ </div>
77
+
78
+ <div className="text-base text-gray-200 leading-relaxed whitespace-pre-wrap font-medium max-w-lg">
79
+ {announcement}
80
+ </div>
81
+
82
+ {timeLeft && (
83
+ <div className="flex items-center gap-2 text-xs font-mono text-gray-400 bg-black/30 px-3 py-1.5 rounded-full border border-gray-800">
84
+ <Timer className="w-3.5 h-3.5" />
85
+ <span>Expira en: {timeLeft}</span>
86
+ </div>
87
+ )}
88
+ </div>
89
+ </div>
90
+ );
91
+ }
src/components/ChapterReader.tsx CHANGED
@@ -1,119 +1,119 @@
1
- import { ArrowLeft, ChevronLeft, ChevronRight } from 'lucide-react';
2
- import { useState } from 'react';
3
- import { Chapter, Manga } from '../types/manga';
4
- import { ImageLoader } from './ImageLoader';
5
- import { GlobalFooter } from './GlobalFooter';
6
-
7
- interface ChapterReaderProps {
8
- manga: Manga;
9
- chapter: Chapter;
10
- onBack: () => void;
11
- }
12
-
13
- export function ChapterReader({ manga, chapter, onBack }: ChapterReaderProps) {
14
- const [currentPageIndex, setCurrentPageIndex] = useState(0);
15
-
16
- if (!chapter.pages || chapter.pages.length === 0) {
17
- return (
18
- <div className="h-screen bg-[#121212] flex flex-col items-center justify-center">
19
- <button
20
- onClick={onBack}
21
- className="absolute top-6 left-6 p-2 hover:bg-[#333] rounded-lg transition-colors text-gray-300 hover:text-white"
22
- >
23
- <ArrowLeft className="w-5 h-5" />
24
- </button>
25
- <div className="text-gray-400 text-lg">No hay páginas disponibles</div>
26
- </div>
27
- );
28
- }
29
-
30
- const handlePrevPage = () => {
31
- if (currentPageIndex > 0) setCurrentPageIndex(currentPageIndex - 1);
32
- };
33
-
34
- const handleNextPage = () => {
35
- if (currentPageIndex < chapter.pages.length - 1) setCurrentPageIndex(currentPageIndex + 1);
36
- };
37
-
38
-
39
- return (
40
- <div className="h-screen flex flex-col bg-[#121212] overflow-hidden">
41
- <header className="border-b border-gray-700/60 bg-gradient-to-r from-[#2a2a2a] to-[#252525] px-6 py-4 flex-shrink-0">
42
- <div className="max-w-7xl mx-auto flex items-center justify-between">
43
- <div className="flex items-center gap-4">
44
- <button
45
- onClick={onBack}
46
- className="p-2 hover:bg-[#333] rounded-lg transition-colors text-gray-300 hover:text-white"
47
- >
48
- <ArrowLeft className="w-5 h-5" />
49
- </button>
50
- <div>
51
- <h1 className="text-lg font-bold text-white">{manga.title}</h1>
52
- <p className="text-sm text-gray-400">{chapter.title}</p>
53
- </div>
54
- </div>
55
- <div className="text-sm text-gray-400">
56
- {currentPageIndex + 1} / {chapter.pages.length}
57
- </div>
58
- </div>
59
- </header>
60
-
61
- <main className="flex-1 overflow-y-auto bg-[#121212]">
62
- <div className="flex flex-col items-center gap-4 w-full py-8">
63
- {chapter.pages.map((page, index) => (
64
- <div key={index} className="w-full flex justify-center">
65
- <ImageLoader
66
- src={page}
67
- alt={`Página ${index + 1}`}
68
- aspectRatio="auto"
69
- objectFit="contain"
70
- loading="eager"
71
- className="max-w-full shadow-2xl"
72
- showPlaceholder={index > 0}
73
- />
74
- </div>
75
- ))}
76
- <div className="w-full mt-8">
77
- <GlobalFooter />
78
- </div>
79
- </div>
80
- </main>
81
-
82
- <div className="border-t border-gray-700/60 bg-gradient-to-r from-[#2a2a2a] to-[#252525] px-6 py-6 flex-shrink-0">
83
- <div className="max-w-7xl mx-auto flex items-center justify-between">
84
- <button
85
- onClick={handlePrevPage}
86
- disabled={currentPageIndex === 0}
87
- className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-800 hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-white transition-all"
88
- >
89
- <ChevronLeft className="w-5 h-5" />
90
- Anterior
91
- </button>
92
-
93
- <div className="flex items-center gap-2">
94
- <input
95
- type="range"
96
- min="0"
97
- max={chapter.pages.length - 1}
98
- value={currentPageIndex}
99
- onChange={(e) => setCurrentPageIndex(parseInt(e.target.value))}
100
- className="w-64 h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-[#bb86fc]"
101
- />
102
- <span className="text-sm text-gray-400 w-12 text-right">
103
- {currentPageIndex + 1}/{chapter.pages.length}
104
- </span>
105
- </div>
106
-
107
- <button
108
- onClick={handleNextPage}
109
- disabled={currentPageIndex === chapter.pages.length - 1}
110
- className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-800 hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-white transition-all"
111
- >
112
- Siguiente
113
- <ChevronRight className="w-5 h-5" />
114
- </button>
115
- </div>
116
- </div>
117
- </div >
118
- );
119
- }
 
1
+ import { ArrowLeft, ChevronLeft, ChevronRight } from 'lucide-react';
2
+ import { useState } from 'react';
3
+ import { Chapter, Manga } from '../types/manga';
4
+ import { ImageLoader } from './ImageLoader';
5
+ import { GlobalFooter } from './GlobalFooter';
6
+
7
+ interface ChapterReaderProps {
8
+ manga: Manga;
9
+ chapter: Chapter;
10
+ onBack: () => void;
11
+ }
12
+
13
+ export function ChapterReader({ manga, chapter, onBack }: ChapterReaderProps) {
14
+ const [currentPageIndex, setCurrentPageIndex] = useState(0);
15
+
16
+ if (!chapter.pages || chapter.pages.length === 0) {
17
+ return (
18
+ <div className="h-screen bg-[#121212] flex flex-col items-center justify-center">
19
+ <button
20
+ onClick={onBack}
21
+ className="absolute top-6 left-6 p-2 hover:bg-[#333] rounded-lg transition-colors text-gray-300 hover:text-white"
22
+ >
23
+ <ArrowLeft className="w-5 h-5" />
24
+ </button>
25
+ <div className="text-gray-400 text-lg">No hay páginas disponibles</div>
26
+ </div>
27
+ );
28
+ }
29
+
30
+ const handlePrevPage = () => {
31
+ if (currentPageIndex > 0) setCurrentPageIndex(currentPageIndex - 1);
32
+ };
33
+
34
+ const handleNextPage = () => {
35
+ if (currentPageIndex < chapter.pages.length - 1) setCurrentPageIndex(currentPageIndex + 1);
36
+ };
37
+
38
+
39
+ return (
40
+ <div className="h-screen flex flex-col bg-[#121212] overflow-hidden">
41
+ <header className="border-b border-gray-700/60 bg-gradient-to-r from-[#2a2a2a] to-[#252525] px-6 py-4 flex-shrink-0">
42
+ <div className="max-w-7xl mx-auto flex items-center justify-between">
43
+ <div className="flex items-center gap-4">
44
+ <button
45
+ onClick={onBack}
46
+ className="p-2 hover:bg-[#333] rounded-lg transition-colors text-gray-300 hover:text-white"
47
+ >
48
+ <ArrowLeft className="w-5 h-5" />
49
+ </button>
50
+ <div>
51
+ <h1 className="text-lg font-bold text-white">{manga.title}</h1>
52
+ <p className="text-sm text-gray-400">{chapter.title}</p>
53
+ </div>
54
+ </div>
55
+ <div className="text-sm text-gray-400">
56
+ {currentPageIndex + 1} / {chapter.pages.length}
57
+ </div>
58
+ </div>
59
+ </header>
60
+
61
+ <main className="flex-1 overflow-y-auto bg-[#121212]">
62
+ <div className="flex flex-col items-center gap-4 w-full py-8">
63
+ {chapter.pages.map((page, index) => (
64
+ <div key={index} className="w-full flex justify-center">
65
+ <ImageLoader
66
+ src={page}
67
+ alt={`Página ${index + 1}`}
68
+ aspectRatio="auto"
69
+ objectFit="contain"
70
+ loading="eager"
71
+ className="max-w-full shadow-2xl"
72
+ showPlaceholder={index > 0}
73
+ />
74
+ </div>
75
+ ))}
76
+ <div className="w-full mt-8">
77
+ <GlobalFooter />
78
+ </div>
79
+ </div>
80
+ </main>
81
+
82
+ <div className="border-t border-gray-700/60 bg-gradient-to-r from-[#2a2a2a] to-[#252525] px-6 py-6 flex-shrink-0">
83
+ <div className="max-w-7xl mx-auto flex items-center justify-between">
84
+ <button
85
+ onClick={handlePrevPage}
86
+ disabled={currentPageIndex === 0}
87
+ className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-800 hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-white transition-all"
88
+ >
89
+ <ChevronLeft className="w-5 h-5" />
90
+ Anterior
91
+ </button>
92
+
93
+ <div className="flex items-center gap-2">
94
+ <input
95
+ type="range"
96
+ min="0"
97
+ max={chapter.pages.length - 1}
98
+ value={currentPageIndex}
99
+ onChange={(e) => setCurrentPageIndex(parseInt(e.target.value))}
100
+ className="w-64 h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-[#bb86fc]"
101
+ />
102
+ <span className="text-sm text-gray-400 w-12 text-right">
103
+ {currentPageIndex + 1}/{chapter.pages.length}
104
+ </span>
105
+ </div>
106
+
107
+ <button
108
+ onClick={handleNextPage}
109
+ disabled={currentPageIndex === chapter.pages.length - 1}
110
+ className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-800 hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-white transition-all"
111
+ >
112
+ Siguiente
113
+ <ChevronRight className="w-5 h-5" />
114
+ </button>
115
+ </div>
116
+ </div>
117
+ </div >
118
+ );
119
+ }
src/components/ComicDetail.tsx CHANGED
@@ -1,968 +1,968 @@
1
- import { ArrowLeft, BookMarked, User, Download, Link as LinkIcon, X, Plus, Rows, Grid2X2, Grid3X3, FileText, Search, Send, Check, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, Eye } from 'lucide-react';
2
- import { GlobalFooter } from './GlobalFooter';
3
-
4
- import { useState, useEffect } from 'react';
5
- import { getMangaById, incrementMangaViews, addExternalLink, removeExternalLink, getRecommendations, getAllMangas, subscribeToManga } from '../services/manga';
6
- import { Manga } from '../types/manga';
7
- import { detectImageOrientation } from '../utils/imageOptimization';
8
- import { LoadingSpinner } from './LoadingSpinner';
9
- import { ImageLightbox } from './ImageLightbox';
10
- import { ImageLoader } from './ImageLoader';
11
- import { MangaCard } from './MangaCard';
12
-
13
- interface ComicDetailProps {
14
- id: string;
15
- onBack: () => void;
16
- onReadChapter?: (chapter: any) => void;
17
- onMangaLoaded?: (manga: Manga) => void;
18
- onNavigateToManga?: (mangaId: string) => void;
19
- isAdmin?: boolean;
20
- }
21
-
22
- export function ComicDetail({ id, onBack, onNavigateToManga, onMangaLoaded, isAdmin = false }: ComicDetailProps) {
23
- const [manga, setManga] = useState<Manga | null>(null);
24
- const [loading, setLoading] = useState(true);
25
- const [downloading, setDownloading] = useState(false);
26
- const [downloadProgress, setDownloadProgress] = useState(0);
27
- const [showDownloadMenu, setShowDownloadMenu] = useState(false);
28
- const [showPdfMenu, setShowPdfMenu] = useState(false);
29
- const [downloadingPdf, setDownloadingPdf] = useState(false);
30
- const [pdfProgress, setPdfProgress] = useState(0);
31
- const [showExternalLinkModal, setShowExternalLinkModal] = useState(false);
32
- const [externalLinkForm, setExternalLinkForm] = useState({ name: '', url: '' });
33
- const [externalLinks, setExternalLinks] = useState<Array<{ name: string; url: string }>>([]);
34
- const [coverOrientation, setCoverOrientation] = useState<'portrait' | 'landscape' | 'square'>('portrait');
35
- const [viewMode, setViewMode] = useState<'vertical' | 'gallery' | 'grid'>('vertical');
36
- const [lightboxOpen, setLightboxOpen] = useState(false);
37
- const [lightboxIndex, setLightboxIndex] = useState(0);
38
- // const [loadedImages, setLoadedImages] = useState<Set<number>>(new Set());
39
- const [recommendations, setRecommendations] = useState<Manga[]>([]);
40
- const [loadingRecommendations, setLoadingRecommendations] = useState(false);
41
- const [searchTerm, setSearchTerm] = useState('');
42
- const [allMangas, setAllMangas] = useState<Manga[]>([]);
43
- const [loadingAllMangas, setLoadingAllMangas] = useState(false);
44
- const [copiedId, setCopiedId] = useState(false);
45
- const [recPage, setRecPage] = useState(1);
46
- const REC_ITEMS_PER_PAGE = 6;
47
-
48
- useEffect(() => {
49
- // Initial fetch for loading state and increment logic
50
- loadMangaAndInit();
51
-
52
- // Subscribe for real-time updates (views, etc)
53
- const unsubscribe = subscribeToManga(id, (updatedManga) => {
54
- if (updatedManga) {
55
- setManga(() => {
56
- // Determine if we need to update orientation or other heavy stuff?
57
- // For now, just update the data.
58
- // Keep existing derived state if needed? No, just full replacement is safer for data consistency.
59
- return updatedManga;
60
- });
61
- // If it was the first load, we might need to trigger recommendations if we haven't
62
- // But loadMangaAndInit handles that.
63
- setLoading(false);
64
- }
65
- });
66
-
67
- loadAllMangasForSearch();
68
- setSearchTerm('');
69
- const savedViewMode = localStorage.getItem('manga-view-mode');
70
- if (savedViewMode === 'vertical' || savedViewMode === 'gallery' || savedViewMode === 'grid') {
71
- setViewMode(savedViewMode);
72
- }
73
-
74
- return () => unsubscribe();
75
- }, [id]);
76
-
77
- async function loadAllMangasForSearch() {
78
- try {
79
- setLoadingAllMangas(true);
80
- const mangas = await getAllMangas();
81
- setAllMangas(mangas);
82
- } catch (error) {
83
- console.error('Error loading all mangas:', error);
84
- } finally {
85
- setLoadingAllMangas(false);
86
- }
87
- }
88
-
89
- useEffect(() => {
90
- function handleClickOutside(event: MouseEvent) {
91
- const target = event.target as HTMLElement;
92
- if (showDownloadMenu && !target.closest('.download-menu-container')) {
93
- setShowDownloadMenu(false);
94
- }
95
- if (showPdfMenu && !target.closest('.pdf-menu-container')) {
96
- setShowPdfMenu(false);
97
- }
98
- }
99
-
100
- document.addEventListener('mousedown', handleClickOutside);
101
- return () => document.removeEventListener('mousedown', handleClickOutside);
102
- }, [showDownloadMenu, showPdfMenu]);
103
-
104
- const handleAddExternalLink = async () => {
105
- if (externalLinkForm.name.trim() && externalLinkForm.url.trim() && manga) {
106
- try {
107
- await addExternalLink(manga.id, externalLinkForm);
108
- setExternalLinks([...externalLinks, externalLinkForm]);
109
- setExternalLinkForm({ name: '', url: '' });
110
- setShowExternalLinkModal(false);
111
- } catch (error) {
112
- console.error('Error al guardar el enlace:', error);
113
- alert('Error al guardar el enlace');
114
- }
115
- }
116
- };
117
-
118
- const handleRemoveExternalLink = async (index: number) => {
119
- if (manga) {
120
- try {
121
- await removeExternalLink(manga.id, index);
122
- setExternalLinks(externalLinks.filter((_, i) => i !== index));
123
- } catch (error) {
124
- console.error('Error al eliminar el enlace:', error);
125
- alert('Error al eliminar el enlace');
126
- }
127
- }
128
- };
129
-
130
- const handleViewModeChange = (mode: 'vertical' | 'gallery' | 'grid') => {
131
- setViewMode(mode);
132
- localStorage.setItem('manga-view-mode', mode);
133
- };
134
-
135
- async function loadMangaAndInit() {
136
- try {
137
- setLoading(true);
138
-
139
- // We still fetch initially...
140
- const data = await getMangaById(id);
141
- if (data) {
142
- setManga(data);
143
- setExternalLinks(data.external_links || []);
144
-
145
- if (data.cover_url) {
146
- try {
147
- const orientation = await detectImageOrientation(data.cover_url);
148
- setCoverOrientation(orientation);
149
- } catch (error) {
150
- console.warn('Failed to detect image orientation:', error);
151
- setCoverOrientation('portrait');
152
- }
153
- }
154
-
155
- loadRecommendations(data);
156
- }
157
- } catch (error) {
158
- console.error('Error loading manga:', error);
159
- } finally {
160
- // setLoading(false);
161
- }
162
- }
163
-
164
- async function loadRecommendations(currentManga: Manga) {
165
- try {
166
- setLoadingRecommendations(true);
167
- const categoryIds = currentManga.categories?.map(cat => cat.id) || [];
168
- const recs = await getRecommendations(currentManga.id, categoryIds, currentManga.title);
169
- setRecommendations(recs);
170
- setRecPage(1);
171
- } catch (error) {
172
- console.error('Error loading recommendations:', error);
173
- } finally {
174
- setLoadingRecommendations(false);
175
- }
176
- }
177
-
178
- async function handleDownload(format: 'png' | 'jpg' | 'webp' | 'original') {
179
- const targetId = manga?.id || id;
180
-
181
- if (!targetId) {
182
- alert('Error: ID no encontrado.');
183
- return;
184
- }
185
-
186
- const jobId = targetId; // Usamos el ID como identificador de la tarea
187
-
188
- // 1. Abrimos el canal de progreso (SSE)
189
- console.log(`🚀 [CLIENTE] Suscribiendo a progreso: ${jobId}`);
190
- const eventSource = new EventSource(`/api/download/progress/${jobId}`);
191
-
192
- eventSource.onmessage = (event) => {
193
- const data = JSON.parse(event.data);
194
- // console.log("⚡ [PROGRESO]:", data.progress);
195
- setDownloadProgress(data.progress);
196
-
197
- if (data.progress >= 100) {
198
- eventSource.close();
199
- }
200
- };
201
-
202
- try {
203
- console.log("🚀 [CLIENTE] Iniciando descarga para ID:", targetId);
204
- setDownloading(true);
205
- setShowDownloadMenu(false);
206
- setDownloadProgress(0);
207
-
208
- const response = await fetch('/api/download/zip', {
209
- method: 'POST',
210
- headers: { 'Content-Type': 'application/json' },
211
- body: JSON.stringify({
212
- mangaId: targetId,
213
- mangaTitle: manga?.title || 'Descarga',
214
- format: format,
215
- jobId: jobId // Though server uses mangaId mostly now, consistent
216
- }),
217
- });
218
-
219
- if (!response.ok) throw new Error("Error en el servidor");
220
-
221
- const blob = await response.blob();
222
- const urlDownload = window.URL.createObjectURL(blob);
223
- const a = document.createElement('a');
224
- a.href = urlDownload;
225
- a.download = `${manga?.title || 'manga'}.zip`;
226
- document.body.appendChild(a);
227
- a.click();
228
- a.remove();
229
- window.URL.revokeObjectURL(urlDownload);
230
-
231
- console.log("✅ [CLIENTE] Descarga disparada con éxito");
232
-
233
- } catch (error) {
234
- console.error("❌ Error en la descarga:", error);
235
- alert("Hubo un fallo en la matriz de descarga.");
236
- } finally {
237
- setDownloading(false);
238
- eventSource.close();
239
- }
240
- }
241
-
242
- async function handleDownloadPdf(format: 'png' | 'jpg' | 'webp' | 'original') {
243
- const targetId = manga?.id || id;
244
- if (!targetId) {
245
- alert('Error: ID no encontrado.');
246
- return;
247
- }
248
-
249
- const jobId = targetId;
250
-
251
- console.log(`🚀 [CLIENTE] Suscribiendo a progreso PDF: ${jobId}`);
252
- const eventSource = new EventSource(`/api/download/progress/${jobId}`);
253
-
254
- eventSource.onmessage = (event) => {
255
- const data = JSON.parse(event.data);
256
- if (data.progress) {
257
- setPdfProgress(data.progress);
258
- }
259
- if (data.progress >= 100) {
260
- eventSource.close();
261
- }
262
- };
263
-
264
- try {
265
- console.log("🚀 [CLIENTE] Iniciando PDF para ID:", targetId);
266
- setDownloadingPdf(true);
267
- setPdfProgress(0);
268
- setShowPdfMenu(false);
269
-
270
- const response = await fetch('/api/download/pdf', {
271
- method: 'POST',
272
- headers: { 'Content-Type': 'application/json' },
273
- body: JSON.stringify({
274
- mangaId: targetId,
275
- mangaTitle: manga?.title || 'Descarga',
276
- format: format,
277
- jobId: jobId
278
- }),
279
- });
280
-
281
- if (!response.ok) throw new Error("Error en el servidor al generar PDF");
282
-
283
- const blob = await response.blob();
284
- const urlDownload = window.URL.createObjectURL(blob);
285
- const a = document.createElement('a');
286
- a.href = urlDownload;
287
- a.download = `${manga?.title || 'manga'}.pdf`;
288
- document.body.appendChild(a);
289
- a.click();
290
- a.remove();
291
- window.URL.revokeObjectURL(urlDownload);
292
-
293
- console.log("✅ [CLIENTE] PDF descargado con éxito");
294
-
295
- } catch (error) {
296
- console.error('Error initiating PDF generation:', error);
297
- alert('Error al generar PDF (puede que el archivo sea muy grande o Python falló).');
298
- } finally {
299
- setDownloadingPdf(false);
300
- eventSource.close();
301
- }
302
- }
303
-
304
-
305
- if (loading) {
306
- return (
307
- <div className="h-screen bg-[#121212] flex flex-col items-center justify-center gap-4">
308
- <LoadingSpinner size={40} borderWidth={2} />
309
- <div className="text-gray-400 text-sm">Cargando...</div>
310
- </div>
311
- );
312
- }
313
-
314
- if (!manga) {
315
- return (
316
- <div className="h-screen bg-[#121212] flex items-center justify-center">
317
- <div className="text-gray-400 text-lg">Manga no encontrado</div>
318
- </div>
319
- );
320
- }
321
-
322
- const filteredMangas = searchTerm.trim()
323
- ? allMangas.filter(m => {
324
- if (!m.id || !m.title || m.id === manga.id) return false;
325
- const searchLower = searchTerm.toLowerCase();
326
- const titleMatch = m.title.toLowerCase().includes(searchLower);
327
- const authorMatch = m.author ? m.author.toLowerCase().includes(searchLower) : false;
328
- const categoryMatch = m.categories?.some(cat => cat?.name?.toLowerCase().includes(searchLower)) || false;
329
- return titleMatch || authorMatch || categoryMatch;
330
- })
331
- : [];
332
-
333
- return (
334
- <div className="h-screen flex flex-col bg-[#121212] overflow-hidden">
335
- <header className="border-b border-gray-800 z-40 bg-[#121212] flex-shrink-0">
336
- <div className="max-w-7xl mx-auto px-4 sm:px-6 py-3 sm:py-4 flex items-center gap-3 sm:gap-4">
337
- <button
338
- onClick={onBack}
339
- className="p-2 hover:bg-[#333] rounded-lg transition-colors text-gray-300 hover:text-white flex-shrink-0"
340
- >
341
- <ArrowLeft className="w-5 h-5" />
342
- </button>
343
- <h1 className="text-base sm:text-lg font-bold text-white truncate flex-shrink-0">{manga.title}</h1>
344
- <div className="flex-1 max-w-md ml-auto">
345
- <div className="relative">
346
- <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
347
- <input
348
- type="text"
349
- placeholder="Buscar comics…"
350
- value={searchTerm}
351
- onChange={(e) => setSearchTerm(e.target.value)}
352
- className="w-full bg-[#1a1a1a] text-white rounded-lg pl-10 pr-3 py-2 text-sm placeholder-gray-400 focus:ring-2 focus:ring-[#bb86fc] focus:outline-none transition-all border border-gray-700/50 focus:border-[#bb86fc]"
353
- />
354
- </div>
355
- </div>
356
- </div>
357
- </header>
358
-
359
- <main className="flex-1 overflow-y-auto bg-[#121212]">
360
- <div className="max-w-7xl mx-auto px-4 sm:px-6 py-4 sm:py-8">
361
- {!searchTerm.trim() && (
362
- <div className="flex flex-col sm:flex-row gap-4 sm:gap-6">
363
- <div className="flex-shrink-0 mx-auto sm:mx-0">
364
- <div className="group w-56 sm:w-64">
365
- <div className="relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]">
366
- {manga.cover_url ? (
367
- <>
368
- <ImageLoader
369
- src={manga.cover_url}
370
- alt={manga.title}
371
- aspectRatio="2/3"
372
- objectFit="cover"
373
- loading="eager"
374
- imgClassName="group-hover:scale-110"
375
- />
376
- <div className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 ease-in-out pointer-events-none"></div>
377
- </>
378
- ) : (
379
- <div className="w-full aspect-[2/3] flex items-center justify-center text-white/40 bg-black">
380
- <BookMarked className="w-16 h-16" />
381
- </div>
382
- )}
383
- </div>
384
- </div>
385
- </div>
386
-
387
- <div className="flex-1 min-w-0">
388
- <h2 className="text-2xl sm:text-4xl font-bold text-white mb-3 sm:mb-4">{manga.title}</h2>
389
-
390
- <div className="mb-4">
391
- <div className="flex items-center gap-2 text-gray-300">
392
- {manga.author && manga.author.toLowerCase() !== 'anónimo' && manga.author.toLowerCase() !== 'anonimo' && (
393
- <>
394
- <User className="w-4 h-4 text-[#bb86fc]" />
395
- <span className="text-sm">{manga.author}</span>
396
- <div className="w-1 h-1 bg-gray-600 rounded-full mx-2"></div>
397
- </>
398
- )}
399
- <Eye className="w-4 h-4 text-[#bb86fc]" />
400
- <span className="text-sm">{manga.views?.toLocaleString() || 0} vistas</span>
401
- </div>
402
- </div>
403
-
404
- <div className="mb-6">
405
- <h3 className="text-sm font-semibold text-gray-300 mb-3">Categorías</h3>
406
- <div className="flex gap-2 flex-wrap">
407
- {manga.categories?.map((cat) => (
408
- <span
409
- key={cat.id}
410
- className="px-3 py-1.5 bg-[#bb86fc]/20 text-[#bb86fc] text-xs rounded-full border border-[#bb86fc]/40"
411
- >
412
- {cat.name}
413
- </span>
414
- ))}
415
- </div>
416
- </div>
417
-
418
- {manga.description && manga.description.trim() !== '' && (
419
- <div className="mb-6">
420
- <h3 className="text-sm font-semibold text-gray-300 mb-2">Sinopsis</h3>
421
- <p className="text-sm text-gray-400 leading-relaxed whitespace-pre-wrap">
422
- {manga.description}
423
- </p>
424
- </div>
425
- )}
426
-
427
- <div className="flex flex-col gap-3 sm:gap-4">
428
- {manga.chapters && manga.chapters.length > 0 && manga.chapters[0].pages && manga.chapters[0].pages.length > 0 && (
429
- <>
430
- {downloading && (
431
- <div className="w-full">
432
- <div className="flex items-center justify-between mb-2">
433
- <span className="text-xs sm:text-sm font-semibold text-[#bb86fc]">Descargando ZIP</span>
434
- <span className="text-xs sm:text-sm font-bold text-[#bb86fc]">{downloadProgress}%</span>
435
- </div>
436
- <div className="w-full bg-gray-700/40 rounded-full h-2 overflow-hidden border border-[#bb86fc]/30">
437
- <div
438
- className="bg-gradient-to-r from-[#bb86fc] to-[#9966dd] h-full transition-all duration-300 ease-out"
439
- style={{ width: `${downloadProgress}%` }}
440
- />
441
- </div>
442
- </div>
443
- )}
444
- {downloadingPdf && (
445
- <div className="w-full">
446
- <div className="flex items-center justify-between mb-2">
447
- <span className="text-xs sm:text-sm font-semibold text-[#bb86fc]">Generando PDF</span>
448
- <span className="text-xs sm:text-sm font-bold text-[#bb86fc]">{pdfProgress}%</span>
449
- </div>
450
- <div className="w-full bg-gray-700/40 rounded-full h-2 overflow-hidden border border-[#bb86fc]/30">
451
- <div
452
- className="bg-gradient-to-r from-[#bb86fc] to-[#9966dd] h-full transition-all duration-300 ease-out"
453
- style={{ width: `${pdfProgress}%` }}
454
- />
455
- </div>
456
- </div>
457
- )}
458
- <div className="flex flex-wrap gap-2 items-center">
459
- <div className="relative download-menu-container">
460
- <button
461
- onClick={() => setShowDownloadMenu(!showDownloadMenu)}
462
- disabled={downloading}
463
- className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1 font-semibold text-xs sm:text-sm transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
464
- >
465
- <Download className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
466
- <span className="hidden sm:inline">{downloading ? `Descargando (${downloadProgress}%)` : 'ZIP'}</span>
467
- <span className="sm:hidden">ZIP</span>
468
- </button>
469
-
470
- {showDownloadMenu && !downloading && (
471
- <div className="absolute top-full mt-2 left-0 bg-[#1f1f1f] border border-gray-700/60 rounded-lg shadow-2xl shadow-black/50 overflow-hidden z-50 min-w-[200px]">
472
- <button
473
- onClick={() => handleDownload('original')}
474
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
475
- >
476
- <Download className="w-3 h-3 text-[#bb86fc]" />
477
- <div>
478
- <div className="font-semibold">Original</div>
479
- <div className="text-xs text-gray-400">Sin cambios</div>
480
- </div>
481
- </button>
482
- <button
483
- onClick={() => handleDownload('webp')}
484
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
485
- >
486
- <Download className="w-3 h-3 text-[#bb86fc]" />
487
- <div>
488
- <div className="font-semibold">WebP</div>
489
- <div className="text-xs text-gray-400">Optimizado</div>
490
- </div>
491
- </button>
492
- <button
493
- onClick={() => handleDownload('png')}
494
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
495
- >
496
- <Download className="w-3 h-3 text-[#bb86fc]" />
497
- <div>
498
- <div className="font-semibold">PNG</div>
499
- <div className="text-xs text-gray-400">Sin pérdida</div>
500
- </div>
501
- </button>
502
- <button
503
- onClick={() => handleDownload('jpg')}
504
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2"
505
- >
506
- <Download className="w-3 h-3 text-[#bb86fc]" />
507
- <div>
508
- <div className="font-semibold">JPG</div>
509
- <div className="text-xs text-gray-400">Comprimido</div>
510
- </div>
511
- </button>
512
- </div>
513
- )}
514
- </div>
515
-
516
- <div className="relative pdf-menu-container">
517
- <button
518
- onClick={() => setShowPdfMenu(!showPdfMenu)}
519
- disabled={downloadingPdf}
520
- className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1 font-semibold text-xs sm:text-sm transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
521
- >
522
- <FileText className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
523
- <span className="hidden sm:inline">{downloadingPdf ? `Generando (${pdfProgress}%)` : 'PDF'}</span>
524
- <span className="sm:hidden">PDF</span>
525
- </button>
526
-
527
- {showPdfMenu && !downloadingPdf && (
528
- <div className="absolute top-full mt-2 left-0 bg-[#1f1f1f] border border-gray-700/60 rounded-lg shadow-2xl shadow-black/50 overflow-hidden z-50 min-w-[200px]">
529
- <button
530
- onClick={() => handleDownloadPdf('original')}
531
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
532
- >
533
- <FileText className="w-3 h-3 text-[#bb86fc]" />
534
- <div>
535
- <div className="font-semibold">Original</div>
536
- <div className="text-xs text-gray-400">Sin cambios</div>
537
- </div>
538
- </button>
539
- <button
540
- onClick={() => handleDownloadPdf('webp')}
541
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
542
- >
543
- <FileText className="w-3 h-3 text-[#bb86fc]" />
544
- <div>
545
- <div className="font-semibold">WebP</div>
546
- <div className="text-xs text-gray-400">Optimizado</div>
547
- </div>
548
- </button>
549
- <button
550
- onClick={() => handleDownloadPdf('png')}
551
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
552
- >
553
- <FileText className="w-3 h-3 text-[#bb86fc]" />
554
- <div>
555
- <div className="font-semibold">PNG</div>
556
- <div className="text-xs text-gray-400">Sin pérdida</div>
557
- </div>
558
- </button>
559
- <button
560
- onClick={() => handleDownloadPdf('jpg')}
561
- className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2"
562
- >
563
- <FileText className="w-3 h-3 text-[#bb86fc]" />
564
- <div>
565
- <div className="font-semibold">JPG</div>
566
- <div className="text-xs text-gray-400">Comprimido</div>
567
- </div>
568
- </button>
569
- </div>
570
- )}
571
- </div>
572
-
573
- <button
574
- onClick={async () => {
575
- try {
576
- await navigator.clipboard.writeText(manga.id);
577
- setCopiedId(true);
578
- setTimeout(() => setCopiedId(false), 2000);
579
- window.open('https://t.me/waifuofbrodybot', '_blank');
580
- } catch (err) {
581
- console.error('Failed to copy:', err);
582
- }
583
- }}
584
- className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1 font-semibold text-xs sm:text-sm transition-all duration-200"
585
- >
586
- {copiedId ? (
587
- <Check className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
588
- ) : (
589
- <Send className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
590
- )}
591
- <span className="hidden sm:inline">{copiedId ? 'ID Copiado' : 'Bot Telegram'}</span>
592
- <span className="sm:hidden">{copiedId ? 'Copiado' : 'Bot'}</span>
593
- </button>
594
-
595
- {externalLinks.map((link, index) => (
596
- <a
597
- key={index}
598
- href={link.url}
599
- target="_blank"
600
- rel="noopener noreferrer"
601
- className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1.5 font-semibold text-xs sm:text-sm transition-all duration-200 group"
602
- >
603
- <LinkIcon className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
604
- <span className="truncate max-w-[150px]">{link.name}</span>
605
- {isAdmin && (
606
- <button
607
- onClick={(e) => {
608
- e.preventDefault();
609
- e.stopPropagation();
610
- handleRemoveExternalLink(index);
611
- }}
612
- className="opacity-0 group-hover:opacity-100 hover:text-red-400 transition-all flex-shrink-0"
613
- >
614
- <X className="w-3 h-3 sm:w-4 sm:h-4" />
615
- </button>
616
- )}
617
- </a>
618
- ))}
619
-
620
- {isAdmin && (
621
- <button
622
- onClick={() => setShowExternalLinkModal(true)}
623
- className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] p-1.5 sm:p-2 rounded-lg transition-all duration-200 flex items-center justify-center"
624
- title="Añadir enlace externo"
625
- >
626
- <Plus className="w-4 h-4 sm:w-5 sm:h-5" />
627
- </button>
628
- )}
629
- </div>
630
- </>
631
- )}
632
- </div>
633
- </div>
634
- </div>
635
- )}
636
-
637
- {searchTerm.trim() ? (
638
- <div className="mt-2">
639
- <h3 className="text-lg font-semibold text-white mb-4">
640
- Resultados de búsqueda
641
- {filteredMangas.length > 0 && (
642
- <span className="text-sm text-gray-400 ml-2">
643
- ({filteredMangas.length} {filteredMangas.length === 1 ? 'resultado' : 'resultados'})
644
- </span>
645
- )}
646
- </h3>
647
- {loadingAllMangas ? (
648
- <div className="flex justify-center py-12">
649
- <LoadingSpinner size={40} borderWidth={2} />
650
- </div>
651
- ) : filteredMangas.length === 0 ? (
652
- <div className="flex flex-col items-center justify-center py-12">
653
- <Search className="w-12 h-12 text-gray-600 mb-3" />
654
- <p className="text-gray-400 text-sm">No se encontraron comics que coincidan con "{searchTerm}"</p>
655
- </div>
656
- ) : (
657
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3">
658
- {filteredMangas.map((m) => {
659
- if (!m.id || !m.title) return null;
660
- const chapterCount = m.chapters?.length || 0;
661
- const totalPages = m.chapters?.reduce((sum, ch) => sum + (ch.pages?.length || 0), 0) || 0;
662
- return (
663
- <MangaCard
664
- key={m.id}
665
- id={m.id}
666
- title={m.title}
667
- author={m.author || 'Desconocido'}
668
- pageCount={totalPages}
669
- thumbnail={m.cover_url || m.thumbnail_url || undefined}
670
- manga={m}
671
- onSelect={(mangaId) => {
672
- if (onNavigateToManga) {
673
- window.scrollTo({ top: 0, behavior: 'smooth' });
674
- onNavigateToManga(mangaId);
675
- }
676
- }}
677
- />
678
- );
679
- })}
680
- </div>
681
- )}
682
- </div>
683
- ) : manga.chapters && manga.chapters.length > 0 && manga.chapters[0].pages && manga.chapters[0].pages.length > 0 && (
684
- <div className="mt-6 sm:mt-8 border-t border-gray-800 pt-6 sm:pt-8">
685
- <div className="flex items-center justify-between mb-4 sm:mb-6">
686
- <h3 className="text-lg font-semibold text-white">
687
- Páginas
688
- </h3>
689
- <div className="flex items-center gap-1 bg-[#0a0a0a] border border-gray-800 rounded-lg p-1">
690
- <button
691
- onClick={() => handleViewModeChange('vertical')}
692
- className={`px-3 py-2 rounded-md flex items-center gap-2 text-xs sm:text-sm font-medium transition-all duration-200 ${viewMode === 'vertical'
693
- ? 'bg-gradient-to-r from-[#bb86fc] to-[#9966dd] text-white shadow-lg shadow-[#bb86fc]/30'
694
- : 'text-gray-400 hover:text-white hover:bg-[#242424]'
695
- }`}
696
- title="Vista vertical"
697
- >
698
- <Rows className="w-4 h-4" />
699
- <span className="hidden sm:inline">Vertical</span>
700
- </button>
701
- <button
702
- onClick={() => handleViewModeChange('gallery')}
703
- className={`px-3 py-2 rounded-md flex items-center gap-2 text-xs sm:text-sm font-medium transition-all duration-200 ${viewMode === 'gallery'
704
- ? 'bg-gradient-to-r from-[#bb86fc] to-[#9966dd] text-white shadow-lg shadow-[#bb86fc]/30'
705
- : 'text-gray-400 hover:text-white hover:bg-[#242424]'
706
- }`}
707
- title="Vista galería"
708
- >
709
- <Grid2X2 className="w-4 h-4" />
710
- <span className="hidden sm:inline">Galería</span>
711
- </button>
712
- <button
713
- onClick={() => handleViewModeChange('grid')}
714
- className={`px-3 py-2 rounded-md flex items-center gap-2 text-xs sm:text-sm font-medium transition-all duration-200 ${viewMode === 'grid'
715
- ? 'bg-gradient-to-r from-[#bb86fc] to-[#9966dd] text-white shadow-lg shadow-[#bb86fc]/30'
716
- : 'text-gray-400 hover:text-white hover:bg-[#242424]'
717
- }`}
718
- title="Vista cuadrícula"
719
- >
720
- <Grid3X3 className="w-4 h-4" />
721
- <span className="hidden sm:inline">Cuadrícula</span>
722
- </button>
723
- </div>
724
- </div>
725
-
726
- <div className={`bg-[#121212] rounded-lg p-2 sm:p-4 transition-all duration-150 ease-out ${viewMode === 'vertical'
727
- ? 'flex flex-col items-center gap-4'
728
- : viewMode === 'gallery'
729
- ? 'masonry-container'
730
- : 'grid grid-cols-3 md:grid-cols-5 gap-2'
731
- }`}>
732
- {viewMode === 'gallery' ? (
733
- manga.chapters[0].pages
734
- .map((pageUrl, index) => ({ pageUrl, index }))
735
- .map(({ pageUrl, index }) => (
736
- <div
737
- key={index}
738
- className="masonry-item group cursor-pointer relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]"
739
- onClick={() => {
740
- setLightboxIndex(index);
741
- setLightboxOpen(true);
742
- }}
743
- >
744
- <ImageLoader
745
- src={pageUrl}
746
- alt={`Página ${index + 1}`}
747
- aspectRatio="auto"
748
- objectFit="contain"
749
- loading={index > 2 ? "lazy" : "eager"}
750
- className="rounded-lg"
751
- imgClassName="group-hover:scale-110"
752
- />
753
- </div>
754
- ))
755
- ) : (
756
- manga.chapters[0].pages
757
- .map((pageUrl, index) => ({ pageUrl, index }))
758
- .map(({ pageUrl, index }) => (
759
- <div
760
- key={index}
761
- className={viewMode === 'vertical'
762
- ? 'w-full'
763
- : 'group cursor-pointer relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]'}
764
- onClick={() => {
765
- if (viewMode === 'grid') {
766
- setLightboxIndex(index);
767
- setLightboxOpen(true);
768
- }
769
- }}
770
- >
771
- <ImageLoader
772
- src={pageUrl}
773
- alt={`Página ${index + 1}`}
774
- aspectRatio={viewMode === 'vertical' ? 'auto' : '1/1'}
775
- objectFit={viewMode === 'vertical' ? 'contain' : 'cover'}
776
- loading={index > 2 ? "lazy" : "eager"}
777
- className={viewMode === 'vertical' ? 'rounded-lg shadow-2xl' : 'rounded-lg'}
778
- imgClassName={viewMode === 'vertical' ? '' : 'group-hover:scale-110'}
779
- />
780
- </div>
781
- ))
782
- )}
783
- </div>
784
- </div>
785
- )}
786
-
787
- {!searchTerm.trim() && recommendations.length > 0 && (
788
- <div className="mt-8 sm:mt-12 border-t border-gray-800 pt-8 sm:pt-12">
789
- <h3 className="text-xl sm:text-2xl font-bold text-white mb-6">Recomendaciones</h3>
790
- {loadingRecommendations ? (
791
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3">
792
- {Array.from({ length: 6 }).map((_, index) => (
793
- <div key={index} className="animate-pulse">
794
- <div className="bg-gray-800 rounded-lg aspect-[2/3] w-full mb-2"></div>
795
- <div className="h-3 bg-gray-800 rounded w-3/4 mx-auto mb-1"></div>
796
- <div className="h-2 bg-gray-800 rounded w-1/2 mx-auto"></div>
797
- </div>
798
- ))}
799
- </div>
800
- ) : (
801
- <>
802
- <div
803
- key={recPage}
804
- className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 mb-6 animate-slide-in-right"
805
- >
806
- {recommendations.slice((recPage - 1) * REC_ITEMS_PER_PAGE, recPage * REC_ITEMS_PER_PAGE).map((rec, index) => (
807
- <div
808
- key={rec.id}
809
- >
810
- <div
811
- onClick={() => {
812
- window.scrollTo({ top: 0, behavior: 'smooth' });
813
- if (onNavigateToManga) {
814
- onNavigateToManga(rec.id);
815
- }
816
- }}
817
- className="group cursor-pointer flex flex-col"
818
- >
819
- <div className="relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]">
820
- {rec.cover_url || rec.thumbnail_url ? (
821
- <>
822
- <ImageLoader
823
- src={rec.cover_url || rec.thumbnail_url || ''}
824
- alt={rec.title}
825
- aspectRatio="2/3"
826
- objectFit="cover"
827
- loading="lazy"
828
- imgClassName="group-hover:scale-110"
829
- />
830
- <div className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 ease-in-out pointer-events-none"></div>
831
- </>
832
- ) : (
833
- <div className="w-full aspect-[2/3] flex items-center justify-center text-white/40 bg-black">
834
- <BookMarked className="w-8 h-8" />
835
- </div>
836
- )}
837
- </div>
838
-
839
- <div className="mt-2 flex flex-col gap-0.5">
840
- <h4 className="font-semibold text-xs text-white line-clamp-2 text-center group-hover:text-[#bb86fc] transition-colors duration-300">
841
- {rec.title}
842
- </h4>
843
- {rec.categories && rec.categories.length > 0 && (
844
- <p className="text-xs text-gray-500 text-center truncate">
845
- {rec.categories[0].name}
846
- </p>
847
- )}
848
- </div>
849
- </div>
850
- </div>
851
- ))}
852
- </div>
853
-
854
- {recommendations.length > REC_ITEMS_PER_PAGE && (
855
- <div className="flex items-center justify-center gap-2 mt-4 flex-wrap">
856
- <button
857
- onClick={() => setRecPage(1)}
858
- disabled={recPage === 1}
859
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
860
- >
861
- <ChevronsLeft className="w-4 h-4" />
862
- </button>
863
- <button
864
- onClick={() => setRecPage(p => Math.max(1, p - 1))}
865
- disabled={recPage === 1}
866
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
867
- >
868
- <ChevronLeft className="w-4 h-4" />
869
- </button>
870
-
871
- <span className="text-sm text-gray-400 px-2">
872
- Página {recPage} de {Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE)}
873
- </span>
874
-
875
- <button
876
- onClick={() => setRecPage(p => Math.min(Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE), p + 1))}
877
- disabled={recPage === Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE)}
878
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
879
- >
880
- <ChevronRight className="w-4 h-4" />
881
- </button>
882
- <button
883
- onClick={() => setRecPage(Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE))}
884
- disabled={recPage === Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE)}
885
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
886
- >
887
- <ChevronsRight className="w-4 h-4" />
888
- </button>
889
- </div>
890
- )}
891
- </>
892
- )}
893
- </div>
894
- )}
895
- </div>
896
- <GlobalFooter />
897
- </main>
898
-
899
- {lightboxOpen && manga.chapters?.[0]?.pages && (
900
- <ImageLightbox
901
- images={manga.chapters?.[0].pages || []}
902
- initialIndex={lightboxIndex}
903
- onClose={() => setLightboxOpen(false)}
904
- />
905
- )}
906
-
907
- {showExternalLinkModal && (
908
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
909
- <div className="bg-gradient-to-b from-[#1f1f1f] to-[#121212] rounded-2xl border border-gray-700/40 w-full max-w-md shadow-2xl">
910
- <div className="bg-gradient-to-b from-[#2a2a2a]/80 to-[#1f1f1f]/80 border-b border-gray-700/30 px-6 py-4 flex items-center justify-between">
911
- <h2 className="text-xl font-bold text-white">Añadir Enlace Externo</h2>
912
- <button
913
- onClick={() => setShowExternalLinkModal(false)}
914
- className="text-gray-500 hover:text-white transition-colors p-1.5 rounded-lg hover:bg-white/10"
915
- >
916
- <X className="w-5 h-5" />
917
- </button>
918
- </div>
919
-
920
- <div className="p-6 space-y-4">
921
- <div>
922
- <label className="block text-sm font-semibold text-gray-200 mb-2">
923
- Nombre del Enlace
924
- </label>
925
- <input
926
- type="text"
927
- placeholder="Ej: Servidor Alternativo"
928
- value={externalLinkForm.name}
929
- onChange={(e) => setExternalLinkForm({ ...externalLinkForm, name: e.target.value })}
930
- className="w-full bg-[#1a1a1a] border border-gray-600/50 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-[#bb86fc] focus:ring-2 focus:ring-[#bb86fc]/30 transition-all"
931
- />
932
- </div>
933
-
934
- <div>
935
- <label className="block text-sm font-semibold text-gray-200 mb-2">
936
- URL del Enlace
937
- </label>
938
- <input
939
- type="url"
940
- placeholder="https://ejemplo.com/descarga"
941
- value={externalLinkForm.url}
942
- onChange={(e) => setExternalLinkForm({ ...externalLinkForm, url: e.target.value })}
943
- className="w-full bg-[#1a1a1a] border border-gray-600/50 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-[#bb86fc] focus:ring-2 focus:ring-[#bb86fc]/30 transition-all"
944
- />
945
- </div>
946
-
947
- <div className="flex gap-3 pt-2">
948
- <button
949
- onClick={() => setShowExternalLinkModal(false)}
950
- className="flex-1 bg-[#1a1a1a] border border-gray-600/50 hover:border-gray-500 hover:bg-[#242424] text-white px-4 py-3 rounded-lg font-semibold text-sm transition-all"
951
- >
952
- Cancelar
953
- </button>
954
- <button
955
- onClick={handleAddExternalLink}
956
- disabled={!externalLinkForm.name.trim() || !externalLinkForm.url.trim()}
957
- className="flex-1 bg-gradient-to-r from-[#bb86fc] to-[#9966dd] hover:from-[#9966dd] hover:to-[#7744cc] disabled:opacity-50 disabled:cursor-not-allowed text-white px-4 py-3 rounded-lg font-semibold text-sm transition-all shadow-lg shadow-[#bb86fc]/40 hover:shadow-[#bb86fc]/60"
958
- >
959
- Añadir Enlace
960
- </button>
961
- </div>
962
- </div>
963
- </div>
964
- </div>
965
- )}
966
- </div>
967
- );
968
- }
 
1
+ import { ArrowLeft, BookMarked, User, Download, Link as LinkIcon, X, Plus, Rows, Grid2X2, Grid3X3, FileText, Search, Send, Check, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, Eye } from 'lucide-react';
2
+ import { GlobalFooter } from './GlobalFooter';
3
+
4
+ import { useState, useEffect } from 'react';
5
+ import { getMangaById, incrementMangaViews, addExternalLink, removeExternalLink, getRecommendations, getAllMangas, subscribeToManga } from '../services/manga';
6
+ import { Manga } from '../types/manga';
7
+ import { detectImageOrientation } from '../utils/imageOptimization';
8
+ import { LoadingSpinner } from './LoadingSpinner';
9
+ import { ImageLightbox } from './ImageLightbox';
10
+ import { ImageLoader } from './ImageLoader';
11
+ import { MangaCard } from './MangaCard';
12
+
13
+ interface ComicDetailProps {
14
+ id: string;
15
+ onBack: () => void;
16
+ onReadChapter?: (chapter: any) => void;
17
+ onMangaLoaded?: (manga: Manga) => void;
18
+ onNavigateToManga?: (mangaId: string) => void;
19
+ isAdmin?: boolean;
20
+ }
21
+
22
+ export function ComicDetail({ id, onBack, onNavigateToManga, onMangaLoaded, isAdmin = false }: ComicDetailProps) {
23
+ const [manga, setManga] = useState<Manga | null>(null);
24
+ const [loading, setLoading] = useState(true);
25
+ const [downloading, setDownloading] = useState(false);
26
+ const [downloadProgress, setDownloadProgress] = useState(0);
27
+ const [showDownloadMenu, setShowDownloadMenu] = useState(false);
28
+ const [showPdfMenu, setShowPdfMenu] = useState(false);
29
+ const [downloadingPdf, setDownloadingPdf] = useState(false);
30
+ const [pdfProgress, setPdfProgress] = useState(0);
31
+ const [showExternalLinkModal, setShowExternalLinkModal] = useState(false);
32
+ const [externalLinkForm, setExternalLinkForm] = useState({ name: '', url: '' });
33
+ const [externalLinks, setExternalLinks] = useState<Array<{ name: string; url: string }>>([]);
34
+ const [coverOrientation, setCoverOrientation] = useState<'portrait' | 'landscape' | 'square'>('portrait');
35
+ const [viewMode, setViewMode] = useState<'vertical' | 'gallery' | 'grid'>('vertical');
36
+ const [lightboxOpen, setLightboxOpen] = useState(false);
37
+ const [lightboxIndex, setLightboxIndex] = useState(0);
38
+ // const [loadedImages, setLoadedImages] = useState<Set<number>>(new Set());
39
+ const [recommendations, setRecommendations] = useState<Manga[]>([]);
40
+ const [loadingRecommendations, setLoadingRecommendations] = useState(false);
41
+ const [searchTerm, setSearchTerm] = useState('');
42
+ const [allMangas, setAllMangas] = useState<Manga[]>([]);
43
+ const [loadingAllMangas, setLoadingAllMangas] = useState(false);
44
+ const [copiedId, setCopiedId] = useState(false);
45
+ const [recPage, setRecPage] = useState(1);
46
+ const REC_ITEMS_PER_PAGE = 6;
47
+
48
+ useEffect(() => {
49
+ // Initial fetch for loading state and increment logic
50
+ loadMangaAndInit();
51
+
52
+ // Subscribe for real-time updates (views, etc)
53
+ const unsubscribe = subscribeToManga(id, (updatedManga) => {
54
+ if (updatedManga) {
55
+ setManga(() => {
56
+ // Determine if we need to update orientation or other heavy stuff?
57
+ // For now, just update the data.
58
+ // Keep existing derived state if needed? No, just full replacement is safer for data consistency.
59
+ return updatedManga;
60
+ });
61
+ // If it was the first load, we might need to trigger recommendations if we haven't
62
+ // But loadMangaAndInit handles that.
63
+ setLoading(false);
64
+ }
65
+ });
66
+
67
+ loadAllMangasForSearch();
68
+ setSearchTerm('');
69
+ const savedViewMode = localStorage.getItem('manga-view-mode');
70
+ if (savedViewMode === 'vertical' || savedViewMode === 'gallery' || savedViewMode === 'grid') {
71
+ setViewMode(savedViewMode);
72
+ }
73
+
74
+ return () => unsubscribe();
75
+ }, [id]);
76
+
77
+ async function loadAllMangasForSearch() {
78
+ try {
79
+ setLoadingAllMangas(true);
80
+ const mangas = await getAllMangas();
81
+ setAllMangas(mangas);
82
+ } catch (error) {
83
+ console.error('Error loading all mangas:', error);
84
+ } finally {
85
+ setLoadingAllMangas(false);
86
+ }
87
+ }
88
+
89
+ useEffect(() => {
90
+ function handleClickOutside(event: MouseEvent) {
91
+ const target = event.target as HTMLElement;
92
+ if (showDownloadMenu && !target.closest('.download-menu-container')) {
93
+ setShowDownloadMenu(false);
94
+ }
95
+ if (showPdfMenu && !target.closest('.pdf-menu-container')) {
96
+ setShowPdfMenu(false);
97
+ }
98
+ }
99
+
100
+ document.addEventListener('mousedown', handleClickOutside);
101
+ return () => document.removeEventListener('mousedown', handleClickOutside);
102
+ }, [showDownloadMenu, showPdfMenu]);
103
+
104
+ const handleAddExternalLink = async () => {
105
+ if (externalLinkForm.name.trim() && externalLinkForm.url.trim() && manga) {
106
+ try {
107
+ await addExternalLink(manga.id, externalLinkForm);
108
+ setExternalLinks([...externalLinks, externalLinkForm]);
109
+ setExternalLinkForm({ name: '', url: '' });
110
+ setShowExternalLinkModal(false);
111
+ } catch (error) {
112
+ console.error('Error al guardar el enlace:', error);
113
+ alert('Error al guardar el enlace');
114
+ }
115
+ }
116
+ };
117
+
118
+ const handleRemoveExternalLink = async (index: number) => {
119
+ if (manga) {
120
+ try {
121
+ await removeExternalLink(manga.id, index);
122
+ setExternalLinks(externalLinks.filter((_, i) => i !== index));
123
+ } catch (error) {
124
+ console.error('Error al eliminar el enlace:', error);
125
+ alert('Error al eliminar el enlace');
126
+ }
127
+ }
128
+ };
129
+
130
+ const handleViewModeChange = (mode: 'vertical' | 'gallery' | 'grid') => {
131
+ setViewMode(mode);
132
+ localStorage.setItem('manga-view-mode', mode);
133
+ };
134
+
135
+ async function loadMangaAndInit() {
136
+ try {
137
+ setLoading(true);
138
+
139
+ // We still fetch initially...
140
+ const data = await getMangaById(id);
141
+ if (data) {
142
+ setManga(data);
143
+ setExternalLinks(data.external_links || []);
144
+
145
+ if (data.cover_url) {
146
+ try {
147
+ const orientation = await detectImageOrientation(data.cover_url);
148
+ setCoverOrientation(orientation);
149
+ } catch (error) {
150
+ console.warn('Failed to detect image orientation:', error);
151
+ setCoverOrientation('portrait');
152
+ }
153
+ }
154
+
155
+ loadRecommendations(data);
156
+ }
157
+ } catch (error) {
158
+ console.error('Error loading manga:', error);
159
+ } finally {
160
+ // setLoading(false);
161
+ }
162
+ }
163
+
164
+ async function loadRecommendations(currentManga: Manga) {
165
+ try {
166
+ setLoadingRecommendations(true);
167
+ const categoryIds = currentManga.categories?.map(cat => cat.id) || [];
168
+ const recs = await getRecommendations(currentManga.id, categoryIds, currentManga.title);
169
+ setRecommendations(recs);
170
+ setRecPage(1);
171
+ } catch (error) {
172
+ console.error('Error loading recommendations:', error);
173
+ } finally {
174
+ setLoadingRecommendations(false);
175
+ }
176
+ }
177
+
178
+ async function handleDownload(format: 'png' | 'jpg' | 'webp' | 'original') {
179
+ const targetId = manga?.id || id;
180
+
181
+ if (!targetId) {
182
+ alert('Error: ID no encontrado.');
183
+ return;
184
+ }
185
+
186
+ const jobId = targetId; // Usamos el ID como identificador de la tarea
187
+
188
+ // 1. Abrimos el canal de progreso (SSE)
189
+ console.log(`🚀 [CLIENTE] Suscribiendo a progreso: ${jobId}`);
190
+ const eventSource = new EventSource(`/api/download/progress/${jobId}`);
191
+
192
+ eventSource.onmessage = (event) => {
193
+ const data = JSON.parse(event.data);
194
+ // console.log("⚡ [PROGRESO]:", data.progress);
195
+ setDownloadProgress(data.progress);
196
+
197
+ if (data.progress >= 100) {
198
+ eventSource.close();
199
+ }
200
+ };
201
+
202
+ try {
203
+ console.log("🚀 [CLIENTE] Iniciando descarga para ID:", targetId);
204
+ setDownloading(true);
205
+ setShowDownloadMenu(false);
206
+ setDownloadProgress(0);
207
+
208
+ const response = await fetch('/api/download/zip', {
209
+ method: 'POST',
210
+ headers: { 'Content-Type': 'application/json' },
211
+ body: JSON.stringify({
212
+ mangaId: targetId,
213
+ mangaTitle: manga?.title || 'Descarga',
214
+ format: format,
215
+ jobId: jobId // Though server uses mangaId mostly now, consistent
216
+ }),
217
+ });
218
+
219
+ if (!response.ok) throw new Error("Error en el servidor");
220
+
221
+ const blob = await response.blob();
222
+ const urlDownload = window.URL.createObjectURL(blob);
223
+ const a = document.createElement('a');
224
+ a.href = urlDownload;
225
+ a.download = `${manga?.title || 'manga'}.zip`;
226
+ document.body.appendChild(a);
227
+ a.click();
228
+ a.remove();
229
+ window.URL.revokeObjectURL(urlDownload);
230
+
231
+ console.log("✅ [CLIENTE] Descarga disparada con éxito");
232
+
233
+ } catch (error) {
234
+ console.error("❌ Error en la descarga:", error);
235
+ alert("Hubo un fallo en la matriz de descarga.");
236
+ } finally {
237
+ setDownloading(false);
238
+ eventSource.close();
239
+ }
240
+ }
241
+
242
+ async function handleDownloadPdf(format: 'png' | 'jpg' | 'webp' | 'original') {
243
+ const targetId = manga?.id || id;
244
+ if (!targetId) {
245
+ alert('Error: ID no encontrado.');
246
+ return;
247
+ }
248
+
249
+ const jobId = targetId;
250
+
251
+ console.log(`🚀 [CLIENTE] Suscribiendo a progreso PDF: ${jobId}`);
252
+ const eventSource = new EventSource(`/api/download/progress/${jobId}`);
253
+
254
+ eventSource.onmessage = (event) => {
255
+ const data = JSON.parse(event.data);
256
+ if (data.progress) {
257
+ setPdfProgress(data.progress);
258
+ }
259
+ if (data.progress >= 100) {
260
+ eventSource.close();
261
+ }
262
+ };
263
+
264
+ try {
265
+ console.log("🚀 [CLIENTE] Iniciando PDF para ID:", targetId);
266
+ setDownloadingPdf(true);
267
+ setPdfProgress(0);
268
+ setShowPdfMenu(false);
269
+
270
+ const response = await fetch('/api/download/pdf', {
271
+ method: 'POST',
272
+ headers: { 'Content-Type': 'application/json' },
273
+ body: JSON.stringify({
274
+ mangaId: targetId,
275
+ mangaTitle: manga?.title || 'Descarga',
276
+ format: format,
277
+ jobId: jobId
278
+ }),
279
+ });
280
+
281
+ if (!response.ok) throw new Error("Error en el servidor al generar PDF");
282
+
283
+ const blob = await response.blob();
284
+ const urlDownload = window.URL.createObjectURL(blob);
285
+ const a = document.createElement('a');
286
+ a.href = urlDownload;
287
+ a.download = `${manga?.title || 'manga'}.pdf`;
288
+ document.body.appendChild(a);
289
+ a.click();
290
+ a.remove();
291
+ window.URL.revokeObjectURL(urlDownload);
292
+
293
+ console.log("✅ [CLIENTE] PDF descargado con éxito");
294
+
295
+ } catch (error) {
296
+ console.error('Error initiating PDF generation:', error);
297
+ alert('Error al generar PDF (puede que el archivo sea muy grande o Python falló).');
298
+ } finally {
299
+ setDownloadingPdf(false);
300
+ eventSource.close();
301
+ }
302
+ }
303
+
304
+
305
+ if (loading) {
306
+ return (
307
+ <div className="h-screen bg-[#121212] flex flex-col items-center justify-center gap-4">
308
+ <LoadingSpinner size={40} borderWidth={2} />
309
+ <div className="text-gray-400 text-sm">Cargando...</div>
310
+ </div>
311
+ );
312
+ }
313
+
314
+ if (!manga) {
315
+ return (
316
+ <div className="h-screen bg-[#121212] flex items-center justify-center">
317
+ <div className="text-gray-400 text-lg">Manga no encontrado</div>
318
+ </div>
319
+ );
320
+ }
321
+
322
+ const filteredMangas = searchTerm.trim()
323
+ ? allMangas.filter(m => {
324
+ if (!m.id || !m.title || m.id === manga.id) return false;
325
+ const searchLower = searchTerm.toLowerCase();
326
+ const titleMatch = m.title.toLowerCase().includes(searchLower);
327
+ const authorMatch = m.author ? m.author.toLowerCase().includes(searchLower) : false;
328
+ const categoryMatch = m.categories?.some(cat => cat?.name?.toLowerCase().includes(searchLower)) || false;
329
+ return titleMatch || authorMatch || categoryMatch;
330
+ })
331
+ : [];
332
+
333
+ return (
334
+ <div className="h-screen flex flex-col bg-[#121212] overflow-hidden">
335
+ <header className="border-b border-gray-800 z-40 bg-[#121212] flex-shrink-0">
336
+ <div className="max-w-7xl mx-auto px-4 sm:px-6 py-3 sm:py-4 flex items-center gap-3 sm:gap-4">
337
+ <button
338
+ onClick={onBack}
339
+ className="p-2 hover:bg-[#333] rounded-lg transition-colors text-gray-300 hover:text-white flex-shrink-0"
340
+ >
341
+ <ArrowLeft className="w-5 h-5" />
342
+ </button>
343
+ <h1 className="text-base sm:text-lg font-bold text-white truncate flex-shrink-0">{manga.title}</h1>
344
+ <div className="flex-1 max-w-md ml-auto">
345
+ <div className="relative">
346
+ <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
347
+ <input
348
+ type="text"
349
+ placeholder="Buscar comics…"
350
+ value={searchTerm}
351
+ onChange={(e) => setSearchTerm(e.target.value)}
352
+ className="w-full bg-[#1a1a1a] text-white rounded-lg pl-10 pr-3 py-2 text-sm placeholder-gray-400 focus:ring-2 focus:ring-[#bb86fc] focus:outline-none transition-all border border-gray-700/50 focus:border-[#bb86fc]"
353
+ />
354
+ </div>
355
+ </div>
356
+ </div>
357
+ </header>
358
+
359
+ <main className="flex-1 overflow-y-auto bg-[#121212]">
360
+ <div className="max-w-7xl mx-auto px-4 sm:px-6 py-4 sm:py-8">
361
+ {!searchTerm.trim() && (
362
+ <div className="flex flex-col sm:flex-row gap-4 sm:gap-6">
363
+ <div className="flex-shrink-0 mx-auto sm:mx-0">
364
+ <div className="group w-56 sm:w-64">
365
+ <div className="relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]">
366
+ {manga.cover_url ? (
367
+ <>
368
+ <ImageLoader
369
+ src={manga.cover_url}
370
+ alt={manga.title}
371
+ aspectRatio="2/3"
372
+ objectFit="cover"
373
+ loading="eager"
374
+ imgClassName="group-hover:scale-110"
375
+ />
376
+ <div className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 ease-in-out pointer-events-none"></div>
377
+ </>
378
+ ) : (
379
+ <div className="w-full aspect-[2/3] flex items-center justify-center text-white/40 bg-black">
380
+ <BookMarked className="w-16 h-16" />
381
+ </div>
382
+ )}
383
+ </div>
384
+ </div>
385
+ </div>
386
+
387
+ <div className="flex-1 min-w-0">
388
+ <h2 className="text-2xl sm:text-4xl font-bold text-white mb-3 sm:mb-4">{manga.title}</h2>
389
+
390
+ <div className="mb-4">
391
+ <div className="flex items-center gap-2 text-gray-300">
392
+ {manga.author && manga.author.toLowerCase() !== 'anónimo' && manga.author.toLowerCase() !== 'anonimo' && (
393
+ <>
394
+ <User className="w-4 h-4 text-[#bb86fc]" />
395
+ <span className="text-sm">{manga.author}</span>
396
+ <div className="w-1 h-1 bg-gray-600 rounded-full mx-2"></div>
397
+ </>
398
+ )}
399
+ <Eye className="w-4 h-4 text-[#bb86fc]" />
400
+ <span className="text-sm">{manga.views?.toLocaleString() || 0} vistas</span>
401
+ </div>
402
+ </div>
403
+
404
+ <div className="mb-6">
405
+ <h3 className="text-sm font-semibold text-gray-300 mb-3">Categorías</h3>
406
+ <div className="flex gap-2 flex-wrap">
407
+ {manga.categories?.map((cat) => (
408
+ <span
409
+ key={cat.id}
410
+ className="px-3 py-1.5 bg-[#bb86fc]/20 text-[#bb86fc] text-xs rounded-full border border-[#bb86fc]/40"
411
+ >
412
+ {cat.name}
413
+ </span>
414
+ ))}
415
+ </div>
416
+ </div>
417
+
418
+ {manga.description && manga.description.trim() !== '' && (
419
+ <div className="mb-6">
420
+ <h3 className="text-sm font-semibold text-gray-300 mb-2">Sinopsis</h3>
421
+ <p className="text-sm text-gray-400 leading-relaxed whitespace-pre-wrap">
422
+ {manga.description}
423
+ </p>
424
+ </div>
425
+ )}
426
+
427
+ <div className="flex flex-col gap-3 sm:gap-4">
428
+ {manga.chapters && manga.chapters.length > 0 && manga.chapters[0].pages && manga.chapters[0].pages.length > 0 && (
429
+ <>
430
+ {downloading && (
431
+ <div className="w-full">
432
+ <div className="flex items-center justify-between mb-2">
433
+ <span className="text-xs sm:text-sm font-semibold text-[#bb86fc]">Descargando ZIP</span>
434
+ <span className="text-xs sm:text-sm font-bold text-[#bb86fc]">{downloadProgress}%</span>
435
+ </div>
436
+ <div className="w-full bg-gray-700/40 rounded-full h-2 overflow-hidden border border-[#bb86fc]/30">
437
+ <div
438
+ className="bg-gradient-to-r from-[#bb86fc] to-[#9966dd] h-full transition-all duration-300 ease-out"
439
+ style={{ width: `${downloadProgress}%` }}
440
+ />
441
+ </div>
442
+ </div>
443
+ )}
444
+ {downloadingPdf && (
445
+ <div className="w-full">
446
+ <div className="flex items-center justify-between mb-2">
447
+ <span className="text-xs sm:text-sm font-semibold text-[#bb86fc]">Generando PDF</span>
448
+ <span className="text-xs sm:text-sm font-bold text-[#bb86fc]">{pdfProgress}%</span>
449
+ </div>
450
+ <div className="w-full bg-gray-700/40 rounded-full h-2 overflow-hidden border border-[#bb86fc]/30">
451
+ <div
452
+ className="bg-gradient-to-r from-[#bb86fc] to-[#9966dd] h-full transition-all duration-300 ease-out"
453
+ style={{ width: `${pdfProgress}%` }}
454
+ />
455
+ </div>
456
+ </div>
457
+ )}
458
+ <div className="flex flex-wrap gap-2 items-center">
459
+ <div className="relative download-menu-container">
460
+ <button
461
+ onClick={() => setShowDownloadMenu(!showDownloadMenu)}
462
+ disabled={downloading}
463
+ className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1 font-semibold text-xs sm:text-sm transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
464
+ >
465
+ <Download className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
466
+ <span className="hidden sm:inline">{downloading ? `Descargando (${downloadProgress}%)` : 'ZIP'}</span>
467
+ <span className="sm:hidden">ZIP</span>
468
+ </button>
469
+
470
+ {showDownloadMenu && !downloading && (
471
+ <div className="absolute top-full mt-2 left-0 bg-[#1f1f1f] border border-gray-700/60 rounded-lg shadow-2xl shadow-black/50 overflow-hidden z-50 min-w-[200px]">
472
+ <button
473
+ onClick={() => handleDownload('original')}
474
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
475
+ >
476
+ <Download className="w-3 h-3 text-[#bb86fc]" />
477
+ <div>
478
+ <div className="font-semibold">Original</div>
479
+ <div className="text-xs text-gray-400">Sin cambios</div>
480
+ </div>
481
+ </button>
482
+ <button
483
+ onClick={() => handleDownload('webp')}
484
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
485
+ >
486
+ <Download className="w-3 h-3 text-[#bb86fc]" />
487
+ <div>
488
+ <div className="font-semibold">WebP</div>
489
+ <div className="text-xs text-gray-400">Optimizado</div>
490
+ </div>
491
+ </button>
492
+ <button
493
+ onClick={() => handleDownload('png')}
494
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
495
+ >
496
+ <Download className="w-3 h-3 text-[#bb86fc]" />
497
+ <div>
498
+ <div className="font-semibold">PNG</div>
499
+ <div className="text-xs text-gray-400">Sin pérdida</div>
500
+ </div>
501
+ </button>
502
+ <button
503
+ onClick={() => handleDownload('jpg')}
504
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2"
505
+ >
506
+ <Download className="w-3 h-3 text-[#bb86fc]" />
507
+ <div>
508
+ <div className="font-semibold">JPG</div>
509
+ <div className="text-xs text-gray-400">Comprimido</div>
510
+ </div>
511
+ </button>
512
+ </div>
513
+ )}
514
+ </div>
515
+
516
+ <div className="relative pdf-menu-container">
517
+ <button
518
+ onClick={() => setShowPdfMenu(!showPdfMenu)}
519
+ disabled={downloadingPdf}
520
+ className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1 font-semibold text-xs sm:text-sm transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
521
+ >
522
+ <FileText className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
523
+ <span className="hidden sm:inline">{downloadingPdf ? `Generando (${pdfProgress}%)` : 'PDF'}</span>
524
+ <span className="sm:hidden">PDF</span>
525
+ </button>
526
+
527
+ {showPdfMenu && !downloadingPdf && (
528
+ <div className="absolute top-full mt-2 left-0 bg-[#1f1f1f] border border-gray-700/60 rounded-lg shadow-2xl shadow-black/50 overflow-hidden z-50 min-w-[200px]">
529
+ <button
530
+ onClick={() => handleDownloadPdf('original')}
531
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
532
+ >
533
+ <FileText className="w-3 h-3 text-[#bb86fc]" />
534
+ <div>
535
+ <div className="font-semibold">Original</div>
536
+ <div className="text-xs text-gray-400">Sin cambios</div>
537
+ </div>
538
+ </button>
539
+ <button
540
+ onClick={() => handleDownloadPdf('webp')}
541
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
542
+ >
543
+ <FileText className="w-3 h-3 text-[#bb86fc]" />
544
+ <div>
545
+ <div className="font-semibold">WebP</div>
546
+ <div className="text-xs text-gray-400">Optimizado</div>
547
+ </div>
548
+ </button>
549
+ <button
550
+ onClick={() => handleDownloadPdf('png')}
551
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2 border-b border-gray-700/40"
552
+ >
553
+ <FileText className="w-3 h-3 text-[#bb86fc]" />
554
+ <div>
555
+ <div className="font-semibold">PNG</div>
556
+ <div className="text-xs text-gray-400">Sin pérdida</div>
557
+ </div>
558
+ </button>
559
+ <button
560
+ onClick={() => handleDownloadPdf('jpg')}
561
+ className="w-full px-3 py-2 text-left text-xs sm:text-sm text-white hover:bg-[#bb86fc]/20 transition-colors flex items-center gap-2"
562
+ >
563
+ <FileText className="w-3 h-3 text-[#bb86fc]" />
564
+ <div>
565
+ <div className="font-semibold">JPG</div>
566
+ <div className="text-xs text-gray-400">Comprimido</div>
567
+ </div>
568
+ </button>
569
+ </div>
570
+ )}
571
+ </div>
572
+
573
+ <button
574
+ onClick={async () => {
575
+ try {
576
+ await navigator.clipboard.writeText(manga.id);
577
+ setCopiedId(true);
578
+ setTimeout(() => setCopiedId(false), 2000);
579
+ window.open('https://t.me/waifuofbrodybot', '_blank');
580
+ } catch (err) {
581
+ console.error('Failed to copy:', err);
582
+ }
583
+ }}
584
+ className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1 font-semibold text-xs sm:text-sm transition-all duration-200"
585
+ >
586
+ {copiedId ? (
587
+ <Check className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
588
+ ) : (
589
+ <Send className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
590
+ )}
591
+ <span className="hidden sm:inline">{copiedId ? 'ID Copiado' : 'Bot Telegram'}</span>
592
+ <span className="sm:hidden">{copiedId ? 'Copiado' : 'Bot'}</span>
593
+ </button>
594
+
595
+ {externalLinks.map((link, index) => (
596
+ <a
597
+ key={index}
598
+ href={link.url}
599
+ target="_blank"
600
+ rel="noopener noreferrer"
601
+ className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] px-2 sm:px-3 py-1.5 sm:py-2 rounded-lg flex items-center gap-1.5 font-semibold text-xs sm:text-sm transition-all duration-200 group"
602
+ >
603
+ <LinkIcon className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0" />
604
+ <span className="truncate max-w-[150px]">{link.name}</span>
605
+ {isAdmin && (
606
+ <button
607
+ onClick={(e) => {
608
+ e.preventDefault();
609
+ e.stopPropagation();
610
+ handleRemoveExternalLink(index);
611
+ }}
612
+ className="opacity-0 group-hover:opacity-100 hover:text-red-400 transition-all flex-shrink-0"
613
+ >
614
+ <X className="w-3 h-3 sm:w-4 sm:h-4" />
615
+ </button>
616
+ )}
617
+ </a>
618
+ ))}
619
+
620
+ {isAdmin && (
621
+ <button
622
+ onClick={() => setShowExternalLinkModal(true)}
623
+ className="bg-[#121212] hover:bg-[#1f1f1f] border border-[#bb86fc]/50 hover:border-[#bb86fc] text-[#bb86fc] p-1.5 sm:p-2 rounded-lg transition-all duration-200 flex items-center justify-center"
624
+ title="Añadir enlace externo"
625
+ >
626
+ <Plus className="w-4 h-4 sm:w-5 sm:h-5" />
627
+ </button>
628
+ )}
629
+ </div>
630
+ </>
631
+ )}
632
+ </div>
633
+ </div>
634
+ </div>
635
+ )}
636
+
637
+ {searchTerm.trim() ? (
638
+ <div className="mt-2">
639
+ <h3 className="text-lg font-semibold text-white mb-4">
640
+ Resultados de búsqueda
641
+ {filteredMangas.length > 0 && (
642
+ <span className="text-sm text-gray-400 ml-2">
643
+ ({filteredMangas.length} {filteredMangas.length === 1 ? 'resultado' : 'resultados'})
644
+ </span>
645
+ )}
646
+ </h3>
647
+ {loadingAllMangas ? (
648
+ <div className="flex justify-center py-12">
649
+ <LoadingSpinner size={40} borderWidth={2} />
650
+ </div>
651
+ ) : filteredMangas.length === 0 ? (
652
+ <div className="flex flex-col items-center justify-center py-12">
653
+ <Search className="w-12 h-12 text-gray-600 mb-3" />
654
+ <p className="text-gray-400 text-sm">No se encontraron comics que coincidan con "{searchTerm}"</p>
655
+ </div>
656
+ ) : (
657
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3">
658
+ {filteredMangas.map((m) => {
659
+ if (!m.id || !m.title) return null;
660
+ const chapterCount = m.chapters?.length || 0;
661
+ const totalPages = m.chapters?.reduce((sum, ch) => sum + (ch.pages?.length || 0), 0) || 0;
662
+ return (
663
+ <MangaCard
664
+ key={m.id}
665
+ id={m.id}
666
+ title={m.title}
667
+ author={m.author || 'Desconocido'}
668
+ pageCount={totalPages}
669
+ thumbnail={m.cover_url || m.thumbnail_url || undefined}
670
+ manga={m}
671
+ onSelect={(mangaId) => {
672
+ if (onNavigateToManga) {
673
+ window.scrollTo({ top: 0, behavior: 'smooth' });
674
+ onNavigateToManga(mangaId);
675
+ }
676
+ }}
677
+ />
678
+ );
679
+ })}
680
+ </div>
681
+ )}
682
+ </div>
683
+ ) : manga.chapters && manga.chapters.length > 0 && manga.chapters[0].pages && manga.chapters[0].pages.length > 0 && (
684
+ <div className="mt-6 sm:mt-8 border-t border-gray-800 pt-6 sm:pt-8">
685
+ <div className="flex items-center justify-between mb-4 sm:mb-6">
686
+ <h3 className="text-lg font-semibold text-white">
687
+ Páginas
688
+ </h3>
689
+ <div className="flex items-center gap-1 bg-[#0a0a0a] border border-gray-800 rounded-lg p-1">
690
+ <button
691
+ onClick={() => handleViewModeChange('vertical')}
692
+ className={`px-3 py-2 rounded-md flex items-center gap-2 text-xs sm:text-sm font-medium transition-all duration-200 ${viewMode === 'vertical'
693
+ ? 'bg-gradient-to-r from-[#bb86fc] to-[#9966dd] text-white shadow-lg shadow-[#bb86fc]/30'
694
+ : 'text-gray-400 hover:text-white hover:bg-[#242424]'
695
+ }`}
696
+ title="Vista vertical"
697
+ >
698
+ <Rows className="w-4 h-4" />
699
+ <span className="hidden sm:inline">Vertical</span>
700
+ </button>
701
+ <button
702
+ onClick={() => handleViewModeChange('gallery')}
703
+ className={`px-3 py-2 rounded-md flex items-center gap-2 text-xs sm:text-sm font-medium transition-all duration-200 ${viewMode === 'gallery'
704
+ ? 'bg-gradient-to-r from-[#bb86fc] to-[#9966dd] text-white shadow-lg shadow-[#bb86fc]/30'
705
+ : 'text-gray-400 hover:text-white hover:bg-[#242424]'
706
+ }`}
707
+ title="Vista galería"
708
+ >
709
+ <Grid2X2 className="w-4 h-4" />
710
+ <span className="hidden sm:inline">Galería</span>
711
+ </button>
712
+ <button
713
+ onClick={() => handleViewModeChange('grid')}
714
+ className={`px-3 py-2 rounded-md flex items-center gap-2 text-xs sm:text-sm font-medium transition-all duration-200 ${viewMode === 'grid'
715
+ ? 'bg-gradient-to-r from-[#bb86fc] to-[#9966dd] text-white shadow-lg shadow-[#bb86fc]/30'
716
+ : 'text-gray-400 hover:text-white hover:bg-[#242424]'
717
+ }`}
718
+ title="Vista cuadrícula"
719
+ >
720
+ <Grid3X3 className="w-4 h-4" />
721
+ <span className="hidden sm:inline">Cuadrícula</span>
722
+ </button>
723
+ </div>
724
+ </div>
725
+
726
+ <div className={`bg-[#121212] rounded-lg p-2 sm:p-4 transition-all duration-150 ease-out ${viewMode === 'vertical'
727
+ ? 'flex flex-col items-center gap-4'
728
+ : viewMode === 'gallery'
729
+ ? 'masonry-container'
730
+ : 'grid grid-cols-3 md:grid-cols-5 gap-2'
731
+ }`}>
732
+ {viewMode === 'gallery' ? (
733
+ manga.chapters[0].pages
734
+ .map((pageUrl, index) => ({ pageUrl, index }))
735
+ .map(({ pageUrl, index }) => (
736
+ <div
737
+ key={index}
738
+ className="masonry-item group cursor-pointer relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]"
739
+ onClick={() => {
740
+ setLightboxIndex(index);
741
+ setLightboxOpen(true);
742
+ }}
743
+ >
744
+ <ImageLoader
745
+ src={pageUrl}
746
+ alt={`Página ${index + 1}`}
747
+ aspectRatio="auto"
748
+ objectFit="contain"
749
+ loading={index > 2 ? "lazy" : "eager"}
750
+ className="rounded-lg"
751
+ imgClassName="group-hover:scale-110"
752
+ />
753
+ </div>
754
+ ))
755
+ ) : (
756
+ manga.chapters[0].pages
757
+ .map((pageUrl, index) => ({ pageUrl, index }))
758
+ .map(({ pageUrl, index }) => (
759
+ <div
760
+ key={index}
761
+ className={viewMode === 'vertical'
762
+ ? 'w-full'
763
+ : 'group cursor-pointer relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]'}
764
+ onClick={() => {
765
+ if (viewMode === 'grid') {
766
+ setLightboxIndex(index);
767
+ setLightboxOpen(true);
768
+ }
769
+ }}
770
+ >
771
+ <ImageLoader
772
+ src={pageUrl}
773
+ alt={`Página ${index + 1}`}
774
+ aspectRatio={viewMode === 'vertical' ? 'auto' : '1/1'}
775
+ objectFit={viewMode === 'vertical' ? 'contain' : 'cover'}
776
+ loading={index > 2 ? "lazy" : "eager"}
777
+ className={viewMode === 'vertical' ? 'rounded-lg shadow-2xl' : 'rounded-lg'}
778
+ imgClassName={viewMode === 'vertical' ? '' : 'group-hover:scale-110'}
779
+ />
780
+ </div>
781
+ ))
782
+ )}
783
+ </div>
784
+ </div>
785
+ )}
786
+
787
+ {!searchTerm.trim() && recommendations.length > 0 && (
788
+ <div className="mt-8 sm:mt-12 border-t border-gray-800 pt-8 sm:pt-12">
789
+ <h3 className="text-xl sm:text-2xl font-bold text-white mb-6">Recomendaciones</h3>
790
+ {loadingRecommendations ? (
791
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3">
792
+ {Array.from({ length: 6 }).map((_, index) => (
793
+ <div key={index} className="animate-pulse">
794
+ <div className="bg-gray-800 rounded-lg aspect-[2/3] w-full mb-2"></div>
795
+ <div className="h-3 bg-gray-800 rounded w-3/4 mx-auto mb-1"></div>
796
+ <div className="h-2 bg-gray-800 rounded w-1/2 mx-auto"></div>
797
+ </div>
798
+ ))}
799
+ </div>
800
+ ) : (
801
+ <>
802
+ <div
803
+ key={recPage}
804
+ className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 mb-6 animate-slide-in-right"
805
+ >
806
+ {recommendations.slice((recPage - 1) * REC_ITEMS_PER_PAGE, recPage * REC_ITEMS_PER_PAGE).map((rec, index) => (
807
+ <div
808
+ key={rec.id}
809
+ >
810
+ <div
811
+ onClick={() => {
812
+ window.scrollTo({ top: 0, behavior: 'smooth' });
813
+ if (onNavigateToManga) {
814
+ onNavigateToManga(rec.id);
815
+ }
816
+ }}
817
+ className="group cursor-pointer flex flex-col"
818
+ >
819
+ <div className="relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02]">
820
+ {rec.cover_url || rec.thumbnail_url ? (
821
+ <>
822
+ <ImageLoader
823
+ src={rec.cover_url || rec.thumbnail_url || ''}
824
+ alt={rec.title}
825
+ aspectRatio="2/3"
826
+ objectFit="cover"
827
+ loading="lazy"
828
+ imgClassName="group-hover:scale-110"
829
+ />
830
+ <div className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 ease-in-out pointer-events-none"></div>
831
+ </>
832
+ ) : (
833
+ <div className="w-full aspect-[2/3] flex items-center justify-center text-white/40 bg-black">
834
+ <BookMarked className="w-8 h-8" />
835
+ </div>
836
+ )}
837
+ </div>
838
+
839
+ <div className="mt-2 flex flex-col gap-0.5">
840
+ <h4 className="font-semibold text-xs text-white line-clamp-2 text-center group-hover:text-[#bb86fc] transition-colors duration-300">
841
+ {rec.title}
842
+ </h4>
843
+ {rec.categories && rec.categories.length > 0 && (
844
+ <p className="text-xs text-gray-500 text-center truncate">
845
+ {rec.categories[0].name}
846
+ </p>
847
+ )}
848
+ </div>
849
+ </div>
850
+ </div>
851
+ ))}
852
+ </div>
853
+
854
+ {recommendations.length > REC_ITEMS_PER_PAGE && (
855
+ <div className="flex items-center justify-center gap-2 mt-4 flex-wrap">
856
+ <button
857
+ onClick={() => setRecPage(1)}
858
+ disabled={recPage === 1}
859
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
860
+ >
861
+ <ChevronsLeft className="w-4 h-4" />
862
+ </button>
863
+ <button
864
+ onClick={() => setRecPage(p => Math.max(1, p - 1))}
865
+ disabled={recPage === 1}
866
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
867
+ >
868
+ <ChevronLeft className="w-4 h-4" />
869
+ </button>
870
+
871
+ <span className="text-sm text-gray-400 px-2">
872
+ Página {recPage} de {Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE)}
873
+ </span>
874
+
875
+ <button
876
+ onClick={() => setRecPage(p => Math.min(Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE), p + 1))}
877
+ disabled={recPage === Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE)}
878
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
879
+ >
880
+ <ChevronRight className="w-4 h-4" />
881
+ </button>
882
+ <button
883
+ onClick={() => setRecPage(Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE))}
884
+ disabled={recPage === Math.ceil(recommendations.length / REC_ITEMS_PER_PAGE)}
885
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
886
+ >
887
+ <ChevronsRight className="w-4 h-4" />
888
+ </button>
889
+ </div>
890
+ )}
891
+ </>
892
+ )}
893
+ </div>
894
+ )}
895
+ </div>
896
+ <GlobalFooter />
897
+ </main>
898
+
899
+ {lightboxOpen && manga.chapters?.[0]?.pages && (
900
+ <ImageLightbox
901
+ images={manga.chapters?.[0].pages || []}
902
+ initialIndex={lightboxIndex}
903
+ onClose={() => setLightboxOpen(false)}
904
+ />
905
+ )}
906
+
907
+ {showExternalLinkModal && (
908
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
909
+ <div className="bg-gradient-to-b from-[#1f1f1f] to-[#121212] rounded-2xl border border-gray-700/40 w-full max-w-md shadow-2xl">
910
+ <div className="bg-gradient-to-b from-[#2a2a2a]/80 to-[#1f1f1f]/80 border-b border-gray-700/30 px-6 py-4 flex items-center justify-between">
911
+ <h2 className="text-xl font-bold text-white">Añadir Enlace Externo</h2>
912
+ <button
913
+ onClick={() => setShowExternalLinkModal(false)}
914
+ className="text-gray-500 hover:text-white transition-colors p-1.5 rounded-lg hover:bg-white/10"
915
+ >
916
+ <X className="w-5 h-5" />
917
+ </button>
918
+ </div>
919
+
920
+ <div className="p-6 space-y-4">
921
+ <div>
922
+ <label className="block text-sm font-semibold text-gray-200 mb-2">
923
+ Nombre del Enlace
924
+ </label>
925
+ <input
926
+ type="text"
927
+ placeholder="Ej: Servidor Alternativo"
928
+ value={externalLinkForm.name}
929
+ onChange={(e) => setExternalLinkForm({ ...externalLinkForm, name: e.target.value })}
930
+ className="w-full bg-[#1a1a1a] border border-gray-600/50 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-[#bb86fc] focus:ring-2 focus:ring-[#bb86fc]/30 transition-all"
931
+ />
932
+ </div>
933
+
934
+ <div>
935
+ <label className="block text-sm font-semibold text-gray-200 mb-2">
936
+ URL del Enlace
937
+ </label>
938
+ <input
939
+ type="url"
940
+ placeholder="https://ejemplo.com/descarga"
941
+ value={externalLinkForm.url}
942
+ onChange={(e) => setExternalLinkForm({ ...externalLinkForm, url: e.target.value })}
943
+ className="w-full bg-[#1a1a1a] border border-gray-600/50 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-[#bb86fc] focus:ring-2 focus:ring-[#bb86fc]/30 transition-all"
944
+ />
945
+ </div>
946
+
947
+ <div className="flex gap-3 pt-2">
948
+ <button
949
+ onClick={() => setShowExternalLinkModal(false)}
950
+ className="flex-1 bg-[#1a1a1a] border border-gray-600/50 hover:border-gray-500 hover:bg-[#242424] text-white px-4 py-3 rounded-lg font-semibold text-sm transition-all"
951
+ >
952
+ Cancelar
953
+ </button>
954
+ <button
955
+ onClick={handleAddExternalLink}
956
+ disabled={!externalLinkForm.name.trim() || !externalLinkForm.url.trim()}
957
+ className="flex-1 bg-gradient-to-r from-[#bb86fc] to-[#9966dd] hover:from-[#9966dd] hover:to-[#7744cc] disabled:opacity-50 disabled:cursor-not-allowed text-white px-4 py-3 rounded-lg font-semibold text-sm transition-all shadow-lg shadow-[#bb86fc]/40 hover:shadow-[#bb86fc]/60"
958
+ >
959
+ Añadir Enlace
960
+ </button>
961
+ </div>
962
+ </div>
963
+ </div>
964
+ </div>
965
+ )}
966
+ </div>
967
+ );
968
+ }
src/components/GlobalFooter.tsx CHANGED
@@ -1,97 +1,76 @@
1
- import { Info, Users } from 'lucide-react';
2
- import { useState, useEffect } from 'react';
3
-
4
- function LiveCounter() {
5
- const [count, setCount] = useState(1);
6
-
7
- useEffect(() => {
8
- // In a future update, we can connect this to Firebase Realtime Database
9
- // for an accurate count of online users.
10
- // For now, we show 1 to represent the current user.
11
- setCount(1);
12
- }, []);
13
-
14
- return (
15
- <div className="flex items-center gap-2 text-[#bb86fc] bg-[#bb86fc]/10 px-3 py-1 rounded-full border border-[#bb86fc]/20 shadow-[0_0_10px_rgba(187,134,252,0.1)]">
16
- <Users className="w-4 h-4" />
17
- <span className="font-mono font-bold text-sm tracking-wide animate-pulse">
18
- {count.toLocaleString()}
19
- </span>
20
- <span className="text-[10px] text-gray-400 uppercase tracking-wider ml-1">Live</span>
21
- </div>
22
- );
23
- }
24
-
25
- export function GlobalFooter() {
26
- return (
27
- <footer className="py-6 border-t border-gray-800/50 flex flex-col md:flex-row items-center justify-between gap-4 text-gray-400 text-sm mt-auto w-full px-8 relative">
28
-
29
- {/* Left: Live Counter */}
30
- <div className="md:absolute md:left-8">
31
- <LiveCounter />
32
- </div>
33
-
34
- {/* Center: Social Links */}
35
- <div className="flex flex-wrap justify-center gap-6 mx-auto">
36
- <a
37
- href="https://t.me/twistedbrody"
38
- target="_blank"
39
- rel="noopener noreferrer"
40
- className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
41
- >
42
- <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
43
- <path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm5.894 8.221l-1.97 9.28c-.145.658-.537.818-1.084.508l-3-2.21-1.446 1.394c-.16.16-.295.295-.605.295l.213-3.054 5.56-5.022c.242-.213-.054-.333-.373-.121l-6.869 4.326-2.96-.924c-.64-.203-.658-.64.135-.954l11.566-4.458c.538-.196 1.006.128.832.941z" />
44
- </svg>
45
- Twisted Brody
46
- </a>
47
- <a
48
- href="https://t.me/+CmmZFHM9hpViYzMx"
49
- target="_blank"
50
- rel="noopener noreferrer"
51
- className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
52
- >
53
- <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
54
- <path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm5.894 8.221l-1.97 9.28c-.145.658-.537.818-1.084.508l-3-2.21-1.446 1.394c-.16.16-.295.295-.605.295l.213-3.054 5.56-5.022c.242-.213-.054-.333-.373-.121l-6.869 4.326-2.96-.924c-.64-.203-.658-.64.135-.954l11.566-4.458c.538-.196 1.006.128.832.941z" />
55
- </svg>
56
- Canal Hub
57
- </a>
58
- <a
59
- href="https://x.com/TwistedBrody"
60
- target="_blank"
61
- rel="noopener noreferrer"
62
- className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
63
- >
64
- <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
65
- <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
66
- </svg>
67
- X
68
- </a>
69
- <a
70
- href="https://www.patreon.com/cw/Twistedbrody"
71
- target="_blank"
72
- rel="noopener noreferrer"
73
- className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
74
- >
75
- <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
76
- <path d="M0 .48v23.04h4.22V.48zm15.385 0c-4.764 0-8.641 3.88-8.641 8.65 0 4.755 3.877 8.623 8.641 8.623 4.75 0 8.615-3.868 8.615-8.623C24 4.36 20.136.48 15.385.48z" />
77
- </svg>
78
- Patreon
79
- </a>
80
- <button
81
- onClick={() => {
82
- window.location.hash = 'info';
83
- }}
84
- className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
85
- >
86
- <Info className="w-4 h-4" />
87
- <span>Info</span>
88
- </button>
89
- </div>
90
-
91
- {/* Right: Copyright (visible only on md screens and up, or pushed down on mobile) */}
92
- <div className="md:absolute md:right-8 text-xs opacity-50">
93
- Twisted Brody MangaFlow &copy; {new Date().getFullYear()}
94
- </div>
95
- </footer>
96
- );
97
- }
 
1
+ import { Info } from 'lucide-react';
2
+
3
+
4
+
5
+
6
+ export function GlobalFooter() {
7
+ return (
8
+ <footer className="py-6 border-t border-gray-800/50 flex flex-col md:flex-row items-center justify-between gap-4 text-gray-400 text-sm mt-auto w-full px-8 relative">
9
+
10
+ {/* Left: Live Counter */}
11
+
12
+
13
+ {/* Center: Social Links */}
14
+ <div className="flex flex-wrap justify-center gap-6 mx-auto">
15
+ <a
16
+ href="https://t.me/twistedbrody"
17
+ target="_blank"
18
+ rel="noopener noreferrer"
19
+ className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
20
+ >
21
+ <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
22
+ <path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm5.894 8.221l-1.97 9.28c-.145.658-.537.818-1.084.508l-3-2.21-1.446 1.394c-.16.16-.295.295-.605.295l.213-3.054 5.56-5.022c.242-.213-.054-.333-.373-.121l-6.869 4.326-2.96-.924c-.64-.203-.658-.64.135-.954l11.566-4.458c.538-.196 1.006.128.832.941z" />
23
+ </svg>
24
+ Twisted Brody
25
+ </a>
26
+ <a
27
+ href="https://t.me/+CmmZFHM9hpViYzMx"
28
+ target="_blank"
29
+ rel="noopener noreferrer"
30
+ className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
31
+ >
32
+ <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
33
+ <path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm5.894 8.221l-1.97 9.28c-.145.658-.537.818-1.084.508l-3-2.21-1.446 1.394c-.16.16-.295.295-.605.295l.213-3.054 5.56-5.022c.242-.213-.054-.333-.373-.121l-6.869 4.326-2.96-.924c-.64-.203-.658-.64.135-.954l11.566-4.458c.538-.196 1.006.128.832.941z" />
34
+ </svg>
35
+ Canal Hub
36
+ </a>
37
+ <a
38
+ href="https://x.com/TwistedBrody"
39
+ target="_blank"
40
+ rel="noopener noreferrer"
41
+ className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
42
+ >
43
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
44
+ <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
45
+ </svg>
46
+ X
47
+ </a>
48
+ <a
49
+ href="https://www.patreon.com/cw/Twistedbrody"
50
+ target="_blank"
51
+ rel="noopener noreferrer"
52
+ className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
53
+ >
54
+ <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
55
+ <path d="M0 .48v23.04h4.22V.48zm15.385 0c-4.764 0-8.641 3.88-8.641 8.65 0 4.755 3.877 8.623 8.641 8.623 4.75 0 8.615-3.868 8.615-8.623C24 4.36 20.136.48 15.385.48z" />
56
+ </svg>
57
+ Patreon
58
+ </a>
59
+ <button
60
+ onClick={() => {
61
+ window.location.hash = 'info';
62
+ }}
63
+ className="flex items-center gap-2 hover:text-[#bb86fc] transition-colors"
64
+ >
65
+ <Info className="w-4 h-4" />
66
+ <span>Info</span>
67
+ </button>
68
+ </div>
69
+
70
+ {/* Right: Copyright (visible only on md screens and up, or pushed down on mobile) */}
71
+ <div className="md:absolute md:right-8 text-xs opacity-50">
72
+ Twisted Brody MangaFlow &copy; {new Date().getFullYear()}
73
+ </div>
74
+ </footer>
75
+ );
76
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/components/ImageLightbox.tsx CHANGED
@@ -1,275 +1,275 @@
1
- import { ChevronLeft, ChevronRight, X, ZoomIn, ZoomOut } from 'lucide-react';
2
- import { useState, useEffect, useRef } from 'react';
3
- import { ImageLoader } from './ImageLoader';
4
-
5
- interface ImageLightboxProps {
6
- images: string[];
7
- initialIndex: number;
8
- onClose: () => void;
9
- }
10
-
11
- export function ImageLightbox({ images, initialIndex, onClose }: ImageLightboxProps) {
12
- const [currentIndex, setCurrentIndex] = useState(initialIndex);
13
- const [isAnimating, setIsAnimating] = useState(false);
14
-
15
- // Zoom & Pan states
16
- const [scale, setScale] = useState(1);
17
- const [position, setPosition] = useState({ x: 0, y: 0 });
18
- const [isDragging, setIsDragging] = useState(false);
19
- const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
20
-
21
- // Swipe states (only relevant when scale === 1)
22
- const [dragOffset, setDragOffset] = useState(0);
23
-
24
- const containerRef = useRef<HTMLDivElement>(null);
25
-
26
- useEffect(() => {
27
- document.body.style.overflow = 'hidden';
28
- return () => {
29
- document.body.style.overflow = 'unset';
30
- };
31
- }, []);
32
-
33
- // Reset zoom when changing images
34
- useEffect(() => {
35
- setScale(1);
36
- setPosition({ x: 0, y: 0 });
37
- setDragOffset(0);
38
- }, [currentIndex]);
39
-
40
- useEffect(() => {
41
- function handleKeyDown(e: KeyboardEvent) {
42
- if (e.key === 'Escape') {
43
- onClose();
44
- } else if (e.key === 'ArrowLeft') {
45
- handlePrevious();
46
- } else if (e.key === 'ArrowRight') {
47
- handleNext();
48
- } else if (e.key === '+' || e.key === '=') {
49
- handleZoomIn();
50
- } else if (e.key === '-') {
51
- handleZoomOut();
52
- }
53
- }
54
-
55
- window.addEventListener('keydown', handleKeyDown);
56
- return () => window.removeEventListener('keydown', handleKeyDown);
57
- }, [currentIndex, isAnimating, scale]);
58
-
59
- const handlePrevious = () => {
60
- if (isAnimating || scale > 1) return; // Prevent swipe if zoomed in
61
- setIsAnimating(true);
62
- setCurrentIndex((prev) => (prev === 0 ? images.length - 1 : prev - 1));
63
- setTimeout(() => setIsAnimating(false), 300);
64
- };
65
-
66
- const handleNext = () => {
67
- if (isAnimating || scale > 1) return; // Prevent swipe if zoomed in
68
- setIsAnimating(true);
69
- setCurrentIndex((prev) => (prev === images.length - 1 ? 0 : prev + 1));
70
- setTimeout(() => setIsAnimating(false), 300);
71
- };
72
-
73
- const handleZoomIn = () => {
74
- setScale(prev => Math.min(prev + 0.5, 4));
75
- };
76
-
77
- const handleZoomOut = () => {
78
- setScale(prev => {
79
- const newScale = Math.max(prev - 0.5, 1);
80
- if (newScale === 1) setPosition({ x: 0, y: 0 });
81
- return newScale;
82
- });
83
- };
84
-
85
- const handleWheel = (e: React.WheelEvent) => {
86
- e.stopPropagation();
87
- if (e.deltaY < 0) {
88
- handleZoomIn();
89
- } else {
90
- handleZoomOut();
91
- }
92
- };
93
-
94
- const handleDoubleClick = (e: React.MouseEvent) => {
95
- e.stopPropagation();
96
- if (scale > 1) {
97
- setScale(1);
98
- setPosition({ x: 0, y: 0 });
99
- } else {
100
- setScale(2.5);
101
- // Optional: Zoom to cursor could be calculated here, but center zoom is simpler effectively
102
- }
103
- };
104
-
105
- // --- Unified Touch/Mouse Handlers ---
106
-
107
- const handleStart = (clientX: number, clientY: number) => {
108
- setIsDragging(true);
109
- setDragStart({ x: clientX - position.x, y: clientY - position.y });
110
- };
111
-
112
- const handleMove = (clientX: number, clientY: number) => {
113
- if (!isDragging) return;
114
-
115
- if (scale > 1) {
116
- // PANNING
117
- const newX = clientX - dragStart.x;
118
- const newY = clientY - dragStart.y;
119
-
120
- // Basic bounds calculation (optional, to stop panning too far)
121
- // For now, free panning is often acceptable or just limit loosely
122
- setPosition({ x: newX, y: newY });
123
- } else {
124
- // SWIPING
125
- // We only care about X for swiping
126
- const diffX = clientX - (dragStart.x + position.x); // reconstruct original start X efficiently?
127
- // actually dragStart.x was (clientX_start - 0), so clientX - dragStart.x is the difference
128
- setDragOffset(diffX);
129
- }
130
- };
131
-
132
- const handleEnd = () => {
133
- setIsDragging(false);
134
-
135
- if (scale === 1) {
136
- // End Swipe
137
- if (Math.abs(dragOffset) > 50) {
138
- if (dragOffset > 0) handlePrevious();
139
- else handleNext();
140
- }
141
- setDragOffset(0);
142
- } else {
143
- // End Pan - maybe snap back if out of bounds?
144
- // leaving as is for free movement
145
- }
146
- };
147
-
148
- // --- Mouse Events ---
149
- const onMouseDown = (e: React.MouseEvent) => {
150
- e.preventDefault();
151
- handleStart(e.clientX, e.clientY);
152
- };
153
-
154
- const onMouseMove = (e: React.MouseEvent) => {
155
- e.preventDefault();
156
- handleMove(e.clientX, e.clientY);
157
- };
158
-
159
- const onMouseUp = (e: React.MouseEvent) => {
160
- handleEnd();
161
- };
162
-
163
- // --- Touch Events ---
164
- const onTouchStart = (e: React.TouchEvent) => {
165
- if (e.touches.length === 1) {
166
- handleStart(e.touches[0].clientX, e.touches[0].clientY);
167
- }
168
- };
169
-
170
- const onTouchMove = (e: React.TouchEvent) => {
171
- if (e.touches.length === 1) {
172
- handleMove(e.touches[0].clientX, e.touches[0].clientY);
173
- }
174
- };
175
-
176
- const onTouchEnd = (e: React.TouchEvent) => {
177
- handleEnd();
178
- };
179
-
180
- return (
181
- <div
182
- className="fixed inset-0 bg-black/95 flex items-center justify-center z-50 select-none touch-none"
183
- onClick={(e) => {
184
- if (e.target === e.currentTarget) onClose();
185
- }}
186
- onWheel={handleWheel}
187
- // Combine handlers
188
- onMouseDown={onMouseDown}
189
- onMouseMove={onMouseMove}
190
- onMouseUp={onMouseUp}
191
- onMouseLeave={() => {
192
- setIsDragging(false);
193
- if (scale === 1) setDragOffset(0);
194
- }}
195
- onTouchStart={onTouchStart}
196
- onTouchMove={onTouchMove}
197
- onTouchEnd={onTouchEnd}
198
- ref={containerRef}
199
- >
200
- {/* Controls */}
201
- <div className="absolute top-6 right-6 flex items-center gap-4 z-50">
202
- <div className="flex items-center gap-2 bg-black/50 rounded-lg p-1">
203
- <button onClick={handleZoomOut} className="p-2 text-white hover:text-[#bb86fc] transition-colors">
204
- <ZoomOut className="w-5 h-5" />
205
- </button>
206
- <span className="text-white text-sm min-w-[3ch] text-center">{Math.round(scale * 100)}%</span>
207
- <button onClick={handleZoomIn} className="p-2 text-white hover:text-[#bb86fc] transition-colors">
208
- <ZoomIn className="w-5 h-5" />
209
- </button>
210
- </div>
211
-
212
- <button
213
- onClick={onClose}
214
- className="p-2 rounded-lg bg-white/10 hover:bg-white/20 text-white transition-all duration-200"
215
- >
216
- <X className="w-6 h-6" />
217
- </button>
218
- </div>
219
-
220
- <div className="relative w-full h-full flex items-center justify-center overflow-hidden">
221
- <div
222
- className="relative flex items-center justify-center w-full h-full"
223
- style={{
224
- transform: scale === 1
225
- ? `translateX(${dragOffset}px)`
226
- : `translate(${position.x}px, ${position.y}px) scale(${scale})`,
227
- transition: isDragging ? 'none' : 'transform 0.2s ease-out',
228
- cursor: scale > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default'
229
- }}
230
- onDoubleClick={handleDoubleClick}
231
- >
232
-
233
- <div className="relative pointer-events-none">
234
- {/* Image with ImageLoader */}
235
- <ImageLoader
236
- src={images[currentIndex]}
237
- alt={`Página ${currentIndex + 1}`}
238
- aspectRatio="auto"
239
- objectFit="contain"
240
- loading="eager"
241
- draggable={false}
242
- // We remove hover scaling here to avoid conflict with our zoom
243
- className="max-w-[100vw] max-h-[100vh] w-auto h-auto"
244
- imgClassName="max-w-full max-h-screen object-contain"
245
- />
246
- </div>
247
-
248
- </div>
249
-
250
- {/* Navigation Arrows - Only show when not zoomed */}
251
- {scale === 1 && (
252
- <>
253
- <button
254
- onClick={(e) => { e.stopPropagation(); handlePrevious(); }}
255
- className="absolute left-4 sm:left-8 top-1/2 -translate-y-1/2 p-3 sm:p-4 rounded-lg text-white opacity-40 hover:opacity-100 transition-opacity duration-200 z-40"
256
- >
257
- <ChevronLeft className="w-8 h-8 sm:w-10 sm:h-10" />
258
- </button>
259
-
260
- <button
261
- onClick={(e) => { e.stopPropagation(); handleNext(); }}
262
- className="absolute right-4 sm:right-8 top-1/2 -translate-y-1/2 p-3 sm:p-4 rounded-lg text-white opacity-40 hover:opacity-100 transition-opacity duration-200 z-40"
263
- >
264
- <ChevronRight className="w-8 h-8 sm:w-10 sm:h-10" />
265
- </button>
266
- </>
267
- )}
268
-
269
- <div className="absolute bottom-6 left-1/2 -translate-x-1/2 bg-black/60 text-white px-4 py-2 rounded-lg text-sm font-medium z-40 pointer-events-none">
270
- {currentIndex + 1} / {images.length}
271
- </div>
272
- </div>
273
- </div>
274
- );
275
- }
 
1
+ import { ChevronLeft, ChevronRight, X, ZoomIn, ZoomOut } from 'lucide-react';
2
+ import { useState, useEffect, useRef } from 'react';
3
+ import { ImageLoader } from './ImageLoader';
4
+
5
+ interface ImageLightboxProps {
6
+ images: string[];
7
+ initialIndex: number;
8
+ onClose: () => void;
9
+ }
10
+
11
+ export function ImageLightbox({ images, initialIndex, onClose }: ImageLightboxProps) {
12
+ const [currentIndex, setCurrentIndex] = useState(initialIndex);
13
+ const [isAnimating, setIsAnimating] = useState(false);
14
+
15
+ // Zoom & Pan states
16
+ const [scale, setScale] = useState(1);
17
+ const [position, setPosition] = useState({ x: 0, y: 0 });
18
+ const [isDragging, setIsDragging] = useState(false);
19
+ const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
20
+
21
+ // Swipe states (only relevant when scale === 1)
22
+ const [dragOffset, setDragOffset] = useState(0);
23
+
24
+ const containerRef = useRef<HTMLDivElement>(null);
25
+
26
+ useEffect(() => {
27
+ document.body.style.overflow = 'hidden';
28
+ return () => {
29
+ document.body.style.overflow = 'unset';
30
+ };
31
+ }, []);
32
+
33
+ // Reset zoom when changing images
34
+ useEffect(() => {
35
+ setScale(1);
36
+ setPosition({ x: 0, y: 0 });
37
+ setDragOffset(0);
38
+ }, [currentIndex]);
39
+
40
+ useEffect(() => {
41
+ function handleKeyDown(e: KeyboardEvent) {
42
+ if (e.key === 'Escape') {
43
+ onClose();
44
+ } else if (e.key === 'ArrowLeft') {
45
+ handlePrevious();
46
+ } else if (e.key === 'ArrowRight') {
47
+ handleNext();
48
+ } else if (e.key === '+' || e.key === '=') {
49
+ handleZoomIn();
50
+ } else if (e.key === '-') {
51
+ handleZoomOut();
52
+ }
53
+ }
54
+
55
+ window.addEventListener('keydown', handleKeyDown);
56
+ return () => window.removeEventListener('keydown', handleKeyDown);
57
+ }, [currentIndex, isAnimating, scale]);
58
+
59
+ const handlePrevious = () => {
60
+ if (isAnimating || scale > 1) return; // Prevent swipe if zoomed in
61
+ setIsAnimating(true);
62
+ setCurrentIndex((prev) => (prev === 0 ? images.length - 1 : prev - 1));
63
+ setTimeout(() => setIsAnimating(false), 300);
64
+ };
65
+
66
+ const handleNext = () => {
67
+ if (isAnimating || scale > 1) return; // Prevent swipe if zoomed in
68
+ setIsAnimating(true);
69
+ setCurrentIndex((prev) => (prev === images.length - 1 ? 0 : prev + 1));
70
+ setTimeout(() => setIsAnimating(false), 300);
71
+ };
72
+
73
+ const handleZoomIn = () => {
74
+ setScale(prev => Math.min(prev + 0.5, 4));
75
+ };
76
+
77
+ const handleZoomOut = () => {
78
+ setScale(prev => {
79
+ const newScale = Math.max(prev - 0.5, 1);
80
+ if (newScale === 1) setPosition({ x: 0, y: 0 });
81
+ return newScale;
82
+ });
83
+ };
84
+
85
+ const handleWheel = (e: React.WheelEvent) => {
86
+ e.stopPropagation();
87
+ if (e.deltaY < 0) {
88
+ handleZoomIn();
89
+ } else {
90
+ handleZoomOut();
91
+ }
92
+ };
93
+
94
+ const handleDoubleClick = (e: React.MouseEvent) => {
95
+ e.stopPropagation();
96
+ if (scale > 1) {
97
+ setScale(1);
98
+ setPosition({ x: 0, y: 0 });
99
+ } else {
100
+ setScale(2.5);
101
+ // Optional: Zoom to cursor could be calculated here, but center zoom is simpler effectively
102
+ }
103
+ };
104
+
105
+ // --- Unified Touch/Mouse Handlers ---
106
+
107
+ const handleStart = (clientX: number, clientY: number) => {
108
+ setIsDragging(true);
109
+ setDragStart({ x: clientX - position.x, y: clientY - position.y });
110
+ };
111
+
112
+ const handleMove = (clientX: number, clientY: number) => {
113
+ if (!isDragging) return;
114
+
115
+ if (scale > 1) {
116
+ // PANNING
117
+ const newX = clientX - dragStart.x;
118
+ const newY = clientY - dragStart.y;
119
+
120
+ // Basic bounds calculation (optional, to stop panning too far)
121
+ // For now, free panning is often acceptable or just limit loosely
122
+ setPosition({ x: newX, y: newY });
123
+ } else {
124
+ // SWIPING
125
+ // We only care about X for swiping
126
+ const diffX = clientX - (dragStart.x + position.x); // reconstruct original start X efficiently?
127
+ // actually dragStart.x was (clientX_start - 0), so clientX - dragStart.x is the difference
128
+ setDragOffset(diffX);
129
+ }
130
+ };
131
+
132
+ const handleEnd = () => {
133
+ setIsDragging(false);
134
+
135
+ if (scale === 1) {
136
+ // End Swipe
137
+ if (Math.abs(dragOffset) > 50) {
138
+ if (dragOffset > 0) handlePrevious();
139
+ else handleNext();
140
+ }
141
+ setDragOffset(0);
142
+ } else {
143
+ // End Pan - maybe snap back if out of bounds?
144
+ // leaving as is for free movement
145
+ }
146
+ };
147
+
148
+ // --- Mouse Events ---
149
+ const onMouseDown = (e: React.MouseEvent) => {
150
+ e.preventDefault();
151
+ handleStart(e.clientX, e.clientY);
152
+ };
153
+
154
+ const onMouseMove = (e: React.MouseEvent) => {
155
+ e.preventDefault();
156
+ handleMove(e.clientX, e.clientY);
157
+ };
158
+
159
+ const onMouseUp = (e: React.MouseEvent) => {
160
+ handleEnd();
161
+ };
162
+
163
+ // --- Touch Events ---
164
+ const onTouchStart = (e: React.TouchEvent) => {
165
+ if (e.touches.length === 1) {
166
+ handleStart(e.touches[0].clientX, e.touches[0].clientY);
167
+ }
168
+ };
169
+
170
+ const onTouchMove = (e: React.TouchEvent) => {
171
+ if (e.touches.length === 1) {
172
+ handleMove(e.touches[0].clientX, e.touches[0].clientY);
173
+ }
174
+ };
175
+
176
+ const onTouchEnd = (e: React.TouchEvent) => {
177
+ handleEnd();
178
+ };
179
+
180
+ return (
181
+ <div
182
+ className="fixed inset-0 bg-black/95 flex items-center justify-center z-50 select-none touch-none"
183
+ onClick={(e) => {
184
+ if (e.target === e.currentTarget) onClose();
185
+ }}
186
+ onWheel={handleWheel}
187
+ // Combine handlers
188
+ onMouseDown={onMouseDown}
189
+ onMouseMove={onMouseMove}
190
+ onMouseUp={onMouseUp}
191
+ onMouseLeave={() => {
192
+ setIsDragging(false);
193
+ if (scale === 1) setDragOffset(0);
194
+ }}
195
+ onTouchStart={onTouchStart}
196
+ onTouchMove={onTouchMove}
197
+ onTouchEnd={onTouchEnd}
198
+ ref={containerRef}
199
+ >
200
+ {/* Controls */}
201
+ <div className="absolute top-6 right-6 flex items-center gap-4 z-50">
202
+ <div className="flex items-center gap-2 bg-black/50 rounded-lg p-1">
203
+ <button onClick={handleZoomOut} className="p-2 text-white hover:text-[#bb86fc] transition-colors">
204
+ <ZoomOut className="w-5 h-5" />
205
+ </button>
206
+ <span className="text-white text-sm min-w-[3ch] text-center">{Math.round(scale * 100)}%</span>
207
+ <button onClick={handleZoomIn} className="p-2 text-white hover:text-[#bb86fc] transition-colors">
208
+ <ZoomIn className="w-5 h-5" />
209
+ </button>
210
+ </div>
211
+
212
+ <button
213
+ onClick={onClose}
214
+ className="p-2 rounded-lg bg-white/10 hover:bg-white/20 text-white transition-all duration-200"
215
+ >
216
+ <X className="w-6 h-6" />
217
+ </button>
218
+ </div>
219
+
220
+ <div className="relative w-full h-full flex items-center justify-center overflow-hidden">
221
+ <div
222
+ className="relative flex items-center justify-center w-full h-full"
223
+ style={{
224
+ transform: scale === 1
225
+ ? `translateX(${dragOffset}px)`
226
+ : `translate(${position.x}px, ${position.y}px) scale(${scale})`,
227
+ transition: isDragging ? 'none' : 'transform 0.2s ease-out',
228
+ cursor: scale > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default'
229
+ }}
230
+ onDoubleClick={handleDoubleClick}
231
+ >
232
+
233
+ <div className="relative pointer-events-none">
234
+ {/* Image with ImageLoader */}
235
+ <ImageLoader
236
+ src={images[currentIndex]}
237
+ alt={`Página ${currentIndex + 1}`}
238
+ aspectRatio="auto"
239
+ objectFit="contain"
240
+ loading="eager"
241
+ draggable={false}
242
+ // We remove hover scaling here to avoid conflict with our zoom
243
+ className="max-w-[100vw] max-h-[100vh] w-auto h-auto"
244
+ imgClassName="max-w-full max-h-screen object-contain"
245
+ />
246
+ </div>
247
+
248
+ </div>
249
+
250
+ {/* Navigation Arrows - Only show when not zoomed */}
251
+ {scale === 1 && (
252
+ <>
253
+ <button
254
+ onClick={(e) => { e.stopPropagation(); handlePrevious(); }}
255
+ className="absolute left-4 sm:left-8 top-1/2 -translate-y-1/2 p-3 sm:p-4 rounded-lg text-white opacity-40 hover:opacity-100 transition-opacity duration-200 z-40"
256
+ >
257
+ <ChevronLeft className="w-8 h-8 sm:w-10 sm:h-10" />
258
+ </button>
259
+
260
+ <button
261
+ onClick={(e) => { e.stopPropagation(); handleNext(); }}
262
+ className="absolute right-4 sm:right-8 top-1/2 -translate-y-1/2 p-3 sm:p-4 rounded-lg text-white opacity-40 hover:opacity-100 transition-opacity duration-200 z-40"
263
+ >
264
+ <ChevronRight className="w-8 h-8 sm:w-10 sm:h-10" />
265
+ </button>
266
+ </>
267
+ )}
268
+
269
+ <div className="absolute bottom-6 left-1/2 -translate-x-1/2 bg-black/60 text-white px-4 py-2 rounded-lg text-sm font-medium z-40 pointer-events-none">
270
+ {currentIndex + 1} / {images.length}
271
+ </div>
272
+ </div>
273
+ </div>
274
+ );
275
+ }
src/components/ImageLoader.tsx CHANGED
@@ -1,61 +1,61 @@
1
- import { useState } from 'react';
2
-
3
- interface ImageLoaderProps {
4
- src: string;
5
- alt: string;
6
- className?: string;
7
- imgClassName?: string;
8
- objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down';
9
- aspectRatio?: string;
10
- loading?: 'lazy' | 'eager';
11
- showPlaceholder?: boolean;
12
- }
13
-
14
- export function ImageLoader({
15
- src,
16
- alt,
17
- className = '',
18
- imgClassName = '',
19
- objectFit = 'contain',
20
- aspectRatio,
21
- loading,
22
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
23
- showPlaceholder
24
- }: ImageLoaderProps) {
25
- // 1. Estados para controlar qué mostrar
26
- const [isLoaded, setIsLoaded] = useState(false);
27
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
28
- const [hasError, setHasError] = useState(false);
29
-
30
- return (
31
- <div
32
- className={`relative w-full h-full overflow-hidden ${className}`}
33
- style={aspectRatio && aspectRatio !== 'auto' ? { aspectRatio } : undefined}
34
- >
35
-
36
- {/* 2. EL SPINNER (Círculo de carga)
37
- Se muestra solo si NO ha terminado de cargar (!isLoaded).
38
- Cuando carga, se vuelve invisible (opacity-0).
39
- */}
40
- <div className={`absolute inset-0 flex items-center justify-center transition-opacity duration-500 ${isLoaded ? 'opacity-0 pointer-events-none' : 'opacity-100'
41
- }`}>
42
- <div className="w-8 h-8 border-2 border-purple-500 border-t-transparent rounded-full animate-spin"></div>
43
- </div>
44
-
45
- {/* 3. LA IMAGEN REAL
46
- Empieza invisible (opacity-0).
47
- Cuando se dispara onLoad, pasa a 'opacity-100' creando la animación de aparición.
48
- */}
49
- <img
50
- src={src}
51
- alt={alt}
52
- loading={loading}
53
- className={`w-full h-full object-${objectFit} transition-all duration-1000 ease-linear ${imgClassName} ${isLoaded ? 'opacity-100' : 'opacity-0'
54
- }`}
55
- onLoad={() => setIsLoaded(true)} // ¡Aquí ocurre la magia!
56
- onError={() => setHasError(true)}
57
- />
58
-
59
- </div>
60
- );
61
- }
 
1
+ import { useState } from 'react';
2
+
3
+ interface ImageLoaderProps {
4
+ src: string;
5
+ alt: string;
6
+ className?: string;
7
+ imgClassName?: string;
8
+ objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down';
9
+ aspectRatio?: string;
10
+ loading?: 'lazy' | 'eager';
11
+ showPlaceholder?: boolean;
12
+ }
13
+
14
+ export function ImageLoader({
15
+ src,
16
+ alt,
17
+ className = '',
18
+ imgClassName = '',
19
+ objectFit = 'contain',
20
+ aspectRatio,
21
+ loading,
22
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
23
+ showPlaceholder
24
+ }: ImageLoaderProps) {
25
+ // 1. Estados para controlar qué mostrar
26
+ const [isLoaded, setIsLoaded] = useState(false);
27
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
28
+ const [hasError, setHasError] = useState(false);
29
+
30
+ return (
31
+ <div
32
+ className={`relative w-full h-full overflow-hidden ${className}`}
33
+ style={aspectRatio && aspectRatio !== 'auto' ? { aspectRatio } : undefined}
34
+ >
35
+
36
+ {/* 2. EL SPINNER (Círculo de carga)
37
+ Se muestra solo si NO ha terminado de cargar (!isLoaded).
38
+ Cuando carga, se vuelve invisible (opacity-0).
39
+ */}
40
+ <div className={`absolute inset-0 flex items-center justify-center transition-opacity duration-500 ${isLoaded ? 'opacity-0 pointer-events-none' : 'opacity-100'
41
+ }`}>
42
+ <div className="w-8 h-8 border-2 border-purple-500 border-t-transparent rounded-full animate-spin"></div>
43
+ </div>
44
+
45
+ {/* 3. LA IMAGEN REAL
46
+ Empieza invisible (opacity-0).
47
+ Cuando se dispara onLoad, pasa a 'opacity-100' creando la animación de aparición.
48
+ */}
49
+ <img
50
+ src={src}
51
+ alt={alt}
52
+ loading={loading}
53
+ className={`w-full h-full object-${objectFit} transition-all duration-1000 ease-linear ${imgClassName} ${isLoaded ? 'opacity-100' : 'opacity-0'
54
+ }`}
55
+ onLoad={() => setIsLoaded(true)} // ¡Aquí ocurre la magia!
56
+ onError={() => setHasError(true)}
57
+ />
58
+
59
+ </div>
60
+ );
61
+ }
src/components/InfoPage.tsx CHANGED
@@ -1,183 +1,183 @@
1
- import { ArrowLeft, Info, Edit2, Save, X } from 'lucide-react';
2
- import { useState, useEffect } from 'react';
3
- import { subscribeToInfo, saveInfo } from '../services/info';
4
- import ReactMarkdown from 'react-markdown';
5
-
6
- interface InfoPageProps {
7
- onBack: () => void;
8
- isAdmin: boolean;
9
- }
10
-
11
- export function InfoPage({ onBack, isAdmin }: InfoPageProps) {
12
- const [content, setContent] = useState('');
13
- const [isEditing, setIsEditing] = useState(false);
14
- const [editContent, setEditContent] = useState('');
15
- const [isLoading, setIsLoading] = useState(true);
16
-
17
- useEffect(() => {
18
- const unsubscribe = subscribeToInfo((data) => {
19
- if (data) {
20
- setContent(data.content);
21
- }
22
- setIsLoading(false);
23
- });
24
- return () => unsubscribe();
25
- }, []);
26
-
27
- const handleSave = async () => {
28
- try {
29
- await saveInfo(editContent);
30
- setIsEditing(false);
31
- } catch (error) {
32
- console.error('Error saving info:', error);
33
- alert('Error al guardar la información.');
34
- }
35
- };
36
-
37
- const startEditing = () => {
38
- setEditContent(content);
39
- setIsEditing(true);
40
- };
41
-
42
- return (
43
- <div className="min-h-screen bg-[#0a0a0a] text-white p-4 sm:p-6 md:p-12 animate-in fade-in slide-in-from-bottom-4 duration-300">
44
- <div className="max-w-4xl mx-auto">
45
- <button
46
- onClick={onBack}
47
- className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors mb-8 group"
48
- >
49
- <ArrowLeft className="w-5 h-5 group-hover:-translate-x-1 transition-transform" />
50
- <span className="font-medium">Volver al inicio</span>
51
- </button>
52
-
53
- <div className="bg-[#1a1a1a] rounded-2xl border border-gray-800 p-8 sm:p-12 shadow-2xl relative">
54
-
55
- {isAdmin && !isEditing && (
56
- <button
57
- onClick={startEditing}
58
- className="absolute top-8 right-8 p-2 rounded-lg bg-gray-800 text-gray-400 hover:text-[#bb86fc] hover:bg-[#bb86fc]/10 transition-colors"
59
- title="Editar información"
60
- >
61
- <Edit2 className="w-5 h-5" />
62
- </button>
63
- )}
64
-
65
- <div className="flex items-center gap-4 mb-8 border-b border-gray-800 pb-8">
66
- <div className="p-3 bg-gradient-to-br from-[#bb86fc] to-[#9966dd] rounded-xl shadow-lg shadow-[#bb86fc]/20">
67
- <Info className="w-8 h-8 text-white" />
68
- </div>
69
- <div>
70
- <h1 className="text-3xl font-bold bg-gradient-to-r from-white to-gray-400 bg-clip-text text-transparent">
71
- Información
72
- </h1>
73
- <p className="text-gray-400 mt-1">
74
- Sobre Twisted Brody MangaFlow
75
- </p>
76
- </div>
77
- </div>
78
-
79
- {isEditing ? (
80
- <div className="space-y-4">
81
- <textarea
82
- value={editContent}
83
- onChange={(e) => setEditContent(e.target.value)}
84
- className="w-full h-[500px] bg-black/50 border border-[#bb86fc]/50 rounded-lg p-4 text-sm text-white focus:outline-none focus:border-[#bb86fc] font-mono"
85
- placeholder="Escribe el contenido en Markdown..."
86
- />
87
- <div className="flex gap-3 justify-end">
88
- <button
89
- onClick={() => setIsEditing(false)}
90
- className="px-4 py-2 rounded-lg font-semibold text-gray-400 hover:text-white hover:bg-white/10 transition-colors flex items-center gap-2"
91
- >
92
- <X className="w-4 h-4" />
93
- Cancelar
94
- </button>
95
- <button
96
- onClick={handleSave}
97
- className="px-4 py-2 rounded-lg font-semibold bg-[#bb86fc] hover:bg-[#9966dd] text-white transition-colors shadow-lg shadow-[#bb86fc]/20 flex items-center gap-2"
98
- >
99
- <Save className="w-4 h-4" />
100
- Guardar Cambios
101
- </button>
102
- </div>
103
- </div>
104
- ) : (
105
- <div className="prose prose-invert prose-p:text-gray-300 prose-headings:text-white prose-a:no-underline max-w-none">
106
- <ReactMarkdown
107
- components={{
108
- h1: ({ node, ...props }) => (
109
- <h1 className="text-3xl font-bold bg-gradient-to-r from-[#bb86fc] to-[#7744cc] bg-clip-text text-transparent mb-6 pb-2 border-b border-gray-800" {...props} />
110
- ),
111
- h2: ({ node, ...props }) => (
112
- <h2 className="text-xl font-semibold text-white mt-8 mb-4 flex items-center gap-2" {...props} />
113
- ),
114
- p: ({ node, ...props }) => (
115
- <p className="text-gray-300 leading-relaxed mb-4" {...props} />
116
- ),
117
- ul: ({ node, ...props }) => (
118
- <ul className="space-y-2 mb-6" {...props} />
119
- ),
120
- li: ({ node, ...props }) => (
121
- <li className="flex items-start gap-2 text-gray-300" {...props} />
122
- ),
123
- a: ({ node, href, children, ...props }) => {
124
- const isExternal = href?.startsWith('http');
125
- const isButton = href?.includes('t.me') || href?.includes('patreon.com') || href?.includes('x.com');
126
-
127
- if (isButton) {
128
- let bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-gray-500";
129
- let textClass = "text-gray-300 hover:text-white";
130
-
131
- if (href?.includes('patreon')) bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-[#FF424D] hover:text-[#FF424D]";
132
- if (href?.includes('t.me')) bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-[#24A1DE] hover:text-[#24A1DE]";
133
- if (href?.includes('x.com')) bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-white hover:text-white";
134
-
135
- return (
136
- <a
137
- href={href}
138
- target={isExternal ? "_blank" : undefined}
139
- rel={isExternal ? "noopener noreferrer" : undefined}
140
- className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-lg transition-all transform hover:scale-105 shadow-sm my-1 mr-2 no-underline text-xs sm:text-sm font-medium ${bgClass} ${textClass}`}
141
- {...props}
142
- >
143
- {children}
144
- </a>
145
- );
146
- }
147
-
148
- return (
149
- <a
150
- href={href}
151
- className="text-[#bb86fc] hover:underline"
152
- target={isExternal ? "_blank" : undefined}
153
- rel={isExternal ? "noopener noreferrer" : undefined}
154
- {...props}
155
- >
156
- {children}
157
- </a>
158
- );
159
- },
160
- blockquote: ({ node, ...props }) => (
161
- <blockquote className="border-l-4 border-[#bb86fc] pl-4 py-2 bg-[#bb86fc]/10 rounded-r-lg italic text-gray-400 my-6" {...props} />
162
- ),
163
- hr: ({ node, ...props }) => (
164
- <hr className="border-gray-800 my-8" {...props} />
165
- ),
166
- img: () => null
167
- }}
168
- >
169
- {content}
170
- </ReactMarkdown>
171
- </div>
172
- )}
173
-
174
- {!isEditing && (
175
- <div className="pt-8 border-t border-gray-800 text-center text-sm text-gray-500 mt-8">
176
- &copy; {new Date().getFullYear()} Twisted Brody. Todos los derechos reservados.
177
- </div>
178
- )}
179
- </div>
180
- </div>
181
- </div>
182
- );
183
- }
 
1
+ import { ArrowLeft, Info, Edit2, Save, X } from 'lucide-react';
2
+ import { useState, useEffect } from 'react';
3
+ import { subscribeToInfo, saveInfo } from '../services/info';
4
+ import ReactMarkdown from 'react-markdown';
5
+
6
+ interface InfoPageProps {
7
+ onBack: () => void;
8
+ isAdmin: boolean;
9
+ }
10
+
11
+ export function InfoPage({ onBack, isAdmin }: InfoPageProps) {
12
+ const [content, setContent] = useState('');
13
+ const [isEditing, setIsEditing] = useState(false);
14
+ const [editContent, setEditContent] = useState('');
15
+ const [isLoading, setIsLoading] = useState(true);
16
+
17
+ useEffect(() => {
18
+ const unsubscribe = subscribeToInfo((data) => {
19
+ if (data) {
20
+ setContent(data.content);
21
+ }
22
+ setIsLoading(false);
23
+ });
24
+ return () => unsubscribe();
25
+ }, []);
26
+
27
+ const handleSave = async () => {
28
+ try {
29
+ await saveInfo(editContent);
30
+ setIsEditing(false);
31
+ } catch (error) {
32
+ console.error('Error saving info:', error);
33
+ alert('Error al guardar la información.');
34
+ }
35
+ };
36
+
37
+ const startEditing = () => {
38
+ setEditContent(content);
39
+ setIsEditing(true);
40
+ };
41
+
42
+ return (
43
+ <div className="min-h-screen bg-[#0a0a0a] text-white p-4 sm:p-6 md:p-12 animate-in fade-in slide-in-from-bottom-4 duration-300">
44
+ <div className="max-w-4xl mx-auto">
45
+ <button
46
+ onClick={onBack}
47
+ className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors mb-8 group"
48
+ >
49
+ <ArrowLeft className="w-5 h-5 group-hover:-translate-x-1 transition-transform" />
50
+ <span className="font-medium">Volver al inicio</span>
51
+ </button>
52
+
53
+ <div className="bg-[#1a1a1a] rounded-2xl border border-gray-800 p-8 sm:p-12 shadow-2xl relative">
54
+
55
+ {isAdmin && !isEditing && (
56
+ <button
57
+ onClick={startEditing}
58
+ className="absolute top-8 right-8 p-2 rounded-lg bg-gray-800 text-gray-400 hover:text-[#bb86fc] hover:bg-[#bb86fc]/10 transition-colors"
59
+ title="Editar información"
60
+ >
61
+ <Edit2 className="w-5 h-5" />
62
+ </button>
63
+ )}
64
+
65
+ <div className="flex items-center gap-4 mb-8 border-b border-gray-800 pb-8">
66
+ <div className="p-3 bg-gradient-to-br from-[#bb86fc] to-[#9966dd] rounded-xl shadow-lg shadow-[#bb86fc]/20">
67
+ <Info className="w-8 h-8 text-white" />
68
+ </div>
69
+ <div>
70
+ <h1 className="text-3xl font-bold bg-gradient-to-r from-white to-gray-400 bg-clip-text text-transparent">
71
+ Información
72
+ </h1>
73
+ <p className="text-gray-400 mt-1">
74
+ Sobre Twisted Brody MangaFlow
75
+ </p>
76
+ </div>
77
+ </div>
78
+
79
+ {isEditing ? (
80
+ <div className="space-y-4">
81
+ <textarea
82
+ value={editContent}
83
+ onChange={(e) => setEditContent(e.target.value)}
84
+ className="w-full h-[500px] bg-black/50 border border-[#bb86fc]/50 rounded-lg p-4 text-sm text-white focus:outline-none focus:border-[#bb86fc] font-mono"
85
+ placeholder="Escribe el contenido en Markdown..."
86
+ />
87
+ <div className="flex gap-3 justify-end">
88
+ <button
89
+ onClick={() => setIsEditing(false)}
90
+ className="px-4 py-2 rounded-lg font-semibold text-gray-400 hover:text-white hover:bg-white/10 transition-colors flex items-center gap-2"
91
+ >
92
+ <X className="w-4 h-4" />
93
+ Cancelar
94
+ </button>
95
+ <button
96
+ onClick={handleSave}
97
+ className="px-4 py-2 rounded-lg font-semibold bg-[#bb86fc] hover:bg-[#9966dd] text-white transition-colors shadow-lg shadow-[#bb86fc]/20 flex items-center gap-2"
98
+ >
99
+ <Save className="w-4 h-4" />
100
+ Guardar Cambios
101
+ </button>
102
+ </div>
103
+ </div>
104
+ ) : (
105
+ <div className="prose prose-invert prose-p:text-gray-300 prose-headings:text-white prose-a:no-underline max-w-none">
106
+ <ReactMarkdown
107
+ components={{
108
+ h1: ({ node, ...props }) => (
109
+ <h1 className="text-3xl font-bold bg-gradient-to-r from-[#bb86fc] to-[#7744cc] bg-clip-text text-transparent mb-6 pb-2 border-b border-gray-800" {...props} />
110
+ ),
111
+ h2: ({ node, ...props }) => (
112
+ <h2 className="text-xl font-semibold text-white mt-8 mb-4 flex items-center gap-2" {...props} />
113
+ ),
114
+ p: ({ node, ...props }) => (
115
+ <p className="text-gray-300 leading-relaxed mb-4" {...props} />
116
+ ),
117
+ ul: ({ node, ...props }) => (
118
+ <ul className="space-y-2 mb-6" {...props} />
119
+ ),
120
+ li: ({ node, ...props }) => (
121
+ <li className="flex items-start gap-2 text-gray-300" {...props} />
122
+ ),
123
+ a: ({ node, href, children, ...props }) => {
124
+ const isExternal = href?.startsWith('http');
125
+ const isButton = href?.includes('t.me') || href?.includes('patreon.com') || href?.includes('x.com');
126
+
127
+ if (isButton) {
128
+ let bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-gray-500";
129
+ let textClass = "text-gray-300 hover:text-white";
130
+
131
+ if (href?.includes('patreon')) bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-[#FF424D] hover:text-[#FF424D]";
132
+ if (href?.includes('t.me')) bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-[#24A1DE] hover:text-[#24A1DE]";
133
+ if (href?.includes('x.com')) bgClass = "bg-[#1a1a1a] border border-gray-700 hover:border-white hover:text-white";
134
+
135
+ return (
136
+ <a
137
+ href={href}
138
+ target={isExternal ? "_blank" : undefined}
139
+ rel={isExternal ? "noopener noreferrer" : undefined}
140
+ className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-lg transition-all transform hover:scale-105 shadow-sm my-1 mr-2 no-underline text-xs sm:text-sm font-medium ${bgClass} ${textClass}`}
141
+ {...props}
142
+ >
143
+ {children}
144
+ </a>
145
+ );
146
+ }
147
+
148
+ return (
149
+ <a
150
+ href={href}
151
+ className="text-[#bb86fc] hover:underline"
152
+ target={isExternal ? "_blank" : undefined}
153
+ rel={isExternal ? "noopener noreferrer" : undefined}
154
+ {...props}
155
+ >
156
+ {children}
157
+ </a>
158
+ );
159
+ },
160
+ blockquote: ({ node, ...props }) => (
161
+ <blockquote className="border-l-4 border-[#bb86fc] pl-4 py-2 bg-[#bb86fc]/10 rounded-r-lg italic text-gray-400 my-6" {...props} />
162
+ ),
163
+ hr: ({ node, ...props }) => (
164
+ <hr className="border-gray-800 my-8" {...props} />
165
+ ),
166
+ img: () => null
167
+ }}
168
+ >
169
+ {content}
170
+ </ReactMarkdown>
171
+ </div>
172
+ )}
173
+
174
+ {!isEditing && (
175
+ <div className="pt-8 border-t border-gray-800 text-center text-sm text-gray-500 mt-8">
176
+ &copy; {new Date().getFullYear()} Twisted Brody. Todos los derechos reservados.
177
+ </div>
178
+ )}
179
+ </div>
180
+ </div>
181
+ </div>
182
+ );
183
+ }
src/components/LoadingSpinner.tsx CHANGED
@@ -1,27 +1,27 @@
1
- interface LoadingSpinnerProps {
2
- size?: number;
3
- borderWidth?: number;
4
- className?: string;
5
- }
6
-
7
- export function LoadingSpinner({ size = 40, borderWidth = 2, className = '' }: LoadingSpinnerProps) {
8
- return (
9
- <div className={`flex items-center justify-center ${className}`}>
10
- <div className="relative" style={{ width: `${size}px`, height: `${size}px` }}>
11
- <div
12
- className="rounded-full animate-spin"
13
- style={{
14
- width: `${size}px`,
15
- height: `${size}px`,
16
- borderWidth: `${borderWidth}px`,
17
- borderStyle: 'solid',
18
- borderColor: 'rgba(187, 134, 252, 0.3)',
19
- borderTopColor: '#bb86fc',
20
- animation: 'spin 1.2s linear infinite',
21
- boxShadow: '0 0 20px rgba(139, 92, 246, 0.2)',
22
- }}
23
- />
24
- </div>
25
- </div>
26
- );
27
- }
 
1
+ interface LoadingSpinnerProps {
2
+ size?: number;
3
+ borderWidth?: number;
4
+ className?: string;
5
+ }
6
+
7
+ export function LoadingSpinner({ size = 40, borderWidth = 2, className = '' }: LoadingSpinnerProps) {
8
+ return (
9
+ <div className={`flex items-center justify-center ${className}`}>
10
+ <div className="relative" style={{ width: `${size}px`, height: `${size}px` }}>
11
+ <div
12
+ className="rounded-full animate-spin"
13
+ style={{
14
+ width: `${size}px`,
15
+ height: `${size}px`,
16
+ borderWidth: `${borderWidth}px`,
17
+ borderStyle: 'solid',
18
+ borderColor: 'rgba(187, 134, 252, 0.3)',
19
+ borderTopColor: '#bb86fc',
20
+ animation: 'spin 1.2s linear infinite',
21
+ boxShadow: '0 0 20px rgba(139, 92, 246, 0.2)',
22
+ }}
23
+ />
24
+ </div>
25
+ </div>
26
+ );
27
+ }
src/components/MangaCard.tsx CHANGED
@@ -1,131 +1,131 @@
1
- import { useState } from 'react';
2
- import { BookOpen, Edit2, Trash2 } from 'lucide-react';
3
- import { Manga } from '../types/manga';
4
- import { ImageLoader } from './ImageLoader';
5
- import { incrementMangaViews } from '../services/manga';
6
-
7
- interface MangaCardProps {
8
- id: string;
9
- title: string;
10
- author: string;
11
- pageCount: number;
12
- thumbnail?: string;
13
- manga?: Manga;
14
- onSelect?: (id: string) => void;
15
- onEdit?: (manga: Manga) => void;
16
- onDelete?: (id: string) => void;
17
- }
18
-
19
- export function MangaCard({ id, title, author, pageCount, thumbnail, manga, onSelect, onEdit, onDelete }: MangaCardProps) {
20
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
21
-
22
- const handleDeleteClick = (e: React.MouseEvent) => {
23
- e.stopPropagation();
24
- setShowDeleteConfirm(true);
25
- };
26
-
27
- const handleConfirmDelete = (e: React.MouseEvent) => {
28
- e.stopPropagation();
29
- onDelete?.(id);
30
- setShowDeleteConfirm(false);
31
- };
32
-
33
- const handleEditClick = (e: React.MouseEvent) => {
34
- e.stopPropagation();
35
- if (manga) {
36
- onEdit?.(manga);
37
- }
38
- };
39
-
40
- return (
41
- <div className="group cursor-pointer flex flex-col w-full max-w-xs">
42
- <div
43
- onClick={() => {
44
- incrementMangaViews(id);
45
- onSelect?.(id);
46
- }}
47
- className="relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02] aspect-[2/3]"
48
- >
49
- {thumbnail ? (
50
- <>
51
- <ImageLoader
52
- src={thumbnail}
53
- alt={title}
54
- aspectRatio="2/3"
55
- objectFit="cover"
56
- loading="lazy"
57
- imgClassName="group-hover:scale-110"
58
- />
59
- <div className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"></div>
60
- </>
61
- ) : (
62
- <div className="w-full aspect-[2/3] flex items-center justify-center text-white/40 bg-gradient-to-br from-gray-800 to-gray-900 rounded-lg group-hover:text-white/60">
63
- <BookOpen className="w-12 h-12" />
64
- </div>
65
- )}
66
-
67
- <div className="absolute bottom-2 left-2 bg-black/70 text-white text-xs px-2 py-1 rounded-md font-semibold opacity-0 group-hover:opacity-100 transition-opacity duration-300">
68
- {pageCount} paginas
69
- </div>
70
-
71
- <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex gap-1">
72
- {manga && onEdit && (
73
- <button
74
- onClick={handleEditClick}
75
- className="bg-black/60 hover:bg-purple-600 text-white p-1.5 rounded-full transition-colors backdrop-blur-sm"
76
- title="Editar manga"
77
- >
78
- <Edit2 className="w-3 h-3" />
79
- </button>
80
- )}
81
- {onDelete && (
82
- <button
83
- onClick={handleDeleteClick}
84
- className="bg-black/60 hover:bg-red-600 text-white p-1.5 rounded-full transition-colors backdrop-blur-sm"
85
- title="Eliminar manga"
86
- >
87
- <Trash2 className="w-3 h-3" />
88
- </button>
89
- )}
90
- </div>
91
-
92
- {showDeleteConfirm && (
93
- <div className="absolute inset-0 bg-black/80 backdrop-blur-sm flex flex-col items-center justify-center gap-3 rounded-lg z-20 animate-in fade-in duration-200">
94
- <p className="text-white text-sm font-semibold text-center px-3">Eliminar manga?</p>
95
- <div className="flex gap-2">
96
- <button
97
- onClick={(e) => {
98
- e.stopPropagation();
99
- setShowDeleteConfirm(false);
100
- }}
101
- className="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1.5 rounded-md text-xs font-semibold transition-all duration-200 transform hover:scale-105 active:scale-95"
102
- >
103
- Cancelar
104
- </button>
105
- <button
106
- onClick={handleConfirmDelete}
107
- className="bg-red-600 hover:bg-red-700 text-white px-3 py-1.5 rounded-md text-xs font-semibold transition-all duration-200 transform hover:scale-105 active:scale-95"
108
- >
109
- Eliminar
110
- </button>
111
- </div>
112
- </div>
113
- )}
114
- </div>
115
-
116
- <div className="mt-1 sm:mt-2 flex flex-col gap-0.5 text-center mb-2">
117
- <h3
118
- onClick={() => onSelect?.(id)}
119
- className="font-semibold text-xs sm:text-sm text-white line-clamp-2 cursor-pointer text-center group-hover:text-purple-400 transition-colors duration-300 ease-out"
120
- >
121
- {title}
122
- </h3>
123
- {author && author.trim() !== '' && author.toLowerCase() !== 'anónimo' && author.toLowerCase() !== 'anonimo' && (
124
- <p className="text-xs text-gray-400 text-center group-hover:text-gray-300 transition-colors duration-300 ease-out">
125
- {author}
126
- </p>
127
- )}
128
- </div>
129
- </div>
130
- );
131
- }
 
1
+ import { useState } from 'react';
2
+ import { BookOpen, Edit2, Trash2 } from 'lucide-react';
3
+ import { Manga } from '../types/manga';
4
+ import { ImageLoader } from './ImageLoader';
5
+ import { incrementMangaViews } from '../services/manga';
6
+
7
+ interface MangaCardProps {
8
+ id: string;
9
+ title: string;
10
+ author: string;
11
+ pageCount: number;
12
+ thumbnail?: string;
13
+ manga?: Manga;
14
+ onSelect?: (id: string) => void;
15
+ onEdit?: (manga: Manga) => void;
16
+ onDelete?: (id: string) => void;
17
+ }
18
+
19
+ export function MangaCard({ id, title, author, pageCount, thumbnail, manga, onSelect, onEdit, onDelete }: MangaCardProps) {
20
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
21
+
22
+ const handleDeleteClick = (e: React.MouseEvent) => {
23
+ e.stopPropagation();
24
+ setShowDeleteConfirm(true);
25
+ };
26
+
27
+ const handleConfirmDelete = (e: React.MouseEvent) => {
28
+ e.stopPropagation();
29
+ onDelete?.(id);
30
+ setShowDeleteConfirm(false);
31
+ };
32
+
33
+ const handleEditClick = (e: React.MouseEvent) => {
34
+ e.stopPropagation();
35
+ if (manga) {
36
+ onEdit?.(manga);
37
+ }
38
+ };
39
+
40
+ return (
41
+ <div className="group cursor-pointer flex flex-col w-full max-w-xs">
42
+ <div
43
+ onClick={() => {
44
+ incrementMangaViews(id);
45
+ onSelect?.(id);
46
+ }}
47
+ className="relative bg-black rounded-lg shadow-lg overflow-hidden transition-transform duration-300 hover:scale-[1.02] aspect-[2/3]"
48
+ >
49
+ {thumbnail ? (
50
+ <>
51
+ <ImageLoader
52
+ src={thumbnail}
53
+ alt={title}
54
+ aspectRatio="2/3"
55
+ objectFit="cover"
56
+ loading="lazy"
57
+ imgClassName="group-hover:scale-110"
58
+ />
59
+ <div className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"></div>
60
+ </>
61
+ ) : (
62
+ <div className="w-full aspect-[2/3] flex items-center justify-center text-white/40 bg-gradient-to-br from-gray-800 to-gray-900 rounded-lg group-hover:text-white/60">
63
+ <BookOpen className="w-12 h-12" />
64
+ </div>
65
+ )}
66
+
67
+ <div className="absolute bottom-2 left-2 bg-black/70 text-white text-xs px-2 py-1 rounded-md font-semibold opacity-0 group-hover:opacity-100 transition-opacity duration-300">
68
+ {pageCount} paginas
69
+ </div>
70
+
71
+ <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex gap-1">
72
+ {manga && onEdit && (
73
+ <button
74
+ onClick={handleEditClick}
75
+ className="bg-black/60 hover:bg-purple-600 text-white p-1.5 rounded-full transition-colors backdrop-blur-sm"
76
+ title="Editar manga"
77
+ >
78
+ <Edit2 className="w-3 h-3" />
79
+ </button>
80
+ )}
81
+ {onDelete && (
82
+ <button
83
+ onClick={handleDeleteClick}
84
+ className="bg-black/60 hover:bg-red-600 text-white p-1.5 rounded-full transition-colors backdrop-blur-sm"
85
+ title="Eliminar manga"
86
+ >
87
+ <Trash2 className="w-3 h-3" />
88
+ </button>
89
+ )}
90
+ </div>
91
+
92
+ {showDeleteConfirm && (
93
+ <div className="absolute inset-0 bg-black/80 backdrop-blur-sm flex flex-col items-center justify-center gap-3 rounded-lg z-20 animate-in fade-in duration-200">
94
+ <p className="text-white text-sm font-semibold text-center px-3">Eliminar manga?</p>
95
+ <div className="flex gap-2">
96
+ <button
97
+ onClick={(e) => {
98
+ e.stopPropagation();
99
+ setShowDeleteConfirm(false);
100
+ }}
101
+ className="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1.5 rounded-md text-xs font-semibold transition-all duration-200 transform hover:scale-105 active:scale-95"
102
+ >
103
+ Cancelar
104
+ </button>
105
+ <button
106
+ onClick={handleConfirmDelete}
107
+ className="bg-red-600 hover:bg-red-700 text-white px-3 py-1.5 rounded-md text-xs font-semibold transition-all duration-200 transform hover:scale-105 active:scale-95"
108
+ >
109
+ Eliminar
110
+ </button>
111
+ </div>
112
+ </div>
113
+ )}
114
+ </div>
115
+
116
+ <div className="mt-1 sm:mt-2 flex flex-col gap-0.5 text-center mb-2">
117
+ <h3
118
+ onClick={() => onSelect?.(id)}
119
+ className="font-semibold text-xs sm:text-sm text-white line-clamp-2 cursor-pointer text-center group-hover:text-purple-400 transition-colors duration-300 ease-out"
120
+ >
121
+ {title}
122
+ </h3>
123
+ {author && author.trim() !== '' && author.toLowerCase() !== 'anónimo' && author.toLowerCase() !== 'anonimo' && (
124
+ <p className="text-xs text-gray-400 text-center group-hover:text-gray-300 transition-colors duration-300 ease-out">
125
+ {author}
126
+ </p>
127
+ )}
128
+ </div>
129
+ </div>
130
+ );
131
+ }
src/components/MangaCardSkeleton.tsx CHANGED
@@ -1,27 +1,27 @@
1
- export function MangaCardSkeleton() {
2
- return (
3
- <div className="flex flex-col w-full max-w-xs">
4
- <div className="relative bg-black rounded-lg shadow-lg overflow-hidden aspect-[2/3] mb-2">
5
- <div className="absolute inset-0 flex items-center justify-center">
6
- <div
7
- className="rounded-full animate-spin"
8
- style={{
9
- width: '30px',
10
- height: '30px',
11
- borderWidth: '2px',
12
- borderStyle: 'solid',
13
- borderColor: 'rgba(187, 134, 252, 0.2)',
14
- borderTopColor: '#bb86fc',
15
- animation: 'spin 0.6s linear infinite',
16
- }}
17
- />
18
- </div>
19
- </div>
20
-
21
- <div className="flex flex-col gap-2 items-center animate-pulse">
22
- <div className="h-4 bg-gray-800 rounded w-3/4"></div>
23
- <div className="h-3 bg-gray-800 rounded w-1/2"></div>
24
- </div>
25
- </div>
26
- );
27
- }
 
1
+ export function MangaCardSkeleton() {
2
+ return (
3
+ <div className="flex flex-col w-full max-w-xs">
4
+ <div className="relative bg-black rounded-lg shadow-lg overflow-hidden aspect-[2/3] mb-2">
5
+ <div className="absolute inset-0 flex items-center justify-center">
6
+ <div
7
+ className="rounded-full animate-spin"
8
+ style={{
9
+ width: '30px',
10
+ height: '30px',
11
+ borderWidth: '2px',
12
+ borderStyle: 'solid',
13
+ borderColor: 'rgba(187, 134, 252, 0.2)',
14
+ borderTopColor: '#bb86fc',
15
+ animation: 'spin 0.6s linear infinite',
16
+ }}
17
+ />
18
+ </div>
19
+ </div>
20
+
21
+ <div className="flex flex-col gap-2 items-center animate-pulse">
22
+ <div className="h-4 bg-gray-800 rounded w-3/4"></div>
23
+ <div className="h-3 bg-gray-800 rounded w-1/2"></div>
24
+ </div>
25
+ </div>
26
+ );
27
+ }
src/components/MangaGrid.tsx CHANGED
@@ -1,40 +1,40 @@
1
- import { MangaCard } from './MangaCard';
2
- import { Manga } from '../types/manga';
3
-
4
- interface MangaItem {
5
- id: string;
6
- title: string;
7
- author: string;
8
- chapterCount: number;
9
- pageCount: number;
10
- thumbnail?: string;
11
- manga?: Manga;
12
- }
13
-
14
- interface MangaGridProps {
15
- items: MangaItem[];
16
- onSelectComic?: (id: string) => void;
17
- onEditManga?: (manga: Manga) => void;
18
- onDeleteManga?: (id: string) => void;
19
- }
20
-
21
- export function MangaGrid({ items, onSelectComic, onEditManga, onDeleteManga }: MangaGridProps) {
22
- return (
23
- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 w-full justify-center items-start">
24
- {items.map((item) => (
25
- <MangaCard
26
- key={item.id}
27
- id={item.id}
28
- title={item.title}
29
- author={item.author}
30
- pageCount={item.pageCount}
31
- thumbnail={item.thumbnail}
32
- manga={item.manga}
33
- onSelect={onSelectComic}
34
- onEdit={onEditManga}
35
- onDelete={onDeleteManga}
36
- />
37
- ))}
38
- </div>
39
- );
40
- }
 
1
+ import { MangaCard } from './MangaCard';
2
+ import { Manga } from '../types/manga';
3
+
4
+ interface MangaItem {
5
+ id: string;
6
+ title: string;
7
+ author: string;
8
+ chapterCount: number;
9
+ pageCount: number;
10
+ thumbnail?: string;
11
+ manga?: Manga;
12
+ }
13
+
14
+ interface MangaGridProps {
15
+ items: MangaItem[];
16
+ onSelectComic?: (id: string) => void;
17
+ onEditManga?: (manga: Manga) => void;
18
+ onDeleteManga?: (id: string) => void;
19
+ }
20
+
21
+ export function MangaGrid({ items, onSelectComic, onEditManga, onDeleteManga }: MangaGridProps) {
22
+ return (
23
+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 w-full justify-center items-start">
24
+ {items.map((item) => (
25
+ <MangaCard
26
+ key={item.id}
27
+ id={item.id}
28
+ title={item.title}
29
+ author={item.author}
30
+ pageCount={item.pageCount}
31
+ thumbnail={item.thumbnail}
32
+ manga={item.manga}
33
+ onSelect={onSelectComic}
34
+ onEdit={onEditManga}
35
+ onDelete={onDeleteManga}
36
+ />
37
+ ))}
38
+ </div>
39
+ );
40
+ }
src/components/NewMangaModal.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
src/components/SearchBar.tsx CHANGED
@@ -1,104 +1,104 @@
1
- import { Search, X, ArrowUpDown, ChevronsUpDown } from 'lucide-react';
2
- import { useState } from 'react';
3
-
4
- type SortType = 'random' | 'name' | 'date' | 'pages' | 'modified' | 'views';
5
- type SortDirection = 'asc' | 'desc';
6
-
7
- interface SearchBarProps {
8
- value: string;
9
- onChange: (value: string) => void;
10
- placeholder?: string;
11
- sortType?: SortType;
12
- onSortTypeChange?: (sortType: SortType) => void;
13
- sortDirection?: SortDirection;
14
- onSortDirectionChange?: (direction: SortDirection) => void;
15
- }
16
-
17
- const SORT_LABELS: Record<SortType, string> = {
18
- random: 'Aleatorio',
19
- name: 'Nombre',
20
- date: 'Fecha de creación',
21
- modified: 'Última modificación',
22
- pages: 'Páginas',
23
- views: 'Vistas',
24
- };
25
-
26
- export function SearchBar({
27
- value,
28
- onChange,
29
- placeholder = "Buscar manga...",
30
- sortType = 'random',
31
- onSortTypeChange,
32
- sortDirection = 'asc',
33
- onSortDirectionChange,
34
- }: SearchBarProps) {
35
- const [isFocused, setIsFocused] = useState(false);
36
-
37
- const handleClear = () => {
38
- onChange('');
39
- };
40
-
41
- const handleCycleSortType = () => {
42
- const sortTypes: SortType[] = ['modified', 'name', 'date', 'pages', 'views', 'random'];
43
- const currentIndex = sortTypes.indexOf(sortType);
44
- const nextIndex = (currentIndex + 1) % sortTypes.length;
45
- onSortTypeChange?.(sortTypes[nextIndex]);
46
- };
47
-
48
- const handleToggleSortDirection = () => {
49
- const newDirection = sortDirection === 'asc' ? 'desc' : 'asc';
50
- onSortDirectionChange?.(newDirection);
51
- };
52
-
53
- const getDirectionLabel = () => {
54
- if (sortType === 'views') {
55
- return sortDirection === 'asc' ? 'Menos vistos' : 'Más vistos';
56
- }
57
- return sortDirection === 'asc' ? 'ASC' : 'DESC';
58
- };
59
-
60
- return (
61
- <div className="w-full flex gap-2 items-center">
62
- <div className="relative flex-1">
63
- <Search className={`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 pointer-events-none ${isFocused ? 'text-purple-400' : 'text-gray-400'
64
- }`} />
65
- <input
66
- type="text"
67
- placeholder={placeholder}
68
- value={value}
69
- onChange={(e) => onChange(e.target.value)}
70
- onFocus={() => setIsFocused(true)}
71
- onBlur={() => setIsFocused(false)}
72
- className="w-full bg-[#1a1a1a] text-white rounded-lg pl-10 pr-10 py-2.5 text-sm placeholder-gray-400 border border-gray-700/50 focus:border-purple-500 focus:outline-none"
73
- />
74
- {value && (
75
- <button
76
- onClick={handleClear}
77
- className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-purple-400 transition-all p-1 hover:scale-125 hover:rotate-90 duration-300"
78
- title="Limpiar búsqueda"
79
- >
80
- <X className="w-4 h-4" />
81
- </button>
82
- )}
83
- </div>
84
-
85
- <button
86
- onClick={handleCycleSortType}
87
- className="bg-gradient-to-r from-gray-700/40 to-gray-600/40 hover:from-gray-700/60 hover:to-gray-600/60 border border-gray-600/50 hover:border-purple-500/50 text-white px-2.5 py-2.5 rounded-lg flex items-center justify-center gap-1.5 font-medium text-xs transition-all duration-300 active:scale-95 whitespace-nowrap hover:scale-110 hover:shadow-lg hover:shadow-purple-500/20 hover:border-purple-500"
88
- title="Cambiar tipo de ordenamiento"
89
- >
90
- <ChevronsUpDown className="w-3.5 h-3.5 transition-transform duration-300 hover:rotate-180" />
91
- <span className="hidden sm:inline">{SORT_LABELS[sortType]}</span>
92
- </button>
93
-
94
- <button
95
- onClick={handleToggleSortDirection}
96
- className="bg-gradient-to-r from-gray-700/40 to-gray-600/40 hover:from-gray-700/60 hover:to-gray-600/60 border border-gray-600/50 hover:border-purple-500/50 text-white px-2.5 py-2.5 rounded-lg flex items-center justify-center gap-1.5 font-medium text-xs transition-all duration-300 active:scale-95 whitespace-nowrap hover:scale-110 hover:shadow-lg hover:shadow-purple-500/20 hover:border-purple-500"
97
- title={sortDirection === 'asc' ? 'Cambiar a descendente' : 'Cambiar a ascendente'}
98
- >
99
- <ArrowUpDown className={`w-3.5 h-3.5 transition-all duration-500 ${sortDirection === 'desc' ? 'rotate-180' : ''} hover:scale-125`} />
100
- <span className="hidden sm:inline text-[10px]">{getDirectionLabel()}</span>
101
- </button>
102
- </div>
103
- );
104
- }
 
1
+ import { Search, X, ArrowUpDown, ChevronsUpDown } from 'lucide-react';
2
+ import { useState } from 'react';
3
+
4
+ type SortType = 'random' | 'name' | 'date' | 'pages' | 'modified' | 'views';
5
+ type SortDirection = 'asc' | 'desc';
6
+
7
+ interface SearchBarProps {
8
+ value: string;
9
+ onChange: (value: string) => void;
10
+ placeholder?: string;
11
+ sortType?: SortType;
12
+ onSortTypeChange?: (sortType: SortType) => void;
13
+ sortDirection?: SortDirection;
14
+ onSortDirectionChange?: (direction: SortDirection) => void;
15
+ }
16
+
17
+ const SORT_LABELS: Record<SortType, string> = {
18
+ random: 'Aleatorio',
19
+ name: 'Nombre',
20
+ date: 'Fecha de creación',
21
+ modified: 'Última modificación',
22
+ pages: 'P��ginas',
23
+ views: 'Vistas',
24
+ };
25
+
26
+ export function SearchBar({
27
+ value,
28
+ onChange,
29
+ placeholder = "Buscar manga...",
30
+ sortType = 'random',
31
+ onSortTypeChange,
32
+ sortDirection = 'asc',
33
+ onSortDirectionChange,
34
+ }: SearchBarProps) {
35
+ const [isFocused, setIsFocused] = useState(false);
36
+
37
+ const handleClear = () => {
38
+ onChange('');
39
+ };
40
+
41
+ const handleCycleSortType = () => {
42
+ const sortTypes: SortType[] = ['modified', 'name', 'date', 'pages', 'views', 'random'];
43
+ const currentIndex = sortTypes.indexOf(sortType);
44
+ const nextIndex = (currentIndex + 1) % sortTypes.length;
45
+ onSortTypeChange?.(sortTypes[nextIndex]);
46
+ };
47
+
48
+ const handleToggleSortDirection = () => {
49
+ const newDirection = sortDirection === 'asc' ? 'desc' : 'asc';
50
+ onSortDirectionChange?.(newDirection);
51
+ };
52
+
53
+ const getDirectionLabel = () => {
54
+ if (sortType === 'views') {
55
+ return sortDirection === 'asc' ? 'Menos vistos' : 'Más vistos';
56
+ }
57
+ return sortDirection === 'asc' ? 'ASC' : 'DESC';
58
+ };
59
+
60
+ return (
61
+ <div className="w-full flex gap-2 items-center">
62
+ <div className="relative flex-1">
63
+ <Search className={`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 pointer-events-none ${isFocused ? 'text-purple-400' : 'text-gray-400'
64
+ }`} />
65
+ <input
66
+ type="text"
67
+ placeholder={placeholder}
68
+ value={value}
69
+ onChange={(e) => onChange(e.target.value)}
70
+ onFocus={() => setIsFocused(true)}
71
+ onBlur={() => setIsFocused(false)}
72
+ className="w-full bg-[#1a1a1a] text-white rounded-lg pl-10 pr-10 py-2.5 text-sm placeholder-gray-400 border border-gray-700/50 focus:border-purple-500 focus:outline-none"
73
+ />
74
+ {value && (
75
+ <button
76
+ onClick={handleClear}
77
+ className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-purple-400 transition-all p-1 hover:scale-125 hover:rotate-90 duration-300"
78
+ title="Limpiar búsqueda"
79
+ >
80
+ <X className="w-4 h-4" />
81
+ </button>
82
+ )}
83
+ </div>
84
+
85
+ <button
86
+ onClick={handleCycleSortType}
87
+ className="bg-gradient-to-r from-gray-700/40 to-gray-600/40 hover:from-gray-700/60 hover:to-gray-600/60 border border-gray-600/50 hover:border-purple-500/50 text-white px-2.5 py-2.5 rounded-lg flex items-center justify-center gap-1.5 font-medium text-xs transition-all duration-300 active:scale-95 whitespace-nowrap hover:scale-110 hover:shadow-lg hover:shadow-purple-500/20 hover:border-purple-500"
88
+ title="Cambiar tipo de ordenamiento"
89
+ >
90
+ <ChevronsUpDown className="w-3.5 h-3.5 transition-transform duration-300 hover:rotate-180" />
91
+ <span className="hidden sm:inline">{SORT_LABELS[sortType]}</span>
92
+ </button>
93
+
94
+ <button
95
+ onClick={handleToggleSortDirection}
96
+ className="bg-gradient-to-r from-gray-700/40 to-gray-600/40 hover:from-gray-700/60 hover:to-gray-600/60 border border-gray-600/50 hover:border-purple-500/50 text-white px-2.5 py-2.5 rounded-lg flex items-center justify-center gap-1.5 font-medium text-xs transition-all duration-300 active:scale-95 whitespace-nowrap hover:scale-110 hover:shadow-lg hover:shadow-purple-500/20 hover:border-purple-500"
97
+ title={sortDirection === 'asc' ? 'Cambiar a descendente' : 'Cambiar a ascendente'}
98
+ >
99
+ <ArrowUpDown className={`w-3.5 h-3.5 transition-all duration-500 ${sortDirection === 'desc' ? 'rotate-180' : ''} hover:scale-125`} />
100
+ <span className="hidden sm:inline text-[10px]">{getDirectionLabel()}</span>
101
+ </button>
102
+ </div>
103
+ );
104
+ }
src/components/SearchResults.tsx CHANGED
@@ -1,230 +1,230 @@
1
- import { BookOpen, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
2
- import { useState, useEffect } from 'react';
3
- import { MangaCard } from './MangaCard';
4
- import { MangaCardSkeleton } from './MangaCardSkeleton';
5
- import { Manga } from '../types/manga';
6
-
7
- interface SearchResult {
8
- id: string;
9
- title: string;
10
- author: string;
11
- chapterCount: number;
12
- pageCount: number;
13
- thumbnail?: string;
14
- manga?: Manga;
15
- }
16
-
17
- interface SearchResultsProps {
18
- items: SearchResult[];
19
- searchTerm: string;
20
- isSearching: boolean;
21
- onSelectComic: (id: string) => void;
22
- onEditManga?: (manga: Manga) => void;
23
- onDeleteManga?: (id: string) => void;
24
- isLoading?: boolean;
25
- }
26
-
27
- const ITEMS_PER_PAGE = 24;
28
-
29
- export function SearchResults({
30
- items,
31
- searchTerm,
32
- isSearching,
33
- onSelectComic,
34
- onEditManga,
35
- onDeleteManga,
36
- isLoading = false,
37
- }: SearchResultsProps) {
38
- const [currentPage, setCurrentPage] = useState(() => {
39
- const params = new URLSearchParams(window.location.search);
40
- const page = params.get('page');
41
- return page ? Math.max(1, Number(page)) : 1;
42
- });
43
-
44
- // Listen for browser back/forward buttons
45
- useEffect(() => {
46
- const handlePopState = () => {
47
- const params = new URLSearchParams(window.location.search);
48
- const page = params.get('page');
49
- setCurrentPage(page ? Math.max(1, Number(page)) : 1);
50
- };
51
-
52
- window.addEventListener('popstate', handlePopState);
53
- return () => window.removeEventListener('popstate', handlePopState);
54
- }, []);
55
-
56
- // Correct page if out of bounds (e.g. after filtering changes)
57
- const totalPages = Math.ceil(items.length / ITEMS_PER_PAGE);
58
-
59
- useEffect(() => {
60
- if (totalPages > 0 && currentPage > totalPages) {
61
- // Silent correction
62
- setCurrentPage(totalPages);
63
- const url = new URL(window.location.href);
64
- url.searchParams.set('page', String(totalPages));
65
- window.history.replaceState({}, '', url);
66
- }
67
- }, [totalPages, currentPage]);
68
-
69
- // Reset page ONLY when search term changes (not when items change due to sorting)
70
- useEffect(() => {
71
- if (searchTerm) {
72
- setCurrentPage(1);
73
- const url = new URL(window.location.href);
74
- url.searchParams.delete('page');
75
- window.history.replaceState({}, '', url);
76
- }
77
- }, [searchTerm]);
78
-
79
- // Get current items
80
- const currentItems = items.slice(
81
- (currentPage - 1) * ITEMS_PER_PAGE,
82
- currentPage * ITEMS_PER_PAGE
83
- );
84
-
85
- const handlePageChange = (page: number) => {
86
- setCurrentPage(page);
87
- const url = new URL(window.location.href);
88
- url.searchParams.set('page', String(page));
89
- window.history.pushState({}, '', url);
90
- window.scrollTo({ top: 0, behavior: 'smooth' });
91
- };
92
-
93
- const renderPagination = () => {
94
- if (totalPages <= 1) return null;
95
-
96
- const pages = [];
97
- // Logic to show a window of pages for better UX (e.g. 1 ... 4 5 6 ... 10)
98
- const showMax = 5;
99
- let startPage = Math.max(1, currentPage - Math.floor(showMax / 2));
100
- let endPage = Math.min(totalPages, startPage + showMax - 1);
101
-
102
- if (endPage - startPage + 1 < showMax) {
103
- startPage = Math.max(1, endPage - showMax + 1);
104
- }
105
-
106
- for (let i = startPage; i <= endPage; i++) {
107
- pages.push(i);
108
- }
109
-
110
- return (
111
- <div className="flex items-center justify-center gap-2 mt-8 flex-wrap">
112
- <button
113
- onClick={() => handlePageChange(1)}
114
- disabled={currentPage === 1}
115
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
116
- title="Primera página"
117
- >
118
- <ChevronsLeft className="w-4 h-4" />
119
- </button>
120
- <button
121
- onClick={() => handlePageChange(currentPage - 1)}
122
- disabled={currentPage === 1}
123
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
124
- title="Anterior"
125
- >
126
- <ChevronLeft className="w-4 h-4" />
127
- </button>
128
-
129
- {startPage > 1 && (
130
- <span className="text-gray-500 px-1">...</span>
131
- )}
132
-
133
- {pages.map((page) => (
134
- <button
135
- key={page}
136
- onClick={() => handlePageChange(page)}
137
- className={`w-8 h-8 rounded-lg text-sm font-medium transition-colors ${currentPage === page
138
- ? 'bg-[#bb86fc] text-white'
139
- : 'bg-[#1a1a1a] text-gray-400 hover:bg-[#333] hover:text-white'
140
- }`}
141
- >
142
- {page}
143
- </button>
144
- ))}
145
-
146
- {endPage < totalPages && (
147
- <span className="text-gray-500 px-1">...</span>
148
- )}
149
-
150
- <button
151
- onClick={() => handlePageChange(currentPage + 1)}
152
- disabled={currentPage === totalPages}
153
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
154
- title="Siguiente"
155
- >
156
- <ChevronRight className="w-4 h-4" />
157
- </button>
158
- <button
159
- onClick={() => handlePageChange(totalPages)}
160
- disabled={currentPage === totalPages}
161
- className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
162
- title="Última página"
163
- >
164
- <ChevronsRight className="w-4 h-4" />
165
- </button>
166
- </div>
167
- );
168
- };
169
-
170
- if (isSearching && searchTerm) {
171
- return (
172
- <div className="flex flex-col items-center justify-center py-16 animate-in fade-in duration-300">
173
- <div className="text-gray-400 text-sm animate-pulse">Buscando "{searchTerm}"...</div>
174
- </div>
175
- );
176
- }
177
-
178
- if (isLoading) {
179
- return (
180
- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 justify-center items-start animate-in fade-in duration-300">
181
- {Array.from({ length: 12 }).map((_, index) => (
182
- <MangaCardSkeleton key={index} />
183
- ))}
184
- </div>
185
- );
186
- }
187
- if (searchTerm && items.length === 0) {
188
- return (
189
- <div className="flex flex-col items-center justify-center py-16 animate-in fade-in duration-300">
190
- <BookOpen className="w-16 h-16 text-gray-600 mb-4 animate-bounce" />
191
- <p className="text-gray-400 text-lg mb-2">No se encontraron resultados</p>
192
- <p className="text-gray-500 text-sm">Intenta con otros términos de búsqueda</p>
193
- </div>
194
- );
195
- }
196
-
197
- if (!searchTerm && items.length === 0) {
198
- return (
199
- <div className="flex flex-col items-center justify-center py-20 animate-in fade-in duration-300">
200
- <BookOpen className="w-16 h-16 text-gray-600 mb-4 animate-bounce" />
201
- <p className="text-gray-400 text-lg mb-2">No hay mangas disponibles</p>
202
- <p className="text-gray-500 text-sm">Crea tu primer manga usando el botón "Nuevo"</p>
203
- </div>
204
- );
205
- }
206
-
207
- return (
208
- <div className="flex flex-col gap-6">
209
- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 justify-center items-start">
210
- {currentItems.map((item) => (
211
- <div key={item.id}>
212
- <MangaCard
213
- id={item.id}
214
- title={item.title}
215
- author={item.author}
216
- pageCount={item.pageCount}
217
- thumbnail={item.thumbnail}
218
- manga={item.manga}
219
- onSelect={() => onSelectComic(item.id)}
220
- onEdit={onEditManga}
221
- onDelete={onDeleteManga ? () => onDeleteManga(item.id) : undefined}
222
- />
223
- </div>
224
- ))}
225
- </div>
226
-
227
- {renderPagination()}
228
- </div>
229
- );
230
- }
 
1
+ import { BookOpen, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
2
+ import { useState, useEffect } from 'react';
3
+ import { MangaCard } from './MangaCard';
4
+ import { MangaCardSkeleton } from './MangaCardSkeleton';
5
+ import { Manga } from '../types/manga';
6
+
7
+ interface SearchResult {
8
+ id: string;
9
+ title: string;
10
+ author: string;
11
+ chapterCount: number;
12
+ pageCount: number;
13
+ thumbnail?: string;
14
+ manga?: Manga;
15
+ }
16
+
17
+ interface SearchResultsProps {
18
+ items: SearchResult[];
19
+ searchTerm: string;
20
+ isSearching: boolean;
21
+ onSelectComic: (id: string) => void;
22
+ onEditManga?: (manga: Manga) => void;
23
+ onDeleteManga?: (id: string) => void;
24
+ isLoading?: boolean;
25
+ }
26
+
27
+ const ITEMS_PER_PAGE = 24;
28
+
29
+ export function SearchResults({
30
+ items,
31
+ searchTerm,
32
+ isSearching,
33
+ onSelectComic,
34
+ onEditManga,
35
+ onDeleteManga,
36
+ isLoading = false,
37
+ }: SearchResultsProps) {
38
+ const [currentPage, setCurrentPage] = useState(() => {
39
+ const params = new URLSearchParams(window.location.search);
40
+ const page = params.get('page');
41
+ return page ? Math.max(1, Number(page)) : 1;
42
+ });
43
+
44
+ // Listen for browser back/forward buttons
45
+ useEffect(() => {
46
+ const handlePopState = () => {
47
+ const params = new URLSearchParams(window.location.search);
48
+ const page = params.get('page');
49
+ setCurrentPage(page ? Math.max(1, Number(page)) : 1);
50
+ };
51
+
52
+ window.addEventListener('popstate', handlePopState);
53
+ return () => window.removeEventListener('popstate', handlePopState);
54
+ }, []);
55
+
56
+ // Correct page if out of bounds (e.g. after filtering changes)
57
+ const totalPages = Math.ceil(items.length / ITEMS_PER_PAGE);
58
+
59
+ useEffect(() => {
60
+ if (totalPages > 0 && currentPage > totalPages) {
61
+ // Silent correction
62
+ setCurrentPage(totalPages);
63
+ const url = new URL(window.location.href);
64
+ url.searchParams.set('page', String(totalPages));
65
+ window.history.replaceState({}, '', url);
66
+ }
67
+ }, [totalPages, currentPage]);
68
+
69
+ // Reset page ONLY when search term changes (not when items change due to sorting)
70
+ useEffect(() => {
71
+ if (searchTerm) {
72
+ setCurrentPage(1);
73
+ const url = new URL(window.location.href);
74
+ url.searchParams.delete('page');
75
+ window.history.replaceState({}, '', url);
76
+ }
77
+ }, [searchTerm]);
78
+
79
+ // Get current items
80
+ const currentItems = items.slice(
81
+ (currentPage - 1) * ITEMS_PER_PAGE,
82
+ currentPage * ITEMS_PER_PAGE
83
+ );
84
+
85
+ const handlePageChange = (page: number) => {
86
+ setCurrentPage(page);
87
+ const url = new URL(window.location.href);
88
+ url.searchParams.set('page', String(page));
89
+ window.history.pushState({}, '', url);
90
+ window.scrollTo({ top: 0, behavior: 'smooth' });
91
+ };
92
+
93
+ const renderPagination = () => {
94
+ if (totalPages <= 1) return null;
95
+
96
+ const pages = [];
97
+ // Logic to show a window of pages for better UX (e.g. 1 ... 4 5 6 ... 10)
98
+ const showMax = 5;
99
+ let startPage = Math.max(1, currentPage - Math.floor(showMax / 2));
100
+ let endPage = Math.min(totalPages, startPage + showMax - 1);
101
+
102
+ if (endPage - startPage + 1 < showMax) {
103
+ startPage = Math.max(1, endPage - showMax + 1);
104
+ }
105
+
106
+ for (let i = startPage; i <= endPage; i++) {
107
+ pages.push(i);
108
+ }
109
+
110
+ return (
111
+ <div className="flex items-center justify-center gap-2 mt-8 flex-wrap">
112
+ <button
113
+ onClick={() => handlePageChange(1)}
114
+ disabled={currentPage === 1}
115
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
116
+ title="Primera página"
117
+ >
118
+ <ChevronsLeft className="w-4 h-4" />
119
+ </button>
120
+ <button
121
+ onClick={() => handlePageChange(currentPage - 1)}
122
+ disabled={currentPage === 1}
123
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
124
+ title="Anterior"
125
+ >
126
+ <ChevronLeft className="w-4 h-4" />
127
+ </button>
128
+
129
+ {startPage > 1 && (
130
+ <span className="text-gray-500 px-1">...</span>
131
+ )}
132
+
133
+ {pages.map((page) => (
134
+ <button
135
+ key={page}
136
+ onClick={() => handlePageChange(page)}
137
+ className={`w-8 h-8 rounded-lg text-sm font-medium transition-colors ${currentPage === page
138
+ ? 'bg-[#bb86fc] text-white'
139
+ : 'bg-[#1a1a1a] text-gray-400 hover:bg-[#333] hover:text-white'
140
+ }`}
141
+ >
142
+ {page}
143
+ </button>
144
+ ))}
145
+
146
+ {endPage < totalPages && (
147
+ <span className="text-gray-500 px-1">...</span>
148
+ )}
149
+
150
+ <button
151
+ onClick={() => handlePageChange(currentPage + 1)}
152
+ disabled={currentPage === totalPages}
153
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
154
+ title="Siguiente"
155
+ >
156
+ <ChevronRight className="w-4 h-4" />
157
+ </button>
158
+ <button
159
+ onClick={() => handlePageChange(totalPages)}
160
+ disabled={currentPage === totalPages}
161
+ className="p-2 rounded-lg bg-[#1a1a1a] text-white hover:bg-[#bb86fc] disabled:opacity-50 disabled:hover:bg-[#1a1a1a] transition-colors"
162
+ title="Última página"
163
+ >
164
+ <ChevronsRight className="w-4 h-4" />
165
+ </button>
166
+ </div>
167
+ );
168
+ };
169
+
170
+ if (isSearching && searchTerm) {
171
+ return (
172
+ <div className="flex flex-col items-center justify-center py-16 animate-in fade-in duration-300">
173
+ <div className="text-gray-400 text-sm animate-pulse">Buscando "{searchTerm}"...</div>
174
+ </div>
175
+ );
176
+ }
177
+
178
+ if (isLoading) {
179
+ return (
180
+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 justify-center items-start animate-in fade-in duration-300">
181
+ {Array.from({ length: 12 }).map((_, index) => (
182
+ <MangaCardSkeleton key={index} />
183
+ ))}
184
+ </div>
185
+ );
186
+ }
187
+ if (searchTerm && items.length === 0) {
188
+ return (
189
+ <div className="flex flex-col items-center justify-center py-16 animate-in fade-in duration-300">
190
+ <BookOpen className="w-16 h-16 text-gray-600 mb-4 animate-bounce" />
191
+ <p className="text-gray-400 text-lg mb-2">No se encontraron resultados</p>
192
+ <p className="text-gray-500 text-sm">Intenta con otros términos de búsqueda</p>
193
+ </div>
194
+ );
195
+ }
196
+
197
+ if (!searchTerm && items.length === 0) {
198
+ return (
199
+ <div className="flex flex-col items-center justify-center py-20 animate-in fade-in duration-300">
200
+ <BookOpen className="w-16 h-16 text-gray-600 mb-4 animate-bounce" />
201
+ <p className="text-gray-400 text-lg mb-2">No hay mangas disponibles</p>
202
+ <p className="text-gray-500 text-sm">Crea tu primer manga usando el botón "Nuevo"</p>
203
+ </div>
204
+ );
205
+ }
206
+
207
+ return (
208
+ <div className="flex flex-col gap-6">
209
+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-1.5 sm:gap-2 md:gap-3 justify-center items-start">
210
+ {currentItems.map((item) => (
211
+ <div key={item.id}>
212
+ <MangaCard
213
+ id={item.id}
214
+ title={item.title}
215
+ author={item.author}
216
+ pageCount={item.pageCount}
217
+ thumbnail={item.thumbnail}
218
+ manga={item.manga}
219
+ onSelect={() => onSelectComic(item.id)}
220
+ onEdit={onEditManga}
221
+ onDelete={onDeleteManga ? () => onDeleteManga(item.id) : undefined}
222
+ />
223
+ </div>
224
+ ))}
225
+ </div>
226
+
227
+ {renderPagination()}
228
+ </div>
229
+ );
230
+ }
src/components/SettingsModal.tsx CHANGED
@@ -1,622 +1,622 @@
1
- import { X, Key, Trash2, Save, Settings, Shield, Lock, Unlock, Megaphone, Clock, LogOut, UserPlus, UserMinus, Eye } from 'lucide-react';
2
- import { useState, useEffect } from 'react';
3
- import { getUserApiKey, saveUserApiKey, deleteUserApiKey } from '../utils/apiKeyManager';
4
- import { saveAnnouncement } from '../services/announcement';
5
- import { auth, googleProvider } from '../lib/firebase';
6
- import { signInWithPopup, signOut, signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';
7
- import { isUserAdmin, addAdminEmail, removeAdminEmail, getAllowedEmails } from '../services/admin';
8
- import { resetAllMangaViews } from '../services/manga';
9
-
10
- interface SettingsModalProps {
11
- isOpen: boolean;
12
- onClose: () => void;
13
- isAdmin: boolean;
14
- onAdminChange: (isAdmin: boolean) => void;
15
- }
16
-
17
- // SHA-256 Hash for 'Loyola069012*'
18
-
19
-
20
- export function SettingsModal({ isOpen, onClose, isAdmin, onAdminChange }: SettingsModalProps) {
21
- // API Key State
22
- const [apiKey, setApiKey] = useState('');
23
- const [hasUserApiKey, setHasUserApiKey] = useState(false);
24
-
25
- // Admin Config State
26
- const [isLoadingAuth, setIsLoadingAuth] = useState(false);
27
- const [authError, setAuthError] = useState('');
28
- const [emailInput, setEmailInput] = useState('');
29
- const [passwordInput, setPasswordInput] = useState('');
30
- const [adminEmails, setAdminEmails] = useState<string[]>([]);
31
- const [newAdminEmail, setNewAdminEmail] = useState('');
32
- const [currentUserEmail, setCurrentUserEmail] = useState<string | null>(null);
33
-
34
- // Announcement State
35
- const [announcementText, setAnnouncementText] = useState('');
36
- const [durationValue, setDurationValue] = useState(24);
37
- const [durationUnit, setDurationUnit] = useState<'seconds' | 'minutes' | 'hours' | 'days'>('hours');
38
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
39
-
40
- // Reset state when modal opens
41
- useEffect(() => {
42
- if (isOpen) {
43
- // API Key init
44
- const userKey = getUserApiKey();
45
- if (userKey) {
46
- setApiKey(userKey);
47
- setHasUserApiKey(true);
48
- } else {
49
- setApiKey('');
50
- setHasUserApiKey(false);
51
- }
52
-
53
- // Admin init
54
- setAuthError('');
55
- setEmailInput('');
56
- setPasswordInput('');
57
-
58
- // Check current auth status
59
- const user = auth.currentUser;
60
- if (user) {
61
- setCurrentUserEmail(user.email);
62
- if (isAdmin) {
63
- loadAdminEmails();
64
- }
65
- } else {
66
- if (isAdmin) {
67
- // If stored state is admin but no firebase user, logout
68
- onAdminChange(false);
69
- }
70
- }
71
- }
72
- }, [isOpen]);
73
-
74
- const loadAdminEmails = async () => {
75
- const emails = await getAllowedEmails();
76
- setAdminEmails(emails);
77
- };
78
-
79
- const handleSaveApiKey = () => {
80
- if (!apiKey.trim()) {
81
- alert('Por favor ingresa una API válida');
82
- return;
83
- }
84
- saveUserApiKey(apiKey.trim());
85
- setHasUserApiKey(true);
86
- alert('API guardada exitosamente.');
87
- };
88
-
89
- const handleDeleteApiKey = () => {
90
- if (window.confirm('¿Eliminar tu API personal?')) {
91
- deleteUserApiKey();
92
- setApiKey('');
93
- setHasUserApiKey(false);
94
- }
95
- };
96
-
97
- const handleGoogleLogin = async () => {
98
- setIsLoadingAuth(true);
99
- setAuthError('');
100
- try {
101
- const result = await signInWithPopup(auth, googleProvider);
102
- const email = result.user.email;
103
-
104
- if (!email) {
105
- throw new Error('No se pudo obtener el email.');
106
- }
107
-
108
- const hasPermission = await isUserAdmin(email);
109
-
110
- if (hasPermission) {
111
- onAdminChange(true);
112
- setCurrentUserEmail(email);
113
- await loadAdminEmails();
114
- } else {
115
- await signOut(auth); // Logout immediately if not allowed
116
- setAuthError('Este correo no tiene permisos de administrador.');
117
- onAdminChange(false);
118
- }
119
- } catch (error: any) {
120
- console.error('Login error:', error);
121
- setAuthError(error.message || 'Error al iniciar sesión.');
122
- } finally {
123
- setIsLoadingAuth(false);
124
- }
125
- };
126
-
127
- const handleEmailLogin = async () => {
128
- if (!emailInput || !passwordInput) {
129
- setAuthError('Por favor ingresa correo y contraseña.');
130
- return;
131
- }
132
-
133
- setIsLoadingAuth(true);
134
- setAuthError('');
135
- try {
136
- const result = await signInWithEmailAndPassword(auth, emailInput.trim(), passwordInput);
137
- const email = result.user.email;
138
-
139
- if (!email) {
140
- throw new Error('No se pudo obtener el email.');
141
- }
142
-
143
- const hasPermission = await isUserAdmin(email);
144
-
145
- if (hasPermission) {
146
- onAdminChange(true);
147
- setCurrentUserEmail(email);
148
- await loadAdminEmails();
149
- } else {
150
- await signOut(auth); // Logout immediately if not allowed
151
- setAuthError('Este correo no tiene permisos de administrador.');
152
- onAdminChange(false);
153
- }
154
- } catch (error: any) {
155
- console.error('Login error:', error);
156
- if (error.code === 'auth/invalid-credential' || error.code === 'auth/user-not-found') {
157
- setAuthError('Cuenta no encontrada o contraseña incorrecta. Si es tu primera vez, usa "Registrarse".');
158
- } else {
159
- setAuthError(error.message || 'Error al iniciar sesión.');
160
- }
161
- } finally {
162
- setIsLoadingAuth(false);
163
- }
164
- };
165
-
166
- const handleRegister = async () => {
167
- if (!emailInput || !passwordInput) {
168
- setAuthError('Ingresa un correo y contraseña para registrarte.');
169
- return;
170
- }
171
-
172
- setIsLoadingAuth(true);
173
- setAuthError('');
174
- try {
175
- // 1. Create User
176
- const result = await createUserWithEmailAndPassword(auth, emailInput.trim(), passwordInput);
177
- const email = result.user.email;
178
-
179
- if (!email) throw new Error('Error al obtener email.');
180
-
181
- // 2. Verify if Allowed
182
- const hasPermission = await isUserAdmin(email);
183
-
184
- if (hasPermission) {
185
- onAdminChange(true);
186
- setCurrentUserEmail(email);
187
- await loadAdminEmails();
188
- alert('Cuenta creada y verificada exitosamente.');
189
- } else {
190
- // If not allowed, delete/logout immediately
191
- // (Deleting user requires re-auth usually, so we just sign out for now to block access)
192
- await signOut(auth);
193
- setAuthError('Cuenta creada, pero tu correo NO está autorizado como administrador.');
194
- onAdminChange(false);
195
- }
196
-
197
- } catch (error: any) {
198
- console.error('Register error:', error);
199
- if (error.code === 'auth/email-already-in-use') {
200
- setAuthError('Este correo ya está registrado. Intenta "Ingresar".');
201
- } else if (error.code === 'auth/weak-password') {
202
- setAuthError('La contraseña debe tener al menos 6 caracteres.');
203
- } else {
204
- setAuthError(error.message || 'Error al registrar.');
205
- }
206
- } finally {
207
- setIsLoadingAuth(false);
208
- }
209
- };
210
-
211
- const handleLogout = async () => {
212
- try {
213
- await signOut(auth);
214
- onAdminChange(false);
215
- setCurrentUserEmail(null);
216
- setAdminEmails([]);
217
- } catch (error) {
218
- console.error('Logout error:', error);
219
- }
220
- };
221
-
222
- const handleAddAdmin = async () => {
223
- if (!newAdminEmail.trim()) return;
224
- try {
225
- await addAdminEmail(newAdminEmail.trim());
226
- setNewAdminEmail('');
227
- await loadAdminEmails();
228
- alert('Administrador añadido correctamente.');
229
- } catch (error: any) {
230
- alert('Error al añadir: ' + error.message);
231
- }
232
- };
233
-
234
- const handleRemoveAdmin = async (email: string) => {
235
- if (!window.confirm(`¿Seguro que quieres eliminar a ${email}?`)) return;
236
- try {
237
- await removeAdminEmail(email);
238
- await loadAdminEmails();
239
- } catch (error: any) {
240
- alert('Error: ' + error.message);
241
- }
242
- };
243
-
244
- const handlePublishAnnouncement = async () => {
245
- if (!announcementText.trim()) {
246
- alert('El texto del anuncio no puede estar vacío');
247
- return;
248
- }
249
-
250
- let durationMs = 0;
251
- if (durationUnit === 'seconds') durationMs = durationValue * 1000;
252
- if (durationUnit === 'minutes') durationMs = durationValue * 60 * 1000;
253
- if (durationUnit === 'hours') durationMs = durationValue * 60 * 60 * 1000;
254
- if (durationUnit === 'days') durationMs = durationValue * 24 * 60 * 60 * 1000;
255
-
256
- try {
257
- await saveAnnouncement(announcementText, durationMs);
258
- alert('Anuncio publicado exitosamente');
259
- setAnnouncementText('');
260
- onClose();
261
- } catch (err) {
262
- console.error(err);
263
- alert('Error al publicar el anuncio');
264
- }
265
- };
266
-
267
- const handleDeleteAnnouncement = async () => {
268
- try {
269
- await saveAnnouncement('', null);
270
- setAnnouncementText('');
271
- setShowDeleteConfirm(false);
272
- } catch (e) {
273
- console.error(e);
274
- alert('Error al eliminar');
275
- }
276
- };
277
-
278
- if (!isOpen) return null;
279
-
280
- return (
281
- <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
282
- <div className="bg-[#121212] rounded-2xl border border-gray-800 w-full max-w-lg shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
283
-
284
- {/* Header */}
285
- <div className="bg-[#1a1a1a] border-b border-gray-800 px-6 py-4 flex items-center justify-between sticky top-0 z-10">
286
- <div className="flex items-center gap-3">
287
- <div className="p-2 bg-[#bb86fc]/10 rounded-lg text-[#bb86fc]">
288
- <Settings className="w-5 h-5" />
289
- </div>
290
- <h2 className="text-xl font-bold text-white">Ajustes</h2>
291
- </div>
292
- <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors p-2 hover:bg-white/5 rounded-lg">
293
- <X className="w-5 h-5" />
294
- </button>
295
- </div>
296
-
297
- <div className="p-6 space-y-8 overflow-y-auto custom-scrollbar">
298
-
299
- {/* Admin Section */}
300
- <section className="space-y-4">
301
- <div className="flex items-center justify-between">
302
- <div className="flex items-center gap-3">
303
- <div className={`p-2 rounded-lg ${isAdmin ? 'bg-green-500/10 text-green-500' : 'bg-gray-800 text-gray-400'}`}>
304
- {isAdmin ? <Unlock className="w-5 h-5" /> : <Lock className="w-5 h-5" />}
305
- </div>
306
- <div>
307
- <h3 className="tex-sm font-semibold text-white">Modo Administrador</h3>
308
- <p className="text-xs text-gray-400">
309
- {isAdmin ? `Conectado como ${currentUserEmail}` : 'Requiere acceso autorizado'}
310
- </p>
311
- </div>
312
- </div>
313
-
314
- {isAdmin && (
315
- <button
316
- onClick={handleLogout}
317
- className="text-gray-400 hover:text-white p-2 rounded-lg hover:bg-white/5 transition-colors"
318
- title="Cerrar Sessión"
319
- >
320
- <LogOut className="w-5 h-5" />
321
- </button>
322
- )}
323
- </div>
324
-
325
- {!isAdmin ? (
326
- <div className="bg-[#1a1a1a] p-6 rounded-xl border border-gray-800 animate-in slide-in-from-top-2 duration-200 text-center">
327
- <p className="text-sm text-gray-400 mb-4">Inicia sesión con una cuenta autorizada.</p>
328
-
329
- {/* Email/Password Form */}
330
- <div className="space-y-3 mb-4">
331
- <input
332
- type="email"
333
- placeholder="Correo electrónico"
334
- value={emailInput}
335
- onChange={(e) => setEmailInput(e.target.value)}
336
- className="w-full bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
337
- />
338
- <input
339
- type="password"
340
- placeholder="Contraseña"
341
- value={passwordInput}
342
- onChange={(e) => setPasswordInput(e.target.value)}
343
- onKeyDown={(e) => e.key === 'Enter' && handleEmailLogin()}
344
- className="w-full bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
345
- />
346
- <button
347
- onClick={handleEmailLogin}
348
- disabled={isLoadingAuth}
349
- className="w-full bg-[#bb86fc] text-white hover:bg-[#9966dd] py-2 rounded-lg font-semibold text-sm transition-colors disabled:opacity-70"
350
- >
351
- {isLoadingAuth ? 'Verificando...' : 'Ingresar'}
352
- </button>
353
-
354
- <button
355
- onClick={handleRegister}
356
- disabled={isLoadingAuth}
357
- className="w-full bg-transparent border border-gray-600 text-gray-300 hover:border-gray-400 hover:text-white py-1.5 rounded-lg text-xs transition-colors disabled:opacity-50"
358
- >
359
- ¿Primera vez? Crear cuenta
360
- </button>
361
- </div>
362
-
363
- <div className="flex items-center gap-2 my-4">
364
- <div className="h-px bg-gray-800 flex-1" />
365
- <span className="text-xs text-gray-500">O usa Google</span>
366
- <div className="h-px bg-gray-800 flex-1" />
367
- </div>
368
-
369
- <button
370
- onClick={handleGoogleLogin}
371
- disabled={isLoadingAuth}
372
- className="w-full bg-white text-gray-900 hover:bg-gray-100 py-2.5 rounded-lg font-semibold flex items-center justify-center gap-2 transition-colors disabled:opacity-70"
373
- >
374
- {isLoadingAuth ? (
375
- <div className="w-5 h-5 border-2 border-gray-900 border-t-transparent rounded-full animate-spin"></div>
376
- ) : (
377
- <svg className="w-5 h-5" viewBox="0 0 24 24">
378
- <path fill="currentColor" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
379
- <path fill="currentColor" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
380
- <path fill="currentColor" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.84z" />
381
- <path fill="currentColor" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
382
- </svg>
383
- )}
384
- Iniciar con Google
385
- </button>
386
- {authError && <p className="text-red-500 text-xs mt-3 bg-red-500/10 p-2 rounded border border-red-500/20">{authError}</p>}
387
- </div>
388
- ) : (
389
- // MANAGE ADMINS SECTION (Only visible to admins)
390
- <div className="bg-[#1a1a1a] p-4 rounded-xl border border-gray-800 space-y-4">
391
- <h4 className="text-sm font-semibold text-white mb-2 flex items-center gap-2">
392
- <Shield className="w-4 h-4 text-[#bb86fc]" />
393
- Gestión de Administradores
394
- </h4>
395
-
396
- <div className="flex gap-2">
397
- <input
398
- type="email"
399
- placeholder="nuevo_admin@gmail.com"
400
- value={newAdminEmail}
401
- onChange={(e) => setNewAdminEmail(e.target.value)}
402
- className="flex-1 bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
403
- />
404
- <button
405
- onClick={handleAddAdmin}
406
- disabled={!newAdminEmail.trim()}
407
- className="bg-[#bb86fc]/20 hover:bg-[#bb86fc]/30 text-[#bb86fc] p-2 rounded-lg transition-colors disabled:opacity-50"
408
- >
409
- <UserPlus className="w-5 h-5" />
410
- </button>
411
- </div>
412
-
413
- <div className="space-y-2 max-h-40 overflow-y-auto pr-1 custom-scrollbar">
414
- {adminEmails.map(email => (
415
- <div key={email} className="flex items-center justify-between bg-black/30 p-2 rounded-lg border border-gray-800/50">
416
- <span className="text-xs text-gray-300 truncate">{email}</span>
417
- {/* Don't allow removing yourself or hardcoded owners (though owners are protected in service, UI feedback is nice) */}
418
- <button
419
- onClick={() => handleRemoveAdmin(email)}
420
- className="text-gray-500 hover:text-red-400 p-1 hover:bg-white/5 rounded transition-colors"
421
- title="Eliminar admin"
422
- >
423
- <UserMinus className="w-4 h-4" />
424
- </button>
425
- </div>
426
- ))}
427
- </div>
428
- </div>
429
- )}
430
- </section>
431
-
432
- {isAdmin && (
433
- <section className="space-y-4 pt-4 border-t border-gray-800">
434
- <div className="flex items-center gap-3 mb-2">
435
- <div className="p-2 bg-red-500/10 rounded-lg text-red-500">
436
- <Eye className="w-5 h-5" />
437
- </div>
438
- <div>
439
- <h3 className="tex-sm font-semibold text-white">Gestión de Vistas</h3>
440
- <p className="text-xs text-gray-400">Restablecer contadores de visualización</p>
441
- </div>
442
- </div>
443
-
444
- <button
445
- onClick={async () => {
446
- if (window.confirm('¿Seguro que quieres reiniciar las vistas de TODOS los mangas a 0? Esta acción no se puede deshacer.')) {
447
- try {
448
- await resetAllMangaViews();
449
- alert('Vistas reiniciadas correctamente.');
450
- } catch (e) {
451
- console.error(e);
452
- alert('Error al reiniciar vistas.');
453
- }
454
- }
455
- }}
456
- className="w-full bg-red-500/10 hover:bg-red-500/20 text-red-500 py-2.5 rounded-lg font-semibold text-sm transition-all border border-red-500/20 hover:border-red-500/40"
457
- >
458
- Reiniciar Vistas a 0
459
- </button>
460
- </section>
461
- )}
462
-
463
- {isAdmin && (
464
- <>
465
- <div className="h-px bg-gray-800" />
466
- <section className="space-y-4">
467
- <div className="flex items-center gap-3 mb-2">
468
- <div className="p-2 bg-purple-500/10 rounded-lg text-purple-400">
469
- <Megaphone className="w-5 h-5" />
470
- </div>
471
- <div>
472
- <h3 className="tex-sm font-semibold text-white">Publicar Anuncio</h3>
473
- <p className="text-xs text-gray-400">Visible para todos los usuarios</p>
474
- </div>
475
- </div>
476
-
477
- <div className="space-y-3">
478
- <textarea
479
- value={announcementText}
480
- onChange={(e) => setAnnouncementText(e.target.value)}
481
- placeholder="Escribe el mensaje del anuncio..."
482
- className="w-full bg-[#1a1a1a] border border-gray-700 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#bb86fc] min-h-[100px] resize-none"
483
- />
484
-
485
- <div className="flex gap-3">
486
- <div className="flex-1 bg-[#1a1a1a] border border-gray-700 rounded-lg px-3 py-2 flex items-center gap-2">
487
- <Clock className="w-4 h-4 text-gray-400" />
488
- <input
489
- type="number"
490
- min="1"
491
- value={durationValue}
492
- onChange={(e) => setDurationValue(Number(e.target.value))}
493
- className="bg-transparent text-white text-sm w-full focus:outline-none"
494
- />
495
- </div>
496
- <select
497
- value={durationUnit}
498
- onChange={(e) => setDurationUnit(e.target.value as any)}
499
- className="bg-[#1a1a1a] border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
500
- >
501
- <option value="seconds">Segundos</option>
502
- <option value="minutes">Minutos</option>
503
- <option value="hours">Horas</option>
504
- <option value="days">Días</option>
505
- </select>
506
- </div>
507
-
508
- <div className="flex gap-2">
509
- <button
510
- onClick={() => setShowDeleteConfirm(true)}
511
- className="px-4 py-2.5 rounded-lg font-semibold text-sm bg-red-500/10 text-red-500 border border-red-500/20 hover:bg-red-500/20 transition-colors"
512
- title="Eliminar anuncio"
513
- >
514
- <Trash2 className="w-5 h-5" />
515
- </button>
516
- <button
517
- onClick={handlePublishAnnouncement}
518
- className="flex-1 bg-gradient-to-r from-[#bb86fc] to-[#9966dd] hover:from-[#9966dd] hover:to-[#7744cc] text-white py-2.5 rounded-lg font-semibold text-sm transition-all shadow-lg shadow-[#bb86fc]/20"
519
- >
520
- Publicar Anuncio
521
- </button>
522
- </div>
523
- </div>
524
- </section>
525
- </>
526
- )}
527
-
528
- <div className="h-px bg-gray-800" />
529
-
530
- {/* API Config Section */}
531
- <section className="space-y-4">
532
- <div className="flex items-center gap-3 mb-2">
533
- <div className="p-2 bg-blue-500/10 rounded-lg text-blue-400">
534
- <Key className="w-5 h-5" />
535
- </div>
536
- <div>
537
- <h3 className="tex-sm font-semibold text-white">Configuración de API</h3>
538
- <p className="text-xs text-gray-400">Gestiona tu clave personal de ImgBB</p>
539
- </div>
540
- </div>
541
-
542
- {hasUserApiKey && (
543
- <div className="bg-green-500/10 border border-green-500/20 rounded-lg p-3">
544
- <p className="text-green-400 text-xs font-medium flex items-center gap-2">
545
- <Shield className="w-3 h-3" />
546
- API personal activa
547
- </p>
548
- </div>
549
- )}
550
-
551
- <div className="space-y-2">
552
- <input
553
- type="text"
554
- placeholder="Pega tu API Key de ImgBB aquí..."
555
- value={apiKey}
556
- onChange={(e) => setApiKey(e.target.value)}
557
- className="w-full bg-[#1a1a1a] border border-gray-700 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#bb86fc] focus:ring-1 focus:ring-[#bb86fc] transition-all font-mono"
558
- />
559
- <p className="text-xs text-gray-500">
560
- Obtén tu API key gratuitamente en <a href="https://api.imgbb.com/" target="_blank" rel="noopener noreferrer" className="text-[#bb86fc] hover:underline">api.imgbb.com</a>
561
- </p>
562
- </div>
563
-
564
- <div className="flex gap-3">
565
- {hasUserApiKey && (
566
- <button
567
- onClick={handleDeleteApiKey}
568
- className="flex-1 bg-red-500/10 border border-red-500/30 hover:bg-red-500/20 text-red-500 px-4 py-2.5 rounded-lg font-medium text-sm transition-colors flex items-center justify-center gap-2"
569
- >
570
- <Trash2 className="w-4 h-4" />
571
- Eliminar
572
- </button>
573
- )}
574
- <button
575
- onClick={handleSaveApiKey}
576
- disabled={!apiKey.trim()}
577
- className="flex-1 bg-[#1a1a1a] border border-gray-700 hover:border-[#bb86fc] hover:text-[#bb86fc] disabled:opacity-50 disabled:hover:border-gray-700 disabled:hover:text-gray-500 text-gray-300 px-4 py-2.5 rounded-lg font-medium text-sm transition-all flex items-center justify-center gap-2 group"
578
- >
579
- <Save className="w-4 h-4 group-hover:scale-110 transition-transform" />
580
- Guardar Cambios
581
- </button>
582
- </div>
583
- </section>
584
- </div>
585
-
586
- {/* Confirm Delete Overlay */}
587
- {showDeleteConfirm && (
588
- <div className="absolute inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 p-6 animate-in fade-in duration-200">
589
- <div className="bg-[#1a1a1a] border border-gray-700 w-full max-w-sm rounded-xl shadow-2xl p-6 transform scale-100 animate-in zoom-in-95 duration-200">
590
- <div className="flex flex-col items-center text-center gap-4">
591
- <div className="p-3 bg-red-500/10 rounded-full text-red-500">
592
- <Trash2 className="w-8 h-8" />
593
- </div>
594
- <div>
595
- <h3 className="text-lg font-bold text-white mb-1">¿Eliminar anuncio?</h3>
596
- <p className="text-sm text-gray-400">
597
- Esta acción eliminará el anuncio actual inmediatamente. No se puede deshacer.
598
- </p>
599
- </div>
600
- <div className="flex gap-3 w-full mt-2">
601
- <button
602
- onClick={() => setShowDeleteConfirm(false)}
603
- className="flex-1 px-4 py-2 rounded-lg text-sm font-semibold text-gray-300 hover:bg-gray-800 transition-colors"
604
- >
605
- Cancelar
606
- </button>
607
- <button
608
- onClick={handleDeleteAnnouncement}
609
- className="flex-1 px-4 py-2 rounded-lg text-sm font-semibold bg-red-500 hover:bg-red-600 text-white transition-colors shadow-lg shadow-red-500/20"
610
- >
611
- Eliminar
612
- </button>
613
- </div>
614
- </div>
615
- </div>
616
- </div>
617
- )}
618
- </div>
619
- </div>
620
- );
621
- }
622
-
 
1
+ import { X, Key, Trash2, Save, Settings, Shield, Lock, Unlock, Megaphone, Clock, LogOut, UserPlus, UserMinus, Eye } from 'lucide-react';
2
+ import { useState, useEffect } from 'react';
3
+ import { getUserApiKey, saveUserApiKey, deleteUserApiKey } from '../utils/apiKeyManager';
4
+ import { saveAnnouncement } from '../services/announcement';
5
+ import { auth, googleProvider } from '../lib/firebase';
6
+ import { signInWithPopup, signOut, signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';
7
+ import { isUserAdmin, addAdminEmail, removeAdminEmail, getAllowedEmails } from '../services/admin';
8
+ import { resetAllMangaViews } from '../services/manga';
9
+
10
+ interface SettingsModalProps {
11
+ isOpen: boolean;
12
+ onClose: () => void;
13
+ isAdmin: boolean;
14
+ onAdminChange: (isAdmin: boolean) => void;
15
+ }
16
+
17
+ // SHA-256 Hash for 'Loyola069012*'
18
+
19
+
20
+ export function SettingsModal({ isOpen, onClose, isAdmin, onAdminChange }: SettingsModalProps) {
21
+ // API Key State
22
+ const [apiKey, setApiKey] = useState('');
23
+ const [hasUserApiKey, setHasUserApiKey] = useState(false);
24
+
25
+ // Admin Config State
26
+ const [isLoadingAuth, setIsLoadingAuth] = useState(false);
27
+ const [authError, setAuthError] = useState('');
28
+ const [emailInput, setEmailInput] = useState('');
29
+ const [passwordInput, setPasswordInput] = useState('');
30
+ const [adminEmails, setAdminEmails] = useState<string[]>([]);
31
+ const [newAdminEmail, setNewAdminEmail] = useState('');
32
+ const [currentUserEmail, setCurrentUserEmail] = useState<string | null>(null);
33
+
34
+ // Announcement State
35
+ const [announcementText, setAnnouncementText] = useState('');
36
+ const [durationValue, setDurationValue] = useState(24);
37
+ const [durationUnit, setDurationUnit] = useState<'seconds' | 'minutes' | 'hours' | 'days'>('hours');
38
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
39
+
40
+ // Reset state when modal opens
41
+ useEffect(() => {
42
+ if (isOpen) {
43
+ // API Key init
44
+ const userKey = getUserApiKey();
45
+ if (userKey) {
46
+ setApiKey(userKey);
47
+ setHasUserApiKey(true);
48
+ } else {
49
+ setApiKey('');
50
+ setHasUserApiKey(false);
51
+ }
52
+
53
+ // Admin init
54
+ setAuthError('');
55
+ setEmailInput('');
56
+ setPasswordInput('');
57
+
58
+ // Check current auth status
59
+ const user = auth.currentUser;
60
+ if (user) {
61
+ setCurrentUserEmail(user.email);
62
+ if (isAdmin) {
63
+ loadAdminEmails();
64
+ }
65
+ } else {
66
+ if (isAdmin) {
67
+ // If stored state is admin but no firebase user, logout
68
+ onAdminChange(false);
69
+ }
70
+ }
71
+ }
72
+ }, [isOpen]);
73
+
74
+ const loadAdminEmails = async () => {
75
+ const emails = await getAllowedEmails();
76
+ setAdminEmails(emails);
77
+ };
78
+
79
+ const handleSaveApiKey = () => {
80
+ if (!apiKey.trim()) {
81
+ alert('Por favor ingresa una API válida');
82
+ return;
83
+ }
84
+ saveUserApiKey(apiKey.trim());
85
+ setHasUserApiKey(true);
86
+ alert('API guardada exitosamente.');
87
+ };
88
+
89
+ const handleDeleteApiKey = () => {
90
+ if (window.confirm('¿Eliminar tu API personal?')) {
91
+ deleteUserApiKey();
92
+ setApiKey('');
93
+ setHasUserApiKey(false);
94
+ }
95
+ };
96
+
97
+ const handleGoogleLogin = async () => {
98
+ setIsLoadingAuth(true);
99
+ setAuthError('');
100
+ try {
101
+ const result = await signInWithPopup(auth, googleProvider);
102
+ const email = result.user.email;
103
+
104
+ if (!email) {
105
+ throw new Error('No se pudo obtener el email.');
106
+ }
107
+
108
+ const hasPermission = await isUserAdmin(email);
109
+
110
+ if (hasPermission) {
111
+ onAdminChange(true);
112
+ setCurrentUserEmail(email);
113
+ await loadAdminEmails();
114
+ } else {
115
+ await signOut(auth); // Logout immediately if not allowed
116
+ setAuthError('Este correo no tiene permisos de administrador.');
117
+ onAdminChange(false);
118
+ }
119
+ } catch (error: any) {
120
+ console.error('Login error:', error);
121
+ setAuthError(error.message || 'Error al iniciar sesión.');
122
+ } finally {
123
+ setIsLoadingAuth(false);
124
+ }
125
+ };
126
+
127
+ const handleEmailLogin = async () => {
128
+ if (!emailInput || !passwordInput) {
129
+ setAuthError('Por favor ingresa correo y contraseña.');
130
+ return;
131
+ }
132
+
133
+ setIsLoadingAuth(true);
134
+ setAuthError('');
135
+ try {
136
+ const result = await signInWithEmailAndPassword(auth, emailInput.trim(), passwordInput);
137
+ const email = result.user.email;
138
+
139
+ if (!email) {
140
+ throw new Error('No se pudo obtener el email.');
141
+ }
142
+
143
+ const hasPermission = await isUserAdmin(email);
144
+
145
+ if (hasPermission) {
146
+ onAdminChange(true);
147
+ setCurrentUserEmail(email);
148
+ await loadAdminEmails();
149
+ } else {
150
+ await signOut(auth); // Logout immediately if not allowed
151
+ setAuthError('Este correo no tiene permisos de administrador.');
152
+ onAdminChange(false);
153
+ }
154
+ } catch (error: any) {
155
+ console.error('Login error:', error);
156
+ if (error.code === 'auth/invalid-credential' || error.code === 'auth/user-not-found') {
157
+ setAuthError('Cuenta no encontrada o contraseña incorrecta. Si es tu primera vez, usa "Registrarse".');
158
+ } else {
159
+ setAuthError(error.message || 'Error al iniciar sesión.');
160
+ }
161
+ } finally {
162
+ setIsLoadingAuth(false);
163
+ }
164
+ };
165
+
166
+ const handleRegister = async () => {
167
+ if (!emailInput || !passwordInput) {
168
+ setAuthError('Ingresa un correo y contraseña para registrarte.');
169
+ return;
170
+ }
171
+
172
+ setIsLoadingAuth(true);
173
+ setAuthError('');
174
+ try {
175
+ // 1. Create User
176
+ const result = await createUserWithEmailAndPassword(auth, emailInput.trim(), passwordInput);
177
+ const email = result.user.email;
178
+
179
+ if (!email) throw new Error('Error al obtener email.');
180
+
181
+ // 2. Verify if Allowed
182
+ const hasPermission = await isUserAdmin(email);
183
+
184
+ if (hasPermission) {
185
+ onAdminChange(true);
186
+ setCurrentUserEmail(email);
187
+ await loadAdminEmails();
188
+ alert('Cuenta creada y verificada exitosamente.');
189
+ } else {
190
+ // If not allowed, delete/logout immediately
191
+ // (Deleting user requires re-auth usually, so we just sign out for now to block access)
192
+ await signOut(auth);
193
+ setAuthError('Cuenta creada, pero tu correo NO está autorizado como administrador.');
194
+ onAdminChange(false);
195
+ }
196
+
197
+ } catch (error: any) {
198
+ console.error('Register error:', error);
199
+ if (error.code === 'auth/email-already-in-use') {
200
+ setAuthError('Este correo ya está registrado. Intenta "Ingresar".');
201
+ } else if (error.code === 'auth/weak-password') {
202
+ setAuthError('La contraseña debe tener al menos 6 caracteres.');
203
+ } else {
204
+ setAuthError(error.message || 'Error al registrar.');
205
+ }
206
+ } finally {
207
+ setIsLoadingAuth(false);
208
+ }
209
+ };
210
+
211
+ const handleLogout = async () => {
212
+ try {
213
+ await signOut(auth);
214
+ onAdminChange(false);
215
+ setCurrentUserEmail(null);
216
+ setAdminEmails([]);
217
+ } catch (error) {
218
+ console.error('Logout error:', error);
219
+ }
220
+ };
221
+
222
+ const handleAddAdmin = async () => {
223
+ if (!newAdminEmail.trim()) return;
224
+ try {
225
+ await addAdminEmail(newAdminEmail.trim());
226
+ setNewAdminEmail('');
227
+ await loadAdminEmails();
228
+ alert('Administrador añadido correctamente.');
229
+ } catch (error: any) {
230
+ alert('Error al añadir: ' + error.message);
231
+ }
232
+ };
233
+
234
+ const handleRemoveAdmin = async (email: string) => {
235
+ if (!window.confirm(`¿Seguro que quieres eliminar a ${email}?`)) return;
236
+ try {
237
+ await removeAdminEmail(email);
238
+ await loadAdminEmails();
239
+ } catch (error: any) {
240
+ alert('Error: ' + error.message);
241
+ }
242
+ };
243
+
244
+ const handlePublishAnnouncement = async () => {
245
+ if (!announcementText.trim()) {
246
+ alert('El texto del anuncio no puede estar vacío');
247
+ return;
248
+ }
249
+
250
+ let durationMs = 0;
251
+ if (durationUnit === 'seconds') durationMs = durationValue * 1000;
252
+ if (durationUnit === 'minutes') durationMs = durationValue * 60 * 1000;
253
+ if (durationUnit === 'hours') durationMs = durationValue * 60 * 60 * 1000;
254
+ if (durationUnit === 'days') durationMs = durationValue * 24 * 60 * 60 * 1000;
255
+
256
+ try {
257
+ await saveAnnouncement(announcementText, durationMs);
258
+ alert('Anuncio publicado exitosamente');
259
+ setAnnouncementText('');
260
+ onClose();
261
+ } catch (err) {
262
+ console.error(err);
263
+ alert('Error al publicar el anuncio');
264
+ }
265
+ };
266
+
267
+ const handleDeleteAnnouncement = async () => {
268
+ try {
269
+ await saveAnnouncement('', null);
270
+ setAnnouncementText('');
271
+ setShowDeleteConfirm(false);
272
+ } catch (e) {
273
+ console.error(e);
274
+ alert('Error al eliminar');
275
+ }
276
+ };
277
+
278
+ if (!isOpen) return null;
279
+
280
+ return (
281
+ <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
282
+ <div className="bg-[#121212] rounded-2xl border border-gray-800 w-full max-w-lg shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
283
+
284
+ {/* Header */}
285
+ <div className="bg-[#1a1a1a] border-b border-gray-800 px-6 py-4 flex items-center justify-between sticky top-0 z-10">
286
+ <div className="flex items-center gap-3">
287
+ <div className="p-2 bg-[#bb86fc]/10 rounded-lg text-[#bb86fc]">
288
+ <Settings className="w-5 h-5" />
289
+ </div>
290
+ <h2 className="text-xl font-bold text-white">Ajustes</h2>
291
+ </div>
292
+ <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors p-2 hover:bg-white/5 rounded-lg">
293
+ <X className="w-5 h-5" />
294
+ </button>
295
+ </div>
296
+
297
+ <div className="p-6 space-y-8 overflow-y-auto custom-scrollbar">
298
+
299
+ {/* Admin Section */}
300
+ <section className="space-y-4">
301
+ <div className="flex items-center justify-between">
302
+ <div className="flex items-center gap-3">
303
+ <div className={`p-2 rounded-lg ${isAdmin ? 'bg-green-500/10 text-green-500' : 'bg-gray-800 text-gray-400'}`}>
304
+ {isAdmin ? <Unlock className="w-5 h-5" /> : <Lock className="w-5 h-5" />}
305
+ </div>
306
+ <div>
307
+ <h3 className="tex-sm font-semibold text-white">Modo Administrador</h3>
308
+ <p className="text-xs text-gray-400">
309
+ {isAdmin ? `Conectado como ${currentUserEmail}` : 'Requiere acceso autorizado'}
310
+ </p>
311
+ </div>
312
+ </div>
313
+
314
+ {isAdmin && (
315
+ <button
316
+ onClick={handleLogout}
317
+ className="text-gray-400 hover:text-white p-2 rounded-lg hover:bg-white/5 transition-colors"
318
+ title="Cerrar Sessión"
319
+ >
320
+ <LogOut className="w-5 h-5" />
321
+ </button>
322
+ )}
323
+ </div>
324
+
325
+ {!isAdmin ? (
326
+ <div className="bg-[#1a1a1a] p-6 rounded-xl border border-gray-800 animate-in slide-in-from-top-2 duration-200 text-center">
327
+ <p className="text-sm text-gray-400 mb-4">Inicia sesión con una cuenta autorizada.</p>
328
+
329
+ {/* Email/Password Form */}
330
+ <div className="space-y-3 mb-4">
331
+ <input
332
+ type="email"
333
+ placeholder="Correo electrónico"
334
+ value={emailInput}
335
+ onChange={(e) => setEmailInput(e.target.value)}
336
+ className="w-full bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
337
+ />
338
+ <input
339
+ type="password"
340
+ placeholder="Contraseña"
341
+ value={passwordInput}
342
+ onChange={(e) => setPasswordInput(e.target.value)}
343
+ onKeyDown={(e) => e.key === 'Enter' && handleEmailLogin()}
344
+ className="w-full bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
345
+ />
346
+ <button
347
+ onClick={handleEmailLogin}
348
+ disabled={isLoadingAuth}
349
+ className="w-full bg-[#bb86fc] text-white hover:bg-[#9966dd] py-2 rounded-lg font-semibold text-sm transition-colors disabled:opacity-70"
350
+ >
351
+ {isLoadingAuth ? 'Verificando...' : 'Ingresar'}
352
+ </button>
353
+
354
+ <button
355
+ onClick={handleRegister}
356
+ disabled={isLoadingAuth}
357
+ className="w-full bg-transparent border border-gray-600 text-gray-300 hover:border-gray-400 hover:text-white py-1.5 rounded-lg text-xs transition-colors disabled:opacity-50"
358
+ >
359
+ ¿Primera vez? Crear cuenta
360
+ </button>
361
+ </div>
362
+
363
+ <div className="flex items-center gap-2 my-4">
364
+ <div className="h-px bg-gray-800 flex-1" />
365
+ <span className="text-xs text-gray-500">O usa Google</span>
366
+ <div className="h-px bg-gray-800 flex-1" />
367
+ </div>
368
+
369
+ <button
370
+ onClick={handleGoogleLogin}
371
+ disabled={isLoadingAuth}
372
+ className="w-full bg-white text-gray-900 hover:bg-gray-100 py-2.5 rounded-lg font-semibold flex items-center justify-center gap-2 transition-colors disabled:opacity-70"
373
+ >
374
+ {isLoadingAuth ? (
375
+ <div className="w-5 h-5 border-2 border-gray-900 border-t-transparent rounded-full animate-spin"></div>
376
+ ) : (
377
+ <svg className="w-5 h-5" viewBox="0 0 24 24">
378
+ <path fill="currentColor" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
379
+ <path fill="currentColor" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
380
+ <path fill="currentColor" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.84z" />
381
+ <path fill="currentColor" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
382
+ </svg>
383
+ )}
384
+ Iniciar con Google
385
+ </button>
386
+ {authError && <p className="text-red-500 text-xs mt-3 bg-red-500/10 p-2 rounded border border-red-500/20">{authError}</p>}
387
+ </div>
388
+ ) : (
389
+ // MANAGE ADMINS SECTION (Only visible to admins)
390
+ <div className="bg-[#1a1a1a] p-4 rounded-xl border border-gray-800 space-y-4">
391
+ <h4 className="text-sm font-semibold text-white mb-2 flex items-center gap-2">
392
+ <Shield className="w-4 h-4 text-[#bb86fc]" />
393
+ Gestión de Administradores
394
+ </h4>
395
+
396
+ <div className="flex gap-2">
397
+ <input
398
+ type="email"
399
+ placeholder="nuevo_admin@gmail.com"
400
+ value={newAdminEmail}
401
+ onChange={(e) => setNewAdminEmail(e.target.value)}
402
+ className="flex-1 bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
403
+ />
404
+ <button
405
+ onClick={handleAddAdmin}
406
+ disabled={!newAdminEmail.trim()}
407
+ className="bg-[#bb86fc]/20 hover:bg-[#bb86fc]/30 text-[#bb86fc] p-2 rounded-lg transition-colors disabled:opacity-50"
408
+ >
409
+ <UserPlus className="w-5 h-5" />
410
+ </button>
411
+ </div>
412
+
413
+ <div className="space-y-2 max-h-40 overflow-y-auto pr-1 custom-scrollbar">
414
+ {adminEmails.map(email => (
415
+ <div key={email} className="flex items-center justify-between bg-black/30 p-2 rounded-lg border border-gray-800/50">
416
+ <span className="text-xs text-gray-300 truncate">{email}</span>
417
+ {/* Don't allow removing yourself or hardcoded owners (though owners are protected in service, UI feedback is nice) */}
418
+ <button
419
+ onClick={() => handleRemoveAdmin(email)}
420
+ className="text-gray-500 hover:text-red-400 p-1 hover:bg-white/5 rounded transition-colors"
421
+ title="Eliminar admin"
422
+ >
423
+ <UserMinus className="w-4 h-4" />
424
+ </button>
425
+ </div>
426
+ ))}
427
+ </div>
428
+ </div>
429
+ )}
430
+ </section>
431
+
432
+ {isAdmin && (
433
+ <section className="space-y-4 pt-4 border-t border-gray-800">
434
+ <div className="flex items-center gap-3 mb-2">
435
+ <div className="p-2 bg-red-500/10 rounded-lg text-red-500">
436
+ <Eye className="w-5 h-5" />
437
+ </div>
438
+ <div>
439
+ <h3 className="tex-sm font-semibold text-white">Gestión de Vistas</h3>
440
+ <p className="text-xs text-gray-400">Restablecer contadores de visualización</p>
441
+ </div>
442
+ </div>
443
+
444
+ <button
445
+ onClick={async () => {
446
+ if (window.confirm('¿Seguro que quieres reiniciar las vistas de TODOS los mangas a 0? Esta acción no se puede deshacer.')) {
447
+ try {
448
+ await resetAllMangaViews();
449
+ alert('Vistas reiniciadas correctamente.');
450
+ } catch (e) {
451
+ console.error(e);
452
+ alert('Error al reiniciar vistas.');
453
+ }
454
+ }
455
+ }}
456
+ className="w-full bg-red-500/10 hover:bg-red-500/20 text-red-500 py-2.5 rounded-lg font-semibold text-sm transition-all border border-red-500/20 hover:border-red-500/40"
457
+ >
458
+ Reiniciar Vistas a 0
459
+ </button>
460
+ </section>
461
+ )}
462
+
463
+ {isAdmin && (
464
+ <>
465
+ <div className="h-px bg-gray-800" />
466
+ <section className="space-y-4">
467
+ <div className="flex items-center gap-3 mb-2">
468
+ <div className="p-2 bg-purple-500/10 rounded-lg text-purple-400">
469
+ <Megaphone className="w-5 h-5" />
470
+ </div>
471
+ <div>
472
+ <h3 className="tex-sm font-semibold text-white">Publicar Anuncio</h3>
473
+ <p className="text-xs text-gray-400">Visible para todos los usuarios</p>
474
+ </div>
475
+ </div>
476
+
477
+ <div className="space-y-3">
478
+ <textarea
479
+ value={announcementText}
480
+ onChange={(e) => setAnnouncementText(e.target.value)}
481
+ placeholder="Escribe el mensaje del anuncio..."
482
+ className="w-full bg-[#1a1a1a] border border-gray-700 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#bb86fc] min-h-[100px] resize-none"
483
+ />
484
+
485
+ <div className="flex gap-3">
486
+ <div className="flex-1 bg-[#1a1a1a] border border-gray-700 rounded-lg px-3 py-2 flex items-center gap-2">
487
+ <Clock className="w-4 h-4 text-gray-400" />
488
+ <input
489
+ type="number"
490
+ min="1"
491
+ value={durationValue}
492
+ onChange={(e) => setDurationValue(Number(e.target.value))}
493
+ className="bg-transparent text-white text-sm w-full focus:outline-none"
494
+ />
495
+ </div>
496
+ <select
497
+ value={durationUnit}
498
+ onChange={(e) => setDurationUnit(e.target.value as any)}
499
+ className="bg-[#1a1a1a] border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-[#bb86fc]"
500
+ >
501
+ <option value="seconds">Segundos</option>
502
+ <option value="minutes">Minutos</option>
503
+ <option value="hours">Horas</option>
504
+ <option value="days">Días</option>
505
+ </select>
506
+ </div>
507
+
508
+ <div className="flex gap-2">
509
+ <button
510
+ onClick={() => setShowDeleteConfirm(true)}
511
+ className="px-4 py-2.5 rounded-lg font-semibold text-sm bg-red-500/10 text-red-500 border border-red-500/20 hover:bg-red-500/20 transition-colors"
512
+ title="Eliminar anuncio"
513
+ >
514
+ <Trash2 className="w-5 h-5" />
515
+ </button>
516
+ <button
517
+ onClick={handlePublishAnnouncement}
518
+ className="flex-1 bg-gradient-to-r from-[#bb86fc] to-[#9966dd] hover:from-[#9966dd] hover:to-[#7744cc] text-white py-2.5 rounded-lg font-semibold text-sm transition-all shadow-lg shadow-[#bb86fc]/20"
519
+ >
520
+ Publicar Anuncio
521
+ </button>
522
+ </div>
523
+ </div>
524
+ </section>
525
+ </>
526
+ )}
527
+
528
+ <div className="h-px bg-gray-800" />
529
+
530
+ {/* API Config Section */}
531
+ <section className="space-y-4">
532
+ <div className="flex items-center gap-3 mb-2">
533
+ <div className="p-2 bg-blue-500/10 rounded-lg text-blue-400">
534
+ <Key className="w-5 h-5" />
535
+ </div>
536
+ <div>
537
+ <h3 className="tex-sm font-semibold text-white">Configuración de API</h3>
538
+ <p className="text-xs text-gray-400">Gestiona tu clave personal de ImgBB</p>
539
+ </div>
540
+ </div>
541
+
542
+ {hasUserApiKey && (
543
+ <div className="bg-green-500/10 border border-green-500/20 rounded-lg p-3">
544
+ <p className="text-green-400 text-xs font-medium flex items-center gap-2">
545
+ <Shield className="w-3 h-3" />
546
+ API personal activa
547
+ </p>
548
+ </div>
549
+ )}
550
+
551
+ <div className="space-y-2">
552
+ <input
553
+ type="text"
554
+ placeholder="Pega tu API Key de ImgBB aquí..."
555
+ value={apiKey}
556
+ onChange={(e) => setApiKey(e.target.value)}
557
+ className="w-full bg-[#1a1a1a] border border-gray-700 rounded-lg px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#bb86fc] focus:ring-1 focus:ring-[#bb86fc] transition-all font-mono"
558
+ />
559
+ <p className="text-xs text-gray-500">
560
+ Obtén tu API key gratuitamente en <a href="https://api.imgbb.com/" target="_blank" rel="noopener noreferrer" className="text-[#bb86fc] hover:underline">api.imgbb.com</a>
561
+ </p>
562
+ </div>
563
+
564
+ <div className="flex gap-3">
565
+ {hasUserApiKey && (
566
+ <button
567
+ onClick={handleDeleteApiKey}
568
+ className="flex-1 bg-red-500/10 border border-red-500/30 hover:bg-red-500/20 text-red-500 px-4 py-2.5 rounded-lg font-medium text-sm transition-colors flex items-center justify-center gap-2"
569
+ >
570
+ <Trash2 className="w-4 h-4" />
571
+ Eliminar
572
+ </button>
573
+ )}
574
+ <button
575
+ onClick={handleSaveApiKey}
576
+ disabled={!apiKey.trim()}
577
+ className="flex-1 bg-[#1a1a1a] border border-gray-700 hover:border-[#bb86fc] hover:text-[#bb86fc] disabled:opacity-50 disabled:hover:border-gray-700 disabled:hover:text-gray-500 text-gray-300 px-4 py-2.5 rounded-lg font-medium text-sm transition-all flex items-center justify-center gap-2 group"
578
+ >
579
+ <Save className="w-4 h-4 group-hover:scale-110 transition-transform" />
580
+ Guardar Cambios
581
+ </button>
582
+ </div>
583
+ </section>
584
+ </div>
585
+
586
+ {/* Confirm Delete Overlay */}
587
+ {showDeleteConfirm && (
588
+ <div className="absolute inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 p-6 animate-in fade-in duration-200">
589
+ <div className="bg-[#1a1a1a] border border-gray-700 w-full max-w-sm rounded-xl shadow-2xl p-6 transform scale-100 animate-in zoom-in-95 duration-200">
590
+ <div className="flex flex-col items-center text-center gap-4">
591
+ <div className="p-3 bg-red-500/10 rounded-full text-red-500">
592
+ <Trash2 className="w-8 h-8" />
593
+ </div>
594
+ <div>
595
+ <h3 className="text-lg font-bold text-white mb-1">¿Eliminar anuncio?</h3>
596
+ <p className="text-sm text-gray-400">
597
+ Esta acción eliminará el anuncio actual inmediatamente. No se puede deshacer.
598
+ </p>
599
+ </div>
600
+ <div className="flex gap-3 w-full mt-2">
601
+ <button
602
+ onClick={() => setShowDeleteConfirm(false)}
603
+ className="flex-1 px-4 py-2 rounded-lg text-sm font-semibold text-gray-300 hover:bg-gray-800 transition-colors"
604
+ >
605
+ Cancelar
606
+ </button>
607
+ <button
608
+ onClick={handleDeleteAnnouncement}
609
+ className="flex-1 px-4 py-2 rounded-lg text-sm font-semibold bg-red-500 hover:bg-red-600 text-white transition-colors shadow-lg shadow-red-500/20"
610
+ >
611
+ Eliminar
612
+ </button>
613
+ </div>
614
+ </div>
615
+ </div>
616
+ </div>
617
+ )}
618
+ </div>
619
+ </div>
620
+ );
621
+ }
622
+
src/index.css CHANGED
@@ -1,215 +1,215 @@
1
- @tailwind base;
2
- @tailwind components;
3
- @tailwind utilities;
4
-
5
- @keyframes spin {
6
- from {
7
- transform: rotate(0deg);
8
- }
9
- to {
10
- transform: rotate(360deg);
11
- }
12
- }
13
-
14
- .animate-spin {
15
- animation: spin 1s linear infinite;
16
- }
17
-
18
- @keyframes fadeIn {
19
- from {
20
- opacity: 0;
21
- transform: scale(0.95);
22
- }
23
- to {
24
- opacity: 1;
25
- transform: scale(1);
26
- }
27
- }
28
-
29
- @keyframes fadeOut {
30
- from {
31
- opacity: 1;
32
- }
33
- to {
34
- opacity: 0;
35
- }
36
- }
37
-
38
- @keyframes fadeInUp {
39
- from {
40
- opacity: 0;
41
- transform: translateY(20px);
42
- }
43
- to {
44
- opacity: 1;
45
- transform: translateY(0);
46
- }
47
- }
48
-
49
- @keyframes quickFadeIn {
50
- from {
51
- opacity: 0;
52
- transform: scale(0.98);
53
- }
54
- to {
55
- opacity: 1;
56
- transform: scale(1);
57
- }
58
- }
59
-
60
- .animate-quick-fade-in {
61
- animation: quickFadeIn 0.15s ease-out forwards;
62
- }
63
-
64
- @keyframes smoothFadeIn {
65
- 0% {
66
- opacity: 0;
67
- transform: scale(0.98);
68
- }
69
- 50% {
70
- opacity: 0.5;
71
- }
72
- 100% {
73
- opacity: 1;
74
- transform: scale(1);
75
- }
76
- }
77
-
78
- .animate-smooth-fade-in {
79
- animation: smoothFadeIn 1.2s ease-out forwards;
80
- }
81
-
82
- .masonry-container {
83
- column-count: 2;
84
- column-gap: 4px;
85
- }
86
-
87
- @media (min-width: 640px) {
88
- .masonry-container {
89
- column-count: 3;
90
- }
91
- }
92
-
93
- @media (min-width: 768px) {
94
- .masonry-container {
95
- column-count: 4;
96
- }
97
- }
98
-
99
- @media (min-width: 1024px) {
100
- .masonry-container {
101
- column-count: 5;
102
- }
103
- }
104
-
105
- @media (min-width: 1280px) {
106
- .masonry-container {
107
- column-count: 6;
108
- }
109
- }
110
-
111
- @keyframes shimmer {
112
- 0% {
113
- background-position: -1000px 0;
114
- }
115
- 100% {
116
- background-position: 1000px 0;
117
- }
118
- }
119
-
120
- .animate-shimmer {
121
- animation: shimmer 2.5s infinite;
122
- }
123
-
124
- .masonry-item {
125
- break-inside: avoid;
126
- margin-bottom: 4px;
127
- display: inline-block;
128
- width: 100%;
129
- }
130
-
131
- @keyframes slideInUp {
132
- from {
133
- opacity: 0;
134
- transform: translateY(20px);
135
- }
136
- to {
137
- opacity: 1;
138
- transform: translateY(0);
139
- }
140
- }
141
-
142
- @keyframes slideInDown {
143
- from {
144
- opacity: 0;
145
- transform: translateY(-20px);
146
- }
147
- to {
148
- opacity: 1;
149
- transform: translateY(0);
150
- }
151
- }
152
-
153
- @keyframes slideInLeft {
154
- from {
155
- opacity: 0;
156
- transform: translateX(-20px);
157
- }
158
- to {
159
- opacity: 1;
160
- transform: translateX(0);
161
- }
162
- }
163
-
164
- @keyframes slideInRight {
165
- from {
166
- opacity: 0;
167
- transform: translateX(20px);
168
- }
169
- to {
170
- opacity: 1;
171
- transform: translateX(0);
172
- }
173
- }
174
-
175
- @keyframes glow {
176
- 0%, 100% {
177
- box-shadow: 0 0 5px rgba(139, 92, 246, 0.1);
178
- }
179
- 50% {
180
- box-shadow: 0 0 20px rgba(139, 92, 246, 0.3);
181
- }
182
- }
183
-
184
- @keyframes pulse-color {
185
- 0%, 100% {
186
- color: currentColor;
187
- }
188
- 50% {
189
- color: rgba(139, 92, 246, 0.6);
190
- }
191
- }
192
-
193
- .animate-slide-in-up {
194
- animation: slideInUp 0.5s ease-out forwards;
195
- }
196
-
197
- .animate-slide-in-down {
198
- animation: slideInDown 0.5s ease-out forwards;
199
- }
200
-
201
- .animate-slide-in-left {
202
- animation: slideInLeft 0.5s ease-out forwards;
203
- }
204
-
205
- .animate-slide-in-right {
206
- animation: slideInRight 0.5s ease-out forwards;
207
- }
208
-
209
- .animate-glow {
210
- animation: glow 2s ease-in-out infinite;
211
- }
212
-
213
- .animate-pulse-color {
214
- animation: pulse-color 2s ease-in-out infinite;
215
- }
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ @keyframes spin {
6
+ from {
7
+ transform: rotate(0deg);
8
+ }
9
+ to {
10
+ transform: rotate(360deg);
11
+ }
12
+ }
13
+
14
+ .animate-spin {
15
+ animation: spin 1s linear infinite;
16
+ }
17
+
18
+ @keyframes fadeIn {
19
+ from {
20
+ opacity: 0;
21
+ transform: scale(0.95);
22
+ }
23
+ to {
24
+ opacity: 1;
25
+ transform: scale(1);
26
+ }
27
+ }
28
+
29
+ @keyframes fadeOut {
30
+ from {
31
+ opacity: 1;
32
+ }
33
+ to {
34
+ opacity: 0;
35
+ }
36
+ }
37
+
38
+ @keyframes fadeInUp {
39
+ from {
40
+ opacity: 0;
41
+ transform: translateY(20px);
42
+ }
43
+ to {
44
+ opacity: 1;
45
+ transform: translateY(0);
46
+ }
47
+ }
48
+
49
+ @keyframes quickFadeIn {
50
+ from {
51
+ opacity: 0;
52
+ transform: scale(0.98);
53
+ }
54
+ to {
55
+ opacity: 1;
56
+ transform: scale(1);
57
+ }
58
+ }
59
+
60
+ .animate-quick-fade-in {
61
+ animation: quickFadeIn 0.15s ease-out forwards;
62
+ }
63
+
64
+ @keyframes smoothFadeIn {
65
+ 0% {
66
+ opacity: 0;
67
+ transform: scale(0.98);
68
+ }
69
+ 50% {
70
+ opacity: 0.5;
71
+ }
72
+ 100% {
73
+ opacity: 1;
74
+ transform: scale(1);
75
+ }
76
+ }
77
+
78
+ .animate-smooth-fade-in {
79
+ animation: smoothFadeIn 1.2s ease-out forwards;
80
+ }
81
+
82
+ .masonry-container {
83
+ column-count: 2;
84
+ column-gap: 4px;
85
+ }
86
+
87
+ @media (min-width: 640px) {
88
+ .masonry-container {
89
+ column-count: 3;
90
+ }
91
+ }
92
+
93
+ @media (min-width: 768px) {
94
+ .masonry-container {
95
+ column-count: 4;
96
+ }
97
+ }
98
+
99
+ @media (min-width: 1024px) {
100
+ .masonry-container {
101
+ column-count: 5;
102
+ }
103
+ }
104
+
105
+ @media (min-width: 1280px) {
106
+ .masonry-container {
107
+ column-count: 6;
108
+ }
109
+ }
110
+
111
+ @keyframes shimmer {
112
+ 0% {
113
+ background-position: -1000px 0;
114
+ }
115
+ 100% {
116
+ background-position: 1000px 0;
117
+ }
118
+ }
119
+
120
+ .animate-shimmer {
121
+ animation: shimmer 2.5s infinite;
122
+ }
123
+
124
+ .masonry-item {
125
+ break-inside: avoid;
126
+ margin-bottom: 4px;
127
+ display: inline-block;
128
+ width: 100%;
129
+ }
130
+
131
+ @keyframes slideInUp {
132
+ from {
133
+ opacity: 0;
134
+ transform: translateY(20px);
135
+ }
136
+ to {
137
+ opacity: 1;
138
+ transform: translateY(0);
139
+ }
140
+ }
141
+
142
+ @keyframes slideInDown {
143
+ from {
144
+ opacity: 0;
145
+ transform: translateY(-20px);
146
+ }
147
+ to {
148
+ opacity: 1;
149
+ transform: translateY(0);
150
+ }
151
+ }
152
+
153
+ @keyframes slideInLeft {
154
+ from {
155
+ opacity: 0;
156
+ transform: translateX(-20px);
157
+ }
158
+ to {
159
+ opacity: 1;
160
+ transform: translateX(0);
161
+ }
162
+ }
163
+
164
+ @keyframes slideInRight {
165
+ from {
166
+ opacity: 0;
167
+ transform: translateX(20px);
168
+ }
169
+ to {
170
+ opacity: 1;
171
+ transform: translateX(0);
172
+ }
173
+ }
174
+
175
+ @keyframes glow {
176
+ 0%, 100% {
177
+ box-shadow: 0 0 5px rgba(139, 92, 246, 0.1);
178
+ }
179
+ 50% {
180
+ box-shadow: 0 0 20px rgba(139, 92, 246, 0.3);
181
+ }
182
+ }
183
+
184
+ @keyframes pulse-color {
185
+ 0%, 100% {
186
+ color: currentColor;
187
+ }
188
+ 50% {
189
+ color: rgba(139, 92, 246, 0.6);
190
+ }
191
+ }
192
+
193
+ .animate-slide-in-up {
194
+ animation: slideInUp 0.5s ease-out forwards;
195
+ }
196
+
197
+ .animate-slide-in-down {
198
+ animation: slideInDown 0.5s ease-out forwards;
199
+ }
200
+
201
+ .animate-slide-in-left {
202
+ animation: slideInLeft 0.5s ease-out forwards;
203
+ }
204
+
205
+ .animate-slide-in-right {
206
+ animation: slideInRight 0.5s ease-out forwards;
207
+ }
208
+
209
+ .animate-glow {
210
+ animation: glow 2s ease-in-out infinite;
211
+ }
212
+
213
+ .animate-pulse-color {
214
+ animation: pulse-color 2s ease-in-out infinite;
215
+ }
src/lib/firebase.ts CHANGED
@@ -1,21 +1,21 @@
1
- import { initializeApp } from 'firebase/app';
2
- import { getFirestore } from 'firebase/firestore';
3
- import { getStorage } from 'firebase/storage';
4
-
5
- const firebaseConfig = {
6
- apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
7
- authDomain: "twistedbrody-9d163.firebaseapp.com",
8
- projectId: "twistedbrody-9d163",
9
- storageBucket: "twistedbrody-9d163.firebasestorage.app",
10
- messagingSenderId: "733213514129",
11
- appId: "1:733213514129:web:e9694684f5c3994ed06230",
12
- measurementId: "G-N8TQ7MY42W"
13
- };
14
-
15
- import { getAuth, GoogleAuthProvider } from 'firebase/auth';
16
-
17
- const app = initializeApp(firebaseConfig);
18
- export const db = getFirestore(app);
19
- export const storage = getStorage(app);
20
- export const auth = getAuth(app);
21
- export const googleProvider = new GoogleAuthProvider();
 
1
+ import { initializeApp } from 'firebase/app';
2
+ import { getFirestore } from 'firebase/firestore';
3
+ import { getStorage } from 'firebase/storage';
4
+
5
+ const firebaseConfig = {
6
+ apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
7
+ authDomain: "twistedbrody-9d163.firebaseapp.com",
8
+ projectId: "twistedbrody-9d163",
9
+ storageBucket: "twistedbrody-9d163.firebasestorage.app",
10
+ messagingSenderId: "733213514129",
11
+ appId: "1:733213514129:web:e9694684f5c3994ed06230",
12
+ measurementId: "G-N8TQ7MY42W"
13
+ };
14
+
15
+ import { getAuth, GoogleAuthProvider } from 'firebase/auth';
16
+
17
+ const app = initializeApp(firebaseConfig);
18
+ export const db = getFirestore(app);
19
+ export const storage = getStorage(app);
20
+ export const auth = getAuth(app);
21
+ export const googleProvider = new GoogleAuthProvider();
src/main.tsx CHANGED
@@ -1,10 +1,10 @@
1
- import { StrictMode } from 'react';
2
- import { createRoot } from 'react-dom/client';
3
- import App from './App.tsx';
4
- import './index.css';
5
-
6
- createRoot(document.getElementById('root')!).render(
7
- <StrictMode>
8
- <App />
9
- </StrictMode>
10
- );
 
1
+ import { StrictMode } from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+ import App from './App.tsx';
4
+ import './index.css';
5
+
6
+ createRoot(document.getElementById('root')!).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>
10
+ );
src/services/admin.ts CHANGED
@@ -1,84 +1,84 @@
1
- import { db } from '../lib/firebase';
2
- import { doc, getDoc, setDoc, updateDoc, arrayUnion, arrayRemove } from 'firebase/firestore';
3
-
4
- const ADMIN_SETTINGS_ID = 'general';
5
- const ADMIN_COLLECTION = 'admin_settings';
6
-
7
- // Initial hardcoded owners
8
- const OWNERS = [
9
- 'gonzalosalvadorloyolahuarauya@gmail.com',
10
- 'loyolahuarauyagonzalosalvador@gmail.com',
11
- 'brody.loyola@gmail.com'
12
- ];
13
-
14
- export interface AdminSettings {
15
- allowed_emails: string[];
16
- }
17
-
18
- export async function isUserAdmin(email: string): Promise<boolean> {
19
- if (!email) return false;
20
-
21
- // Check if owner
22
- if (OWNERS.includes(email)) return true;
23
-
24
- try {
25
- const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
26
- const docSnap = await getDoc(docRef);
27
-
28
- if (docSnap.exists()) {
29
- const data = docSnap.data() as AdminSettings;
30
- return data.allowed_emails.includes(email);
31
- }
32
- return false;
33
- } catch (error) {
34
- console.error('Error checking admin status:', error);
35
- return false;
36
- }
37
- }
38
-
39
- export async function getAllowedEmails(): Promise<string[]> {
40
- try {
41
- const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
42
- const docSnap = await getDoc(docRef);
43
-
44
- if (docSnap.exists()) {
45
- const data = docSnap.data() as AdminSettings;
46
- // Combine owners and allowed emails, removing duplicates
47
- return Array.from(new Set([...OWNERS, ...data.allowed_emails]));
48
- }
49
- return [...OWNERS];
50
- } catch (error) {
51
- console.error('Error getting allowed emails:', error);
52
- return [...OWNERS];
53
- }
54
- }
55
-
56
- export async function addAdminEmail(email: string): Promise<void> {
57
- const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
58
-
59
- try {
60
- await updateDoc(docRef, {
61
- allowed_emails: arrayUnion(email)
62
- });
63
- } catch (error: any) {
64
- // If document doesn't exist, create it
65
- if (error.code === 'not-found' || error.message.includes('No document to update')) {
66
- await setDoc(docRef, {
67
- allowed_emails: [email]
68
- });
69
- } else {
70
- throw error;
71
- }
72
- }
73
- }
74
-
75
- export async function removeAdminEmail(email: string): Promise<void> {
76
- if (OWNERS.includes(email)) {
77
- throw new Error('No puedes eliminar a un propietario.');
78
- }
79
-
80
- const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
81
- await updateDoc(docRef, {
82
- allowed_emails: arrayRemove(email)
83
- });
84
- }
 
1
+ import { db } from '../lib/firebase';
2
+ import { doc, getDoc, setDoc, updateDoc, arrayUnion, arrayRemove } from 'firebase/firestore';
3
+
4
+ const ADMIN_SETTINGS_ID = 'general';
5
+ const ADMIN_COLLECTION = 'admin_settings';
6
+
7
+ // Initial hardcoded owners
8
+ const OWNERS = [
9
+ 'gonzalosalvadorloyolahuarauya@gmail.com',
10
+ 'loyolahuarauyagonzalosalvador@gmail.com',
11
+ 'brody.loyola@gmail.com'
12
+ ];
13
+
14
+ export interface AdminSettings {
15
+ allowed_emails: string[];
16
+ }
17
+
18
+ export async function isUserAdmin(email: string): Promise<boolean> {
19
+ if (!email) return false;
20
+
21
+ // Check if owner
22
+ if (OWNERS.includes(email)) return true;
23
+
24
+ try {
25
+ const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
26
+ const docSnap = await getDoc(docRef);
27
+
28
+ if (docSnap.exists()) {
29
+ const data = docSnap.data() as AdminSettings;
30
+ return data.allowed_emails.includes(email);
31
+ }
32
+ return false;
33
+ } catch (error) {
34
+ console.error('Error checking admin status:', error);
35
+ return false;
36
+ }
37
+ }
38
+
39
+ export async function getAllowedEmails(): Promise<string[]> {
40
+ try {
41
+ const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
42
+ const docSnap = await getDoc(docRef);
43
+
44
+ if (docSnap.exists()) {
45
+ const data = docSnap.data() as AdminSettings;
46
+ // Combine owners and allowed emails, removing duplicates
47
+ return Array.from(new Set([...OWNERS, ...data.allowed_emails]));
48
+ }
49
+ return [...OWNERS];
50
+ } catch (error) {
51
+ console.error('Error getting allowed emails:', error);
52
+ return [...OWNERS];
53
+ }
54
+ }
55
+
56
+ export async function addAdminEmail(email: string): Promise<void> {
57
+ const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
58
+
59
+ try {
60
+ await updateDoc(docRef, {
61
+ allowed_emails: arrayUnion(email)
62
+ });
63
+ } catch (error: any) {
64
+ // If document doesn't exist, create it
65
+ if (error.code === 'not-found' || error.message.includes('No document to update')) {
66
+ await setDoc(docRef, {
67
+ allowed_emails: [email]
68
+ });
69
+ } else {
70
+ throw error;
71
+ }
72
+ }
73
+ }
74
+
75
+ export async function removeAdminEmail(email: string): Promise<void> {
76
+ if (OWNERS.includes(email)) {
77
+ throw new Error('No puedes eliminar a un propietario.');
78
+ }
79
+
80
+ const docRef = doc(db, ADMIN_COLLECTION, ADMIN_SETTINGS_ID);
81
+ await updateDoc(docRef, {
82
+ allowed_emails: arrayRemove(email)
83
+ });
84
+ }
src/services/announcement.ts CHANGED
@@ -1,49 +1,49 @@
1
- import { db } from '../lib/firebase';
2
- import { doc, getDoc, setDoc, onSnapshot } from 'firebase/firestore';
3
-
4
- const SETTINGS_COLLECTION = 'settings';
5
- const ANNOUNCEMENT_DOC = 'announcement';
6
-
7
- export interface AnnouncementData {
8
- text: string;
9
- updatedAt: string;
10
- expiresAt: string | null;
11
- }
12
-
13
- export async function getAnnouncement(): Promise<AnnouncementData | null> {
14
- const docRef = doc(db, SETTINGS_COLLECTION, ANNOUNCEMENT_DOC);
15
- const docSnap = await getDoc(docRef);
16
-
17
- if (docSnap.exists()) {
18
- return docSnap.data() as AnnouncementData;
19
- }
20
- return null;
21
- }
22
-
23
- export async function saveAnnouncement(text: string, durationMs: number | null): Promise<void> {
24
- const docRef = doc(db, SETTINGS_COLLECTION, ANNOUNCEMENT_DOC);
25
- const now = new Date();
26
- let expiresAt: string | null = null;
27
-
28
- if (durationMs) {
29
- expiresAt = new Date(now.getTime() + durationMs).toISOString();
30
- }
31
-
32
- const data: AnnouncementData = {
33
- text,
34
- updatedAt: now.toISOString(),
35
- expiresAt
36
- };
37
- await setDoc(docRef, data);
38
- }
39
-
40
- export function subscribeToAnnouncement(callback: (data: AnnouncementData | null) => void) {
41
- const docRef = doc(db, SETTINGS_COLLECTION, ANNOUNCEMENT_DOC);
42
- return onSnapshot(docRef, (doc) => {
43
- if (doc.exists()) {
44
- callback(doc.data() as AnnouncementData);
45
- } else {
46
- callback(null);
47
- }
48
- });
49
- }
 
1
+ import { db } from '../lib/firebase';
2
+ import { doc, getDoc, setDoc, onSnapshot } from 'firebase/firestore';
3
+
4
+ const SETTINGS_COLLECTION = 'settings';
5
+ const ANNOUNCEMENT_DOC = 'announcement';
6
+
7
+ export interface AnnouncementData {
8
+ text: string;
9
+ updatedAt: string;
10
+ expiresAt: string | null;
11
+ }
12
+
13
+ export async function getAnnouncement(): Promise<AnnouncementData | null> {
14
+ const docRef = doc(db, SETTINGS_COLLECTION, ANNOUNCEMENT_DOC);
15
+ const docSnap = await getDoc(docRef);
16
+
17
+ if (docSnap.exists()) {
18
+ return docSnap.data() as AnnouncementData;
19
+ }
20
+ return null;
21
+ }
22
+
23
+ export async function saveAnnouncement(text: string, durationMs: number | null): Promise<void> {
24
+ const docRef = doc(db, SETTINGS_COLLECTION, ANNOUNCEMENT_DOC);
25
+ const now = new Date();
26
+ let expiresAt: string | null = null;
27
+
28
+ if (durationMs) {
29
+ expiresAt = new Date(now.getTime() + durationMs).toISOString();
30
+ }
31
+
32
+ const data: AnnouncementData = {
33
+ text,
34
+ updatedAt: now.toISOString(),
35
+ expiresAt
36
+ };
37
+ await setDoc(docRef, data);
38
+ }
39
+
40
+ export function subscribeToAnnouncement(callback: (data: AnnouncementData | null) => void) {
41
+ const docRef = doc(db, SETTINGS_COLLECTION, ANNOUNCEMENT_DOC);
42
+ return onSnapshot(docRef, (doc) => {
43
+ if (doc.exists()) {
44
+ callback(doc.data() as AnnouncementData);
45
+ } else {
46
+ callback(null);
47
+ }
48
+ });
49
+ }
src/services/imgbb.ts CHANGED
@@ -1,105 +1,105 @@
1
- import { getUserApiKey } from '../utils/apiKeyManager';
2
- import { getBatchSize } from '../utils/batchSizeManager';
3
-
4
- const IMGBB_API_KEY = '90ba8efe6890e9e76175089dc182a22a';
5
- const IMGBB_UPLOAD_URL = 'https://api.imgbb.com/1/upload';
6
-
7
- export interface ImgBBResponse {
8
- success: boolean;
9
- data: {
10
- url: string;
11
- display_url: string;
12
- thumb: {
13
- url: string;
14
- };
15
- };
16
- }
17
-
18
- function getActiveApiKey(): string {
19
- const userApiKey = getUserApiKey();
20
- return userApiKey || IMGBB_API_KEY;
21
- }
22
-
23
- export async function uploadToImgBB(base64Image: string, name?: string): Promise<ImgBBResponse> {
24
- const base64Data = base64Image.includes(',')
25
- ? base64Image.split(',')[1]
26
- : base64Image;
27
-
28
- const apiKey = getActiveApiKey();
29
- const url = `${IMGBB_UPLOAD_URL}?key=${apiKey}`;
30
-
31
- const formData = new FormData();
32
- formData.append('image', base64Data);
33
-
34
- if (name) {
35
- formData.append('name', name);
36
- }
37
-
38
- const response = await fetch(url, {
39
- method: 'POST',
40
- body: formData,
41
- });
42
-
43
- if (!response.ok) {
44
- const errorText = await response.text();
45
-
46
- if (response.status === 429 || errorText.includes('rate limit')) {
47
- throw new Error('API_BURNED');
48
- }
49
-
50
- if (response.status === 403 || response.status === 401) {
51
- throw new Error('API_INVALID_KEY');
52
- }
53
-
54
- throw new Error(`Error al subir imagen a ImgBB: ${errorText}`);
55
- }
56
-
57
- const data = await response.json();
58
-
59
- if (!data.success) {
60
- throw new Error('API_BURNED');
61
- }
62
-
63
- return data;
64
- }
65
-
66
- export async function uploadMultipleToImgBB(
67
- base64Images: string[],
68
- namePrefix?: string,
69
- onProgress?: (current: number, total: number) => void
70
- ): Promise<ImgBBResponse[]> {
71
- const BATCH_SIZE = getBatchSize();
72
- const results: ImgBBResponse[] = [];
73
-
74
- if (BATCH_SIZE === 0 || BATCH_SIZE >= base64Images.length) {
75
- const uploadPromises = base64Images.map((image, index) => {
76
- const name = namePrefix ? `${namePrefix}_${index + 1}` : undefined;
77
- return uploadToImgBB(image, name);
78
- });
79
-
80
- const allResults = await Promise.all(uploadPromises);
81
- results.push(...allResults);
82
-
83
- if (onProgress) {
84
- onProgress(base64Images.length, base64Images.length);
85
- }
86
- } else {
87
- for (let i = 0; i < base64Images.length; i += BATCH_SIZE) {
88
- const batch = base64Images.slice(i, i + BATCH_SIZE);
89
- const uploadPromises = batch.map((image, batchIndex) => {
90
- const globalIndex = i + batchIndex;
91
- const name = namePrefix ? `${namePrefix}_${globalIndex + 1}` : undefined;
92
- return uploadToImgBB(image, name);
93
- });
94
-
95
- const batchResults = await Promise.all(uploadPromises);
96
- results.push(...batchResults);
97
-
98
- if (onProgress) {
99
- onProgress(Math.min(i + BATCH_SIZE, base64Images.length), base64Images.length);
100
- }
101
- }
102
- }
103
-
104
- return results;
105
- }
 
1
+ import { getUserApiKey } from '../utils/apiKeyManager';
2
+ import { getBatchSize } from '../utils/batchSizeManager';
3
+
4
+ const IMGBB_API_KEY = '90ba8efe6890e9e76175089dc182a22a';
5
+ const IMGBB_UPLOAD_URL = 'https://api.imgbb.com/1/upload';
6
+
7
+ export interface ImgBBResponse {
8
+ success: boolean;
9
+ data: {
10
+ url: string;
11
+ display_url: string;
12
+ thumb: {
13
+ url: string;
14
+ };
15
+ };
16
+ }
17
+
18
+ function getActiveApiKey(): string {
19
+ const userApiKey = getUserApiKey();
20
+ return userApiKey || IMGBB_API_KEY;
21
+ }
22
+
23
+ export async function uploadToImgBB(base64Image: string, name?: string): Promise<ImgBBResponse> {
24
+ const base64Data = base64Image.includes(',')
25
+ ? base64Image.split(',')[1]
26
+ : base64Image;
27
+
28
+ const apiKey = getActiveApiKey();
29
+ const url = `${IMGBB_UPLOAD_URL}?key=${apiKey}`;
30
+
31
+ const formData = new FormData();
32
+ formData.append('image', base64Data);
33
+
34
+ if (name) {
35
+ formData.append('name', name);
36
+ }
37
+
38
+ const response = await fetch(url, {
39
+ method: 'POST',
40
+ body: formData,
41
+ });
42
+
43
+ if (!response.ok) {
44
+ const errorText = await response.text();
45
+
46
+ if (response.status === 429 || errorText.includes('rate limit')) {
47
+ throw new Error('API_BURNED');
48
+ }
49
+
50
+ if (response.status === 403 || response.status === 401) {
51
+ throw new Error('API_INVALID_KEY');
52
+ }
53
+
54
+ throw new Error(`Error al subir imagen a ImgBB: ${errorText}`);
55
+ }
56
+
57
+ const data = await response.json();
58
+
59
+ if (!data.success) {
60
+ throw new Error('API_BURNED');
61
+ }
62
+
63
+ return data;
64
+ }
65
+
66
+ export async function uploadMultipleToImgBB(
67
+ base64Images: string[],
68
+ namePrefix?: string,
69
+ onProgress?: (current: number, total: number) => void
70
+ ): Promise<ImgBBResponse[]> {
71
+ const BATCH_SIZE = getBatchSize();
72
+ const results: ImgBBResponse[] = [];
73
+
74
+ if (BATCH_SIZE === 0 || BATCH_SIZE >= base64Images.length) {
75
+ const uploadPromises = base64Images.map((image, index) => {
76
+ const name = namePrefix ? `${namePrefix}_${index + 1}` : undefined;
77
+ return uploadToImgBB(image, name);
78
+ });
79
+
80
+ const allResults = await Promise.all(uploadPromises);
81
+ results.push(...allResults);
82
+
83
+ if (onProgress) {
84
+ onProgress(base64Images.length, base64Images.length);
85
+ }
86
+ } else {
87
+ for (let i = 0; i < base64Images.length; i += BATCH_SIZE) {
88
+ const batch = base64Images.slice(i, i + BATCH_SIZE);
89
+ const uploadPromises = batch.map((image, batchIndex) => {
90
+ const globalIndex = i + batchIndex;
91
+ const name = namePrefix ? `${namePrefix}_${globalIndex + 1}` : undefined;
92
+ return uploadToImgBB(image, name);
93
+ });
94
+
95
+ const batchResults = await Promise.all(uploadPromises);
96
+ results.push(...batchResults);
97
+
98
+ if (onProgress) {
99
+ onProgress(Math.min(i + BATCH_SIZE, base64Images.length), base64Images.length);
100
+ }
101
+ }
102
+ }
103
+
104
+ return results;
105
+ }
src/services/info.ts CHANGED
@@ -1,76 +1,76 @@
1
- import { db } from '../lib/firebase';
2
- import { doc, getDoc, setDoc, onSnapshot } from 'firebase/firestore';
3
-
4
- const SETTINGS_COLLECTION = 'settings';
5
- const INFO_DOC = 'info';
6
-
7
- export interface InfoData {
8
- content: string;
9
- updatedAt: string;
10
- }
11
-
12
- const DEFAULT_CONTENT = `# Bienvenid@ a Twisted Brody MangaFlow
13
- ¡Tu plataforma definitiva para la gestión y lectura de mangas!
14
-
15
- Este proyecto nació con la misión de ofrecer una experiencia de lectura fluida, moderna y sin interrupciones, diseñada por fans para fans.
16
-
17
- ## 🌟 Características Principales
18
-
19
- * **⚡ Lectura sin límites:** Disfruta de una interfaz optimizada, rápida y responsiva.
20
- * **📥 Descargas Flexibles:** Baja tus capítulos favoritos en formato **ZIP** o **PDF** para leer offline.
21
- * **🔄 Conversión Inteligente:** Nuestro servidor procesa las imágenes para darte la mejor calidad y compatibilidad.
22
-
23
- ## 🤝 Comunidad y Apoyo
24
-
25
- Este es un proyecto **sin fines de lucro**, desarrollado por pura pasión.
26
-
27
- Sin embargo, si valoras mi trabajo y quieres apoyarme para mantener el proyecto vivo, puedes suscribirte a mi **Patreon**. ¡Tu apoyo significa mucho!
28
-
29
- * [**💜 Apóyame en Patreon**](https://www.patreon.com/cw/Twistedbrody)
30
-
31
- ### 💡 ¿Tienes nuevas ideas?
32
- ¡Quiero escucharlas! Si tienes sugerencias, feedback o ideas locas, háblame directamente:
33
-
34
- * **Telegram:** [@twistedbrodyoficial](https://t.me/twistedbrodyoficial)
35
-
36
- También puedes unirte a nuestros canales:
37
- * [Canal Principal](https://t.me/twistedbrody)
38
- * [Canal Hub](https://t.me/+CmmZFHM9hpViYzMx)
39
- * [X (Twitter)](https://x.com/TwistedBrody)
40
-
41
- ---
42
- > **Disclaimer:** Todo el contenido es propiedad de sus respectivos autores. Apoya el material original siempre que sea posible.
43
-
44
-
45
- `;
46
-
47
-
48
- export async function getInfo(): Promise<InfoData | null> {
49
- const docRef = doc(db, SETTINGS_COLLECTION, INFO_DOC);
50
- const docSnap = await getDoc(docRef);
51
-
52
- if (docSnap.exists()) {
53
- return docSnap.data() as InfoData;
54
- }
55
- return null;
56
- }
57
-
58
- export async function saveInfo(content: string): Promise<void> {
59
- const docRef = doc(db, SETTINGS_COLLECTION, INFO_DOC);
60
- const data: InfoData = {
61
- content,
62
- updatedAt: new Date().toISOString()
63
- };
64
- await setDoc(docRef, data);
65
- }
66
-
67
- export function subscribeToInfo(callback: (data: InfoData | null) => void) {
68
- const docRef = doc(db, SETTINGS_COLLECTION, INFO_DOC);
69
- return onSnapshot(docRef, (doc) => {
70
- if (doc.exists()) {
71
- callback(doc.data() as InfoData);
72
- } else {
73
- callback({ content: DEFAULT_CONTENT, updatedAt: new Date().toISOString() });
74
- }
75
- });
76
- }
 
1
+ import { db } from '../lib/firebase';
2
+ import { doc, getDoc, setDoc, onSnapshot } from 'firebase/firestore';
3
+
4
+ const SETTINGS_COLLECTION = 'settings';
5
+ const INFO_DOC = 'info';
6
+
7
+ export interface InfoData {
8
+ content: string;
9
+ updatedAt: string;
10
+ }
11
+
12
+ const DEFAULT_CONTENT = `# Bienvenid@ a Twisted Brody MangaFlow
13
+ ¡Tu plataforma definitiva para la gestión y lectura de mangas!
14
+
15
+ Este proyecto nació con la misión de ofrecer una experiencia de lectura fluida, moderna y sin interrupciones, diseñada por fans para fans.
16
+
17
+ ## 🌟 Características Principales
18
+
19
+ * **⚡ Lectura sin límites:** Disfruta de una interfaz optimizada, rápida y responsiva.
20
+ * **📥 Descargas Flexibles:** Baja tus capítulos favoritos en formato **ZIP** o **PDF** para leer offline.
21
+ * **🔄 Conversión Inteligente:** Nuestro servidor procesa las imágenes para darte la mejor calidad y compatibilidad.
22
+
23
+ ## 🤝 Comunidad y Apoyo
24
+
25
+ Este es un proyecto **sin fines de lucro**, desarrollado por pura pasión.
26
+
27
+ Sin embargo, si valoras mi trabajo y quieres apoyarme para mantener el proyecto vivo, puedes suscribirte a mi **Patreon**. ¡Tu apoyo significa mucho!
28
+
29
+ * [**💜 Apóyame en Patreon**](https://www.patreon.com/cw/Twistedbrody)
30
+
31
+ ### 💡 ¿Tienes nuevas ideas?
32
+ ¡Quiero escucharlas! Si tienes sugerencias, feedback o ideas locas, háblame directamente:
33
+
34
+ * **Telegram:** [@twistedbrodyoficial](https://t.me/twistedbrodyoficial)
35
+
36
+ También puedes unirte a nuestros canales:
37
+ * [Canal Principal](https://t.me/twistedbrody)
38
+ * [Canal Hub](https://t.me/+CmmZFHM9hpViYzMx)
39
+ * [X (Twitter)](https://x.com/TwistedBrody)
40
+
41
+ ---
42
+ > **Disclaimer:** Todo el contenido es propiedad de sus respectivos autores. Apoya el material original siempre que sea posible.
43
+
44
+
45
+ `;
46
+
47
+
48
+ export async function getInfo(): Promise<InfoData | null> {
49
+ const docRef = doc(db, SETTINGS_COLLECTION, INFO_DOC);
50
+ const docSnap = await getDoc(docRef);
51
+
52
+ if (docSnap.exists()) {
53
+ return docSnap.data() as InfoData;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ export async function saveInfo(content: string): Promise<void> {
59
+ const docRef = doc(db, SETTINGS_COLLECTION, INFO_DOC);
60
+ const data: InfoData = {
61
+ content,
62
+ updatedAt: new Date().toISOString()
63
+ };
64
+ await setDoc(docRef, data);
65
+ }
66
+
67
+ export function subscribeToInfo(callback: (data: InfoData | null) => void) {
68
+ const docRef = doc(db, SETTINGS_COLLECTION, INFO_DOC);
69
+ return onSnapshot(docRef, (doc) => {
70
+ if (doc.exists()) {
71
+ callback(doc.data() as InfoData);
72
+ } else {
73
+ callback({ content: DEFAULT_CONTENT, updatedAt: new Date().toISOString() });
74
+ }
75
+ });
76
+ }
src/services/manga.ts CHANGED
@@ -1,731 +1,731 @@
1
- import { db } from '../lib/firebase';
2
- import {
3
- collection,
4
- getDocs,
5
- doc,
6
- getDoc,
7
- addDoc,
8
- updateDoc,
9
- deleteDoc,
10
- increment,
11
- query,
12
- orderBy,
13
- where,
14
- Timestamp,
15
- onSnapshot,
16
- Unsubscribe,
17
- } from 'firebase/firestore';
18
- import { Manga, Category, Chapter } from '../types/manga';
19
-
20
- function cleanUndefinedDeep(obj: any): any {
21
- if (obj === null || obj === undefined) {
22
- return undefined;
23
- }
24
-
25
- if (Array.isArray(obj)) {
26
- const cleaned = obj
27
- .map(item => cleanUndefinedDeep(item))
28
- .filter(item => item !== undefined && item !== null && item !== '');
29
- return cleaned.length > 0 ? cleaned : undefined;
30
- }
31
-
32
- if (typeof obj === 'object' && !(obj instanceof Timestamp)) {
33
- const cleaned: any = {};
34
- for (const key in obj) {
35
- if (obj.hasOwnProperty(key)) {
36
- const value = cleanUndefinedDeep(obj[key]);
37
- if (value !== undefined && value !== null) {
38
- cleaned[key] = value;
39
- }
40
- }
41
- }
42
- return Object.keys(cleaned).length > 0 ? cleaned : undefined;
43
- }
44
-
45
- return obj;
46
- }
47
-
48
- // Helper functions for localStorage
49
- const STORAGE_KEYS = {
50
- ALL_MANGAS: 'mangalib_all_v2',
51
- MANGA_PREFIX: 'mangalib_detail_v2_',
52
- };
53
-
54
- function getLocal<T>(key: string): T | null {
55
- try {
56
- const item = localStorage.getItem(key);
57
- return item ? JSON.parse(item) : null;
58
- } catch (error) {
59
- console.warn(`Error reading ${key} from localStorage`, error);
60
- return null;
61
- }
62
- }
63
-
64
- function saveLocal(key: string, data: any): void {
65
- try {
66
- localStorage.setItem(key, JSON.stringify(data));
67
- } catch (error) {
68
- console.warn(`Error saving ${key} to localStorage`, error);
69
- }
70
- }
71
-
72
- function removeLocal(key: string): void {
73
- try {
74
- localStorage.removeItem(key);
75
- } catch (error) {
76
- console.warn(`Error removing ${key} from localStorage`, error);
77
- }
78
- }
79
-
80
-
81
- // Cache global for all mangas
82
- let allMangasCache: Manga[] | null = null;
83
-
84
- export async function getAllMangas(): Promise<Manga[]> {
85
- // Try memory first
86
- if (allMangasCache) {
87
- return allMangasCache;
88
- }
89
-
90
- // Try localStorage
91
- const localData = getLocal<Manga[]>(STORAGE_KEYS.ALL_MANGAS);
92
- if (localData) {
93
- allMangasCache = localData;
94
- // Populate individual cache from local data too
95
- localData.forEach(m => mangaCache.set(m.id, m));
96
- return localData;
97
- }
98
-
99
- const q = query(collection(db, 'mangas'), orderBy('created_at', 'desc'));
100
- const querySnapshot = await getDocs(q);
101
-
102
- // Fetch all categories once
103
- const categoriesSnapshot = await getDocs(collection(db, 'categories'));
104
- const allCategories = categoriesSnapshot.docs.reduce((acc, doc) => {
105
- acc[doc.id] = { id: doc.id, ...doc.data() } as Category;
106
- return acc;
107
- }, {} as Record<string, Category>);
108
-
109
- const mangas = await Promise.all(
110
- querySnapshot.docs.map(async (mangaDoc) => {
111
- const mangaData = mangaDoc.data();
112
-
113
- const chaptersQuery = query(
114
- collection(db, 'chapters'),
115
- where('manga_id', '==', mangaDoc.id)
116
- );
117
- const chaptersSnapshot = await getDocs(chaptersQuery);
118
- const chapters = chaptersSnapshot.docs
119
- .map(chapterDoc => {
120
- const chapterData = chapterDoc.data();
121
- return {
122
- id: chapterDoc.id,
123
- manga_id: chapterData.manga_id,
124
- number: chapterData.number,
125
- title: chapterData.title,
126
- pages: chapterData.pages || [],
127
- page_formats: chapterData.page_formats || [],
128
- original_pages: chapterData.original_pages || [],
129
- created_at: (chapterData.created_at as Timestamp).toDate().toISOString(),
130
- updated_at: (chapterData.updated_at as Timestamp).toDate().toISOString(),
131
- } as Chapter;
132
- })
133
- .sort((a, b) => a.number - b.number);
134
-
135
- // Map category IDs to full category objects
136
- const categoryIds = (mangaData.categories as string[]) || [];
137
- const populatedCategories = categoryIds
138
- .map(id => allCategories[id])
139
- .filter(c => c !== undefined);
140
-
141
- return {
142
- id: mangaDoc.id,
143
- ...mangaData,
144
- created_at: (mangaData.created_at as Timestamp).toDate().toISOString(),
145
- updated_at: mangaData.updated_at ? (mangaData.updated_at as Timestamp).toDate().toISOString() : (mangaData.created_at as Timestamp).toDate().toISOString(),
146
- categories: populatedCategories,
147
- chapters,
148
- } as Manga;
149
- })
150
- );
151
-
152
- // Populate individual cache as well
153
- mangas.forEach(manga => {
154
- mangaCache.set(manga.id, manga);
155
- });
156
-
157
- allMangasCache = mangas;
158
- saveLocal(STORAGE_KEYS.ALL_MANGAS, mangas);
159
- return mangas;
160
- }
161
-
162
- const mangaCache = new Map<string, Manga>();
163
-
164
- export async function getMangaById(id: string): Promise<Manga | null> {
165
- // Check cache first
166
- if (mangaCache.has(id)) {
167
- return mangaCache.get(id)!;
168
- }
169
-
170
- // Try localStorage
171
- const localData = getLocal<Manga>(`${STORAGE_KEYS.MANGA_PREFIX}${id}`);
172
- if (localData) {
173
- mangaCache.set(id, localData);
174
- return localData;
175
- }
176
-
177
- const docRef = doc(db, 'mangas', id);
178
- const docSnap = await getDoc(docRef);
179
-
180
- if (!docSnap.exists()) return null;
181
-
182
- const data = docSnap.data();
183
-
184
- const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', id));
185
- const chaptersSnapshot = await getDocs(chaptersQuery);
186
- const chapters = chaptersSnapshot.docs
187
- .map(doc => {
188
- const chapterData = doc.data();
189
- return {
190
- id: doc.id,
191
- manga_id: chapterData.manga_id,
192
- number: chapterData.number,
193
- title: chapterData.title,
194
- pages: chapterData.pages || [],
195
- page_formats: chapterData.page_formats || [],
196
- original_pages: chapterData.original_pages || [],
197
- created_at: (chapterData.created_at as Timestamp).toDate().toISOString(),
198
- updated_at: (chapterData.updated_at as Timestamp).toDate().toISOString(),
199
- } as Chapter;
200
- })
201
- .sort((a, b) => a.number - b.number);
202
-
203
- const categoryIds = data.categories || [];
204
- const categories: Category[] = [];
205
-
206
- for (const categoryId of categoryIds) {
207
- const catDocRef = doc(db, 'categories', categoryId);
208
- const catDocSnap = await getDoc(catDocRef);
209
- if (catDocSnap.exists()) {
210
- categories.push({
211
- id: catDocSnap.id,
212
- ...catDocSnap.data(),
213
- created_at: catDocSnap.data().created_at?.toDate?.().toISOString() || new Date().toISOString(),
214
- } as Category);
215
- }
216
- }
217
-
218
- const mangaData = {
219
- id: docSnap.id,
220
- ...data,
221
- created_at: (data.created_at as Timestamp).toDate().toISOString(),
222
- categories,
223
- chapters,
224
- updated_at: data.updated_at ? (data.updated_at as Timestamp).toDate().toISOString() : (data.created_at as Timestamp).toDate().toISOString(),
225
- } as Manga;
226
-
227
- // Save to cache
228
- mangaCache.set(id, mangaData);
229
- saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${id}`, mangaData);
230
-
231
- return mangaData;
232
- }
233
-
234
- export function subscribeToManga(id: string, callback: (manga: Manga | null) => void): Unsubscribe {
235
- const docRef = doc(db, 'mangas', id);
236
-
237
- return onSnapshot(docRef, async (docSnap) => {
238
- if (!docSnap.exists()) {
239
- callback(null);
240
- return;
241
- }
242
-
243
- const data = docSnap.data();
244
-
245
- // We also need chapters and categories
246
- // Note: This inside a snapshot might be expensive if chapters change often,
247
- // but for views increment only the manga doc changes, so this is fine.
248
- // However, fast view updates might trigger this often.
249
-
250
- // To avoid refetching sub-collections on every view increment if not needed,
251
- // we could optimize, but for now we follow the pattern to ensure data consistency.
252
- // Actually, `getDocs` inside a snapshot callback for every view increment is bad practice (Read accumulation).
253
- // The view count is on the main doc. The chapters/categories usually don't change.
254
- // We can rely on a mix: get the cached chapters/categories or fetch them if missing.
255
- // But since the user wants real-time, let's assume fully fresh data is safer.
256
- // Or better: Use the cache for heavy stuff and update the fields from the docSnap.
257
-
258
- // Let's reuse getMangaById logic but with the new data from snapshot.
259
- // Actually, passing the snapshot data to a helper would be better.
260
- // For simplicity and preventing "infinite reads" loop if not careful:
261
-
262
- // Strategy: Just update the fields present in the manga document (like views)
263
- // and assume chapters/categories are relatively static or handled separately.
264
- // But `manga` object needs chapters/categories to render `ComicDetail`.
265
-
266
- // Let's grab the existing cache if available to fill in the gaps (chapters),
267
- // effectively only updating the 'manga' doc fields (views, title, etc).
268
-
269
- let cached = mangaCache.get(id);
270
- let chapters = cached?.chapters || [];
271
- let categories = cached?.categories || [];
272
-
273
- // If not in cache, we MUST fetch chapters/categories at least once.
274
- if (!cached) {
275
- // Fallback to fetch data once
276
- // But doing async work in snapshot callback is tricky if we want to return immediately.
277
- // We will do the fetch.
278
- const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', id));
279
- const chaptersSnapshot = await getDocs(chaptersQuery);
280
- chapters = chaptersSnapshot.docs
281
- .map(c => ({
282
- id: c.id,
283
- ...c.data(),
284
- created_at: (c.data().created_at as Timestamp).toDate().toISOString(),
285
- updated_at: (c.data().updated_at as Timestamp).toDate().toISOString(),
286
- } as any))
287
- .sort((a: any, b: any) => a.number - b.number);
288
-
289
- const categoryIds = data.categories || [];
290
- categories = []; // We would verify categories here, but skipping for brevity/perf to avoid N+1 reads loop in high frequency.
291
- // Ideally categories are embedded or we trust the component to handle.
292
- // Let's stick to the current architecture.
293
- // Fetch categories
294
- for (const catId of categoryIds) {
295
- const catDoc = await getDoc(doc(db, 'categories', catId));
296
- if (catDoc.exists()) categories.push({ id: catDoc.id, ...catDoc.data() } as any);
297
- }
298
- }
299
-
300
- const updatedManga: Manga = {
301
- id: docSnap.id,
302
- ...data,
303
- chapters,
304
- categories,
305
- created_at: (data.created_at as Timestamp).toDate().toISOString(),
306
- updated_at: data.updated_at ? (data.updated_at as Timestamp).toDate().toISOString() : (data.created_at as Timestamp).toDate().toISOString(),
307
- } as Manga;
308
-
309
- // Update cache
310
- mangaCache.set(id, updatedManga);
311
- saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${id}`, updatedManga);
312
-
313
- callback(updatedManga);
314
- });
315
- }
316
-
317
- export async function createManga(manga: {
318
- title: string;
319
- author: string;
320
- description?: string;
321
- thumbnail_url?: string;
322
- cover_url?: string;
323
- status?: string;
324
- categoryIds?: string[];
325
- }): Promise<Manga> {
326
- const now = Timestamp.now();
327
-
328
- const mangaData: any = {
329
- title: manga.title,
330
- author: manga.author,
331
- description: manga.description || '',
332
- status: manga.status || 'En curso',
333
- categories: manga.categoryIds || [],
334
- views: 0,
335
- rating: 0,
336
- created_at: now,
337
- updated_at: now,
338
- };
339
-
340
- if (manga.thumbnail_url) {
341
- mangaData.thumbnail_url = manga.thumbnail_url;
342
- }
343
-
344
- if (manga.cover_url) {
345
- mangaData.cover_url = manga.cover_url;
346
- }
347
-
348
- const docRef = await addDoc(collection(db, 'mangas'), mangaData);
349
-
350
- const nowISO = new Date().toISOString();
351
- const data: any = {
352
- id: docRef.id,
353
- title: manga.title,
354
- author: manga.author,
355
- description: manga.description || '',
356
- status: manga.status || 'En curso',
357
- categories: manga.categoryIds || [],
358
- chapters: [],
359
- views: 0,
360
- rating: 0,
361
- created_at: nowISO,
362
- updated_at: nowISO,
363
- };
364
-
365
- if (manga.thumbnail_url) {
366
- data.thumbnail_url = manga.thumbnail_url;
367
- }
368
-
369
- if (manga.cover_url) {
370
- data.cover_url = manga.cover_url;
371
- }
372
-
373
- // Invalidate global cache
374
- allMangasCache = null;
375
- removeLocal(STORAGE_KEYS.ALL_MANGAS);
376
-
377
- // Use the new data to update individual cache
378
- mangaCache.set(data.id, data as Manga);
379
- saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${data.id}`, data);
380
-
381
- return data as Manga;
382
- }
383
-
384
- export async function getAllCategories(): Promise<Category[]> {
385
- const querySnapshot = await getDocs(collection(db, 'categories'));
386
- return querySnapshot.docs.map(doc => ({
387
- id: doc.id,
388
- ...doc.data(),
389
- } as Category));
390
- }
391
-
392
- export async function createCategory(name: string): Promise<Category> {
393
- const docRef = await addDoc(collection(db, 'categories'), { name });
394
- const docSnap = await getDoc(docRef);
395
-
396
- return {
397
- id: docSnap.id,
398
- ...docSnap.data(),
399
- } as Category;
400
- }
401
-
402
- export async function deleteAllCategories(): Promise<void> {
403
- const categories = await getAllCategories();
404
-
405
- // Delete all category documents
406
- const deletePromises = categories.map(cat => deleteDoc(doc(db, 'categories', cat.id)));
407
- await Promise.all(deletePromises);
408
-
409
- // Update all mangas to remove category associations
410
- const mangas = await getAllMangas();
411
- const updatePromises = mangas.map(manga => {
412
- if (manga.categories && manga.categories.length > 0) {
413
- return updateDoc(doc(db, 'mangas', manga.id), { categories: [] });
414
- }
415
- return Promise.resolve();
416
- });
417
- await Promise.all(updatePromises);
418
- }
419
-
420
- export async function regenerateAllMangaCategories(): Promise<{ updated: number, errors: number }> {
421
- try {
422
- const mangas = await getAllMangas();
423
- const categories = await getAllCategories();
424
- let updatedCount = 0;
425
- let errorCount = 0;
426
-
427
- // Helper to get or create category
428
- const getCallback = async (name: string): Promise<string> => {
429
- const existing = categories.find(c => c.name.toLowerCase() === name.toLowerCase());
430
- if (existing) return existing.id;
431
-
432
- try {
433
- const newCat = await createCategory(name);
434
- categories.push(newCat);
435
- return newCat.id;
436
- } catch (e) {
437
- console.error(`Error creating category ${name}`, e);
438
- return '';
439
- }
440
- };
441
-
442
- const delimiters = /[|()[\]{}]/g;
443
-
444
- for (const manga of mangas) {
445
- try {
446
- const chunks: string[] = [];
447
-
448
- // Parse Title
449
- const titleParts = manga.title.split(delimiters);
450
- chunks.push(...titleParts);
451
-
452
- // Parse Author
453
- if (manga.author && manga.author !== 'Anónimo') {
454
- const authorParts = manga.author.split(/[,&]/);
455
- chunks.push(...authorParts);
456
- }
457
-
458
- // Clean up
459
- const potentialNames = chunks
460
- .map(s => s.trim())
461
- .filter(s => s.length > 1)
462
- .filter(s => !['-', '_', '.', ','].includes(s));
463
-
464
- if (potentialNames.length === 0) continue;
465
-
466
- const newCategoryIds: string[] = [];
467
-
468
- for (const name of potentialNames) {
469
- const id = await getCallback(name);
470
- if (id && !newCategoryIds.includes(id)) {
471
- newCategoryIds.push(id);
472
- }
473
- }
474
-
475
- // Update manga if categories changed (or if it had none)
476
- // Even if it has some, we might be adding new ones or replacing old bad ones if we wiped them.
477
- // The user wiped them, so currently they should be empty.
478
- if (newCategoryIds.length > 0) {
479
- await updateDoc(doc(db, 'mangas', manga.id), { categories: newCategoryIds });
480
- updatedCount++;
481
- }
482
-
483
- } catch (err) {
484
- console.error(`Error processing manga ${manga.id}`, err);
485
- errorCount++;
486
- }
487
- }
488
-
489
- return { updated: updatedCount, errors: errorCount };
490
- } catch (error) {
491
- console.error('Error in bulk regeneration:', error);
492
- throw error;
493
- }
494
- }
495
-
496
- export async function createChapter(chapter: {
497
- manga_id: string;
498
- number: number;
499
- title: string;
500
- pages: string[];
501
- page_formats?: string[];
502
- original_pages?: string[];
503
- }): Promise<Chapter> {
504
- const now = Timestamp.now();
505
- const docRef = await addDoc(collection(db, 'chapters'), {
506
- manga_id: chapter.manga_id,
507
- number: chapter.number,
508
- title: chapter.title,
509
- pages: chapter.pages,
510
- page_formats: chapter.page_formats || [],
511
- original_pages: chapter.original_pages || [],
512
- created_at: now,
513
- updated_at: now,
514
- });
515
-
516
- const docSnap = await getDoc(docRef);
517
- const data = docSnap.data();
518
-
519
- return {
520
- id: docSnap.id,
521
- manga_id: data!.manga_id,
522
- number: data!.number,
523
- title: data!.title,
524
- pages: data!.pages || [],
525
- page_formats: data!.page_formats || [],
526
- original_pages: data!.original_pages || [],
527
- created_at: (data!.created_at as Timestamp).toDate().toISOString(),
528
- updated_at: (data!.updated_at as Timestamp).toDate().toISOString(),
529
- } as Chapter;
530
- }
531
-
532
- export async function resetAllMangaViews(): Promise<void> {
533
- const mangas = await getAllMangas();
534
- const updatePromises = mangas.map(manga => {
535
- const docRef = doc(db, 'mangas', manga.id);
536
- return updateDoc(docRef, { views: 0 });
537
- });
538
- await Promise.all(updatePromises);
539
- }
540
-
541
- export async function incrementMangaViews(mangaId: string): Promise<void> {
542
- const docRef = doc(db, 'mangas', mangaId);
543
- await updateDoc(docRef, {
544
- views: increment(1),
545
- });
546
- }
547
-
548
- export async function updateManga(mangaId: string, manga: {
549
- title: string;
550
- author: string;
551
- description?: string;
552
- thumbnail_url?: string;
553
- cover_url?: string;
554
- status?: string;
555
- categoryIds?: string[];
556
- }): Promise<Manga> {
557
- const docRef = doc(db, 'mangas', mangaId);
558
- const now = Timestamp.now();
559
-
560
- const updateData: any = {
561
- title: manga.title,
562
- author: manga.author,
563
- categories: manga.categoryIds || [],
564
- updated_at: now,
565
- };
566
-
567
- if (manga.status) {
568
- updateData.status = manga.status;
569
- }
570
-
571
- if (manga.description !== undefined && manga.description !== null) {
572
- updateData.description = manga.description;
573
- }
574
-
575
- if (manga.thumbnail_url) {
576
- updateData.thumbnail_url = manga.thumbnail_url;
577
- }
578
-
579
- if (manga.cover_url) {
580
- updateData.cover_url = manga.cover_url;
581
- }
582
-
583
- const cleanData = cleanUndefinedDeep(updateData);
584
- await updateDoc(docRef, cleanData);
585
-
586
- const docSnap = await getDoc(docRef);
587
- if (!docSnap.exists()) {
588
- throw new Error('Manga no encontrado');
589
- }
590
-
591
- const data = docSnap.data();
592
- const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', mangaId));
593
- const chaptersSnapshot = await getDocs(chaptersQuery);
594
- const chapters = chaptersSnapshot.docs
595
- .map(chapterDoc => {
596
- const chapterData = chapterDoc.data();
597
- return {
598
- id: chapterDoc.id,
599
- manga_id: chapterData.manga_id,
600
- number: chapterData.number,
601
- title: chapterData.title,
602
- pages: chapterData.pages || [],
603
- page_formats: chapterData.page_formats || [],
604
- original_pages: chapterData.original_pages || [],
605
- created_at: (chapterData.created_at as Timestamp).toDate().toISOString(),
606
- updated_at: (chapterData.updated_at as Timestamp).toDate().toISOString(),
607
- } as Chapter;
608
- })
609
- .sort((a, b) => a.number - b.number);
610
-
611
- const categoryIds = data.categories || [];
612
- const categories: Category[] = [];
613
-
614
- for (const categoryId of categoryIds) {
615
- const catDocRef = doc(db, 'categories', categoryId);
616
- const catDocSnap = await getDoc(catDocRef);
617
- if (catDocSnap.exists()) {
618
- categories.push({
619
- id: catDocSnap.id,
620
- ...catDocSnap.data(),
621
- created_at: catDocSnap.data().created_at?.toDate?.().toISOString() || new Date().toISOString(),
622
- } as Category);
623
- }
624
- }
625
-
626
- const updatedManga = {
627
- id: docSnap.id,
628
- ...data,
629
- created_at: (data.created_at as Timestamp).toDate().toISOString(),
630
- categories,
631
- chapters,
632
- updated_at: (data.updated_at as Timestamp).toDate().toISOString(),
633
- } as Manga;
634
-
635
- // Invalidate global cache
636
- allMangasCache = null;
637
- removeLocal(STORAGE_KEYS.ALL_MANGAS);
638
-
639
- // Update individual cache
640
- mangaCache.set(updatedManga.id, updatedManga);
641
- saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${updatedManga.id}`, updatedManga);
642
-
643
- return updatedManga;
644
- }
645
-
646
- export async function deleteManga(mangaId: string): Promise<void> {
647
- const mangaRef = doc(db, 'mangas', mangaId);
648
-
649
- const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', mangaId));
650
- const chaptersSnapshot = await getDocs(chaptersQuery);
651
-
652
- for (const chapterDoc of chaptersSnapshot.docs) {
653
- await deleteDoc(chapterDoc.ref);
654
- }
655
-
656
- await deleteDoc(mangaRef);
657
-
658
- // Invalidate global cache to remove the deleted manga from list
659
- allMangasCache = null;
660
- removeLocal(STORAGE_KEYS.ALL_MANGAS);
661
-
662
- // Remove from individual cache
663
- mangaCache.delete(mangaId);
664
- removeLocal(`${STORAGE_KEYS.MANGA_PREFIX}${mangaId}`);
665
- }
666
-
667
- export async function addExternalLink(mangaId: string, link: { name: string; url: string }): Promise<void> {
668
- const docRef = doc(db, 'mangas', mangaId);
669
- const docSnap = await getDoc(docRef);
670
-
671
- if (!docSnap.exists()) {
672
- throw new Error('Manga no encontrado');
673
- }
674
-
675
- const currentLinks = docSnap.data().external_links || [];
676
- const updateData = {
677
- external_links: [...currentLinks, link],
678
- };
679
- const cleanData = cleanUndefinedDeep(updateData);
680
- await updateDoc(docRef, cleanData);
681
- }
682
-
683
- export async function removeExternalLink(mangaId: string, index: number): Promise<void> {
684
- const docRef = doc(db, 'mangas', mangaId);
685
- const docSnap = await getDoc(docRef);
686
-
687
- if (!docSnap.exists()) {
688
- throw new Error('Manga no encontrado');
689
- }
690
-
691
- const currentLinks = docSnap.data().external_links || [];
692
- const updateData = {
693
- external_links: currentLinks.filter((_: any, i: number) => i !== index),
694
- };
695
- const cleanData = cleanUndefinedDeep(updateData);
696
- await updateDoc(docRef, cleanData);
697
- }
698
-
699
- export async function getRecommendations(currentMangaId: string, categoryIds: string[], title: string, limit?: number): Promise<Manga[]> {
700
- const allMangas = await getAllMangas();
701
-
702
- const recommendations = allMangas
703
- .filter(manga => manga.id !== currentMangaId)
704
- .map(manga => {
705
- let score = 0;
706
-
707
- const mangaCategoryIds = manga.categories?.map(cat => cat.id) || [];
708
- const sharedCategories = categoryIds.filter(catId => mangaCategoryIds.includes(catId));
709
- score += sharedCategories.length * 10;
710
-
711
- const currentTitleWords = title.toLowerCase().split(/\s+/).filter(w => w.length > 2);
712
- const mangaTitleWords = manga.title.toLowerCase().split(/\s+/).filter(w => w.length > 2);
713
- const sharedWords = currentTitleWords.filter(word => mangaTitleWords.includes(word));
714
- score += sharedWords.length * 5;
715
-
716
- const currentAuthorWords = manga.author?.toLowerCase().split(/\s+/).filter(w => w.length > 2) || [];
717
- const sharedAuthorWords = currentTitleWords.filter(word => currentAuthorWords.includes(word));
718
- score += sharedAuthorWords.length * 3;
719
-
720
- return { manga, score };
721
- })
722
- .filter(item => item.score > 0)
723
- .sort((a, b) => {
724
- const titleA = a.manga.title.toLowerCase();
725
- const titleB = b.manga.title.toLowerCase();
726
- return titleA.localeCompare(titleB);
727
- })
728
- .map(item => item.manga);
729
-
730
- return limit ? recommendations.slice(0, limit) : recommendations;
731
- }
 
1
+ import { db } from '../lib/firebase';
2
+ import {
3
+ collection,
4
+ getDocs,
5
+ doc,
6
+ getDoc,
7
+ addDoc,
8
+ updateDoc,
9
+ deleteDoc,
10
+ increment,
11
+ query,
12
+ orderBy,
13
+ where,
14
+ Timestamp,
15
+ onSnapshot,
16
+ Unsubscribe,
17
+ } from 'firebase/firestore';
18
+ import { Manga, Category, Chapter } from '../types/manga';
19
+
20
+ function cleanUndefinedDeep(obj: any): any {
21
+ if (obj === null || obj === undefined) {
22
+ return undefined;
23
+ }
24
+
25
+ if (Array.isArray(obj)) {
26
+ const cleaned = obj
27
+ .map(item => cleanUndefinedDeep(item))
28
+ .filter(item => item !== undefined && item !== null && item !== '');
29
+ return cleaned.length > 0 ? cleaned : undefined;
30
+ }
31
+
32
+ if (typeof obj === 'object' && !(obj instanceof Timestamp)) {
33
+ const cleaned: any = {};
34
+ for (const key in obj) {
35
+ if (obj.hasOwnProperty(key)) {
36
+ const value = cleanUndefinedDeep(obj[key]);
37
+ if (value !== undefined && value !== null) {
38
+ cleaned[key] = value;
39
+ }
40
+ }
41
+ }
42
+ return Object.keys(cleaned).length > 0 ? cleaned : undefined;
43
+ }
44
+
45
+ return obj;
46
+ }
47
+
48
+ // Helper functions for localStorage
49
+ const STORAGE_KEYS = {
50
+ ALL_MANGAS: 'mangalib_all_v2',
51
+ MANGA_PREFIX: 'mangalib_detail_v2_',
52
+ };
53
+
54
+ function getLocal<T>(key: string): T | null {
55
+ try {
56
+ const item = localStorage.getItem(key);
57
+ return item ? JSON.parse(item) : null;
58
+ } catch (error) {
59
+ console.warn(`Error reading ${key} from localStorage`, error);
60
+ return null;
61
+ }
62
+ }
63
+
64
+ function saveLocal(key: string, data: any): void {
65
+ try {
66
+ localStorage.setItem(key, JSON.stringify(data));
67
+ } catch (error) {
68
+ console.warn(`Error saving ${key} to localStorage`, error);
69
+ }
70
+ }
71
+
72
+ function removeLocal(key: string): void {
73
+ try {
74
+ localStorage.removeItem(key);
75
+ } catch (error) {
76
+ console.warn(`Error removing ${key} from localStorage`, error);
77
+ }
78
+ }
79
+
80
+
81
+ // Cache global for all mangas
82
+ let allMangasCache: Manga[] | null = null;
83
+
84
+ export async function getAllMangas(): Promise<Manga[]> {
85
+ // Try memory first
86
+ if (allMangasCache) {
87
+ return allMangasCache;
88
+ }
89
+
90
+ // Try localStorage
91
+ const localData = getLocal<Manga[]>(STORAGE_KEYS.ALL_MANGAS);
92
+ if (localData) {
93
+ allMangasCache = localData;
94
+ // Populate individual cache from local data too
95
+ localData.forEach(m => mangaCache.set(m.id, m));
96
+ return localData;
97
+ }
98
+
99
+ const q = query(collection(db, 'mangas'), orderBy('created_at', 'desc'));
100
+ const querySnapshot = await getDocs(q);
101
+
102
+ // Fetch all categories once
103
+ const categoriesSnapshot = await getDocs(collection(db, 'categories'));
104
+ const allCategories = categoriesSnapshot.docs.reduce((acc, doc) => {
105
+ acc[doc.id] = { id: doc.id, ...doc.data() } as Category;
106
+ return acc;
107
+ }, {} as Record<string, Category>);
108
+
109
+ const mangas = await Promise.all(
110
+ querySnapshot.docs.map(async (mangaDoc) => {
111
+ const mangaData = mangaDoc.data();
112
+
113
+ const chaptersQuery = query(
114
+ collection(db, 'chapters'),
115
+ where('manga_id', '==', mangaDoc.id)
116
+ );
117
+ const chaptersSnapshot = await getDocs(chaptersQuery);
118
+ const chapters = chaptersSnapshot.docs
119
+ .map(chapterDoc => {
120
+ const chapterData = chapterDoc.data();
121
+ return {
122
+ id: chapterDoc.id,
123
+ manga_id: chapterData.manga_id,
124
+ number: chapterData.number,
125
+ title: chapterData.title,
126
+ pages: chapterData.pages || [],
127
+ page_formats: chapterData.page_formats || [],
128
+ original_pages: chapterData.original_pages || [],
129
+ created_at: (chapterData.created_at as Timestamp).toDate().toISOString(),
130
+ updated_at: (chapterData.updated_at as Timestamp).toDate().toISOString(),
131
+ } as Chapter;
132
+ })
133
+ .sort((a, b) => a.number - b.number);
134
+
135
+ // Map category IDs to full category objects
136
+ const categoryIds = (mangaData.categories as string[]) || [];
137
+ const populatedCategories = categoryIds
138
+ .map(id => allCategories[id])
139
+ .filter(c => c !== undefined);
140
+
141
+ return {
142
+ id: mangaDoc.id,
143
+ ...mangaData,
144
+ created_at: (mangaData.created_at as Timestamp).toDate().toISOString(),
145
+ updated_at: mangaData.updated_at ? (mangaData.updated_at as Timestamp).toDate().toISOString() : (mangaData.created_at as Timestamp).toDate().toISOString(),
146
+ categories: populatedCategories,
147
+ chapters,
148
+ } as Manga;
149
+ })
150
+ );
151
+
152
+ // Populate individual cache as well
153
+ mangas.forEach(manga => {
154
+ mangaCache.set(manga.id, manga);
155
+ });
156
+
157
+ allMangasCache = mangas;
158
+ saveLocal(STORAGE_KEYS.ALL_MANGAS, mangas);
159
+ return mangas;
160
+ }
161
+
162
+ const mangaCache = new Map<string, Manga>();
163
+
164
+ export async function getMangaById(id: string): Promise<Manga | null> {
165
+ // Check cache first
166
+ if (mangaCache.has(id)) {
167
+ return mangaCache.get(id)!;
168
+ }
169
+
170
+ // Try localStorage
171
+ const localData = getLocal<Manga>(`${STORAGE_KEYS.MANGA_PREFIX}${id}`);
172
+ if (localData) {
173
+ mangaCache.set(id, localData);
174
+ return localData;
175
+ }
176
+
177
+ const docRef = doc(db, 'mangas', id);
178
+ const docSnap = await getDoc(docRef);
179
+
180
+ if (!docSnap.exists()) return null;
181
+
182
+ const data = docSnap.data();
183
+
184
+ const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', id));
185
+ const chaptersSnapshot = await getDocs(chaptersQuery);
186
+ const chapters = chaptersSnapshot.docs
187
+ .map(doc => {
188
+ const chapterData = doc.data();
189
+ return {
190
+ id: doc.id,
191
+ manga_id: chapterData.manga_id,
192
+ number: chapterData.number,
193
+ title: chapterData.title,
194
+ pages: chapterData.pages || [],
195
+ page_formats: chapterData.page_formats || [],
196
+ original_pages: chapterData.original_pages || [],
197
+ created_at: (chapterData.created_at as Timestamp).toDate().toISOString(),
198
+ updated_at: (chapterData.updated_at as Timestamp).toDate().toISOString(),
199
+ } as Chapter;
200
+ })
201
+ .sort((a, b) => a.number - b.number);
202
+
203
+ const categoryIds = data.categories || [];
204
+ const categories: Category[] = [];
205
+
206
+ for (const categoryId of categoryIds) {
207
+ const catDocRef = doc(db, 'categories', categoryId);
208
+ const catDocSnap = await getDoc(catDocRef);
209
+ if (catDocSnap.exists()) {
210
+ categories.push({
211
+ id: catDocSnap.id,
212
+ ...catDocSnap.data(),
213
+ created_at: catDocSnap.data().created_at?.toDate?.().toISOString() || new Date().toISOString(),
214
+ } as Category);
215
+ }
216
+ }
217
+
218
+ const mangaData = {
219
+ id: docSnap.id,
220
+ ...data,
221
+ created_at: (data.created_at as Timestamp).toDate().toISOString(),
222
+ categories,
223
+ chapters,
224
+ updated_at: data.updated_at ? (data.updated_at as Timestamp).toDate().toISOString() : (data.created_at as Timestamp).toDate().toISOString(),
225
+ } as Manga;
226
+
227
+ // Save to cache
228
+ mangaCache.set(id, mangaData);
229
+ saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${id}`, mangaData);
230
+
231
+ return mangaData;
232
+ }
233
+
234
+ export function subscribeToManga(id: string, callback: (manga: Manga | null) => void): Unsubscribe {
235
+ const docRef = doc(db, 'mangas', id);
236
+
237
+ return onSnapshot(docRef, async (docSnap) => {
238
+ if (!docSnap.exists()) {
239
+ callback(null);
240
+ return;
241
+ }
242
+
243
+ const data = docSnap.data();
244
+
245
+ // We also need chapters and categories
246
+ // Note: This inside a snapshot might be expensive if chapters change often,
247
+ // but for views increment only the manga doc changes, so this is fine.
248
+ // However, fast view updates might trigger this often.
249
+
250
+ // To avoid refetching sub-collections on every view increment if not needed,
251
+ // we could optimize, but for now we follow the pattern to ensure data consistency.
252
+ // Actually, `getDocs` inside a snapshot callback for every view increment is bad practice (Read accumulation).
253
+ // The view count is on the main doc. The chapters/categories usually don't change.
254
+ // We can rely on a mix: get the cached chapters/categories or fetch them if missing.
255
+ // But since the user wants real-time, let's assume fully fresh data is safer.
256
+ // Or better: Use the cache for heavy stuff and update the fields from the docSnap.
257
+
258
+ // Let's reuse getMangaById logic but with the new data from snapshot.
259
+ // Actually, passing the snapshot data to a helper would be better.
260
+ // For simplicity and preventing "infinite reads" loop if not careful:
261
+
262
+ // Strategy: Just update the fields present in the manga document (like views)
263
+ // and assume chapters/categories are relatively static or handled separately.
264
+ // But `manga` object needs chapters/categories to render `ComicDetail`.
265
+
266
+ // Let's grab the existing cache if available to fill in the gaps (chapters),
267
+ // effectively only updating the 'manga' doc fields (views, title, etc).
268
+
269
+ let cached = mangaCache.get(id);
270
+ let chapters = cached?.chapters || [];
271
+ let categories = cached?.categories || [];
272
+
273
+ // If not in cache, we MUST fetch chapters/categories at least once.
274
+ if (!cached) {
275
+ // Fallback to fetch data once
276
+ // But doing async work in snapshot callback is tricky if we want to return immediately.
277
+ // We will do the fetch.
278
+ const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', id));
279
+ const chaptersSnapshot = await getDocs(chaptersQuery);
280
+ chapters = chaptersSnapshot.docs
281
+ .map(c => ({
282
+ id: c.id,
283
+ ...c.data(),
284
+ created_at: (c.data().created_at as Timestamp).toDate().toISOString(),
285
+ updated_at: (c.data().updated_at as Timestamp).toDate().toISOString(),
286
+ } as any))
287
+ .sort((a: any, b: any) => a.number - b.number);
288
+
289
+ const categoryIds = data.categories || [];
290
+ categories = []; // We would verify categories here, but skipping for brevity/perf to avoid N+1 reads loop in high frequency.
291
+ // Ideally categories are embedded or we trust the component to handle.
292
+ // Let's stick to the current architecture.
293
+ // Fetch categories
294
+ for (const catId of categoryIds) {
295
+ const catDoc = await getDoc(doc(db, 'categories', catId));
296
+ if (catDoc.exists()) categories.push({ id: catDoc.id, ...catDoc.data() } as any);
297
+ }
298
+ }
299
+
300
+ const updatedManga: Manga = {
301
+ id: docSnap.id,
302
+ ...data,
303
+ chapters,
304
+ categories,
305
+ created_at: (data.created_at as Timestamp).toDate().toISOString(),
306
+ updated_at: data.updated_at ? (data.updated_at as Timestamp).toDate().toISOString() : (data.created_at as Timestamp).toDate().toISOString(),
307
+ } as Manga;
308
+
309
+ // Update cache
310
+ mangaCache.set(id, updatedManga);
311
+ saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${id}`, updatedManga);
312
+
313
+ callback(updatedManga);
314
+ });
315
+ }
316
+
317
+ export async function createManga(manga: {
318
+ title: string;
319
+ author: string;
320
+ description?: string;
321
+ thumbnail_url?: string;
322
+ cover_url?: string;
323
+ status?: string;
324
+ categoryIds?: string[];
325
+ }): Promise<Manga> {
326
+ const now = Timestamp.now();
327
+
328
+ const mangaData: any = {
329
+ title: manga.title,
330
+ author: manga.author,
331
+ description: manga.description || '',
332
+ status: manga.status || 'En curso',
333
+ categories: manga.categoryIds || [],
334
+ views: 0,
335
+ rating: 0,
336
+ created_at: now,
337
+ updated_at: now,
338
+ };
339
+
340
+ if (manga.thumbnail_url) {
341
+ mangaData.thumbnail_url = manga.thumbnail_url;
342
+ }
343
+
344
+ if (manga.cover_url) {
345
+ mangaData.cover_url = manga.cover_url;
346
+ }
347
+
348
+ const docRef = await addDoc(collection(db, 'mangas'), mangaData);
349
+
350
+ const nowISO = new Date().toISOString();
351
+ const data: any = {
352
+ id: docRef.id,
353
+ title: manga.title,
354
+ author: manga.author,
355
+ description: manga.description || '',
356
+ status: manga.status || 'En curso',
357
+ categories: manga.categoryIds || [],
358
+ chapters: [],
359
+ views: 0,
360
+ rating: 0,
361
+ created_at: nowISO,
362
+ updated_at: nowISO,
363
+ };
364
+
365
+ if (manga.thumbnail_url) {
366
+ data.thumbnail_url = manga.thumbnail_url;
367
+ }
368
+
369
+ if (manga.cover_url) {
370
+ data.cover_url = manga.cover_url;
371
+ }
372
+
373
+ // Invalidate global cache
374
+ allMangasCache = null;
375
+ removeLocal(STORAGE_KEYS.ALL_MANGAS);
376
+
377
+ // Use the new data to update individual cache
378
+ mangaCache.set(data.id, data as Manga);
379
+ saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${data.id}`, data);
380
+
381
+ return data as Manga;
382
+ }
383
+
384
+ export async function getAllCategories(): Promise<Category[]> {
385
+ const querySnapshot = await getDocs(collection(db, 'categories'));
386
+ return querySnapshot.docs.map(doc => ({
387
+ id: doc.id,
388
+ ...doc.data(),
389
+ } as Category));
390
+ }
391
+
392
+ export async function createCategory(name: string): Promise<Category> {
393
+ const docRef = await addDoc(collection(db, 'categories'), { name });
394
+ const docSnap = await getDoc(docRef);
395
+
396
+ return {
397
+ id: docSnap.id,
398
+ ...docSnap.data(),
399
+ } as Category;
400
+ }
401
+
402
+ export async function deleteAllCategories(): Promise<void> {
403
+ const categories = await getAllCategories();
404
+
405
+ // Delete all category documents
406
+ const deletePromises = categories.map(cat => deleteDoc(doc(db, 'categories', cat.id)));
407
+ await Promise.all(deletePromises);
408
+
409
+ // Update all mangas to remove category associations
410
+ const mangas = await getAllMangas();
411
+ const updatePromises = mangas.map(manga => {
412
+ if (manga.categories && manga.categories.length > 0) {
413
+ return updateDoc(doc(db, 'mangas', manga.id), { categories: [] });
414
+ }
415
+ return Promise.resolve();
416
+ });
417
+ await Promise.all(updatePromises);
418
+ }
419
+
420
+ export async function regenerateAllMangaCategories(): Promise<{ updated: number, errors: number }> {
421
+ try {
422
+ const mangas = await getAllMangas();
423
+ const categories = await getAllCategories();
424
+ let updatedCount = 0;
425
+ let errorCount = 0;
426
+
427
+ // Helper to get or create category
428
+ const getCallback = async (name: string): Promise<string> => {
429
+ const existing = categories.find(c => c.name.toLowerCase() === name.toLowerCase());
430
+ if (existing) return existing.id;
431
+
432
+ try {
433
+ const newCat = await createCategory(name);
434
+ categories.push(newCat);
435
+ return newCat.id;
436
+ } catch (e) {
437
+ console.error(`Error creating category ${name}`, e);
438
+ return '';
439
+ }
440
+ };
441
+
442
+ const delimiters = /[|()[\]{}]/g;
443
+
444
+ for (const manga of mangas) {
445
+ try {
446
+ const chunks: string[] = [];
447
+
448
+ // Parse Title
449
+ const titleParts = manga.title.split(delimiters);
450
+ chunks.push(...titleParts);
451
+
452
+ // Parse Author
453
+ if (manga.author && manga.author !== 'Anónimo') {
454
+ const authorParts = manga.author.split(/[,&]/);
455
+ chunks.push(...authorParts);
456
+ }
457
+
458
+ // Clean up
459
+ const potentialNames = chunks
460
+ .map(s => s.trim())
461
+ .filter(s => s.length > 1)
462
+ .filter(s => !['-', '_', '.', ','].includes(s));
463
+
464
+ if (potentialNames.length === 0) continue;
465
+
466
+ const newCategoryIds: string[] = [];
467
+
468
+ for (const name of potentialNames) {
469
+ const id = await getCallback(name);
470
+ if (id && !newCategoryIds.includes(id)) {
471
+ newCategoryIds.push(id);
472
+ }
473
+ }
474
+
475
+ // Update manga if categories changed (or if it had none)
476
+ // Even if it has some, we might be adding new ones or replacing old bad ones if we wiped them.
477
+ // The user wiped them, so currently they should be empty.
478
+ if (newCategoryIds.length > 0) {
479
+ await updateDoc(doc(db, 'mangas', manga.id), { categories: newCategoryIds });
480
+ updatedCount++;
481
+ }
482
+
483
+ } catch (err) {
484
+ console.error(`Error processing manga ${manga.id}`, err);
485
+ errorCount++;
486
+ }
487
+ }
488
+
489
+ return { updated: updatedCount, errors: errorCount };
490
+ } catch (error) {
491
+ console.error('Error in bulk regeneration:', error);
492
+ throw error;
493
+ }
494
+ }
495
+
496
+ export async function createChapter(chapter: {
497
+ manga_id: string;
498
+ number: number;
499
+ title: string;
500
+ pages: string[];
501
+ page_formats?: string[];
502
+ original_pages?: string[];
503
+ }): Promise<Chapter> {
504
+ const now = Timestamp.now();
505
+ const docRef = await addDoc(collection(db, 'chapters'), {
506
+ manga_id: chapter.manga_id,
507
+ number: chapter.number,
508
+ title: chapter.title,
509
+ pages: chapter.pages,
510
+ page_formats: chapter.page_formats || [],
511
+ original_pages: chapter.original_pages || [],
512
+ created_at: now,
513
+ updated_at: now,
514
+ });
515
+
516
+ const docSnap = await getDoc(docRef);
517
+ const data = docSnap.data();
518
+
519
+ return {
520
+ id: docSnap.id,
521
+ manga_id: data!.manga_id,
522
+ number: data!.number,
523
+ title: data!.title,
524
+ pages: data!.pages || [],
525
+ page_formats: data!.page_formats || [],
526
+ original_pages: data!.original_pages || [],
527
+ created_at: (data!.created_at as Timestamp).toDate().toISOString(),
528
+ updated_at: (data!.updated_at as Timestamp).toDate().toISOString(),
529
+ } as Chapter;
530
+ }
531
+
532
+ export async function resetAllMangaViews(): Promise<void> {
533
+ const mangas = await getAllMangas();
534
+ const updatePromises = mangas.map(manga => {
535
+ const docRef = doc(db, 'mangas', manga.id);
536
+ return updateDoc(docRef, { views: 0 });
537
+ });
538
+ await Promise.all(updatePromises);
539
+ }
540
+
541
+ export async function incrementMangaViews(mangaId: string): Promise<void> {
542
+ const docRef = doc(db, 'mangas', mangaId);
543
+ await updateDoc(docRef, {
544
+ views: increment(1),
545
+ });
546
+ }
547
+
548
+ export async function updateManga(mangaId: string, manga: {
549
+ title: string;
550
+ author: string;
551
+ description?: string;
552
+ thumbnail_url?: string;
553
+ cover_url?: string;
554
+ status?: string;
555
+ categoryIds?: string[];
556
+ }): Promise<Manga> {
557
+ const docRef = doc(db, 'mangas', mangaId);
558
+ const now = Timestamp.now();
559
+
560
+ const updateData: any = {
561
+ title: manga.title,
562
+ author: manga.author,
563
+ categories: manga.categoryIds || [],
564
+ updated_at: now,
565
+ };
566
+
567
+ if (manga.status) {
568
+ updateData.status = manga.status;
569
+ }
570
+
571
+ if (manga.description !== undefined && manga.description !== null) {
572
+ updateData.description = manga.description;
573
+ }
574
+
575
+ if (manga.thumbnail_url) {
576
+ updateData.thumbnail_url = manga.thumbnail_url;
577
+ }
578
+
579
+ if (manga.cover_url) {
580
+ updateData.cover_url = manga.cover_url;
581
+ }
582
+
583
+ const cleanData = cleanUndefinedDeep(updateData);
584
+ await updateDoc(docRef, cleanData);
585
+
586
+ const docSnap = await getDoc(docRef);
587
+ if (!docSnap.exists()) {
588
+ throw new Error('Manga no encontrado');
589
+ }
590
+
591
+ const data = docSnap.data();
592
+ const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', mangaId));
593
+ const chaptersSnapshot = await getDocs(chaptersQuery);
594
+ const chapters = chaptersSnapshot.docs
595
+ .map(chapterDoc => {
596
+ const chapterData = chapterDoc.data();
597
+ return {
598
+ id: chapterDoc.id,
599
+ manga_id: chapterData.manga_id,
600
+ number: chapterData.number,
601
+ title: chapterData.title,
602
+ pages: chapterData.pages || [],
603
+ page_formats: chapterData.page_formats || [],
604
+ original_pages: chapterData.original_pages || [],
605
+ created_at: (chapterData.created_at as Timestamp).toDate().toISOString(),
606
+ updated_at: (chapterData.updated_at as Timestamp).toDate().toISOString(),
607
+ } as Chapter;
608
+ })
609
+ .sort((a, b) => a.number - b.number);
610
+
611
+ const categoryIds = data.categories || [];
612
+ const categories: Category[] = [];
613
+
614
+ for (const categoryId of categoryIds) {
615
+ const catDocRef = doc(db, 'categories', categoryId);
616
+ const catDocSnap = await getDoc(catDocRef);
617
+ if (catDocSnap.exists()) {
618
+ categories.push({
619
+ id: catDocSnap.id,
620
+ ...catDocSnap.data(),
621
+ created_at: catDocSnap.data().created_at?.toDate?.().toISOString() || new Date().toISOString(),
622
+ } as Category);
623
+ }
624
+ }
625
+
626
+ const updatedManga = {
627
+ id: docSnap.id,
628
+ ...data,
629
+ created_at: (data.created_at as Timestamp).toDate().toISOString(),
630
+ categories,
631
+ chapters,
632
+ updated_at: (data.updated_at as Timestamp).toDate().toISOString(),
633
+ } as Manga;
634
+
635
+ // Invalidate global cache
636
+ allMangasCache = null;
637
+ removeLocal(STORAGE_KEYS.ALL_MANGAS);
638
+
639
+ // Update individual cache
640
+ mangaCache.set(updatedManga.id, updatedManga);
641
+ saveLocal(`${STORAGE_KEYS.MANGA_PREFIX}${updatedManga.id}`, updatedManga);
642
+
643
+ return updatedManga;
644
+ }
645
+
646
+ export async function deleteManga(mangaId: string): Promise<void> {
647
+ const mangaRef = doc(db, 'mangas', mangaId);
648
+
649
+ const chaptersQuery = query(collection(db, 'chapters'), where('manga_id', '==', mangaId));
650
+ const chaptersSnapshot = await getDocs(chaptersQuery);
651
+
652
+ for (const chapterDoc of chaptersSnapshot.docs) {
653
+ await deleteDoc(chapterDoc.ref);
654
+ }
655
+
656
+ await deleteDoc(mangaRef);
657
+
658
+ // Invalidate global cache to remove the deleted manga from list
659
+ allMangasCache = null;
660
+ removeLocal(STORAGE_KEYS.ALL_MANGAS);
661
+
662
+ // Remove from individual cache
663
+ mangaCache.delete(mangaId);
664
+ removeLocal(`${STORAGE_KEYS.MANGA_PREFIX}${mangaId}`);
665
+ }
666
+
667
+ export async function addExternalLink(mangaId: string, link: { name: string; url: string }): Promise<void> {
668
+ const docRef = doc(db, 'mangas', mangaId);
669
+ const docSnap = await getDoc(docRef);
670
+
671
+ if (!docSnap.exists()) {
672
+ throw new Error('Manga no encontrado');
673
+ }
674
+
675
+ const currentLinks = docSnap.data().external_links || [];
676
+ const updateData = {
677
+ external_links: [...currentLinks, link],
678
+ };
679
+ const cleanData = cleanUndefinedDeep(updateData);
680
+ await updateDoc(docRef, cleanData);
681
+ }
682
+
683
+ export async function removeExternalLink(mangaId: string, index: number): Promise<void> {
684
+ const docRef = doc(db, 'mangas', mangaId);
685
+ const docSnap = await getDoc(docRef);
686
+
687
+ if (!docSnap.exists()) {
688
+ throw new Error('Manga no encontrado');
689
+ }
690
+
691
+ const currentLinks = docSnap.data().external_links || [];
692
+ const updateData = {
693
+ external_links: currentLinks.filter((_: any, i: number) => i !== index),
694
+ };
695
+ const cleanData = cleanUndefinedDeep(updateData);
696
+ await updateDoc(docRef, cleanData);
697
+ }
698
+
699
+ export async function getRecommendations(currentMangaId: string, categoryIds: string[], title: string, limit?: number): Promise<Manga[]> {
700
+ const allMangas = await getAllMangas();
701
+
702
+ const recommendations = allMangas
703
+ .filter(manga => manga.id !== currentMangaId)
704
+ .map(manga => {
705
+ let score = 0;
706
+
707
+ const mangaCategoryIds = manga.categories?.map(cat => cat.id) || [];
708
+ const sharedCategories = categoryIds.filter(catId => mangaCategoryIds.includes(catId));
709
+ score += sharedCategories.length * 10;
710
+
711
+ const currentTitleWords = title.toLowerCase().split(/\s+/).filter(w => w.length > 2);
712
+ const mangaTitleWords = manga.title.toLowerCase().split(/\s+/).filter(w => w.length > 2);
713
+ const sharedWords = currentTitleWords.filter(word => mangaTitleWords.includes(word));
714
+ score += sharedWords.length * 5;
715
+
716
+ const currentAuthorWords = manga.author?.toLowerCase().split(/\s+/).filter(w => w.length > 2) || [];
717
+ const sharedAuthorWords = currentTitleWords.filter(word => currentAuthorWords.includes(word));
718
+ score += sharedAuthorWords.length * 3;
719
+
720
+ return { manga, score };
721
+ })
722
+ .filter(item => item.score > 0)
723
+ .sort((a, b) => {
724
+ const titleA = a.manga.title.toLowerCase();
725
+ const titleB = b.manga.title.toLowerCase();
726
+ return titleA.localeCompare(titleB);
727
+ })
728
+ .map(item => item.manga);
729
+
730
+ return limit ? recommendations.slice(0, limit) : recommendations;
731
+ }
src/types/manga.ts CHANGED
@@ -1,39 +1,39 @@
1
- export interface Manga {
2
- id: string;
3
- title: string;
4
- author: string;
5
- description: string;
6
- thumbnail_url: string | null;
7
- cover_url: string | null;
8
- status: string;
9
- rating: number;
10
- views: number;
11
- created_at: string;
12
- updated_at: string;
13
- categories?: Category[];
14
- chapters?: Chapter[];
15
- external_links?: Array<{ name: string; url: string }>;
16
- }
17
-
18
- export interface Category {
19
- id: string;
20
- name: string;
21
- created_at: string;
22
- }
23
-
24
- export interface Chapter {
25
- id: string;
26
- manga_id: string;
27
- number: number;
28
- title: string;
29
- pages: string[];
30
- page_formats?: string[];
31
- original_pages?: string[];
32
- created_at: string;
33
- updated_at: string;
34
- }
35
-
36
- export interface MangaCategory {
37
- manga_id: string;
38
- category_id: string;
39
- }
 
1
+ export interface Manga {
2
+ id: string;
3
+ title: string;
4
+ author: string;
5
+ description: string;
6
+ thumbnail_url: string | null;
7
+ cover_url: string | null;
8
+ status: string;
9
+ rating: number;
10
+ views: number;
11
+ created_at: string;
12
+ updated_at: string;
13
+ categories?: Category[];
14
+ chapters?: Chapter[];
15
+ external_links?: Array<{ name: string; url: string }>;
16
+ }
17
+
18
+ export interface Category {
19
+ id: string;
20
+ name: string;
21
+ created_at: string;
22
+ }
23
+
24
+ export interface Chapter {
25
+ id: string;
26
+ manga_id: string;
27
+ number: number;
28
+ title: string;
29
+ pages: string[];
30
+ page_formats?: string[];
31
+ original_pages?: string[];
32
+ created_at: string;
33
+ updated_at: string;
34
+ }
35
+
36
+ export interface MangaCategory {
37
+ manga_id: string;
38
+ category_id: string;
39
+ }
src/utils/apiKeyManager.ts CHANGED
@@ -1,20 +1,20 @@
1
- const USER_API_KEY_STORAGE = 'userApiKey';
2
-
3
- export function saveUserApiKey(apiKey: string): void {
4
- if (!apiKey || apiKey.trim() === '') {
5
- throw new Error('API key no puede estar vacía');
6
- }
7
- localStorage.setItem(USER_API_KEY_STORAGE, apiKey.trim());
8
- }
9
-
10
- export function getUserApiKey(): string | null {
11
- return localStorage.getItem(USER_API_KEY_STORAGE);
12
- }
13
-
14
- export function deleteUserApiKey(): void {
15
- localStorage.removeItem(USER_API_KEY_STORAGE);
16
- }
17
-
18
- export function hasUserApiKey(): boolean {
19
- return !!getUserApiKey();
20
- }
 
1
+ const USER_API_KEY_STORAGE = 'userApiKey';
2
+
3
+ export function saveUserApiKey(apiKey: string): void {
4
+ if (!apiKey || apiKey.trim() === '') {
5
+ throw new Error('API key no puede estar vacía');
6
+ }
7
+ localStorage.setItem(USER_API_KEY_STORAGE, apiKey.trim());
8
+ }
9
+
10
+ export function getUserApiKey(): string | null {
11
+ return localStorage.getItem(USER_API_KEY_STORAGE);
12
+ }
13
+
14
+ export function deleteUserApiKey(): void {
15
+ localStorage.removeItem(USER_API_KEY_STORAGE);
16
+ }
17
+
18
+ export function hasUserApiKey(): boolean {
19
+ return !!getUserApiKey();
20
+ }
src/utils/batchSizeManager.ts CHANGED
@@ -1,28 +1,28 @@
1
- const BATCH_SIZE_STORAGE_KEY = 'imageBatchSize';
2
- const DEFAULT_BATCH_SIZE = 10;
3
-
4
- export function saveBatchSize(size: number): void {
5
- if (size < 0) {
6
- throw new Error('El tamaño del lote no puede ser negativo');
7
- }
8
- localStorage.setItem(BATCH_SIZE_STORAGE_KEY, size.toString());
9
- }
10
-
11
- export function getBatchSize(): number {
12
- const stored = localStorage.getItem(BATCH_SIZE_STORAGE_KEY);
13
- if (!stored) {
14
- return DEFAULT_BATCH_SIZE;
15
- }
16
- const parsed = parseInt(stored, 10);
17
- if (isNaN(parsed) || parsed < 0) {
18
- return DEFAULT_BATCH_SIZE;
19
- }
20
- if (parsed >= 999999) {
21
- return 0;
22
- }
23
- return parsed;
24
- }
25
-
26
- export function resetBatchSize(): void {
27
- localStorage.removeItem(BATCH_SIZE_STORAGE_KEY);
28
- }
 
1
+ const BATCH_SIZE_STORAGE_KEY = 'imageBatchSize';
2
+ const DEFAULT_BATCH_SIZE = 10;
3
+
4
+ export function saveBatchSize(size: number): void {
5
+ if (size < 0) {
6
+ throw new Error('El tamaño del lote no puede ser negativo');
7
+ }
8
+ localStorage.setItem(BATCH_SIZE_STORAGE_KEY, size.toString());
9
+ }
10
+
11
+ export function getBatchSize(): number {
12
+ const stored = localStorage.getItem(BATCH_SIZE_STORAGE_KEY);
13
+ if (!stored) {
14
+ return DEFAULT_BATCH_SIZE;
15
+ }
16
+ const parsed = parseInt(stored, 10);
17
+ if (isNaN(parsed) || parsed < 0) {
18
+ return DEFAULT_BATCH_SIZE;
19
+ }
20
+ if (parsed >= 999999) {
21
+ return 0;
22
+ }
23
+ return parsed;
24
+ }
25
+
26
+ export function resetBatchSize(): void {
27
+ localStorage.removeItem(BATCH_SIZE_STORAGE_KEY);
28
+ }
src/utils/downloadHelpers.ts CHANGED
@@ -1,100 +1,100 @@
1
- import { convertImageToFormat } from './imageOptimization';
2
-
3
- export async function downloadImageAs(
4
- imageUrl: string,
5
- fileName: string,
6
- format: 'png' | 'jpg' | 'webp' | 'original',
7
- originalFormat?: string
8
- ): Promise<void> {
9
- try {
10
- if (format === 'original') {
11
- const response = await fetch(imageUrl);
12
- const blob = await response.blob();
13
- const url = URL.createObjectURL(blob);
14
- const a = document.createElement('a');
15
- a.href = url;
16
- a.download = `${fileName}.${originalFormat || 'jpg'}`;
17
- document.body.appendChild(a);
18
- a.click();
19
- document.body.removeChild(a);
20
- URL.revokeObjectURL(url);
21
- } else {
22
- const blob = await convertImageToFormat(imageUrl, format);
23
- const url = URL.createObjectURL(blob);
24
- const a = document.createElement('a');
25
- a.href = url;
26
- a.download = `${fileName}.${format}`;
27
- document.body.appendChild(a);
28
- a.click();
29
- document.body.removeChild(a);
30
- URL.revokeObjectURL(url);
31
- }
32
- } catch (error) {
33
- console.error(`Error downloading image as ${format}:`, error);
34
- throw error;
35
- }
36
- }
37
-
38
- export async function downloadAllPagesAsZip(
39
- pages: string[],
40
- formats: string[],
41
- mangaTitle: string,
42
- downloadFormat: 'png' | 'jpg' | 'webp' | 'original',
43
- onProgress?: (progress: number) => void
44
- ): Promise<void> {
45
- const JSZip = (await import('jszip')).default;
46
- const zip = new JSZip();
47
- const BATCH_SIZE = 10;
48
-
49
- for (let batchStart = 0; batchStart < pages.length; batchStart += BATCH_SIZE) {
50
- const batchEnd = Math.min(batchStart + BATCH_SIZE, pages.length);
51
- const batchPromises = [];
52
-
53
- for (let i = batchStart; i < batchEnd; i++) {
54
- const promise = (async () => {
55
- try {
56
- let blob: Blob;
57
- let ext: string;
58
-
59
- if (downloadFormat === 'original') {
60
- const response = await fetch(pages[i]);
61
- blob = await response.blob();
62
- ext = formats[i] || 'jpg';
63
- } else {
64
- blob = await convertImageToFormat(pages[i], downloadFormat);
65
- ext = downloadFormat;
66
- }
67
-
68
- return { index: i, blob, ext };
69
- } catch (error) {
70
- console.error(`Error processing page ${i + 1}:`, error);
71
- return null;
72
- }
73
- })();
74
-
75
- batchPromises.push(promise);
76
- }
77
-
78
- const results = await Promise.all(batchPromises);
79
-
80
- for (const result of results) {
81
- if (result) {
82
- zip.file(`pagina_${(result.index + 1).toString().padStart(3, '0')}.${result.ext}`, result.blob);
83
- }
84
- }
85
-
86
- const progress = Math.round(((batchEnd / pages.length) * 100));
87
- onProgress?.(progress);
88
- }
89
-
90
- const content = await zip.generateAsync({ type: 'blob' });
91
- const url = URL.createObjectURL(content);
92
- const a = document.createElement('a');
93
- a.href = url;
94
- const formatLabel = downloadFormat === 'original' ? 'original' : downloadFormat.toUpperCase();
95
- a.download = `${mangaTitle.replace(/[^a-z0-9]/gi, '_')}_${formatLabel}.zip`;
96
- document.body.appendChild(a);
97
- a.click();
98
- document.body.removeChild(a);
99
- URL.revokeObjectURL(url);
100
- }
 
1
+ import { convertImageToFormat } from './imageOptimization';
2
+
3
+ export async function downloadImageAs(
4
+ imageUrl: string,
5
+ fileName: string,
6
+ format: 'png' | 'jpg' | 'webp' | 'original',
7
+ originalFormat?: string
8
+ ): Promise<void> {
9
+ try {
10
+ if (format === 'original') {
11
+ const response = await fetch(imageUrl);
12
+ const blob = await response.blob();
13
+ const url = URL.createObjectURL(blob);
14
+ const a = document.createElement('a');
15
+ a.href = url;
16
+ a.download = `${fileName}.${originalFormat || 'jpg'}`;
17
+ document.body.appendChild(a);
18
+ a.click();
19
+ document.body.removeChild(a);
20
+ URL.revokeObjectURL(url);
21
+ } else {
22
+ const blob = await convertImageToFormat(imageUrl, format);
23
+ const url = URL.createObjectURL(blob);
24
+ const a = document.createElement('a');
25
+ a.href = url;
26
+ a.download = `${fileName}.${format}`;
27
+ document.body.appendChild(a);
28
+ a.click();
29
+ document.body.removeChild(a);
30
+ URL.revokeObjectURL(url);
31
+ }
32
+ } catch (error) {
33
+ console.error(`Error downloading image as ${format}:`, error);
34
+ throw error;
35
+ }
36
+ }
37
+
38
+ export async function downloadAllPagesAsZip(
39
+ pages: string[],
40
+ formats: string[],
41
+ mangaTitle: string,
42
+ downloadFormat: 'png' | 'jpg' | 'webp' | 'original',
43
+ onProgress?: (progress: number) => void
44
+ ): Promise<void> {
45
+ const JSZip = (await import('jszip')).default;
46
+ const zip = new JSZip();
47
+ const BATCH_SIZE = 10;
48
+
49
+ for (let batchStart = 0; batchStart < pages.length; batchStart += BATCH_SIZE) {
50
+ const batchEnd = Math.min(batchStart + BATCH_SIZE, pages.length);
51
+ const batchPromises = [];
52
+
53
+ for (let i = batchStart; i < batchEnd; i++) {
54
+ const promise = (async () => {
55
+ try {
56
+ let blob: Blob;
57
+ let ext: string;
58
+
59
+ if (downloadFormat === 'original') {
60
+ const response = await fetch(pages[i]);
61
+ blob = await response.blob();
62
+ ext = formats[i] || 'jpg';
63
+ } else {
64
+ blob = await convertImageToFormat(pages[i], downloadFormat);
65
+ ext = downloadFormat;
66
+ }
67
+
68
+ return { index: i, blob, ext };
69
+ } catch (error) {
70
+ console.error(`Error processing page ${i + 1}:`, error);
71
+ return null;
72
+ }
73
+ })();
74
+
75
+ batchPromises.push(promise);
76
+ }
77
+
78
+ const results = await Promise.all(batchPromises);
79
+
80
+ for (const result of results) {
81
+ if (result) {
82
+ zip.file(`pagina_${(result.index + 1).toString().padStart(3, '0')}.${result.ext}`, result.blob);
83
+ }
84
+ }
85
+
86
+ const progress = Math.round(((batchEnd / pages.length) * 100));
87
+ onProgress?.(progress);
88
+ }
89
+
90
+ const content = await zip.generateAsync({ type: 'blob' });
91
+ const url = URL.createObjectURL(content);
92
+ const a = document.createElement('a');
93
+ a.href = url;
94
+ const formatLabel = downloadFormat === 'original' ? 'original' : downloadFormat.toUpperCase();
95
+ a.download = `${mangaTitle.replace(/[^a-z0-9]/gi, '_')}_${formatLabel}.zip`;
96
+ document.body.appendChild(a);
97
+ a.click();
98
+ document.body.removeChild(a);
99
+ URL.revokeObjectURL(url);
100
+ }
src/utils/imageOptimization.ts CHANGED
@@ -1,326 +1,326 @@
1
- export interface OptimizedImage {
2
- thumbnail: string;
3
- original: string;
4
- webpDisplay: string;
5
- webpCover: string;
6
- originalFormat: string;
7
- originalBase64: string;
8
- originalUnmodified: string;
9
- }
10
-
11
- const MAX_FILE_SIZE = 5 * 1024 * 1024;
12
- const QUALITY = 0.8;
13
- const WEBP_QUALITY = 0.85;
14
- const THUMBNAIL_WIDTH = 400;
15
- const DISPLAY_WIDTH = 1200;
16
-
17
- export async function compressImage(file: File): Promise<string> {
18
- return new Promise((resolve, reject) => {
19
- const reader = new FileReader();
20
-
21
- reader.onload = (e) => {
22
- const img = new Image();
23
- img.onload = () => {
24
- const canvas = document.createElement('canvas');
25
- const ctx = canvas.getContext('2d');
26
-
27
- if (!ctx) {
28
- reject(new Error('Failed to get canvas context'));
29
- return;
30
- }
31
-
32
- let width = img.width;
33
- let height = img.height;
34
-
35
- if (width > DISPLAY_WIDTH) {
36
- height = (height * DISPLAY_WIDTH) / width;
37
- width = DISPLAY_WIDTH;
38
- }
39
-
40
- canvas.width = width;
41
- canvas.height = height;
42
-
43
- ctx.imageSmoothingEnabled = true;
44
- ctx.imageSmoothingQuality = 'high';
45
- ctx.drawImage(img, 0, 0, width, height);
46
-
47
- const mimeType = file.type === 'image/png' ? 'image/png' :
48
- file.type === 'image/jpeg' || file.type === 'image/jpg' ? 'image/jpeg' :
49
- file.type === 'image/gif' ? 'image/gif' :
50
- file.type === 'image/webp' ? 'image/webp' : 'image/png';
51
-
52
- let quality = QUALITY;
53
- let compressed = canvas.toDataURL(mimeType, quality);
54
-
55
- while (compressed.length > MAX_FILE_SIZE && quality > 0.4) {
56
- quality -= 0.05;
57
- compressed = canvas.toDataURL(mimeType, quality);
58
- }
59
-
60
- resolve(compressed);
61
- };
62
-
63
- img.onerror = () => reject(new Error('Failed to load image'));
64
- img.src = e.target?.result as string;
65
- };
66
-
67
- reader.onerror = () => reject(new Error('Failed to read file'));
68
- reader.readAsDataURL(file);
69
- });
70
- }
71
-
72
- export async function generateThumbnail(file: File): Promise<string> {
73
- return new Promise((resolve, reject) => {
74
- const reader = new FileReader();
75
-
76
- reader.onload = (e) => {
77
- const img = new Image();
78
- img.onload = () => {
79
- const canvas = document.createElement('canvas');
80
- const ctx = canvas.getContext('2d', { willReadFrequently: false });
81
-
82
- if (!ctx) {
83
- reject(new Error('Failed to get canvas context'));
84
- return;
85
- }
86
-
87
- let width = img.width;
88
- let height = img.height;
89
-
90
- if (width > THUMBNAIL_WIDTH) {
91
- height = (height * THUMBNAIL_WIDTH) / width;
92
- width = THUMBNAIL_WIDTH;
93
- }
94
-
95
- canvas.width = width;
96
- canvas.height = height;
97
-
98
- ctx.imageSmoothingEnabled = true;
99
- ctx.imageSmoothingQuality = 'high';
100
- ctx.drawImage(img, 0, 0, width, height);
101
-
102
- const mimeType = file.type === 'image/png' ? 'image/png' :
103
- file.type === 'image/jpeg' || file.type === 'image/jpg' ? 'image/jpeg' :
104
- file.type === 'image/gif' ? 'image/gif' :
105
- file.type === 'image/webp' ? 'image/webp' : 'image/png';
106
-
107
- const thumbnail = canvas.toDataURL(mimeType, 0.85);
108
-
109
- resolve(thumbnail);
110
- };
111
-
112
- img.onerror = () => reject(new Error('Failed to load image'));
113
- img.src = e.target?.result as string;
114
- };
115
-
116
- reader.onerror = () => reject(new Error('Failed to read file'));
117
- reader.readAsDataURL(file);
118
- });
119
- }
120
-
121
- export async function getOriginalBase64(file: File): Promise<string> {
122
- return new Promise((resolve, reject) => {
123
- const reader = new FileReader();
124
- reader.onload = (e) => resolve(e.target?.result as string);
125
- reader.onerror = () => reject(new Error('Failed to read file'));
126
- reader.readAsDataURL(file);
127
- });
128
- }
129
-
130
- export function getFileExtension(file: File): string {
131
- const mimeType = file.type;
132
- if (mimeType === 'image/png') return 'png';
133
- if (mimeType === 'image/jpeg') return 'jpg';
134
- if (mimeType === 'image/gif') return 'gif';
135
- if (mimeType === 'image/webp') return 'webp';
136
-
137
- const ext = file.name.split('.').pop()?.toLowerCase();
138
- if (ext && ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {
139
- return ext === 'jpeg' ? 'jpg' : ext;
140
- }
141
-
142
- return 'jpg';
143
- }
144
-
145
- export async function generateWebPDisplay(file: File): Promise<string> {
146
- return new Promise((resolve, reject) => {
147
- const reader = new FileReader();
148
-
149
- reader.onload = (e) => {
150
- const img = new Image();
151
- img.onload = () => {
152
- const canvas = document.createElement('canvas');
153
- const ctx = canvas.getContext('2d');
154
-
155
- if (!ctx) {
156
- reject(new Error('Failed to get canvas context'));
157
- return;
158
- }
159
-
160
- let width = img.width;
161
- let height = img.height;
162
-
163
- if (width > DISPLAY_WIDTH) {
164
- height = (height * DISPLAY_WIDTH) / width;
165
- width = DISPLAY_WIDTH;
166
- }
167
-
168
- canvas.width = width;
169
- canvas.height = height;
170
-
171
- ctx.imageSmoothingEnabled = true;
172
- ctx.imageSmoothingQuality = 'high';
173
- ctx.drawImage(img, 0, 0, width, height);
174
-
175
- const webp = canvas.toDataURL('image/webp', 0.90);
176
- resolve(webp);
177
- };
178
-
179
- img.onerror = () => reject(new Error('Failed to load image'));
180
- img.src = e.target?.result as string;
181
- };
182
-
183
- reader.onerror = () => reject(new Error('Failed to read file'));
184
- reader.readAsDataURL(file);
185
- });
186
- }
187
-
188
- export async function generateWebPCover(file: File): Promise<string> {
189
- return new Promise((resolve, reject) => {
190
- const reader = new FileReader();
191
-
192
- reader.onload = (e) => {
193
- const img = new Image();
194
- img.onload = () => {
195
- const canvas = document.createElement('canvas');
196
- const ctx = canvas.getContext('2d');
197
-
198
- if (!ctx) {
199
- reject(new Error('Failed to get canvas context'));
200
- return;
201
- }
202
-
203
- let width = img.width;
204
- let height = img.height;
205
- const MAX_COVER_SIZE = 2000;
206
-
207
- if (width > MAX_COVER_SIZE || height > MAX_COVER_SIZE) {
208
- if (width > height) {
209
- height = (height * MAX_COVER_SIZE) / width;
210
- width = MAX_COVER_SIZE;
211
- } else {
212
- width = (width * MAX_COVER_SIZE) / height;
213
- height = MAX_COVER_SIZE;
214
- }
215
- }
216
-
217
- canvas.width = width;
218
- canvas.height = height;
219
-
220
- ctx.imageSmoothingEnabled = true;
221
- ctx.imageSmoothingQuality = 'high';
222
- ctx.drawImage(img, 0, 0, width, height);
223
-
224
- const webp = canvas.toDataURL('image/webp', 0.95);
225
- resolve(webp);
226
- };
227
-
228
- img.onerror = () => reject(new Error('Failed to load image'));
229
- img.src = e.target?.result as string;
230
- };
231
-
232
- reader.onerror = () => reject(new Error('Failed to read file'));
233
- reader.readAsDataURL(file);
234
- });
235
- }
236
-
237
- export async function processImage(file: File): Promise<OptimizedImage> {
238
- const [thumbnail, original, webpDisplay, webpCover, originalBase64] = await Promise.all([
239
- generateThumbnail(file),
240
- compressImage(file),
241
- generateWebPDisplay(file),
242
- generateWebPCover(file),
243
- getOriginalBase64(file),
244
- ]);
245
-
246
- const originalFormat = getFileExtension(file);
247
- const originalUnmodified = originalBase64;
248
-
249
- return { thumbnail, original, webpDisplay, webpCover, originalFormat, originalBase64, originalUnmodified };
250
- }
251
-
252
- export async function convertImageToFormat(
253
- imageUrl: string,
254
- format: 'png' | 'jpg' | 'webp',
255
- quality: number = 0.92
256
- ): Promise<Blob> {
257
- return new Promise((resolve, reject) => {
258
- const img = new Image();
259
- img.crossOrigin = 'anonymous';
260
-
261
- img.onload = () => {
262
- const canvas = document.createElement('canvas');
263
- canvas.width = img.width;
264
- canvas.height = img.height;
265
-
266
- const ctx = canvas.getContext('2d');
267
- if (!ctx) {
268
- reject(new Error('Failed to get canvas context'));
269
- return;
270
- }
271
-
272
- ctx.imageSmoothingEnabled = true;
273
- ctx.imageSmoothingQuality = 'high';
274
- ctx.drawImage(img, 0, 0);
275
-
276
- const mimeType = format === 'png' ? 'image/png' :
277
- format === 'jpg' ? 'image/jpeg' :
278
- 'image/webp';
279
-
280
- canvas.toBlob(
281
- (blob) => {
282
- if (blob) {
283
- resolve(blob);
284
- } else {
285
- reject(new Error('Failed to create blob'));
286
- }
287
- },
288
- mimeType,
289
- quality
290
- );
291
- };
292
-
293
- img.onerror = () => reject(new Error('Failed to load image'));
294
- img.src = imageUrl;
295
- });
296
- }
297
-
298
- export function createImageElement(src: string, alt: string): HTMLImageElement {
299
- const img = document.createElement('img');
300
- img.src = src;
301
- img.alt = alt;
302
- img.loading = 'lazy';
303
- img.decoding = 'async';
304
- return img;
305
- }
306
-
307
- export async function detectImageOrientation(imageUrl: string): Promise<'portrait' | 'landscape' | 'square'> {
308
- return new Promise((resolve, reject) => {
309
- const img = new Image();
310
- img.crossOrigin = 'anonymous';
311
-
312
- img.onload = () => {
313
- const aspectRatio = img.width / img.height;
314
- if (aspectRatio < 0.9) {
315
- resolve('portrait');
316
- } else if (aspectRatio > 1.1) {
317
- resolve('landscape');
318
- } else {
319
- resolve('square');
320
- }
321
- };
322
-
323
- img.onerror = () => reject(new Error('Failed to load image for orientation detection'));
324
- img.src = imageUrl;
325
- });
326
- }
 
1
+ export interface OptimizedImage {
2
+ thumbnail: string;
3
+ original: string;
4
+ webpDisplay: string;
5
+ webpCover: string;
6
+ originalFormat: string;
7
+ originalBase64: string;
8
+ originalUnmodified: string;
9
+ }
10
+
11
+ const MAX_FILE_SIZE = 5 * 1024 * 1024;
12
+ const QUALITY = 0.8;
13
+ const WEBP_QUALITY = 0.85;
14
+ const THUMBNAIL_WIDTH = 400;
15
+ const DISPLAY_WIDTH = 1200;
16
+
17
+ export async function compressImage(file: File): Promise<string> {
18
+ return new Promise((resolve, reject) => {
19
+ const reader = new FileReader();
20
+
21
+ reader.onload = (e) => {
22
+ const img = new Image();
23
+ img.onload = () => {
24
+ const canvas = document.createElement('canvas');
25
+ const ctx = canvas.getContext('2d');
26
+
27
+ if (!ctx) {
28
+ reject(new Error('Failed to get canvas context'));
29
+ return;
30
+ }
31
+
32
+ let width = img.width;
33
+ let height = img.height;
34
+
35
+ if (width > DISPLAY_WIDTH) {
36
+ height = (height * DISPLAY_WIDTH) / width;
37
+ width = DISPLAY_WIDTH;
38
+ }
39
+
40
+ canvas.width = width;
41
+ canvas.height = height;
42
+
43
+ ctx.imageSmoothingEnabled = true;
44
+ ctx.imageSmoothingQuality = 'high';
45
+ ctx.drawImage(img, 0, 0, width, height);
46
+
47
+ const mimeType = file.type === 'image/png' ? 'image/png' :
48
+ file.type === 'image/jpeg' || file.type === 'image/jpg' ? 'image/jpeg' :
49
+ file.type === 'image/gif' ? 'image/gif' :
50
+ file.type === 'image/webp' ? 'image/webp' : 'image/png';
51
+
52
+ let quality = QUALITY;
53
+ let compressed = canvas.toDataURL(mimeType, quality);
54
+
55
+ while (compressed.length > MAX_FILE_SIZE && quality > 0.4) {
56
+ quality -= 0.05;
57
+ compressed = canvas.toDataURL(mimeType, quality);
58
+ }
59
+
60
+ resolve(compressed);
61
+ };
62
+
63
+ img.onerror = () => reject(new Error('Failed to load image'));
64
+ img.src = e.target?.result as string;
65
+ };
66
+
67
+ reader.onerror = () => reject(new Error('Failed to read file'));
68
+ reader.readAsDataURL(file);
69
+ });
70
+ }
71
+
72
+ export async function generateThumbnail(file: File): Promise<string> {
73
+ return new Promise((resolve, reject) => {
74
+ const reader = new FileReader();
75
+
76
+ reader.onload = (e) => {
77
+ const img = new Image();
78
+ img.onload = () => {
79
+ const canvas = document.createElement('canvas');
80
+ const ctx = canvas.getContext('2d', { willReadFrequently: false });
81
+
82
+ if (!ctx) {
83
+ reject(new Error('Failed to get canvas context'));
84
+ return;
85
+ }
86
+
87
+ let width = img.width;
88
+ let height = img.height;
89
+
90
+ if (width > THUMBNAIL_WIDTH) {
91
+ height = (height * THUMBNAIL_WIDTH) / width;
92
+ width = THUMBNAIL_WIDTH;
93
+ }
94
+
95
+ canvas.width = width;
96
+ canvas.height = height;
97
+
98
+ ctx.imageSmoothingEnabled = true;
99
+ ctx.imageSmoothingQuality = 'high';
100
+ ctx.drawImage(img, 0, 0, width, height);
101
+
102
+ const mimeType = file.type === 'image/png' ? 'image/png' :
103
+ file.type === 'image/jpeg' || file.type === 'image/jpg' ? 'image/jpeg' :
104
+ file.type === 'image/gif' ? 'image/gif' :
105
+ file.type === 'image/webp' ? 'image/webp' : 'image/png';
106
+
107
+ const thumbnail = canvas.toDataURL(mimeType, 0.85);
108
+
109
+ resolve(thumbnail);
110
+ };
111
+
112
+ img.onerror = () => reject(new Error('Failed to load image'));
113
+ img.src = e.target?.result as string;
114
+ };
115
+
116
+ reader.onerror = () => reject(new Error('Failed to read file'));
117
+ reader.readAsDataURL(file);
118
+ });
119
+ }
120
+
121
+ export async function getOriginalBase64(file: File): Promise<string> {
122
+ return new Promise((resolve, reject) => {
123
+ const reader = new FileReader();
124
+ reader.onload = (e) => resolve(e.target?.result as string);
125
+ reader.onerror = () => reject(new Error('Failed to read file'));
126
+ reader.readAsDataURL(file);
127
+ });
128
+ }
129
+
130
+ export function getFileExtension(file: File): string {
131
+ const mimeType = file.type;
132
+ if (mimeType === 'image/png') return 'png';
133
+ if (mimeType === 'image/jpeg') return 'jpg';
134
+ if (mimeType === 'image/gif') return 'gif';
135
+ if (mimeType === 'image/webp') return 'webp';
136
+
137
+ const ext = file.name.split('.').pop()?.toLowerCase();
138
+ if (ext && ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {
139
+ return ext === 'jpeg' ? 'jpg' : ext;
140
+ }
141
+
142
+ return 'jpg';
143
+ }
144
+
145
+ export async function generateWebPDisplay(file: File): Promise<string> {
146
+ return new Promise((resolve, reject) => {
147
+ const reader = new FileReader();
148
+
149
+ reader.onload = (e) => {
150
+ const img = new Image();
151
+ img.onload = () => {
152
+ const canvas = document.createElement('canvas');
153
+ const ctx = canvas.getContext('2d');
154
+
155
+ if (!ctx) {
156
+ reject(new Error('Failed to get canvas context'));
157
+ return;
158
+ }
159
+
160
+ let width = img.width;
161
+ let height = img.height;
162
+
163
+ if (width > DISPLAY_WIDTH) {
164
+ height = (height * DISPLAY_WIDTH) / width;
165
+ width = DISPLAY_WIDTH;
166
+ }
167
+
168
+ canvas.width = width;
169
+ canvas.height = height;
170
+
171
+ ctx.imageSmoothingEnabled = true;
172
+ ctx.imageSmoothingQuality = 'high';
173
+ ctx.drawImage(img, 0, 0, width, height);
174
+
175
+ const webp = canvas.toDataURL('image/webp', 0.90);
176
+ resolve(webp);
177
+ };
178
+
179
+ img.onerror = () => reject(new Error('Failed to load image'));
180
+ img.src = e.target?.result as string;
181
+ };
182
+
183
+ reader.onerror = () => reject(new Error('Failed to read file'));
184
+ reader.readAsDataURL(file);
185
+ });
186
+ }
187
+
188
+ export async function generateWebPCover(file: File): Promise<string> {
189
+ return new Promise((resolve, reject) => {
190
+ const reader = new FileReader();
191
+
192
+ reader.onload = (e) => {
193
+ const img = new Image();
194
+ img.onload = () => {
195
+ const canvas = document.createElement('canvas');
196
+ const ctx = canvas.getContext('2d');
197
+
198
+ if (!ctx) {
199
+ reject(new Error('Failed to get canvas context'));
200
+ return;
201
+ }
202
+
203
+ let width = img.width;
204
+ let height = img.height;
205
+ const MAX_COVER_SIZE = 2000;
206
+
207
+ if (width > MAX_COVER_SIZE || height > MAX_COVER_SIZE) {
208
+ if (width > height) {
209
+ height = (height * MAX_COVER_SIZE) / width;
210
+ width = MAX_COVER_SIZE;
211
+ } else {
212
+ width = (width * MAX_COVER_SIZE) / height;
213
+ height = MAX_COVER_SIZE;
214
+ }
215
+ }
216
+
217
+ canvas.width = width;
218
+ canvas.height = height;
219
+
220
+ ctx.imageSmoothingEnabled = true;
221
+ ctx.imageSmoothingQuality = 'high';
222
+ ctx.drawImage(img, 0, 0, width, height);
223
+
224
+ const webp = canvas.toDataURL('image/webp', 0.95);
225
+ resolve(webp);
226
+ };
227
+
228
+ img.onerror = () => reject(new Error('Failed to load image'));
229
+ img.src = e.target?.result as string;
230
+ };
231
+
232
+ reader.onerror = () => reject(new Error('Failed to read file'));
233
+ reader.readAsDataURL(file);
234
+ });
235
+ }
236
+
237
+ export async function processImage(file: File): Promise<OptimizedImage> {
238
+ const [thumbnail, original, webpDisplay, webpCover, originalBase64] = await Promise.all([
239
+ generateThumbnail(file),
240
+ compressImage(file),
241
+ generateWebPDisplay(file),
242
+ generateWebPCover(file),
243
+ getOriginalBase64(file),
244
+ ]);
245
+
246
+ const originalFormat = getFileExtension(file);
247
+ const originalUnmodified = originalBase64;
248
+
249
+ return { thumbnail, original, webpDisplay, webpCover, originalFormat, originalBase64, originalUnmodified };
250
+ }
251
+
252
+ export async function convertImageToFormat(
253
+ imageUrl: string,
254
+ format: 'png' | 'jpg' | 'webp',
255
+ quality: number = 0.92
256
+ ): Promise<Blob> {
257
+ return new Promise((resolve, reject) => {
258
+ const img = new Image();
259
+ img.crossOrigin = 'anonymous';
260
+
261
+ img.onload = () => {
262
+ const canvas = document.createElement('canvas');
263
+ canvas.width = img.width;
264
+ canvas.height = img.height;
265
+
266
+ const ctx = canvas.getContext('2d');
267
+ if (!ctx) {
268
+ reject(new Error('Failed to get canvas context'));
269
+ return;
270
+ }
271
+
272
+ ctx.imageSmoothingEnabled = true;
273
+ ctx.imageSmoothingQuality = 'high';
274
+ ctx.drawImage(img, 0, 0);
275
+
276
+ const mimeType = format === 'png' ? 'image/png' :
277
+ format === 'jpg' ? 'image/jpeg' :
278
+ 'image/webp';
279
+
280
+ canvas.toBlob(
281
+ (blob) => {
282
+ if (blob) {
283
+ resolve(blob);
284
+ } else {
285
+ reject(new Error('Failed to create blob'));
286
+ }
287
+ },
288
+ mimeType,
289
+ quality
290
+ );
291
+ };
292
+
293
+ img.onerror = () => reject(new Error('Failed to load image'));
294
+ img.src = imageUrl;
295
+ });
296
+ }
297
+
298
+ export function createImageElement(src: string, alt: string): HTMLImageElement {
299
+ const img = document.createElement('img');
300
+ img.src = src;
301
+ img.alt = alt;
302
+ img.loading = 'lazy';
303
+ img.decoding = 'async';
304
+ return img;
305
+ }
306
+
307
+ export async function detectImageOrientation(imageUrl: string): Promise<'portrait' | 'landscape' | 'square'> {
308
+ return new Promise((resolve, reject) => {
309
+ const img = new Image();
310
+ img.crossOrigin = 'anonymous';
311
+
312
+ img.onload = () => {
313
+ const aspectRatio = img.width / img.height;
314
+ if (aspectRatio < 0.9) {
315
+ resolve('portrait');
316
+ } else if (aspectRatio > 1.1) {
317
+ resolve('landscape');
318
+ } else {
319
+ resolve('square');
320
+ }
321
+ };
322
+
323
+ img.onerror = () => reject(new Error('Failed to load image for orientation detection'));
324
+ img.src = imageUrl;
325
+ });
326
+ }
src/utils/pdfHelpers.ts CHANGED
@@ -1,77 +1,77 @@
1
- import jsPDF from 'jspdf';
2
- import { convertImageToFormat } from './imageOptimization';
3
-
4
- export async function generatePDFFromPages(
5
- pages: string[],
6
- formats: string[],
7
- mangaTitle: string,
8
- downloadFormat: 'png' | 'jpg' | 'webp' | 'original',
9
- onProgress?: (progress: number) => void
10
- ): Promise<void> {
11
- const pdf = new jsPDF({
12
- orientation: 'portrait',
13
- unit: 'px',
14
- format: [1, 1],
15
- compress: true,
16
- });
17
-
18
- let isFirstPage = true;
19
-
20
- for (let i = 0; i < pages.length; i++) {
21
- try {
22
- let imageData: string;
23
-
24
- if (downloadFormat === 'original') {
25
- const response = await fetch(pages[i]);
26
- const blob = await response.blob();
27
- imageData = await blobToBase64(blob);
28
- } else {
29
- const blob = await convertImageToFormat(pages[i], downloadFormat);
30
- imageData = await blobToBase64(blob);
31
- }
32
-
33
- const img = await loadImage(imageData);
34
- const imgWidth = img.width;
35
- const imgHeight = img.height;
36
-
37
- if (isFirstPage) {
38
- pdf.internal.pageSize.setWidth(imgWidth);
39
- pdf.internal.pageSize.setHeight(imgHeight);
40
- isFirstPage = false;
41
- } else {
42
- pdf.addPage([imgWidth, imgHeight]);
43
- }
44
-
45
- const format = downloadFormat === 'original' ? (formats[i] === 'jpg' ? 'JPEG' : 'PNG') :
46
- downloadFormat === 'jpg' ? 'JPEG' : 'PNG';
47
-
48
- pdf.addImage(imageData, format, 0, 0, imgWidth, imgHeight);
49
-
50
- const progress = Math.round(((i + 1) / pages.length) * 100);
51
- onProgress?.(progress);
52
- } catch (error) {
53
- console.error(`Error processing page ${i + 1}:`, error);
54
- }
55
- }
56
-
57
- const formatLabel = downloadFormat === 'original' ? 'original' : downloadFormat.toUpperCase();
58
- pdf.save(`${mangaTitle.replace(/[^a-z0-9]/gi, '_')}_${formatLabel}.pdf`);
59
- }
60
-
61
- function blobToBase64(blob: Blob): Promise<string> {
62
- return new Promise((resolve, reject) => {
63
- const reader = new FileReader();
64
- reader.onloadend = () => resolve(reader.result as string);
65
- reader.onerror = reject;
66
- reader.readAsDataURL(blob);
67
- });
68
- }
69
-
70
- function loadImage(src: string): Promise<HTMLImageElement> {
71
- return new Promise((resolve, reject) => {
72
- const img = new Image();
73
- img.onload = () => resolve(img);
74
- img.onerror = reject;
75
- img.src = src;
76
- });
77
- }
 
1
+ import jsPDF from 'jspdf';
2
+ import { convertImageToFormat } from './imageOptimization';
3
+
4
+ export async function generatePDFFromPages(
5
+ pages: string[],
6
+ formats: string[],
7
+ mangaTitle: string,
8
+ downloadFormat: 'png' | 'jpg' | 'webp' | 'original',
9
+ onProgress?: (progress: number) => void
10
+ ): Promise<void> {
11
+ const pdf = new jsPDF({
12
+ orientation: 'portrait',
13
+ unit: 'px',
14
+ format: [1, 1],
15
+ compress: true,
16
+ });
17
+
18
+ let isFirstPage = true;
19
+
20
+ for (let i = 0; i < pages.length; i++) {
21
+ try {
22
+ let imageData: string;
23
+
24
+ if (downloadFormat === 'original') {
25
+ const response = await fetch(pages[i]);
26
+ const blob = await response.blob();
27
+ imageData = await blobToBase64(blob);
28
+ } else {
29
+ const blob = await convertImageToFormat(pages[i], downloadFormat);
30
+ imageData = await blobToBase64(blob);
31
+ }
32
+
33
+ const img = await loadImage(imageData);
34
+ const imgWidth = img.width;
35
+ const imgHeight = img.height;
36
+
37
+ if (isFirstPage) {
38
+ pdf.internal.pageSize.setWidth(imgWidth);
39
+ pdf.internal.pageSize.setHeight(imgHeight);
40
+ isFirstPage = false;
41
+ } else {
42
+ pdf.addPage([imgWidth, imgHeight]);
43
+ }
44
+
45
+ const format = downloadFormat === 'original' ? (formats[i] === 'jpg' ? 'JPEG' : 'PNG') :
46
+ downloadFormat === 'jpg' ? 'JPEG' : 'PNG';
47
+
48
+ pdf.addImage(imageData, format, 0, 0, imgWidth, imgHeight);
49
+
50
+ const progress = Math.round(((i + 1) / pages.length) * 100);
51
+ onProgress?.(progress);
52
+ } catch (error) {
53
+ console.error(`Error processing page ${i + 1}:`, error);
54
+ }
55
+ }
56
+
57
+ const formatLabel = downloadFormat === 'original' ? 'original' : downloadFormat.toUpperCase();
58
+ pdf.save(`${mangaTitle.replace(/[^a-z0-9]/gi, '_')}_${formatLabel}.pdf`);
59
+ }
60
+
61
+ function blobToBase64(blob: Blob): Promise<string> {
62
+ return new Promise((resolve, reject) => {
63
+ const reader = new FileReader();
64
+ reader.onloadend = () => resolve(reader.result as string);
65
+ reader.onerror = reject;
66
+ reader.readAsDataURL(blob);
67
+ });
68
+ }
69
+
70
+ function loadImage(src: string): Promise<HTMLImageElement> {
71
+ return new Promise((resolve, reject) => {
72
+ const img = new Image();
73
+ img.onload = () => resolve(img);
74
+ img.onerror = reject;
75
+ img.src = src;
76
+ });
77
+ }
src/utils/searchUtils.ts CHANGED
@@ -1,104 +1,104 @@
1
- export interface SearchOptions {
2
- caseSensitive?: boolean;
3
- fuzzyMatch?: boolean;
4
- minChars?: number;
5
- }
6
-
7
- function normalizeString(str: string): string {
8
- return str
9
- .toLowerCase()
10
- .trim()
11
- .normalize('NFD')
12
- .replace(/[\u0300-\u036f]/g, '');
13
- }
14
-
15
- function calculateSimilarity(str1: string, str2: string): number {
16
- const s1 = normalizeString(str1);
17
- const s2 = normalizeString(str2);
18
-
19
- if (s1 === s2) return 1;
20
- if (s1.length < 2 || s2.length < 2) return s1.includes(s2) ? 0.8 : 0;
21
-
22
- const longer = s1.length > s2.length ? s1 : s2;
23
- const shorter = s1.length > s2.length ? s2 : s1;
24
-
25
- const editDistance = getLevenshteinDistance(shorter, longer);
26
- return (longer.length - editDistance) / longer.length;
27
- }
28
-
29
- function getLevenshteinDistance(s1: string, s2: string): number {
30
- const costs = [];
31
- for (let i = 0; i <= s1.length; i++) {
32
- let lastValue = i;
33
- for (let j = 0; j <= s2.length; j++) {
34
- if (i === 0) {
35
- costs[j] = j;
36
- } else if (j > 0) {
37
- let newValue = costs[j - 1];
38
- if (s1.charAt(i - 1) !== s2.charAt(j - 1)) {
39
- newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
40
- }
41
- costs[j - 1] = lastValue;
42
- lastValue = newValue;
43
- }
44
- }
45
- if (i > 0) costs[s2.length] = lastValue;
46
- }
47
- return costs[s2.length];
48
- }
49
-
50
- export interface SearchableItem {
51
- id: string;
52
- title: string;
53
- author: string;
54
- [key: string]: any;
55
- }
56
-
57
- export function searchItems<T extends SearchableItem>(
58
- items: T[],
59
- query: string,
60
- options: SearchOptions = {}
61
- ): { items: T[]; query: string; resultCount: number } {
62
- const { minChars = 1, fuzzyMatch = true } = options;
63
-
64
- if (!query.trim() || query.length < minChars) {
65
- return { items, query, resultCount: items.length };
66
- }
67
-
68
- const normalizedQuery = normalizeString(query);
69
-
70
- const results = items
71
- .map((item) => {
72
- let score = 0;
73
-
74
- const titleScore = calculateSimilarity(item.title, query);
75
- const authorScore = calculateSimilarity(item.author, query);
76
-
77
- const titleExactMatch = normalizeString(item.title).includes(normalizedQuery) ? 0.3 : 0;
78
- const authorExactMatch = normalizeString(item.author).includes(normalizedQuery) ? 0.2 : 0;
79
-
80
- score = Math.max(titleScore * 0.6 + titleExactMatch, authorScore * 0.4 + authorExactMatch);
81
-
82
- return { item, score };
83
- })
84
- .filter((result) => fuzzyMatch ? result.score > 0.3 : result.score > 0.7)
85
- .sort((a, b) => b.score - a.score)
86
- .map((result) => result.item);
87
-
88
- return { items: results, query, resultCount: results.length };
89
- }
90
-
91
- export function debounce<T extends (...args: any[]) => any>(
92
- func: T,
93
- wait: number
94
- ): (...args: Parameters<T>) => void {
95
- let timeout: NodeJS.Timeout;
96
- return function executedFunction(...args: Parameters<T>) {
97
- const later = () => {
98
- clearTimeout(timeout);
99
- func(...args);
100
- };
101
- clearTimeout(timeout);
102
- timeout = setTimeout(later, wait);
103
- };
104
- }
 
1
+ export interface SearchOptions {
2
+ caseSensitive?: boolean;
3
+ fuzzyMatch?: boolean;
4
+ minChars?: number;
5
+ }
6
+
7
+ function normalizeString(str: string): string {
8
+ return str
9
+ .toLowerCase()
10
+ .trim()
11
+ .normalize('NFD')
12
+ .replace(/[\u0300-\u036f]/g, '');
13
+ }
14
+
15
+ function calculateSimilarity(str1: string, str2: string): number {
16
+ const s1 = normalizeString(str1);
17
+ const s2 = normalizeString(str2);
18
+
19
+ if (s1 === s2) return 1;
20
+ if (s1.length < 2 || s2.length < 2) return s1.includes(s2) ? 0.8 : 0;
21
+
22
+ const longer = s1.length > s2.length ? s1 : s2;
23
+ const shorter = s1.length > s2.length ? s2 : s1;
24
+
25
+ const editDistance = getLevenshteinDistance(shorter, longer);
26
+ return (longer.length - editDistance) / longer.length;
27
+ }
28
+
29
+ function getLevenshteinDistance(s1: string, s2: string): number {
30
+ const costs = [];
31
+ for (let i = 0; i <= s1.length; i++) {
32
+ let lastValue = i;
33
+ for (let j = 0; j <= s2.length; j++) {
34
+ if (i === 0) {
35
+ costs[j] = j;
36
+ } else if (j > 0) {
37
+ let newValue = costs[j - 1];
38
+ if (s1.charAt(i - 1) !== s2.charAt(j - 1)) {
39
+ newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
40
+ }
41
+ costs[j - 1] = lastValue;
42
+ lastValue = newValue;
43
+ }
44
+ }
45
+ if (i > 0) costs[s2.length] = lastValue;
46
+ }
47
+ return costs[s2.length];
48
+ }
49
+
50
+ export interface SearchableItem {
51
+ id: string;
52
+ title: string;
53
+ author: string;
54
+ [key: string]: any;
55
+ }
56
+
57
+ export function searchItems<T extends SearchableItem>(
58
+ items: T[],
59
+ query: string,
60
+ options: SearchOptions = {}
61
+ ): { items: T[]; query: string; resultCount: number } {
62
+ const { minChars = 1, fuzzyMatch = true } = options;
63
+
64
+ if (!query.trim() || query.length < minChars) {
65
+ return { items, query, resultCount: items.length };
66
+ }
67
+
68
+ const normalizedQuery = normalizeString(query);
69
+
70
+ const results = items
71
+ .map((item) => {
72
+ let score = 0;
73
+
74
+ const titleScore = calculateSimilarity(item.title, query);
75
+ const authorScore = calculateSimilarity(item.author, query);
76
+
77
+ const titleExactMatch = normalizeString(item.title).includes(normalizedQuery) ? 0.3 : 0;
78
+ const authorExactMatch = normalizeString(item.author).includes(normalizedQuery) ? 0.2 : 0;
79
+
80
+ score = Math.max(titleScore * 0.6 + titleExactMatch, authorScore * 0.4 + authorExactMatch);
81
+
82
+ return { item, score };
83
+ })
84
+ .filter((result) => fuzzyMatch ? result.score > 0.3 : result.score > 0.7)
85
+ .sort((a, b) => b.score - a.score)
86
+ .map((result) => result.item);
87
+
88
+ return { items: results, query, resultCount: results.length };
89
+ }
90
+
91
+ export function debounce<T extends (...args: any[]) => any>(
92
+ func: T,
93
+ wait: number
94
+ ): (...args: Parameters<T>) => void {
95
+ let timeout: NodeJS.Timeout;
96
+ return function executedFunction(...args: Parameters<T>) {
97
+ const later = () => {
98
+ clearTimeout(timeout);
99
+ func(...args);
100
+ };
101
+ clearTimeout(timeout);
102
+ timeout = setTimeout(later, wait);
103
+ };
104
+ }
src/vite-env.d.ts CHANGED
@@ -1,15 +1,15 @@
1
- /// <reference types="vite/client" />
2
-
3
- declare global {
4
- interface Window {
5
- Telegram: {
6
- WebApp: {
7
- ready: () => void;
8
- close: () => void;
9
- sendData: (data: string) => void;
10
- initData: string;
11
- initDataUnsafe: any;
12
- };
13
- };
14
- }
15
- }
 
1
+ /// <reference types="vite/client" />
2
+
3
+ declare global {
4
+ interface Window {
5
+ Telegram: {
6
+ WebApp: {
7
+ ready: () => void;
8
+ close: () => void;
9
+ sendData: (data: string) => void;
10
+ initData: string;
11
+ initDataUnsafe: any;
12
+ };
13
+ };
14
+ }
15
+ }