---
import Layout from '../../layouts/Layout.astro';
import TutorialCard from '../../components/tutorials/TutorialCard.astro';
import {
	getTutorials,
	getFeaturedTutorials,
	getAllTutorialCategories,
	getAllTutorialDifficulties,
	getCategoryDisplayName,
	getCategoryIcon,
	getDifficultyDisplayName,
	getDifficultyIcon,
	getTutorialStats,
} from '../../utils/tutorials';

const language = 'en';
const allTutorials = await getTutorials(language);
const featuredTutorials = await getFeaturedTutorials(language);
const categories = getAllTutorialCategories();
const difficulties = getAllTutorialDifficulties();
const stats = await getTutorialStats(language);

const tutorialsByCategory = categories.map((category) => ({
	category,
	displayName: getCategoryDisplayName(category),
	icon: getCategoryIcon(category),
	tutorials: allTutorials.filter((t) => t.data.category === category),
}));
---

<Layout
	title="Tutorials - Learn AI Image Generation | Picture"
	description="Step-by-step tutorials to master AI image generation with Picture. From beginner guides to advanced techniques, learn how to create stunning images."
>
	<div class="min-h-screen bg-dark-bg">
		<!-- Hero -->
		<div class="bg-gradient-to-b from-dark-elevated to-dark-bg py-16 md:py-24">
			<div class="mx-auto max-w-6xl px-6 text-center">
				<div
					class="mb-6 inline-block rounded-full border border-primary/20 bg-primary/10 px-4 py-1.5"
				>
					<span class="text-sm font-medium text-primary">📚 Tutorials</span>
				</div>
				<h1 class="mb-6 text-4xl font-bold text-white md:text-5xl lg:text-6xl">
					Master AI Image Generation
				</h1>
				<p class="mx-auto mb-8 max-w-3xl text-xl text-gray-300">
					From first steps to advanced techniques. Learn with step-by-step guides, video tutorials,
					and expert tips.
				</p>

				<!-- Search -->
				<div class="mx-auto mb-8 max-w-2xl">
					<div class="relative">
						<input
							type="text"
							id="tutorial-search"
							placeholder="Search tutorials..."
							class="w-full rounded-xl border border-dark-border bg-dark-elevated px-6 py-4 pl-14 text-white placeholder-gray-400 focus:border-primary focus:outline-none"
						/>
						<svg
							class="absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
						</svg>
					</div>
				</div>

				<!-- Stats -->
				<div class="flex flex-wrap items-center justify-center gap-8 text-sm text-gray-400">
					<div>
						<span class="text-2xl font-bold text-primary">{stats.totalTutorials}</span> tutorials
					</div>
					<div>
						<span class="text-2xl font-bold text-primary">{categories.length}</span> categories
					</div>
					<div>
						<span class="text-2xl font-bold text-primary">{stats.withVideoCount}</span> with video
					</div>
				</div>
			</div>
		</div>

		<!-- Featured -->
		{
			featuredTutorials.length > 0 && (
				<div class="mx-auto max-w-6xl px-6 py-12">
					<h2 class="mb-6 flex items-center gap-3 text-2xl font-bold text-white">
						<>
							<span>⭐</span>
							<span>Featured Tutorials</span>
						</>
					</h2>
					<div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
						{featuredTutorials.map((tutorial) => (
							<TutorialCard tutorial={tutorial} />
						))}
					</div>
				</div>
			)
		}

		<!-- Filters -->
		<div class="mx-auto max-w-6xl px-6 py-8">
			<!-- Difficulty Filter -->
			<div class="mb-6">
				<h3 class="mb-3 text-sm font-medium text-gray-400">Filter by difficulty:</h3>
				<div class="flex flex-wrap gap-3">
					<button class="difficulty-btn active" data-difficulty="all">
						<span>All Levels</span>
					</button>
					{
						difficulties.map((difficulty) => (
							<button class="difficulty-btn" data-difficulty={difficulty}>
								<span>
									{getDifficultyIcon(difficulty)} {getDifficultyDisplayName(difficulty)}(
									{stats.difficultyCounts.find((d) => d.difficulty === difficulty)?.count || 0})
								</span>
							</button>
						))
					}
				</div>
			</div>

			<!-- Category Filter -->
			<div>
				<h3 class="mb-3 text-sm font-medium text-gray-400">Filter by category:</h3>
				<div class="flex flex-wrap gap-3">
					<button class="category-btn active" data-category="all">
						<span>📚 All ({stats.totalTutorials})</span>
					</button>
					{
						stats.categoryCounts.map(({ category, displayName, icon, count }) => (
							<button class="category-btn" data-category={category}>
								<span>
									{icon} {displayName} ({count})
								</span>
							</button>
						))
					}
				</div>
			</div>
		</div>

		<!-- Tutorials Grid -->
		<div class="mx-auto max-w-6xl px-6 pb-16">
			<div id="tutorials-grid" class="space-y-12">
				{
					tutorialsByCategory.map(
						({ category, displayName, icon, tutorials }) =>
							tutorials.length > 0 && (
								<div class="tutorial-category" data-category={category}>
									<h3 class="mb-6 text-xl font-bold text-white">
										{icon} {displayName} ({tutorials.length})
									</h3>
									<div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
										{tutorials.map((tutorial) => (
											<TutorialCard tutorial={tutorial} />
										))}
									</div>
								</div>
							)
					)
				}
			</div>
			<div id="no-results" class="hidden py-12 text-center">
				<div class="mb-4 text-6xl">🔍</div>
				<h3 class="mb-2 text-xl text-white">No tutorials found</h3>
				<p class="text-gray-400">Try a different search term or filter</p>
			</div>
		</div>

		<!-- CTA -->
		<div class="mx-auto max-w-4xl px-6 py-16">
			<div
				class="rounded-2xl border border-primary/20 bg-gradient-to-r from-primary/10 to-purple-500/10 p-12 text-center"
			>
				<h2 class="mb-4 text-3xl font-bold text-white">Ready to start creating?</h2>
				<p class="mb-8 text-gray-300">
					Put your new skills to practice with Picture's AI image generator.
				</p>
				<a
					href="#"
					class="inline-block rounded-lg bg-primary px-8 py-3 font-medium text-white transition hover:bg-primary/90"
				>
					Get Started Free
				</a>
			</div>
		</div>
	</div>

	<script>
		const search = document.getElementById('tutorial-search') as HTMLInputElement;
		const categoryBtns = document.querySelectorAll('.category-btn');
		const difficultyBtns = document.querySelectorAll('.difficulty-btn');
		const categories = document.querySelectorAll('.tutorial-category');
		const noResults = document.getElementById('no-results');
		let activeCategory = 'all';
		let activeDifficulty = 'all';

		search?.addEventListener('input', (e) =>
			filter((e.target as HTMLInputElement).value.toLowerCase(), activeCategory, activeDifficulty)
		);

		categoryBtns.forEach((btn) => {
			btn.addEventListener('click', () => {
				const cat = btn.getAttribute('data-category') || 'all';
				activeCategory = cat;
				categoryBtns.forEach((b) => b.classList.remove('active'));
				btn.classList.add('active');
				filter(search?.value.toLowerCase() || '', cat, activeDifficulty);
			});
		});

		difficultyBtns.forEach((btn) => {
			btn.addEventListener('click', () => {
				const diff = btn.getAttribute('data-difficulty') || 'all';
				activeDifficulty = diff;
				difficultyBtns.forEach((b) => b.classList.remove('active'));
				btn.classList.add('active');
				filter(search?.value.toLowerCase() || '', activeCategory, diff);
			});
		});

		function filter(query: string, category: string, difficulty: string) {
			let visibleCount = 0;

			categories.forEach((cat) => {
				const catName = cat.getAttribute('data-category');
				const categoryMatches = category === 'all' || catName === category;

				if (!categoryMatches) {
					(cat as HTMLElement).style.display = 'none';
					return;
				}

				const cards = cat.querySelectorAll('.tutorial-card');
				let hasVisibleCards = false;

				cards.forEach((card) => {
					const cardDifficulty = card.getAttribute('data-difficulty');
					const difficultyMatches = difficulty === 'all' || cardDifficulty === difficulty;

					const text = card.textContent?.toLowerCase() || '';
					const searchMatches = !query || text.includes(query);

					if (difficultyMatches && searchMatches) {
						(card as HTMLElement).style.display = 'block';
						hasVisibleCards = true;
						visibleCount++;
					} else {
						(card as HTMLElement).style.display = 'none';
					}
				});

				(cat as HTMLElement).style.display = hasVisibleCards ? 'block' : 'none';
			});

			if (noResults) {
				noResults.style.display = visibleCount === 0 ? 'block' : 'none';
			}
		}
	</script>

	<style>
		.category-btn,
		.difficulty-btn {
			@apply rounded-lg border border-dark-border bg-dark-elevated px-4 py-2 text-sm text-gray-300 transition hover:border-primary hover:text-primary;
		}
		.category-btn.active,
		.difficulty-btn.active {
			@apply border-primary bg-primary/10 text-primary;
		}
	</style>
</Layout>
