---
interface Props {
	categories: Array<{ category: string; count: number }>;
}

const { categories } = Astro.props;
---

<div class="rounded-2xl bg-gray-50 p-6 dark:bg-gray-900">
	<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
		<!-- Search -->
		<div>
			<label for="search" class="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300">
				Search
			</label>
			<div class="relative">
				<input
					type="text"
					id="search"
					placeholder="Search case studies..."
					class="w-full rounded-lg border border-gray-300 px-4 py-2 pl-10 text-gray-900 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
				/>
				<svg
					class="absolute left-3 top-3 h-5 w-5 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>

		<!-- Sort By -->
		<div>
			<label for="sort" class="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300">
				Sort By
			</label>
			<select
				id="sort"
				class="w-full rounded-lg border border-gray-300 px-4 py-2 text-gray-900 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
			>
				<option value="newest">Newest First</option>
				<option value="popular">Most Popular</option>
				<option value="views">Most Viewed</option>
				<option value="company">Company Name</option>
			</select>
		</div>

		<!-- Industry -->
		<div>
			<label
				for="industry"
				class="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300"
			>
				Industry
			</label>
			<select
				id="industry"
				class="w-full rounded-lg border border-gray-300 px-4 py-2 text-gray-900 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
			>
				<option value="all">All Industries</option>
				{
					categories.map((cat) => (
						<option value={cat.category}>
							{cat.category} ({cat.count})
						</option>
					))
				}
			</select>
		</div>
	</div>

	<!-- Active Filters Display -->
	<div id="active-filters" class="mt-4 hidden">
		<div class="flex flex-wrap items-center gap-2">
			<span class="text-sm font-semibold text-gray-700 dark:text-gray-300">Active filters:</span>
			<div id="filter-tags" class="flex flex-wrap gap-2"></div>
			<button id="clear-filters" class="text-sm text-blue-600 hover:underline dark:text-blue-400">
				Clear all
			</button>
		</div>
	</div>
</div>

<script>
	document.addEventListener('DOMContentLoaded', () => {
		const searchInput = document.getElementById('search') as HTMLInputElement;
		const sortSelect = document.getElementById('sort') as HTMLSelectElement;
		const industrySelect = document.getElementById('industry') as HTMLSelectElement;
		const caseStudyCards = document.querySelectorAll('[data-category]');
		const grid = document.getElementById('case-studies-grid');

		let currentFilters = {
			search: '',
			sort: 'newest',
			industry: 'all',
		};

		function applyFilters() {
			let visibleCards = Array.from(caseStudyCards);

			// Search filter
			if (currentFilters.search) {
				visibleCards = visibleCards.filter((card) => {
					const text = card.textContent?.toLowerCase() || '';
					return text.includes(currentFilters.search.toLowerCase());
				});
			}

			// Industry filter
			if (currentFilters.industry !== 'all') {
				visibleCards = visibleCards.filter((card) => {
					const category = card.getAttribute('data-category');
					return category === currentFilters.industry;
				});
			}

			// Show/hide cards
			caseStudyCards.forEach((card) => {
				(card as HTMLElement).style.display = visibleCards.includes(card) ? '' : 'none';
			});

			// Sort
			if (currentFilters.sort === 'popular') {
				visibleCards.sort((a, b) => {
					const likesA = parseInt(a.querySelector('[data-likes]')?.textContent || '0');
					const likesB = parseInt(b.querySelector('[data-likes]')?.textContent || '0');
					return likesB - likesA;
				});
			}

			// Re-order cards in DOM
			if (grid) {
				visibleCards.forEach((card) => {
					grid.appendChild(card);
				});
			}

			updateActiveFilters();
		}

		function updateActiveFilters() {
			const activeFiltersDiv = document.getElementById('active-filters');
			const filterTagsDiv = document.getElementById('filter-tags');

			const hasActiveFilters =
				currentFilters.search !== '' ||
				currentFilters.sort !== 'newest' ||
				currentFilters.industry !== 'all';

			if (activeFiltersDiv && filterTagsDiv) {
				if (hasActiveFilters) {
					activeFiltersDiv.classList.remove('hidden');
					filterTagsDiv.innerHTML = '';

					if (currentFilters.search) {
						filterTagsDiv.innerHTML += `
							<span class="rounded-full bg-blue-100 px-3 py-1 text-sm text-blue-700 dark:bg-blue-900 dark:text-blue-300">
								Search: "${currentFilters.search}"
							</span>
						`;
					}

					if (currentFilters.industry !== 'all') {
						filterTagsDiv.innerHTML += `
							<span class="rounded-full bg-purple-100 px-3 py-1 text-sm text-purple-700 dark:bg-purple-900 dark:text-purple-300">
								Industry: ${currentFilters.industry}
							</span>
						`;
					}

					if (currentFilters.sort !== 'newest') {
						filterTagsDiv.innerHTML += `
							<span class="rounded-full bg-pink-100 px-3 py-1 text-sm text-pink-700 dark:bg-pink-900 dark:text-pink-300">
								Sort: ${currentFilters.sort}
							</span>
						`;
					}
				} else {
					activeFiltersDiv.classList.add('hidden');
				}
			}
		}

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

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

		if (industrySelect) {
			industrySelect.addEventListener('change', (e) => {
				currentFilters.industry = (e.target as HTMLSelectElement).value;
				applyFilters();
			});
		}

		const clearFiltersBtn = document.getElementById('clear-filters');
		if (clearFiltersBtn) {
			clearFiltersBtn.addEventListener('click', () => {
				currentFilters = { search: '', sort: 'newest', industry: 'all' };
				if (searchInput) searchInput.value = '';
				if (sortSelect) sortSelect.value = 'newest';
				if (industrySelect) industrySelect.value = 'all';
				applyFilters();
			});
		}
	});
</script>
