<script>
	import { onMount } from 'svelte';
	import { browser } from '$app/environment';
	import { createLanguageContext } from "$lib/contexts/languageContext.js";
	import Gebet from "./Gebet.svelte";
	import LanguageToggle from "$lib/components/faith/LanguageToggle.svelte";
	import SearchInput from "$lib/components/SearchInput.svelte";
	import Kreuzzeichen from "$lib/components/faith/prayers/Kreuzzeichen.svelte";
	import GloriaPatri from "$lib/components/faith/prayers/GloriaPatri.svelte";
	import Paternoster from "$lib/components/faith/prayers/Paternoster.svelte";
	import Credo from "$lib/components/faith/prayers/Credo.svelte";
	import AveMaria from "$lib/components/faith/prayers/AveMaria.svelte";
	import SalveRegina from "$lib/components/faith/prayers/SalveRegina.svelte";
	import FatimaGebet from "$lib/components/faith/prayers/FatimaGebet.svelte";
	import Gloria from "$lib/components/faith/prayers/Gloria.svelte";
	import MichaelGebet from "$lib/components/faith/prayers/MichaelGebet.svelte";
	import BruderKlausGebet from "$lib/components/faith/prayers/BruderKlausGebet.svelte";
	import JosephGebet from "$lib/components/faith/prayers/JosephGebet.svelte";
	import Confiteor from "$lib/components/faith/prayers/Confiteor.svelte";
	import GuardianAngel from "$lib/components/faith/prayers/GuardianAngel.svelte";
	import ApostlesCreed from "$lib/components/faith/prayers/ApostlesCreed.svelte";
	import TantumErgo from "$lib/components/faith/prayers/TantumErgo.svelte";
	import Angelus from "$lib/components/faith/prayers/Angelus.svelte";
	import ReginaCaeli from "$lib/components/faith/prayers/ReginaCaeli.svelte";
	import AnimaChristi from "$lib/components/faith/prayers/AnimaChristi.svelte";
	import PrayerBeforeACrucifix from "$lib/components/faith/prayers/PrayerBeforeACrucifix.svelte";
	import Postcommunio from "$lib/components/faith/prayers/Postcommunio.svelte";
	import Prayer from "$lib/components/faith/prayers/Prayer.svelte";
	import { isEastertide as checkEastertide } from "$lib/js/easter.svelte";

	let { data } = $props();

	// Create language context for prayer components
	const langContext = createLanguageContext({ urlLang: /** @type {'de' | 'en'} */(data.lang), initialLatin: data.initialLatin });

	// Update lang store when data.lang changes (e.g., after navigation)
	$effect(() => {
		langContext.lang.set(data.lang);
	});

	// Reactive isEnglish based on data.lang
	const isEnglish = $derived(data.lang === 'en');

	const labels = $derived({
		title: isEnglish ? 'Prayers' : 'Gebete',
		description: isEnglish
			? 'Catholic prayers in Latin and English.'
			: 'Katholische Gebete auf Deutsch und Latein.',
		signOfCross: isEnglish ? 'The Sign of the Cross' : 'Das heilige Kreuzzeichen',
		gloriaPatri: 'Glória Patri',
		paternoster: isEnglish ? 'Our Father' : 'Paternoster',
		credo: isEnglish ? 'Nicene Creed' : 'Credo',
		aveMaria: isEnglish ? 'Hail Mary' : 'Ave Maria',
		salveRegina: 'Salve Regina',
		fatima: isEnglish ? 'Fatima Prayer' : 'Das Fatimagebet',
		gloria: 'Glória',
		michael: isEnglish ? 'Prayer to St. Michael the Archangel' : 'Gebet zum hl. Erzengel Michael',
		bruderKlaus: isEnglish ? 'Prayer of St. Nicholas of Flüe' : 'Bruder Klaus Gebet',
		joseph: isEnglish ? 'Prayer to St. Joseph by Pope St. Pius X' : 'Josephgebet des hl. Papst Pius X',
		confiteor: isEnglish ? 'The Confiteor' : 'Das Confiteor',
		searchPlaceholder: isEnglish ? 'Search prayers...' : 'Gebete suchen...',
		clearSearch: isEnglish ? 'Clear search' : 'Suche löschen',
		textMatch: isEnglish ? 'Match in prayer text' : 'Treffer im Gebetstext',
		postcommunio: isEnglish ? 'Postcommunio Prayers' : 'Nachkommuniongebete',
		animachristi: 'Ánima Christi',
		prayerbeforeacrucifix: isEnglish ? 'Prayer Before a Crucifix' : 'Gebet vor einem Kruzifix',
		guardianAngel: isEnglish ? 'Guardian Angel Prayer' : 'Schutzengel-Gebet',
		apostlesCreed: isEnglish ? "Apostles' Creed" : 'Apostolisches Glaubensbekenntnis',
		tantumErgo: 'Tantum Ergo',
		angelus: 'Angelus',
		reginaCaeli: 'Regína Cæli'
	});

	// TODO: Add categories: 'meal' (Tischgebete/Meal) and 'morning_evening' (Morgen-/Abendgebete/Morning & Evening)
	// when corresponding prayers are added to the collection

	const categories = [
		{ id: 'essential', de: 'Grundgebete', en: 'Essential' },
		{ id: 'marian', de: 'Marianisch', en: 'Marian' },
		{ id: 'saints', de: 'Heilige', en: 'Saints' },
		{ id: 'eucharistic', de: 'Eucharistie', en: 'Eucharistic' },
		{ id: 'praise', de: 'Lobpreis', en: 'Praise' },
		{ id: 'penitential', de: 'Busse', en: 'Penitential' },
	];

	const prayerCategories = {
		signOfCross: ['essential'],
		gloriaPatri: ['essential', 'praise'],
		paternoster: ['essential'],
		credo: ['essential'],
		aveMaria: ['essential', 'marian'],
		salveRegina: ['marian'],
		fatima: ['marian', 'penitential'],
		gloria: ['praise'],
		michael: ['saints'],
		bruderKlaus: ['saints'],
		joseph: ['saints'],
		confiteor: ['penitential'],
		guardianAngel: ['essential'],
		apostlesCreed: ['essential'],
		tantumErgo: ['eucharistic', 'praise'],
		angelus: ['marian'],
		reginaCaeli: ['marian'],
		animachristi: ['eucharistic'],
		prayerbeforeacrucifix: ['eucharistic', 'penitential'],
		postcommunio: ['eucharistic'],
	};

	let selectedCategory = $state(data.initialCategory);

	// JS-only search (hidden without JS)
	let jsEnabled = $state(false);
	let searchQuery = $state('');

	/**
	 * Build href for category filter, preserving latin param state
	 * @param {string|null} categoryId
	 */
	function buildFilterHref(categoryId) {
		const params = new URLSearchParams();
		if (categoryId) params.set('category', categoryId);
		if (!data.initialLatin) params.set('latin', '0');
		const qs = params.toString();
		return qs ? `?${qs}` : '?';
	}

	onMount(() => {
		jsEnabled = true;

		// Clean up URL params after hydration (state is now in component state)
		if (window.location.search) {
			history.replaceState({}, '', window.location.pathname);
		}
	});

	// Match results: 'primary' (name/terms), 'secondary' (text only), or null (no match)
	/** @type {Map<string, 'primary' | 'secondary'>} */
	let matchResults = $state(/** @type {Map<string, 'primary' | 'secondary'>} */ (new Map()));

	// Define prayers with their searchable terms and slugs for URLs
	const prayers = $derived([
		{ id: 'signOfCross', searchTerms: ['kreuzzeichen', 'sign of the cross', 'cross'], slug: isEnglish ? 'the-sign-of-the-cross' : 'das-heilige-kreuzzeichen' },
		{ id: 'gloriaPatri', searchTerms: ['gloria patri', 'glory be', 'ehre sei'], slug: 'gloria-patri' },
		{ id: 'paternoster', searchTerms: ['paternoster', 'our father', 'vater unser', 'pater noster'], slug: isEnglish ? 'our-father' : 'paternoster' },
		{ id: 'credo', searchTerms: ['credo', 'creed', 'glaubensbekenntnis', 'nicene'], slug: isEnglish ? 'nicene-creed' : 'credo' },
		{ id: 'aveMaria', searchTerms: ['ave maria', 'hail mary', 'gegrüsst seist du'], slug: isEnglish ? 'hail-mary' : 'ave-maria' },
		{ id: 'salveRegina', searchTerms: ['salve regina', 'hail holy queen'], slug: 'salve-regina' },
		{ id: 'fatima', searchTerms: ['fatima', 'fatimagebet'], slug: isEnglish ? 'fatima-prayer' : 'das-fatimagebet' },
		{ id: 'gloria', searchTerms: ['gloria', 'glory', 'gloria in excelsis'], slug: 'gloria' },
		{ id: 'michael', searchTerms: ['michael', 'archangel', 'erzengel', 'satan', 'devil', 'teufel'], slug: isEnglish ? 'prayer-to-st-michael-the-archangel' : 'gebet-zum-hl-erzengel-michael' },
		{ id: 'bruderKlaus', searchTerms: ['bruder klaus', 'nicholas', 'niklaus', 'flüe'], slug: isEnglish ? 'prayer-of-st-nicholas-of-flue' : 'bruder-klaus-gebet' },
		{ id: 'joseph', searchTerms: ['joseph', 'josef', 'pius'], slug: isEnglish ? 'prayer-to-st-joseph-by-pope-st-pius-x' : 'josephgebet-des-hl-papst-pius-x' },
		{ id: 'confiteor', searchTerms: ['confiteor', 'i confess', 'ich bekenne', 'mea culpa'], slug: isEnglish ? 'the-confiteor' : 'das-confiteor' },
		{ id: 'guardianAngel', searchTerms: ['schutzengel', 'guardian angel', 'angele dei', 'engel gottes'], slug: isEnglish ? 'guardian-angel-prayer' : 'schutzengel-gebet' },
		{ id: 'apostlesCreed', searchTerms: ['apostolisches glaubensbekenntnis', "apostles' creed", 'symbolum apostolorum', 'ich glaube an gott'], slug: isEnglish ? 'apostles-creed' : 'apostolisches-glaubensbekenntnis' },
		{ id: 'tantumErgo', searchTerms: ['tantum ergo', 'genitori', 'sakrament', 'sacrament'], slug: 'tantum-ergo' },
		{ id: 'angelus', searchTerms: ['angelus', 'engel des herrn', 'angel of the lord'], slug: 'angelus' },
		{ id: 'reginaCaeli', searchTerms: ['regina caeli', 'regina coeli', 'himmelskönigin', 'queen of heaven'], slug: 'regina-caeli' },
		{ id: 'animachristi', searchTerms: ['anima christi', 'seele christi', 'soul of christ'], slug: 'anima-christi' },
		{ id: 'prayerbeforeacrucifix', searchTerms: ['kruzifix', 'crucifix', 'kreuz', 'cross', 'en ego'], slug: isEnglish ? 'prayer-before-a-crucifix' : 'gebet-vor-einem-kruzifix' },
		{ id: 'postcommunio', searchTerms: ['postcommunio', 'nachkommunion', 'kommunion', 'communion'], slug: 'postcommunio' }
	]);

	// Base URL for prayer links
	const baseUrl = $derived(isEnglish ? '/faith/prayers' : '/glaube/gebete');

	// Get prayer name by ID (reactive based on language)
	/** @param {string} id */
	function getPrayerName(id) {
		const nameMap = {
			signOfCross: labels.signOfCross,
			gloriaPatri: labels.gloriaPatri,
			paternoster: labels.paternoster,
			credo: labels.credo,
			aveMaria: labels.aveMaria,
			salveRegina: labels.salveRegina,
			fatima: labels.fatima,
			gloria: labels.gloria,
			michael: labels.michael,
			bruderKlaus: labels.bruderKlaus,
			joseph: labels.joseph,
			confiteor: labels.confiteor,
			guardianAngel: labels.guardianAngel,
			apostlesCreed: labels.apostlesCreed,
			tantumErgo: labels.tantumErgo,
			angelus: labels.angelus,
			reginaCaeli: labels.reginaCaeli,
			animachristi: labels.animachristi,
			prayerbeforeacrucifix: labels.prayerbeforeacrucifix,
			postcommunio: labels.postcommunio
		};
		return /** @type {Record<string, string>} */(nameMap)[id] || id;
	}

	/**
	 * Normalize text for search comparison
	 * @param {string} text
	 */
	function normalize(text) {
		return text.toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, '');
	}

	/**
	 * Search the DOM and update match results
	 */
	function performSearch() {
		if (!browser) return;

		const query = searchQuery.trim();
		const newResults = new Map();

		if (!query) {
			// No search query - show all as primary
			prayers.forEach(p => newResults.set(p.id, 'primary'));
		} else {
			const normalizedQuery = normalize(query);

			prayers.forEach(prayer => {
				const name = getPrayerName(prayer.id);

				// Check name match
				if (normalize(name).includes(normalizedQuery)) {
					newResults.set(prayer.id, 'primary');
					return;
				}

				// Check search terms match
				if (prayer.searchTerms.some(term => normalize(term).includes(normalizedQuery))) {
					newResults.set(prayer.id, 'primary');
					return;
				}

				// Check DOM text content
				const element = document.querySelector(`[data-prayer-id="${prayer.id}"]`);
				if (element) {
					const textContent = normalize(element.textContent || '');
					if (textContent.includes(normalizedQuery)) {
						newResults.set(prayer.id, 'secondary');
					}
				}
			});
		}

		matchResults = newResults;
	}

	// Run search when query changes (debounced)
	$effect(() => {
		if (browser) {
			const query = searchQuery; // track dependency
			const timer = setTimeout(performSearch, 50);
			return () => clearTimeout(timer);
		}
	});

	// Helper to get match class for a prayer
	/** @param {string} id */
	function getMatchClass(id) {
		if (!jsEnabled) return '';
		const match = matchResults.get(id);
		if (!searchQuery.trim()) return '';
		if (match === 'primary') return '';
		if (match === 'secondary') return 'secondary-match';
		return 'no-match';
	}

	// Filtered by category, then sorted by search match
	const filteredPrayers = $derived.by(() => {
		let result = prayers;
		if (selectedCategory) {
			const cat = selectedCategory;
			result = result.filter(p => /** @type {Record<string, string[]>} */(prayerCategories)[p.id]?.includes(cat));
		}
		if (!searchQuery.trim()) return result;

		return [...result].sort((a, b) => {
			const matchA = matchResults.get(a.id);
			const matchB = matchResults.get(b.id);

			const orderA = matchA === 'primary' ? 0 : matchA === 'secondary' ? 1 : 2;
			const orderB = matchB === 'primary' ? 0 : matchB === 'secondary' ? 1 : 2;

			return orderA - orderB;
		});
	});

	// Prayer metadata (bilingue status)
	/** @type {Record<string, {bilingue: boolean}>} */
	const prayerMeta = {
		signOfCross: { bilingue: true },
		gloriaPatri: { bilingue: true },
		paternoster: { bilingue: true },
		credo: { bilingue: true },
		aveMaria: { bilingue: true },
		salveRegina: { bilingue: true },
		fatima: { bilingue: true },
		gloria: { bilingue: true },
		michael: { bilingue: true },
		bruderKlaus: { bilingue: false },
		joseph: { bilingue: false },
		confiteor: { bilingue: true },
		guardianAngel: { bilingue: true },
		apostlesCreed: { bilingue: true },
		tantumErgo: { bilingue: true },
		angelus: { bilingue: true },
		reginaCaeli: { bilingue: true },
		animachristi: { bilingue: true },
		prayerbeforeacrucifix: { bilingue: true },
		postcommunio: { bilingue: true }
	};

	const isEastertide = $derived(checkEastertide());

	// Toggle href for no-JS fallback (navigates to opposite latin state)
	const latinToggleHref = $derived(data.initialLatin ? '?latin=0' : '?');
</script>

<svelte:head>
	<title>{labels.title} - Bocken</title>
	<meta name="description" content={labels.description} />
</svelte:head>
<style>
.ccontainer{
	margin: auto;
	overflow-x: visible;
	max-width: 1000px;
}
.container{
	column-count: 2;
	column-gap: 1em;
}
@media (max-width: 800px) {
	.container{
		column-count: 1;
		padding-left: calc((100% - 600px) * 0.5);
	}
}
h1{
	text-align: center;
	font-size: 3rem;
}
.toggle-controls {
	display: flex;
	justify-content: center;
	margin-bottom: 2rem;
}

/* Category filters */
.category-filters {
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	gap: 0.5em;
	margin-bottom: 1.5rem;
	padding: 0 1em;
}
.category-pill {
	padding: 0.35em 0.9em;
	border: 1.5px solid var(--nord3);
	border-radius: 999px;
	color: var(--nord4);
	text-decoration: none;
	font-size: 0.9em;
	transition: border-color 0.15s, color 0.15s, background-color 0.15s;
}
.category-pill:hover {
	border-color: var(--nord8);
	color: var(--nord8);
}
.category-pill.selected {
	border-color: var(--nord8);
	background-color: var(--nord8);
	color: var(--nord0);
}
@media(prefers-color-scheme: light) {
    :global(:root:not([data-theme="dark"])) .category-pill {
		border-color: var(--nord4);
		color: var(--nord3);
	}
	:global(:root:not([data-theme="dark"])) .category-pill:hover {
		border-color: var(--nord10);
		color: var(--nord10);
	}
	:global(:root:not([data-theme="dark"])) .category-pill.selected {
		border-color: var(--nord10);
		background-color: var(--nord10);
		color: var(--nord6);
	}
  }
:global(:root[data-theme="light"]) .category-pill {
	border-color: var(--nord4);
		color: var(--nord3);
}
:global(:root[data-theme="light"]) .category-pill:hover {
	border-color: var(--nord10);
		color: var(--nord10);
}
:global(:root[data-theme="light"]) .category-pill.selected {
	border-color: var(--nord10);
		background-color: var(--nord10);
		color: var(--nord6);
}

/* Search result styling */
.prayer-wrapper {
	position: relative;
	break-inside: avoid-column;
	margin-bottom: 1em;
}
.prayer-wrapper.no-match {
	display: none;
}
.prayer-wrapper.secondary-match {
	opacity: 0.7;
}
.prayer-wrapper.secondary-match::before {
	content: attr(data-match-label);
	position: absolute;
	top: 0.3em;
	right: 0.3em;
	font-size: 0.65em;
	padding: 0.2em 0.5em;
	background: var(--nord3);
	color: var(--nord6);
	border-radius: 4px;
	z-index: 1;
}
@media(prefers-color-scheme: light) {
    :global(:root:not([data-theme="dark"])) .prayer-wrapper.secondary-match::before {
		background: var(--nord4);
		color: var(--nord0);
	}
  }
:global(:root[data-theme="light"]) .prayer-wrapper.secondary-match::before {
	background: var(--nord4);
		color: var(--nord0);
}

/* Postcommunio section */
.postcommunio-section {
	max-width: 600px;
	margin: 2rem auto;
	padding: 1.5em;
	background-color: var(--accent-dark);
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
@media(prefers-color-scheme: light) {
    :global(:root:not([data-theme="dark"])) .postcommunio-section {
		background-color: var(--nord5);
	}
  }
:global(:root[data-theme="light"]) .postcommunio-section {
	background-color: var(--nord5);
}
/* Seasonal badge */
.seasonal-badge {
	display: inline-block;
	margin-top: 0.5em;
	padding: 0.2em 0.7em;
	font-size: 0.75em;
	border-radius: 999px;
	background-color: var(--nord14);
	color: var(--nord0);
}

/* Search is hidden without JS */
.js-only {
	display: none;
}
.js-enabled .js-only {
	display: block;
}
</style>
<div class:js-enabled={jsEnabled}>
<h1>{labels.title}</h1>

<div class="toggle-controls">
	<LanguageToggle
		initialLatin={data.initialLatin}
		hasUrlLatin={data.hasUrlLatin}
		href={latinToggleHref}
	/>
</div>

<nav class="category-filters" aria-label={isEnglish ? 'Filter by category' : 'Nach Kategorie filtern'}>
	<a
		href={buildFilterHref(null)}
		class="category-pill"
		class:selected={!selectedCategory}
		onclick={(e) => { e.preventDefault(); selectedCategory = null; }
  }
	>{isEnglish ? 'All' : 'Alle'}</a>
	{#each categories as cat (cat.id)}
		<a
			href={buildFilterHref(cat.id)}
			class="category-pill"
			class:selected={selectedCategory === cat.id}
			onclick={(e) => { e.preventDefault(); selectedCategory = cat.id; }
  }
		>{isEnglish ? cat.en : cat.de}</a>
	{/each}
</nav>

<div class="js-only">
	<SearchInput
		bind:value={searchQuery}
		placeholder={labels.searchPlaceholder}
		clearTitle={labels.clearSearch}
	/>
</div>

<div class="ccontainer">
<div class=container>
{#each filteredPrayers as prayer (prayer.id)}
	<div class="prayer-wrapper {getMatchClass(prayer.id)}" data-match-label={labels.textMatch}>
	<Gebet name={getPrayerName(prayer.id)} is_bilingue={prayerMeta[prayer.id]?.bilingue ?? true} id={prayer.id} href="{baseUrl}/{prayer.slug}">
			{#if prayer.id === 'signOfCross'}
				<Kreuzzeichen />
			{:else if prayer.id === 'gloriaPatri'}
				<GloriaPatri />
			{:else if prayer.id === 'paternoster'}
				<Paternoster />
			{:else if prayer.id === 'credo'}
				<Credo />
			{:else if prayer.id === 'aveMaria'}
				<AveMaria />
			{:else if prayer.id === 'salveRegina'}
				<SalveRegina />
			{:else if prayer.id === 'fatima'}
				<FatimaGebet />
			{:else if prayer.id === 'michael'}
				<MichaelGebet />
			{:else if prayer.id === 'bruderKlaus'}
				<BruderKlausGebet />
			{:else if prayer.id === 'joseph'}
				<JosephGebet />
			{:else if prayer.id === 'confiteor'}
				<Confiteor />
			{:else if prayer.id === 'guardianAngel'}
				<GuardianAngel />
			{:else if prayer.id === 'apostlesCreed'}
				<ApostlesCreed />
			{:else if prayer.id === 'tantumErgo'}
				<TantumErgo />
			{:else if prayer.id === 'angelus'}
				<Angelus />
			{:else if prayer.id === 'reginaCaeli'}
				<ReginaCaeli />
			{:else if prayer.id === 'animachristi'}
				<AnimaChristi />
			{:else if prayer.id === 'prayerbeforeacrucifix'}
				<PrayerBeforeACrucifix />
			{:else if prayer.id === 'gloria'}
				<Gloria intro={true} />
			{:else if prayer.id === 'postcommunio'}
				<Postcommunio onlyIntro={true} />
			{/if}
			{#if prayer.id === 'reginaCaeli' && isEastertide}
				<span class="seasonal-badge">{isEnglish ? 'Eastertide' : 'Osterzeit'}</span>
			{/if}
		</Gebet>
	</div>
{/each}
</div>

</div>
</div>
