package templates

import "mal/internal/jikan"
import "fmt"

templ Catalog() {
	@Layout("mal - catalog") {
		<div class="catalog-grid" id="catalog-content">
			<div hx-get="/api/catalog?page=1" hx-trigger="load" hx-swap="outerHTML" style="grid-column: 1 / -1;">
				<div class="loading-indicator">
					<div class="loading-dot"></div>
					<div class="loading-dot"></div>
					<div class="loading-dot"></div>
					<span>loading catalog</span>
				</div>
			</div>
		</div>
	}
}

templ CatalogItems(animes []jikan.Anime, nextPage int, hasNext bool) {
	for _, anime := range animes {
		<div class="catalog-item" data-id={ fmt.Sprintf("%d", anime.MalID) }>
			@CatalogItem(anime)
		</div>
	}
	if hasNext {
		<div class="scroll-trigger" style="grid-column: 1 / -1; height: 20px;" hx-get={ string(templ.URL(fmt.Sprintf("/api/catalog?page=%d", nextPage))) } hx-trigger="revealed" hx-swap="outerHTML"></div>
	}
	<script>
		(function() {
			const items = document.querySelectorAll('#catalog-content .catalog-item[data-id]');
			const seen = new Set();
			items.forEach(item => {
				const id = item.getAttribute('data-id');
				if (id) {
					if (seen.has(id)) {
						item.remove();
					} else {
						seen.add(id);
					}
				}
			});
		})();
	</script>
}

templ CatalogItem(anime jikan.Anime) {
	<a href={ templ.URL(fmt.Sprintf("/anime/%d", anime.MalID)) }>
		if anime.ImageURL() != "" {
			<img src={ anime.ImageURL() } alt={ anime.DisplayTitle() } class="catalog-thumb" loading="lazy"/>
		} else {
			<div class="no-image">no image</div>
		}
	</a>
	<div class="catalog-title">
		{ anime.DisplayTitle() }
	</div>
}
