const moduleSearchBarOrphicUi = {
	/**
	 * Initialise le module de recherche
	 */
	init() {
		// Trouve toutes les barres de recherche sur la page
		const searchBars = document.querySelectorAll(
			".wp-block-orphic-ui-search-bar",
		);

		searchBars.forEach((searchBar) => {
			this.initializeSearchBar(searchBar);
		});
	},

	/**
	 * Initialise une barre de recherche spécifique
	 * @param {HTMLElement} searchBar
	 */
	initializeSearchBar(searchBar) {
		// Récupère les éléments de la barre de recherche
		const input = searchBar.querySelector(".search-input");
		const button = searchBar.querySelector(".search-button");
		const dropdown = searchBar.querySelector(".search-results-dropdown");

		// Récupère la configuration
		const searchConfig = JSON.parse(searchBar.dataset.searchConfig || "{}");
		const urlConfig = JSON.parse(searchBar.dataset.urlConfig || "{}");
		const restUrl = searchBar.dataset.restUrl;
		const nonce = searchBar.dataset.nonce;
		let searchResults = [];

		// Variables pour le debounce
		let debounceTimer;
		const DEBOUNCE_DELAY = 300;

		// Gestionnaire de recherche
		const handleSearch = async (searchTerm) => {
			if (!searchTerm.trim()) {
				dropdown.style.display = "none";
				return;
			}

			// Affiche le loading
			dropdown.innerHTML =
				'<div class="loading-search"><div class="spinner"></div></div>';
			dropdown.style.display = "block";

			try {
				const response = await fetch(restUrl, {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
						"X-WP-Nonce": nonce,
					},
					body: JSON.stringify({
						search_term: searchTerm,
						search_config: searchConfig,
					}),
				});

				const data = await response.json();

				if (data.success) {
					searchResults = data.results;
					this.displayResults(dropdown, data.results, searchBar);
				}
			} catch (error) {
				console.error("Search error:", error);
				dropdown.innerHTML =
					'<div class="no-results">Une erreur est survenue</div>';
			}
		};

		// Fonction pour gérer la soumission de la recherche
		const handleSearchSubmit = (searchTerm) => {
			if (!searchTerm) return;

			if (urlConfig.is_custom_url && urlConfig.url_custom_params) {
				const url = `${urlConfig.url_custom_params}`;
				const urlWithSearchTerm = url.replace(
					"%7Bsearch_term%7D",
					encodeURIComponent(searchTerm),
				);
				window.location.href = urlWithSearchTerm;
			} else {
				window.location.href = `${urlConfig.home_url}/?s=${encodeURIComponent(
					searchTerm,
				)}`;
			}
		};

		// Récupère le terme de recherche depuis l'URL si présent
		const urlParams = new URLSearchParams(window.location.search);
		const searchTermFromUrl =
			urlParams.get("s") || urlParams.get("search_term");
		if (searchTermFromUrl) {
			input.value = decodeURIComponent(searchTermFromUrl);
			// Déclenche la recherche initiale
		}

		// Event listeners
		input.addEventListener("input", (e) => {
			clearTimeout(debounceTimer);
			debounceTimer = setTimeout(() => {
				handleSearch(e.target.value);
			}, DEBOUNCE_DELAY);
		});

		input.addEventListener("focus", () => {
			if (input.value.trim()) {
				if (searchResults.length === 0) {
					handleSearch(input.value);
				}

				dropdown.style.display = "block";
			}
		});

		// Ajout de la gestion de la touche Enter
		input.addEventListener("keypress", (e) => {
			if (e.key === "Enter") {
				e.preventDefault();
				handleSearchSubmit(input.value.trim());
			}
		});

		// Gestion du clic sur le bouton de recherche
		button.addEventListener("click", () => {
			handleSearchSubmit(input.value.trim());
		});

		// Fermeture du dropdown au clic en dehors
		document.addEventListener("click", (e) => {
			if (!searchBar.contains(e.target)) {
				dropdown.style.display = "none";
			}
		});
	},

	/**
	 * Affiche les résultats dans le dropdown
	 * @param {HTMLElement} dropdown
	 * @param {Array} results
	 * @param {Object} urlConfig
	 */
	displayResults(dropdown, results, searchBar) {
		if (!results.length) {
			const noResultsMessage = searchBar.dataset.noResultsMessage;
			dropdown.innerHTML = `<div class="no-results">${noResultsMessage}</div>`;
			dropdown.style.display = "block";
			return;
		}

		const html = results
			.map(
				(result) => `
			<div class="search-result-item" data-url="${result.url}">
				<div class="result-title">${result.title}</div>
				<div class="result-type">${this.formatPostType(result.type)}</div>
				<div class="result-excerpt">${result.excerpt}</div>
			</div>
		`,
			)
			.join("");

		dropdown.innerHTML = html;
		dropdown.style.display = "block";

		// Ajoute les event listeners pour les résultats
		dropdown.querySelectorAll(".search-result-item").forEach((item) => {
			item.addEventListener("click", () => {
				window.location.href = item.dataset.url;
			});
		});
	},

	/**
	 * Formate le type de post pour l'affichage
	 * @param {string} postType
	 * @returns {string}
	 */
	formatPostType(postType) {
		return postType.charAt(0).toUpperCase() + postType.slice(1);
	},

	/**
	 * Formate les termes pour l'affichage
	 * @param {Object} terms
	 * @returns {string}
	 */
	formatTerms(terms) {
		const termsList = Object.entries(terms)
			.map(([taxonomy, termsList]) => {
				const termNames = termsList.map((term) => term.name).join(", ");
				return `<span class="taxonomy-terms">${termNames}</span>`;
			})
			.join(" ");

		return termsList ? `<div class="result-terms">${termsList}</div>` : "";
	},

	/**
	 * Construit l'URL de recherche personnalisée
	 * @param {string} baseUrl
	 * @param {string} searchTerm
	 * @param {Object} searchConfig
	 * @returns {string}
	 */
	buildSearchUrl(baseUrl, searchTerm, searchConfig) {
		const url = new URL(baseUrl, window.location.origin);
		const params = new URLSearchParams(url.search);

		// Ajoute le terme de recherche
		params.set("s", searchTerm);

		// Ajoute les types de post
		if (searchConfig.post_types?.length) {
			params.set("post_type", searchConfig.post_types.join(","));
		}

		// Ajoute les taxonomies
		if (searchConfig.taxonomies) {
			Object.entries(searchConfig.taxonomies).forEach(
				([postType, taxonomies]) => {
					if (taxonomies.length) {
						params.set(`tax_${postType}`, taxonomies.join(","));
					}
				},
			);
		}

		url.search = params.toString();
		return url.toString();
	},
};

// Initialise le module quand le DOM est chargé
document.addEventListener("DOMContentLoaded", () => {
	moduleSearchBarOrphicUi.init();
});
