frontend js refactor

This commit is contained in:
2025-12-10 18:08:19 +01:00
parent 313ead0652
commit c54f034c61
20 changed files with 1936 additions and 2096 deletions

View File

@@ -1,277 +1,301 @@
const animeId = window.location.pathname.split('/').pop();
let player;
let animeData = null;
let extensionName = null;
let animeId = null;
let totalEpisodes = 0;
let currentPage = 1;
const itemsPerPage = 12;
const episodePagination = Object.create(PaginationManager);
episodePagination.init(12, renderEpisodes);
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
YouTubePlayerUtils.init('player');
let extensionName;
document.addEventListener('DOMContentLoaded', () => {
loadAnime();
setupDescriptionModal();
setupEpisodeSearch();
});
async function loadAnime() {
try {
const path = window.location.pathname;
const parts = path.split("/").filter(Boolean);
let animeId;
if (parts.length === 3) {
extensionName = parts[1];
animeId = parts[2];
} else {
animeId = parts[1];
const urlData = URLUtils.parseEntityPath('anime');
if (!urlData) {
showError("Invalid URL");
return;
}
extensionName = urlData.extensionName;
animeId = urlData.entityId;
const fetchUrl = extensionName
? `/api/anime/${animeId}?source=${extensionName}`
: `/api/anime/${animeId}?source=anilist`;
const res = await fetch(fetchUrl);
const res = await fetch(fetchUrl, { headers: AuthUtils.getSimpleAuthHeaders() });
const data = await res.json();
if (data.error) {
document.getElementById('title').innerText = "Anime Not Found";
showError("Anime Not Found");
return;
}
const title = data.title?.english || data.title?.romaji || data.title || "Unknown Title";
document.title = `${title} | WaifuBoard`;
document.getElementById('title').innerText = title;
animeData = data;
let posterUrl = '';
const metadata = MediaMetadataUtils.formatAnimeData(data, !!extensionName);
if (extensionName) {
posterUrl = data.image || '';
updatePageTitle(metadata.title);
updateMetadata(metadata);
updateDescription(data.description || data.summary);
updateCharacters(metadata.characters);
updateExtensionPill();
} else {
posterUrl = data.coverImage?.extraLarge || '';
}
setupWatchButton();
if (posterUrl) {
document.getElementById('poster').src = posterUrl;
}
const hasTrailer = YouTubePlayerUtils.playTrailer(
metadata.trailer,
'player',
metadata.banner
);
const rawDesc = data.description || data.summary || "No description available.";
handleDescription(rawDesc);
setupEpisodes(metadata.episodes);
const score = extensionName ? (data.score ? data.score * 10 : '?') : data.averageScore;
document.getElementById('score').innerText = (score || '?') + '% Score';
document.getElementById('year').innerText =
extensionName ? (data.year || '????') : (data.seasonYear || data.startDate?.year || '????');
document.getElementById('genres').innerText =
data.genres?.length > 0 ? data.genres.slice(0, 3).join(' • ') : '';
document.getElementById('format').innerText = data.format || 'TV';
document.getElementById('status').innerText = data.status || 'Unknown';
const extensionPill = document.getElementById('extension-pill');
if (extensionName && extensionPill) {
extensionPill.textContent = `${extensionName.charAt(0).toUpperCase() + extensionName.slice(1).toLowerCase()}`;
extensionPill.style.display = 'inline-flex';
} else if (extensionPill) {
extensionPill.style.display = 'none';
}
let seasonText = '';
if (extensionName) {
seasonText = data.season || 'Unknown';
} else {
if (data.season && data.seasonYear) {
seasonText = `${data.season} ${data.seasonYear}`;
} else if (data.startDate?.year) {
const months = ['', 'Winter', 'Winter', 'Spring', 'Spring', 'Spring', 'Summer', 'Summer', 'Summer', 'Fall', 'Fall', 'Fall', 'Winter'];
const month = data.startDate.month || 1;
const estimatedSeason = months[month] || '';
seasonText = `${estimatedSeason} ${data.startDate.year}`.trim();
}
}
document.getElementById('season').innerText = seasonText || 'Unknown';
const studio = extensionName
? data.studio || "Unknown"
: (data.studios?.nodes?.[0]?.name ||
data.studios?.edges?.[0]?.node?.name ||
'Unknown Studio');
document.getElementById('studio').innerText = studio;
const charContainer = document.getElementById('char-list');
charContainer.innerHTML = '';
let characters = [];
if (extensionName) {
characters = data.characters || [];
} else {
if (data.characters?.nodes?.length > 0) {
characters = data.characters.nodes.slice(0, 5);
} else if (data.characters?.edges?.length > 0) {
characters = data.characters.edges
.filter(edge => edge?.node?.name?.full)
.slice(0, 5)
.map(edge => edge.node);
}
}
if (characters.length > 0) {
characters.slice(0, 5).forEach(char => {
const name = char?.name?.full || char?.name;
if (name) {
charContainer.innerHTML += `
<div class="character-item">
<div class="char-dot"></div> ${name}
</div>`;
}
});
} else {
charContainer.innerHTML = `
<div class="character-item" style="color: #666;">
No character data available
</div>`;
}
document.getElementById('watch-btn').onclick = () => {
window.location.href = `/watch/${animeId}/1`;
};
if (data.trailer && data.trailer.site === 'youtube') {
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: data.trailer.id,
playerVars: {
autoplay: 1, controls: 0, mute: 1,
loop: 1, playlist: data.trailer.id,
showinfo: 0, modestbranding: 1, disablekb: 1
},
events: { onReady: (e) => e.target.playVideo() }
});
};
} else {
const banner = extensionName
? (data.image || '')
: (data.bannerImage || data.coverImage?.extraLarge || '');
if (banner) {
document.querySelector('.video-background').innerHTML =
`<img src="${banner}" style="width:100%; height:100%; object-fit:cover;">`;
}
}
if (extensionName) {
totalEpisodes = data.episodes || 1;
} else {
if (data.nextAiringEpisode?.episode) {
totalEpisodes = data.nextAiringEpisode.episode - 1;
} else if (data.episodes) {
totalEpisodes = data.episodes;
} else {
totalEpisodes = 12;
}
}
totalEpisodes = Math.min(Math.max(totalEpisodes, 1), 5000);
document.getElementById('episodes').innerText = totalEpisodes;
renderEpisodes();
await setupAddToListButton();
} catch (err) {
console.error('Error loading anime:', err);
document.getElementById('title').innerText = "Error loading anime";
showError("Error loading anime");
}
}
function handleDescription(text) {
const tmp = document.createElement("DIV");
tmp.innerHTML = text;
const cleanText = tmp.textContent || tmp.innerText || "";
function updatePageTitle(title) {
document.title = `${title} | WaifuBoard`;
document.getElementById('title').innerText = title;
}
const sentences = cleanText.match(/[^\.!\?]+[\.!\?]+/g) || [cleanText];
function updateMetadata(metadata) {
document.getElementById('full-description').innerHTML = text;
if (metadata.poster) {
document.getElementById('poster').src = metadata.poster;
}
if (sentences.length > 4) {
const shortText = sentences.slice(0, 4).join(' ');
document.getElementById('description-preview').innerText = shortText + '...';
document.getElementById('read-more-btn').style.display = 'inline-flex';
document.getElementById('score').innerText = `${metadata.score}% Score`;
document.getElementById('year').innerText = metadata.year;
document.getElementById('genres').innerText = metadata.genres;
document.getElementById('format').innerText = metadata.format;
document.getElementById('status').innerText = metadata.status;
document.getElementById('season').innerText = metadata.season;
document.getElementById('studio').innerText = metadata.studio;
document.getElementById('episodes').innerText = metadata.episodes;
}
function updateDescription(rawDescription) {
const desc = MediaMetadataUtils.truncateDescription(rawDescription, 4);
document.getElementById('description-preview').innerHTML = desc.short;
document.getElementById('full-description').innerHTML = desc.full;
const readMoreBtn = document.getElementById('read-more-btn');
if (desc.isTruncated) {
readMoreBtn.style.display = 'inline-flex';
} else {
document.getElementById('description-preview').innerHTML = text;
document.getElementById('read-more-btn').style.display = 'none';
readMoreBtn.style.display = 'none';
}
}
function openModal() {
document.getElementById('desc-modal').classList.add('active');
document.body.style.overflow = 'hidden';
function updateCharacters(characters) {
const container = document.getElementById('char-list');
container.innerHTML = '';
if (characters.length > 0) {
characters.forEach(char => {
container.innerHTML += `
<div class="character-item">
<div class="char-dot"></div> ${char.name}
</div>`;
});
} else {
container.innerHTML = `
<div class="character-item" style="color: #666;">
No character data available
</div>`;
}
}
function closeModal() {
document.getElementById('desc-modal').classList.remove('active');
document.body.style.overflow = '';
function updateExtensionPill() {
const pill = document.getElementById('extension-pill');
if (!pill) return;
if (extensionName) {
pill.textContent = extensionName.charAt(0).toUpperCase() + extensionName.slice(1).toLowerCase();
pill.style.display = 'inline-flex';
} else {
pill.style.display = 'none';
}
}
document.getElementById('desc-modal').addEventListener('click', (e) => {
if (e.target.id === 'desc-modal') closeModal();
});
function setupWatchButton() {
const watchBtn = document.getElementById('watch-btn');
if (watchBtn) {
watchBtn.onclick = () => {
const url = URLUtils.buildWatchUrl(animeId, 1, extensionName);
window.location.href = url;
};
}
}
async function setupAddToListButton() {
const btn = document.getElementById('add-to-list-btn');
if (!btn || !animeData) return;
ListModalManager.currentData = animeData;
const entryType = ListModalManager.getEntryType(animeData);
await ListModalManager.checkIfInList(animeId, extensionName || 'anilist', entryType);
const tempBtn = document.querySelector('.hero-buttons .btn-blur');
if (tempBtn) {
ListModalManager.updateButton('.hero-buttons .btn-blur');
} else {
updateCustomAddButton();
}
btn.onclick = () => ListModalManager.open(animeData, extensionName || 'anilist');
}
function updateCustomAddButton() {
const btn = document.getElementById('add-to-list-btn');
if (!btn) return;
if (ListModalManager.isInList) {
btn.innerHTML = `
<svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
In Your List
`;
btn.style.background = 'rgba(34, 197, 94, 0.2)';
btn.style.color = '#22c55e';
btn.style.borderColor = 'rgba(34, 197, 94, 0.3)';
} else {
btn.innerHTML = '+ Add to List';
btn.style.background = null;
btn.style.color = null;
btn.style.borderColor = null;
}
}
function setupEpisodes(totalEpisodes) {
const limitedTotal = Math.min(Math.max(totalEpisodes, 1), 5000);
episodePagination.setTotalItems(limitedTotal);
renderEpisodes();
}
function renderEpisodes() {
const grid = document.getElementById('episodes-grid');
if (!grid) return;
grid.innerHTML = '';
const start = (currentPage - 1) * itemsPerPage + 1;
const end = Math.min(start + itemsPerPage - 1, totalEpisodes);
const range = episodePagination.getPageRange();
const start = range.start + 1;
for(let i = start; i <= end; i++) {
const end = range.end;
for (let i = start; i <= end; i++) {
createEpisodeButton(i, grid);
}
updatePaginationControls();
episodePagination.renderControls(
'pagination-controls',
'page-info',
'prev-page',
'next-page'
);
}
function createEpisodeButton(num, container) {
const btn = document.createElement('div');
btn.className = 'episode-btn';
btn.innerText = `Ep ${num}`;
btn.onclick = () =>
window.location.href = `/watch/${animeId}/${num}` + (extensionName ? `?${extensionName}` : "");
btn.onclick = () => {
const url = URLUtils.buildWatchUrl(animeId, num, extensionName);
window.location.href = url;
};
container.appendChild(btn);
}
function updatePaginationControls() {
const totalPages = Math.ceil(totalEpisodes / itemsPerPage);
document.getElementById('page-info').innerText = `Page ${currentPage} of ${totalPages}`;
document.getElementById('prev-page').disabled = currentPage === 1;
document.getElementById('next-page').disabled = currentPage === totalPages;
function setupDescriptionModal() {
const modal = document.getElementById('desc-modal');
if (!modal) return;
document.getElementById('pagination-controls').style.display = 'flex';
modal.addEventListener('click', (e) => {
if (e.target.id === 'desc-modal') {
closeDescriptionModal();
}
});
}
function changePage(delta) {
currentPage += delta;
renderEpisodes();
function openDescriptionModal() {
document.getElementById('desc-modal').classList.add('active');
document.body.style.overflow = 'hidden';
}
const searchInput = document.getElementById('ep-search');
searchInput.addEventListener('input', (e) => {
const val = parseInt(e.target.value);
const grid = document.getElementById('episodes-grid');
function closeDescriptionModal() {
document.getElementById('desc-modal').classList.remove('active');
document.body.style.overflow = '';
}
if (val > 0 && val <= totalEpisodes) {
grid.innerHTML = '';
createEpisodeButton(val, grid);
document.getElementById('pagination-controls').style.display = 'none';
} else if (!e.target.value) {
renderEpisodes();
} else {
grid.innerHTML = '<div style="color:#666; width:100%; text-align:center;">Episode not found</div>';
document.getElementById('pagination-controls').style.display = 'none';
}
});
function setupEpisodeSearch() {
const searchInput = document.getElementById('ep-search');
if (!searchInput) return;
loadAnime();
searchInput.addEventListener('input', (e) => {
const val = parseInt(e.target.value);
const grid = document.getElementById('episodes-grid');
const totalEpisodes = episodePagination.totalItems;
if (val > 0 && val <= totalEpisodes) {
grid.innerHTML = '';
createEpisodeButton(val, grid);
document.getElementById('pagination-controls').style.display = 'none';
} else if (!e.target.value) {
renderEpisodes();
} else {
grid.innerHTML = '<div style="color:#666; width:100%; text-align:center;">Episode not found</div>';
document.getElementById('pagination-controls').style.display = 'none';
}
});
}
function showError(message) {
document.getElementById('title').innerText = message;
}
function saveToList() {
if (!animeId) return;
ListModalManager.save(animeId, extensionName || 'anilist');
}
function deleteFromList() {
if (!animeId) return;
ListModalManager.delete(animeId, extensionName || 'anilist');
}
function closeAddToListModal() {
ListModalManager.close();
}
window.openDescriptionModal = openDescriptionModal;
window.closeDescriptionModal = closeDescriptionModal;
window.changePage = (delta) => {
if (delta > 0) episodePagination.nextPage();
else episodePagination.prevPage();
};

View File

@@ -1,633 +1,320 @@
const searchInput = document.getElementById('search-input');
const searchResults = document.getElementById('search-results');
let searchTimeout;
let availableExtensions = [];
let currentAnimeData = null;
let isInList = false;
let currentListEntry = null;
let totalEpisodes = 0;
const API_BASE = '/api';
let currentList = [];
let filteredList = [];
function getAuthToken() {
return localStorage.getItem('token');
document.addEventListener('DOMContentLoaded', async () => {
await loadList();
setupEventListeners();
});
function getEntryLink(item) {
const isAnime = item.entry_type?.toUpperCase() === 'ANIME';
const baseRoute = isAnime ? '/anime' : '/book';
const source = item.source || 'anilist';
if (source === 'anilist') {
return `${baseRoute}/${item.entry_id}`;
} else {
return `${baseRoute}/${source}/${item.entry_id}`;
}
}
function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
async function populateSourceFilter() {
const select = document.getElementById('source-filter');
if (!select) return;
function getSimpleAuthHeaders() {
const token = getAuthToken();
return {
'Authorization': `Bearer ${token}`
};
}
function getTitle(anime) {
return anime.title.english || anime.title.romaji || "Unknown Title";
}
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#8b5cf6'};
color: white;
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
z-index: 9999;
font-weight: 600;
animation: slideInRight 0.3s ease;
select.innerHTML = `
<option value="all">All Sources</option>
<option value="anilist">AniList</option>
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from { transform: translateX(400px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOutRight {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(400px); opacity: 0; }
}
`;
document.head.appendChild(style);
async function checkIfInList(animeId) {
const source = 'anilist';
const entryType = 'ANIME';
const fetchUrl = `${API_BASE}/list/entry/${animeId}?source=${source}&entry_type=${entryType}`;
try {
const response = await fetch(fetchUrl, {
headers: getSimpleAuthHeaders()
});
const response = await fetch(`${API_BASE}/extensions`);
if (response.ok) {
const data = await response.json();
const extensions = data.extensions || [];
if (data.found && data.entry) {
isInList = true;
currentListEntry = data.entry;
} else {
isInList = false;
currentListEntry = null;
}
return true;
extensions.forEach(extName => {
if (extName.toLowerCase() !== 'anilist' && extName.toLowerCase() !== 'local') {
const option = document.createElement('option');
option.value = extName;
option.textContent = extName.charAt(0).toUpperCase() + extName.slice(1);
select.appendChild(option);
}
});
}
return false;
} catch (error) {
console.error('Error checking single list entry:', error);
return false;
console.error('Error loading extensions:', error);
}
}
function updateAddToListButton() {
const btn = document.querySelector('.hero-buttons .btn-blur');
if (!btn) return;
function setupEventListeners() {
if (isInList) {
btn.innerHTML = `
<svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
In Your List
`;
btn.style.background = 'rgba(34, 197, 94, 0.2)';
btn.style.color = '#22c55e';
btn.style.borderColor = 'rgba(34, 197, 94, 0.3)';
} else {
btn.innerHTML = '+ Add to List';
btn.style.background = null;
btn.style.color = null;
btn.style.borderColor = null;
}
document.querySelectorAll('.view-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const view = btn.dataset.view;
const container = document.getElementById('list-container');
if (view === 'list') {
container.classList.add('list-view');
} else {
container.classList.remove('list-view');
}
});
});
document.getElementById('status-filter').addEventListener('change', applyFilters);
document.getElementById('source-filter').addEventListener('change', applyFilters);
document.getElementById('type-filter').addEventListener('change', applyFilters);
document.getElementById('sort-filter').addEventListener('change', applyFilters);
document.querySelector('.search-input').addEventListener('input', (e) => {
const query = e.target.value.toLowerCase();
if (query) {
filteredList = currentList.filter(item =>
item.title?.toLowerCase().includes(query)
);
} else {
filteredList = [...currentList];
}
applyFilters();
});
document.getElementById('modal-save-btn')?.addEventListener('click', async () => {
const entryToSave = window.ListModalManager.currentEntry || window.ListModalManager.currentData;
if (!entryToSave) return;
await window.ListModalManager.save(entryToSave.entry_id, entryToSave.source);
await loadList();
});
document.getElementById('modal-delete-btn')?.addEventListener('click', async () => {
const entryToDelete = window.ListModalManager.currentEntry || window.ListModalManager.currentData;
if (!entryToDelete) return;
await window.ListModalManager.delete(entryToDelete.entry_id, entryToDelete.source);
await loadList();
});
document.getElementById('add-list-modal')?.addEventListener('click', (e) => {
if (e.target.id === 'add-list-modal') {
window.ListModalManager.close();
}
});
}
async function openAddToListModal() {
if (!getAuthToken()) {
showNotification('Please log in to manage your list.', 'error');
return;
}
if (!currentAnimeData) return;
async function loadList() {
const loadingState = document.getElementById('loading-state');
const emptyState = document.getElementById('empty-state');
const container = document.getElementById('list-container');
await checkIfInList(currentAnimeData.id);
const modalTitle = document.getElementById('modal-title');
const deleteBtn = document.getElementById('modal-delete-btn');
const statusEl = document.getElementById('entry-status');
const progressEl = document.getElementById('entry-progress');
const scoreEl = document.getElementById('entry-score');
const startDateEl = document.getElementById('entry-start-date');
const endDateEl = document.getElementById('entry-end-date');
const repeatCountEl = document.getElementById('entry-repeat-count');
const notesEl = document.getElementById('entry-notes');
const privateEl = document.getElementById('entry-is-private');
if (isInList && currentListEntry) {
const statusReverseMap = { CURRENT: 'WATCHING' };
statusEl.value = statusReverseMap[currentListEntry.status] || currentListEntry.status || 'PLANNING';
progressEl.value = currentListEntry.progress || 0;
scoreEl.value = currentListEntry.score || '';
startDateEl.value = currentListEntry.start_date ? currentListEntry.start_date.split('T')[0] : '';
endDateEl.value = currentListEntry.end_date ? currentListEntry.end_date.split('T')[0] : '';
repeatCountEl.value = currentListEntry.repeat_count || 0;
notesEl.value = currentListEntry.notes || '';
privateEl.checked = currentListEntry.is_private === true || currentListEntry.is_private === 1;
modalTitle.textContent = 'Edit List Entry';
deleteBtn.style.display = 'block';
} else {
statusEl.value = 'PLANNING';
progressEl.value = 0;
scoreEl.value = '';
startDateEl.value = '';
endDateEl.value = '';
repeatCountEl.value = 0;
notesEl.value = '';
privateEl.checked = false;
modalTitle.textContent = 'Add to List';
deleteBtn.style.display = 'none';
}
totalEpisodes = currentAnimeData.episodes || 999;
progressEl.max = totalEpisodes;
document.getElementById('add-list-modal').classList.add('active');
}
function closeAddToListModal() {
document.getElementById('add-list-modal').classList.remove('active');
}
async function saveToList() {
const uiStatus = document.getElementById('entry-status').value;
const anilistStatusMap = {
WATCHING: 'CURRENT',
COMPLETED: 'COMPLETED',
PLANNING: 'PLANNING',
PAUSED: 'PAUSED',
DROPPED: 'DROPPED',
REPEATING: 'REPEATING'
};
const status = anilistStatusMap[uiStatus];
const progress = parseInt(document.getElementById('entry-progress').value) || 0;
const scoreValue = document.getElementById('entry-score').value;
const score = scoreValue ? parseFloat(scoreValue) : null;
const start_date = document.getElementById('entry-start-date').value || null;
const end_date = document.getElementById('entry-end-date').value || null;
const repeat_count = parseInt(document.getElementById('entry-repeat-count').value) || 0;
const notes = document.getElementById('entry-notes').value || null;
const is_private = document.getElementById('entry-is-private').checked;
const animeId = currentAnimeData ? currentAnimeData.id : null;
if (!animeId) return;
await populateSourceFilter();
try {
const response = await fetch(`${API_BASE}/list/entry`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
entry_id: animeId,
source: 'anilist',
loadingState.style.display = 'flex';
emptyState.style.display = 'none';
container.innerHTML = '';
entry_type: 'ANIME',
status: status,
progress: progress,
score: score,
start_date: start_date,
end_date: end_date,
repeat_count: repeat_count,
notes: notes,
is_private: is_private
})
const response = await fetch(`${API_BASE}/list`, {
headers: window.AuthUtils.getSimpleAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to save entry');
throw new Error('Failed to load list');
}
const data = await response.json();
currentList = data.results || [];
filteredList = [...currentList];
isInList = true;
currentListEntry = data.entry;
updateAddToListButton();
closeAddToListModal();
showNotification(isInList ? 'Updated successfully!' : 'Added to your list!', 'success');
} catch (error) {
console.error('Error saving to list:', error);
showNotification('Failed to save. Please try again.', 'error');
}
}
loadingState.style.display = 'none';
async function deleteFromList() {
if (!confirm('Remove this anime from your list?')) return;
const animeId = currentAnimeData ? currentAnimeData.id : null;
if (!animeId) return;
const source = 'anilist';
const entryType = 'ANIME';
try {
const response = await fetch(`${API_BASE}/list/entry/${animeId}?source=${source}&entry_type=${entryType}`, {
method: 'DELETE',
headers: getSimpleAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to delete entry');
if (currentList.length === 0) {
emptyState.style.display = 'flex';
} else {
updateStats();
applyFilters();
}
isInList = false;
currentListEntry = null;
updateAddToListButton();
closeAddToListModal();
showNotification('Removed from your list', 'success');
} catch (error) {
console.error('Error deleting from list:', error);
showNotification('Failed to remove. Please try again.', 'error');
}
}
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('add-list-modal');
if (modal) {
modal.addEventListener('click', (e) => {
if (e.target.id === 'add-list-modal') {
closeAddToListModal();
}
});
}
});
searchInput.addEventListener('input', (e) => {
const query = e.target.value;
clearTimeout(searchTimeout);
if (query.length < 2) {
searchResults.classList.remove('active');
searchResults.innerHTML = '';
searchInput.style.borderRadius = '99px';
return;
}
searchTimeout = setTimeout(() => {
fetchSearh(query);
}, 300);
});
document.addEventListener('click', (e) => {
if (!e.target.closest('.search-wrapper')) {
searchResults.classList.remove('active');
searchInput.style.borderRadius = '99px';
}
});
async function fetchSearh(query) {
try {
let apiUrl = `/api/search?q=${encodeURIComponent(query)}`;
let extensionName = null;
let finalQuery = query;
const parts = query.split(':');
if (parts.length >= 2) {
const potentialExtension = parts[0].trim().toLowerCase();
const foundExtension = availableExtensions.find(ext => ext.toLowerCase() === potentialExtension);
if (foundExtension) {
extensionName = foundExtension;
finalQuery = parts.slice(1).join(':').trim();
if (finalQuery.length === 0) {
renderSearchResults([]);
return;
}
apiUrl = `/api/search/${extensionName}?q=${encodeURIComponent(finalQuery)}`;
}
console.error('Error loading list:', error);
loadingState.style.display = 'none';
if (window.NotificationUtils) {
window.NotificationUtils.error('Failed to load your list. Please try again.');
} else {
alert('Failed to load your list. Please try again.');
}
const res = await fetch(apiUrl);
const data = await res.json();
const resultsWithExtension = (data.results || []).map(anime => {
if (extensionName) {
return {
...anime,
isExtensionResult: true,
extensionName: extensionName
};
}
return anime;
});
renderSearchResults(resultsWithExtension);
} catch (err) {
console.error("Search Error:", err);
}
}
async function loadContinueWatching() {
const token = localStorage.getItem('token');
if (!token) return;
function updateStats() {
const total = currentList.length;
const watching = currentList.filter(item => item.status === 'WATCHING').length;
const completed = currentList.filter(item => item.status === 'COMPLETED').length;
const planning = currentList.filter(item => item.status === 'PLANNING').length;
try {
const res = await fetch('/api/list/filter?status=watching&entry_type=ANIME', {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if (!res.ok) return;
const data = await res.json();
const list = data.results || [];
renderContinueWatching('my-status', list);
} catch (err) {
console.error('Continue Watching Error:', err);
}
document.getElementById('total-count').textContent = total;
document.getElementById('watching-count').textContent = watching;
document.getElementById('completed-count').textContent = completed;
document.getElementById('planned-count').textContent = planning;
}
function renderContinueWatching(id, list) {
const container = document.getElementById(id);
if (!container) return;
function applyFilters() {
const statusFilter = document.getElementById('status-filter').value;
const sourceFilter = document.getElementById('source-filter').value;
const typeFilter = document.getElementById('type-filter').value;
const sortFilter = document.getElementById('sort-filter').value;
let filtered = [...filteredList];
if (statusFilter !== 'all') {
filtered = filtered.filter(item => item.status === statusFilter);
}
if (sourceFilter !== 'all') {
filtered = filtered.filter(item => item.source === sourceFilter);
}
if (typeFilter !== 'all') {
filtered = filtered.filter(item => item.entry_type === typeFilter);
}
switch (sortFilter) {
case 'title':
filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
break;
case 'score':
filtered.sort((a, b) => (b.score || 0) - (a.score || 0));
break;
case 'progress':
filtered.sort((a, b) => (b.progress || 0) - (a.progress || 0));
break;
case 'updated':
default:
filtered.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
break;
}
renderList(filtered);
}
function renderList(items) {
const container = document.getElementById('list-container');
container.innerHTML = '';
if (list.length === 0) {
container.innerHTML = `<div style="padding:1rem; color:#888">No watching anime</div>`;
if (items.length === 0) {
container.innerHTML = '<div class="empty-state"><p>No entries match your filters</p></div>';
return;
}
list.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
items.forEach(item => {
const element = createListItem(item);
container.appendChild(element);
});
}
list.forEach(item => {
const el = document.createElement('div');
el.className = 'card';
function createListItem(item) {
const div = document.createElement('div');
div.className = 'list-item';
el.onclick = () => {
const ep = item.progress || 1;
const itemLink = getEntryLink(item);
if (item.source === 'anilist') {
window.location.href = `http://localhost:54322/watch/${item.entry_id}/${ep + 1}`;
} else {
window.location.href = `http://localhost:54322/watch/${item.entry_id}/${ep + 1}?${item.source}`;
}
};
const posterUrl = item.poster || '/public/assets/placeholder.png';
const progress = item.progress || 0;
const progressText = item.total_episodes
? `${item.progress || 0}/${item.total_episodes}`
: `${item.progress || 0}`;
const totalUnits = item.entry_type === 'ANIME' ?
item.total_episodes || 0 :
item.total_chapters || 0;
el.innerHTML = `
<div class="card-img-wrap">
<img src="${item.poster}" loading="lazy">
const progressPercent = totalUnits > 0 ? (progress / totalUnits) * 100 : 0;
const score = item.score ? item.score.toFixed(1) : null;
const repeatCount = item.repeat_count || 0;
const entryType = (item.entry_type).toUpperCase();
let unitLabel = 'units';
if (entryType === 'ANIME') {
unitLabel = 'episodes';
} else if (entryType === 'MANGA') {
unitLabel = 'chapters';
} else if (entryType === 'NOVEL') {
unitLabel = 'chapters/volumes';
}
const statusLabels = {
'WATCHING': entryType === 'ANIME' ? 'Watching' : 'Reading',
'COMPLETED': 'Completed',
'PLANNING': 'Planning',
'PAUSED': 'Paused',
'DROPPED': 'Dropped'
};
const extraInfo = [];
if (repeatCount > 0) {
extraInfo.push(`<span class="meta-pill repeat-pill">🔁 ${repeatCount}</span>`);
}
if (item.is_private) {
extraInfo.push('<span class="meta-pill private-pill">🔒 Private</span>');
}
const entryDataString = JSON.stringify(item).replace(/'/g, '&#39;');
div.innerHTML = `
<a href="${itemLink}" class="item-poster-link">
<img src="${posterUrl}" alt="${item.title || 'Entry'}" class="item-poster" onerror="this.src='/public/assets/placeholder.png'">
</a>
<div class="item-content">
<div>
<a href="${itemLink}" style="text-decoration:none; color:inherit;">
<h3 class="item-title">${item.title || 'Unknown Title'}</h3>
</a>
<div class="item-meta">
<span class="meta-pill status-pill">${statusLabels[item.status] || item.status}</span>
<span class="meta-pill type-pill">${entryType}</span>
<span class="meta-pill source-pill">${item.source.toUpperCase()}</span>
${extraInfo.join('')}
</div>
</div>
<div class="card-content">
<h3>${item.title}</h3>
<p>Ep ${progressText} - ${item.source}</p> </div>
<div>
<div class="progress-bar-container">
<div class="progress-bar" style="width: ${progressPercent}%"></div>
</div>
<div class="progress-text">
<span>${progress}${totalUnits > 0 ? ` / ${totalUnits}` : ''} ${unitLabel}</span> ${score ? `<span class="score-badge">⭐ ${score}</span>` : ''}
</div>
</div>
</div>
<button class="edit-icon-btn" data-entry='${entryDataString}'>
<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
<path d="M15.232 5.232l3.536 3.536m-2.036-5.808a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.536L15.232 5.232z"/>
</svg>
</button>
`;
container.appendChild(el);
});
}
const editBtn = div.querySelector('.edit-icon-btn');
editBtn.addEventListener('click', (e) => {
try {
const entryData = JSON.parse(e.currentTarget.dataset.entry);
function renderSearchResults(results) {
searchResults.innerHTML = '';
if (results.length === 0) {
searchResults.innerHTML = '<div style="padding:1rem; color:#888; text-align:center">No results found</div>';
} else {
results.forEach(anime => {
const title = getTitle(anime);
const img = anime.coverImage.medium || anime.coverImage.large;
const rating = anime.averageScore ? `${anime.averageScore}%` : 'N/A';
const year = anime.seasonYear || '';
const format = anime.format || 'TV';
window.ListModalManager.isInList = true;
window.ListModalManager.currentEntry = entryData;
window.ListModalManager.currentData = entryData;
let href;
if (anime.isExtensionResult) {
href = `/anime/${anime.extensionName}/${anime.id}`;
} else {
href = `/anime/${anime.id}`;
window.ListModalManager.open(entryData, entryData.source);
} catch (error) {
console.error('Error parsing entry data for modal:', error);
if (window.NotificationUtils) {
window.NotificationUtils.error('Could not open modal. Check HTML form IDs.');
}
const item = document.createElement('a');
item.className = 'search-item';
item.href = href;
item.innerHTML = `
<img src="${img}" class="search-poster" alt="${title}">
<div class="search-info">
<div class="search-title">${title}</div>
<div class="search-meta">
<span class="rating-pill">${rating}</span>
<span>• ${year}</span>
<span>• ${format}</span>
</div>
</div>
`;
searchResults.appendChild(item);
});
}
searchResults.classList.add('active');
searchInput.style.borderRadius = '12px 12px 0 0';
}
function scrollCarousel(id, direction) {
const container = document.getElementById(id);
if(container) {
const scrollAmount = container.clientWidth * 0.75;
container.scrollBy({ left: direction * scrollAmount, behavior: 'smooth' });
}
}
let trendingAnimes = [];
let currentHeroIndex = 0;
let player;
let heroInterval;
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '100%', width: '100%',
playerVars: { 'autoplay': 1, 'controls': 0, 'mute': 1, 'loop': 1, 'showinfo': 0, 'modestbranding': 1 },
events: { 'onReady': (e) => { e.target.mute(); if(trendingAnimes.length) updateHeroVideo(trendingAnimes[currentHeroIndex]); } }
}
});
}
async function fetchContent(isUpdate = false) {
try {
const resExt = await fetch('/api/extensions/anime');
const dataExt = await resExt.json();
if (dataExt.extensions) {
availableExtensions = dataExt.extensions;
console.log("Extensiones de anime disponibles cargadas:", availableExtensions);
}
const trendingRes = await fetch('/api/trending');
const trendingData = await trendingRes.json();
if (trendingData.results && trendingData.results.length > 0) {
trendingAnimes = trendingData.results;
if (!isUpdate) {
updateHeroUI(trendingAnimes[0]);
startHeroCycle();
}
renderList('trending', trendingAnimes);
} else if (!isUpdate) {
setTimeout(() => fetchContent(false), 2000);
}
const topRes = await fetch('/api/top-airing');
const topData = await topRes.json();
if (topData.results && topData.results.length > 0) {
renderList('top-airing', topData.results);
}
} catch (e) {
console.error("Fetch Error:", e);
if(!isUpdate) setTimeout(() => fetchContent(false), 5000);
}
}
function startHeroCycle() {
if(heroInterval) clearInterval(heroInterval);
heroInterval = setInterval(() => {
if(trendingAnimes.length > 0) {
currentHeroIndex = (currentHeroIndex + 1) % trendingAnimes.length;
updateHeroUI(trendingAnimes[currentHeroIndex]);
}
}, 10000);
}
async function updateHeroUI(anime) {
if(!anime) return;
currentAnimeData = anime;
const title = getTitle(anime);
const score = anime.averageScore ? anime.averageScore + '% Match' : 'N/A';
const year = anime.seasonYear || '';
const type = anime.format || 'TV';
const desc = anime.description || 'No description available.';
const poster = anime.coverImage ? anime.coverImage.extraLarge : '';
const banner = anime.bannerImage || poster;
document.getElementById('hero-title').innerText = title;
document.getElementById('hero-desc').innerHTML = desc;
document.getElementById('hero-score').innerText = score;
document.getElementById('hero-year').innerText = year;
document.getElementById('hero-type').innerText = type;
document.getElementById('hero-poster').src = poster;
const watchBtn = document.getElementById('watch-btn');
if(watchBtn) watchBtn.onclick = () => window.location.href = `/anime/${anime.id}`;
const addToListBtn = document.querySelector('.hero-buttons .btn-blur');
if(addToListBtn) {
addToListBtn.onclick = openAddToListModal;
const success = await checkIfInList(anime.id);
if (success) {
updateAddToListButton();
} else {
updateAddToListButton();
}
}
const bgImg = document.getElementById('hero-bg-media');
if(bgImg && bgImg.src !== banner) bgImg.src = banner;
updateHeroVideo(anime);
document.getElementById('hero-loading-ui').style.display = 'none';
document.getElementById('hero-real-ui').style.display = 'block';
}
function updateHeroVideo(anime) {
if (!player || !player.loadVideoById) return;
const videoContainer = document.getElementById('player');
if (anime.trailer && anime.trailer.site === 'youtube' && anime.trailer.id) {
if(player.getVideoData && player.getVideoData().video_id !== anime.trailer.id) {
player.loadVideoById(anime.trailer.id);
player.mute();
}
videoContainer.style.opacity = "1";
} else {
videoContainer.style.opacity = "0";
player.stopVideo();
}
}
function renderList(id, list) {
const container = document.getElementById(id);
const firstId = list.length > 0 ? list[0].id : null;
const currentFirstId = container.firstElementChild?.dataset?.id;
if (currentFirstId && parseInt(currentFirstId) === firstId && container.children.length === list.length) {
return;
}
container.innerHTML = '';
list.forEach(anime => {
const title = getTitle(anime);
const cover = anime.coverImage ? anime.coverImage.large : '';
const ep = anime.nextAiringEpisode ? 'Ep ' + anime.nextAiringEpisode.episode : (anime.episodes ? anime.episodes + ' Eps' : 'TV');
const score = anime.averageScore || '--';
const el = document.createElement('div');
el.className = 'card';
el.dataset.id = anime.id;
el.onclick = () => window.location.href = `/anime/${anime.id}`;
el.innerHTML = `
<div class="card-img-wrap"><img src="${cover}" loading="lazy"></div>
<div class="card-content">
<h3>${title}</h3>
<p>${score}% • ${ep}</p>
</div>
`;
container.appendChild(el);
});
}
fetchContent();
loadContinueWatching();
setInterval(() => fetchContent(true), 60000);
return div;
}