---
import Layout from '../../layouts/Layout.astro';
import { getCollection } from 'astro:content';
import {
	getAllPromptTemplates,
	getFeaturedTemplates,
	getAllCategories,
	getAllTags,
	getTemplateStats,
	formatCategoryName,
	getDifficultyColor,
} from '../../utils/promptTemplates';
import { t } from '../../i18n';

const allTemplates = await getAllPromptTemplates();
const featuredTemplates = await getFeaturedTemplates(6);
const categories = await getAllCategories();
const tags = await getAllTags();
const stats = await getTemplateStats();

// Get unique difficulty levels
const difficulties = ['beginner', 'intermediate', 'advanced'];

// Get unique models
const allModels = [...new Set(allTemplates.map((t) => t.data.recommendedModel))].sort();
---

<Layout
	title="AI Prompt Templates - Picture AI Image Generator"
	description="Browse our collection of professional prompt templates for AI image generation. Create stunning images faster with pre-built prompts for FLUX, Ideogram, and more."
>
	<!-- Hero Section -->
	<section class="bg-gradient-to-br from-purple-900 via-purple-800 to-indigo-900 py-20 text-white">
		<div class="container mx-auto px-4">
			<div class="mx-auto max-w-4xl text-center">
				<h1 class="mb-6 text-5xl font-bold md:text-6xl">AI Prompt Templates</h1>
				<p class="mb-8 text-xl text-purple-100 md:text-2xl">
					Professional prompt templates for stunning AI images. Save time and get better results
					with our curated collection.
				</p>

				<!-- Stats -->
				<div class="mb-12 grid grid-cols-2 gap-6 md:grid-cols-4">
					<div class="rounded-lg bg-white/10 p-6 backdrop-blur-sm">
						<div class="text-3xl font-bold">{stats.total}</div>
						<div class="text-purple-200">Templates</div>
					</div>
					<div class="rounded-lg bg-white/10 p-6 backdrop-blur-sm">
						<div class="text-3xl font-bold">{stats.totalUses.toLocaleString()}</div>
						<div class="text-purple-200">Uses</div>
					</div>
					<div class="rounded-lg bg-white/10 p-6 backdrop-blur-sm">
						<div class="text-3xl font-bold">{categories.length}</div>
						<div class="text-purple-200">Categories</div>
					</div>
					<div class="rounded-lg bg-white/10 p-6 backdrop-blur-sm">
						<div class="text-3xl font-bold">{stats.averageRating}</div>
						<div class="text-purple-200">Avg Rating</div>
					</div>
				</div>

				<!-- Search Bar -->
				<div class="mx-auto max-w-2xl">
					<div class="relative">
						<input
							type="text"
							id="search-input"
							placeholder="Search templates..."
							class="w-full rounded-full px-6 py-4 text-lg text-gray-900 focus:outline-none focus:ring-4 focus:ring-purple-300"
						/>
						<button
							class="absolute right-2 top-1/2 -translate-y-1/2 rounded-full bg-purple-600 px-8 py-2 font-semibold text-white transition-colors hover:bg-purple-700"
						>
							Search
						</button>
					</div>
				</div>
			</div>
		</div>
	</section>

	<!-- Filters Section -->
	<section class="sticky top-0 z-10 border-b bg-gray-50">
		<div class="container mx-auto px-4 py-6">
			<div class="flex flex-wrap items-center gap-4">
				<!-- Category Filter -->
				<div class="min-w-[200px] flex-1">
					<label for="category-filter" class="mb-1 block text-sm font-medium text-gray-700">
						Category
					</label>
					<select
						id="category-filter"
						class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-transparent focus:ring-2 focus:ring-purple-500"
					>
						<option value="">All Categories</option>
						{
							categories.map((cat) => (
								<option value={cat.category}>
									{cat.icon} {formatCategoryName(cat.category)} ({cat.count})
								</option>
							))
						}
					</select>
				</div>

				<!-- Difficulty Filter -->
				<div class="min-w-[200px] flex-1">
					<label for="difficulty-filter" class="mb-1 block text-sm font-medium text-gray-700">
						Difficulty
					</label>
					<select
						id="difficulty-filter"
						class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-transparent focus:ring-2 focus:ring-purple-500"
					>
						<option value="">All Levels</option>
						{
							difficulties.map((diff) => (
								<option value={diff}>
									{diff.charAt(0).toUpperCase() + diff.slice(1)} (
									{stats.byDifficulty[diff as keyof typeof stats.byDifficulty]})
								</option>
							))
						}
					</select>
				</div>

				<!-- Model Filter -->
				<div class="min-w-[200px] flex-1">
					<label for="model-filter" class="mb-1 block text-sm font-medium text-gray-700">
						Model
					</label>
					<select
						id="model-filter"
						class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-transparent focus:ring-2 focus:ring-purple-500"
					>
						<option value="">All Models</option>
						{allModels.map((model) => <option value={model}>{model}</option>)}
					</select>
				</div>

				<!-- Sort -->
				<div class="min-w-[200px] flex-1">
					<label for="sort-select" class="mb-1 block text-sm font-medium text-gray-700">
						Sort By
					</label>
					<select
						id="sort-select"
						class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:border-transparent focus:ring-2 focus:ring-purple-500"
					>
						<option value="popular">Most Popular</option>
						<option value="recent">Most Recent</option>
						<option value="rating">Highest Rated</option>
						<option value="uses">Most Used</option>
					</select>
				</div>
			</div>

			<!-- Active Filters -->
			<div id="active-filters" class="mt-4 flex hidden flex-wrap gap-2"></div>
		</div>
	</section>

	<!-- Featured Templates -->
	{
		featuredTemplates.length > 0 && (
			<section class="bg-white py-16">
				<div class="container mx-auto px-4">
					<div class="mb-8 flex items-center justify-between">
						<div>
							<h2 class="text-3xl font-bold text-gray-900">Featured Templates</h2>
							<p class="mt-2 text-gray-600">Hand-picked templates for the best results</p>
						</div>
					</div>

					<div class="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
						{featuredTemplates.map((template) => (
							<a
								href={`/prompt-templates/${template.id}`}
								class="group overflow-hidden rounded-xl border border-gray-200 bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-xl"
							>
								{/* Template Card */}
								<div class="p-6">
									{/* Header */}
									<div class="mb-4 flex items-start justify-between">
										<div class="flex items-center gap-3">
											<span class="text-4xl">{template.data.icon}</span>
											<div>
												<h3 class="text-xl font-bold text-gray-900 transition-colors group-hover:text-purple-600">
													{template.data.title}
												</h3>
												<div class="mt-1 flex items-center gap-2">
													<span
														class={`rounded-full px-2 py-0.5 text-xs font-semibold ${
															template.data.difficulty === 'beginner'
																? 'bg-green-100 text-green-800'
																: template.data.difficulty === 'intermediate'
																	? 'bg-yellow-100 text-yellow-800'
																	: 'bg-red-100 text-red-800'
														}`}
													>
														{template.data.difficulty}
													</span>
													{template.data.featured && (
														<span class="rounded-full bg-purple-100 px-2 py-0.5 text-xs font-semibold text-purple-800">
															Featured
														</span>
													)}
												</div>
											</div>
										</div>
									</div>

									{/* Description */}
									<p class="mb-4 line-clamp-2 text-gray-600">{template.data.description}</p>

									{/* Category & Tags */}
									<div class="mb-4 flex flex-wrap gap-2">
										<span class="rounded-full bg-gray-100 px-3 py-1 text-sm text-gray-700">
											{formatCategoryName(template.data.category)}
										</span>
										{template.data.tags.slice(0, 2).map((tag) => (
											<span class="rounded-full bg-gray-50 px-3 py-1 text-sm text-gray-600">
												#{tag}
											</span>
										))}
									</div>

									{/* Stats */}
									<div class="flex items-center justify-between border-t border-gray-100 pt-4">
										<div class="flex items-center gap-4 text-sm text-gray-500">
											<span class="flex items-center gap-1">
												<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
													/>
												</svg>
												{template.data.likes}
											</span>
											<span class="flex items-center gap-1">
												<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
													/>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
													/>
												</svg>
												{template.data.uses}
											</span>
										</div>
										<div class="flex items-center gap-1 text-yellow-500">
											<svg class="h-4 w-4 fill-current" viewBox="0 0 24 24">
												<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
											</svg>
											<span class="text-sm font-semibold text-gray-700">
												{template.data.rating}
											</span>
										</div>
									</div>

									{/* Model */}
									<div class="mt-4 border-t border-gray-100 pt-4">
										<div class="flex items-center justify-between text-sm">
											<span class="text-gray-500">Recommended:</span>
											<span class="font-semibold text-gray-700">
												{template.data.recommendedModel}
											</span>
										</div>
									</div>
								</div>
							</a>
						))}
					</div>
				</div>
			</section>
		)
	}

	<!-- All Templates Grid -->
	<section class="bg-gray-50 py-16">
		<div class="container mx-auto px-4">
			<div class="mb-8 flex items-center justify-between">
				<div>
					<h2 class="text-3xl font-bold text-gray-900">All Templates</h2>
					<p class="mt-2 text-gray-600" id="results-count">
						Showing {allTemplates.length} templates
					</p>
				</div>
			</div>

			<div
				id="templates-grid"
				class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
			>
				{
					allTemplates.map((template) => (
						<a
							href={`/prompt-templates/${template.slug}`}
							class="template-card group overflow-hidden rounded-lg border border-gray-200 bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-lg"
							data-category={template.data.category}
							data-difficulty={template.data.difficulty}
							data-model={template.data.recommendedModel}
							data-tags={JSON.stringify(template.data.tags)}
							data-title={template.data.title.toLowerCase()}
							data-description={template.data.description.toLowerCase()}
							data-rating={template.data.rating}
							data-uses={template.data.uses}
							data-date={template.data.publishDate.getTime()}
						>
							<div class="p-5">
								{/* Icon & Badges */}
								<div class="mb-3 flex items-start justify-between">
									<span class="text-3xl">{template.data.icon}</span>
									<div class="flex gap-1">
										{template.data.popular && (
											<span class="rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-800">
												Popular
											</span>
										)}
										{template.data.trending && (
											<span class="rounded-full bg-orange-100 px-2 py-0.5 text-xs font-semibold text-orange-800">
												🔥
											</span>
										)}
									</div>
								</div>

								{/* Title */}
								<h3 class="mb-2 line-clamp-2 text-lg font-bold text-gray-900 transition-colors group-hover:text-purple-600">
									{template.data.title}
								</h3>

								{/* Description */}
								<p class="mb-3 line-clamp-2 text-sm text-gray-600">{template.data.description}</p>

								{/* Difficulty */}
								<div class="mb-3">
									<span
										class={`rounded-full px-2 py-1 text-xs font-semibold ${
											template.data.difficulty === 'beginner'
												? 'bg-green-100 text-green-800'
												: template.data.difficulty === 'intermediate'
													? 'bg-yellow-100 text-yellow-800'
													: 'bg-red-100 text-red-800'
										}`}
									>
										{template.data.difficulty}
									</span>
								</div>

								{/* Stats */}
								<div class="mb-3 flex items-center justify-between text-xs text-gray-500">
									<span class="flex items-center gap-1">⭐ {template.data.rating}</span>
									<span>{template.data.uses} uses</span>
								</div>

								{/* Model */}
								<div class="border-t border-gray-100 pt-3">
									<span class="text-xs font-medium text-gray-500">
										{template.data.recommendedModel}
									</span>
								</div>
							</div>
						</a>
					))
				}
			</div>

			<!-- No Results -->
			<div id="no-results" class="hidden py-16 text-center">
				<div class="mb-4 text-6xl">🔍</div>
				<h3 class="mb-2 text-2xl font-bold text-gray-900">No templates found</h3>
				<p class="text-gray-600">Try adjusting your filters or search query</p>
			</div>
		</div>
	</section>

	<!-- Popular Categories -->
	<section class="bg-white py-16">
		<div class="container mx-auto px-4">
			<div class="mb-12 text-center">
				<h2 class="mb-4 text-3xl font-bold text-gray-900">Browse by Category</h2>
				<p class="text-gray-600">Find the perfect template for your use case</p>
			</div>

			<div class="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
				{
					categories.map((cat) => (
						<button
							class="category-btn group rounded-xl border border-gray-200 bg-gray-50 p-6 text-center transition-all duration-300 hover:border-purple-300 hover:bg-purple-50"
							data-category={cat.category}
						>
							<div class="mb-2 text-4xl">{cat.icon}</div>
							<div class="font-semibold text-gray-900 group-hover:text-purple-600">
								{formatCategoryName(cat.category)}
							</div>
							<div class="mt-1 text-sm text-gray-500">{cat.count} templates</div>
						</button>
					))
				}
			</div>
		</div>
	</section>

	<!-- CTA Section -->
	<section class="bg-gradient-to-br from-purple-900 via-purple-800 to-indigo-900 py-20 text-white">
		<div class="container mx-auto px-4 text-center">
			<h2 class="mb-6 text-4xl font-bold">Ready to Create Stunning Images?</h2>
			<p class="mx-auto mb-8 max-w-2xl text-xl text-purple-100">
				Start using our prompt templates today and generate professional-quality AI images in
				seconds.
			</p>
			<div class="flex flex-col justify-center gap-4 sm:flex-row">
				<a
					href="/app"
					class="rounded-full bg-white px-8 py-4 font-semibold text-purple-600 transition-colors hover:bg-purple-50"
				>
					Start Creating Free
				</a>
				<a
					href="/tutorials"
					class="rounded-full border-2 border-white bg-purple-600 px-8 py-4 font-semibold text-white transition-colors hover:bg-purple-700"
				>
					Learn More
				</a>
			</div>
		</div>
	</section>

	<script>
		// Client-side filtering and sorting
		const searchInput = document.getElementById('search-input') as HTMLInputElement;
		const categoryFilter = document.getElementById('category-filter') as HTMLSelectElement;
		const difficultyFilter = document.getElementById('difficulty-filter') as HTMLSelectElement;
		const modelFilter = document.getElementById('model-filter') as HTMLSelectElement;
		const sortSelect = document.getElementById('sort-select') as HTMLSelectElement;
		const templatesGrid = document.getElementById('templates-grid') as HTMLElement;
		const noResults = document.getElementById('no-results') as HTMLElement;
		const resultsCount = document.getElementById('results-count') as HTMLElement;
		const activeFiltersContainer = document.getElementById('active-filters') as HTMLElement;
		const categoryButtons = document.querySelectorAll('.category-btn');

		let currentFilters = {
			search: '',
			category: '',
			difficulty: '',
			model: '',
			sort: 'popular',
		};

		function updateActiveFilters() {
			const filters: string[] = [];

			if (currentFilters.search) filters.push(`Search: "${currentFilters.search}"`);
			if (currentFilters.category) filters.push(`Category: ${currentFilters.category}`);
			if (currentFilters.difficulty) filters.push(`Difficulty: ${currentFilters.difficulty}`);
			if (currentFilters.model) filters.push(`Model: ${currentFilters.model}`);

			if (filters.length > 0) {
				activeFiltersContainer.innerHTML = filters
					.map(
						(filter) => `
					<span class="px-3 py-1 bg-purple-100 text-purple-800 rounded-full text-sm font-medium flex items-center gap-2">
						${filter}
						<button class="hover:text-purple-900" onclick="this.parentElement.remove(); filterTemplates();">×</button>
					</span>
				`
					)
					.join('');
				activeFiltersContainer.classList.remove('hidden');
			} else {
				activeFiltersContainer.classList.add('hidden');
			}
		}

		function filterTemplates() {
			const cards = Array.from(document.querySelectorAll('.template-card')) as HTMLElement[];

			let visibleCount = 0;

			cards.forEach((card) => {
				const matchesSearch =
					!currentFilters.search ||
					card.dataset.title?.includes(currentFilters.search.toLowerCase()) ||
					card.dataset.description?.includes(currentFilters.search.toLowerCase());

				const matchesCategory =
					!currentFilters.category || card.dataset.category === currentFilters.category;

				const matchesDifficulty =
					!currentFilters.difficulty || card.dataset.difficulty === currentFilters.difficulty;

				const matchesModel = !currentFilters.model || card.dataset.model === currentFilters.model;

				if (matchesSearch && matchesCategory && matchesDifficulty && matchesModel) {
					card.style.display = 'block';
					visibleCount++;
				} else {
					card.style.display = 'none';
				}
			});

			// Sort visible cards
			const visibleCards = cards.filter((card) => card.style.display !== 'none');
			sortCards(visibleCards);

			// Update results count
			resultsCount.textContent = `Showing ${visibleCount} template${visibleCount !== 1 ? 's' : ''}`;

			// Show/hide no results
			if (visibleCount === 0) {
				noResults.classList.remove('hidden');
				templatesGrid.classList.add('hidden');
			} else {
				noResults.classList.add('hidden');
				templatesGrid.classList.remove('hidden');
			}

			updateActiveFilters();
		}

		function sortCards(cards: HTMLElement[]) {
			cards.sort((a, b) => {
				const sortBy = currentFilters.sort;

				if (sortBy === 'popular' || sortBy === 'uses') {
					return Number(b.dataset.uses) - Number(a.dataset.uses);
				} else if (sortBy === 'rating') {
					return Number(b.dataset.rating) - Number(a.dataset.rating);
				} else if (sortBy === 'recent') {
					return Number(b.dataset.date) - Number(a.dataset.date);
				}

				return 0;
			});

			cards.forEach((card) => templatesGrid.appendChild(card));
		}

		// Event listeners
		searchInput.addEventListener('input', (e) => {
			currentFilters.search = (e.target as HTMLInputElement).value;
			filterTemplates();
		});

		categoryFilter.addEventListener('change', (e) => {
			currentFilters.category = (e.target as HTMLSelectElement).value;
			filterTemplates();
		});

		difficultyFilter.addEventListener('change', (e) => {
			currentFilters.difficulty = (e.target as HTMLSelectElement).value;
			filterTemplates();
		});

		modelFilter.addEventListener('change', (e) => {
			currentFilters.model = (e.target as HTMLSelectElement).value;
			filterTemplates();
		});

		sortSelect.addEventListener('change', (e) => {
			currentFilters.sort = (e.target as HTMLSelectElement).value;
			filterTemplates();
		});

		// Category button clicks
		categoryButtons.forEach((btn) => {
			btn.addEventListener('click', () => {
				const category = (btn as HTMLElement).dataset.category || '';
				currentFilters.category = category;
				categoryFilter.value = category;
				filterTemplates();

				// Smooth scroll to templates grid
				templatesGrid.scrollIntoView({ behavior: 'smooth', block: 'start' });
			});
		});
	</script>
</Layout>
