---
import '@pagefind/default-ui/css/ui.css';
---

<site-search id="search" class="ms-auto">
	<button
		data-open-modal
		disabled
		class="flex h-9 w-9 items-center justify-center rounded-md ring-zinc-400 transition-all hover:ring-2">
		<svg
			aria-label="search"
			class="h-7 w-7"
			xmlns="http://www.w3.org/2000/svg"
			width="16"
			height="16"
			viewBox="0 0 24 24"
			fill="none"
			stroke="currentColor"
			stroke-linecap="round"
			stroke-linejoin="round"
			stroke-width="1.5">
			<path stroke="none" d="M0 0h24v24H0z"></path>
			<path d="M3 10a7 7 0 1 0 14 0 7 7 0 1 0-14 0M21 21l-6-6"></path>
		</svg>
	</button>
	<dialog
		aria-label="search"
		class="bg-bgColor h-full max-h-full w-full max-w-full border border-zinc-400 shadow backdrop:backdrop-blur sm:mx-auto sm:mb-auto sm:mt-16 sm:h-max sm:max-h-[calc(100%-8rem)] sm:min-h-[15rem] sm:w-5/6 sm:max-w-[48rem] sm:rounded-md">
		<div class="dialog-frame flex flex-col gap-4 p-6 pt-12 sm:pt-6">
			<button
				data-close-modal
				class="ms-auto cursor-pointer rounded-md bg-zinc-200 p-2 font-semibold">
				Close
			</button>
			{
				import.meta.env.DEV ? (
					<div class="mx-auto text-center">
						<p>
							Search is only available in production builds. <br />
							Try building and previewing the site to test it out locally.
						</p>
					</div>
				) : (
					<div class="search-container">
						<div id="deploy__search" />
					</div>
				)
			}
		</div>
	</dialog>
</site-search>

<script>
	class SiteSearch extends HTMLElement {
		private openBtn: HTMLButtonElement;
		private closeBtn: HTMLButtonElement;
		private dialog: HTMLDialogElement;
		private dialogFrame: HTMLDivElement;

		constructor() {
			super();
			this.openBtn = this.querySelector<HTMLButtonElement>('button[data-open-modal]')!;
			this.closeBtn = this.querySelector<HTMLButtonElement>('button[data-close-modal]')!;
			this.dialog = this.querySelector('dialog')!;
			this.dialogFrame = this.querySelector('.dialog-frame')!;

			this.openBtn.addEventListener('click', this.openModal);
			this.openBtn.disabled = false;
			this.closeBtn.addEventListener('click', this.closeModal);
		}

		connectedCallback() {
			// Listen for keyboard shortcut
			window.addEventListener('keydown', this.onWindowKeydown);

			// only add pagefind in production
			if (import.meta.env.DEV) return;
			const onIdle = window.requestIdleCallback || ((cb) => setTimeout(cb, 1));
			onIdle(async () => {
				const { PagefindUI } = await import('@pagefind/default-ui');
				new PagefindUI({
					element: '#deploy__search',
					baseUrl: import.meta.env.BASE_URL,
					bundlePath: import.meta.env.BASE_URL.replace(/\/$/, '') + '/pagefind/',
					showImages: false,
					showSubResults: true,
				});
			});
		}

		disconnectedCallback() {
			window.removeEventListener('keydown', this.onWindowKeydown);
		}

		onWindowClick = (event: MouseEvent) => {
			// check if it's a link
			const isLink = 'href' in (event.target || {});
			// make sure the click is either a link or outside of the dialog
			if (
				isLink ||
				(document.body.contains(event.target as Node) &&
					!this.dialogFrame.contains(event.target as Node))
			)
				this.closeModal();
		};

		onWindowKeydown = (e: KeyboardEvent) => {
			// check if it's the / key
			if (e.key === '/' && !this.dialog.open) {
				this.openModal();
				e.preventDefault();
			}
		};

		openModal = (event?: MouseEvent) => {
			this.dialog.showModal();
			this.querySelector('input')?.focus();
			event?.stopPropagation();
			window.addEventListener('click', this.onWindowClick);
		};

		closeModal = () => {
			if (this.dialog.open) {
				this.dialog.close();
				window.removeEventListener('click', this.onWindowClick);
			}
		};
	}

	customElements.define('site-search', SiteSearch);
</script>

<style is:global>
	:root {
		--pagefind-ui-font: inherit;
	}

	#deploy__search .pagefind-ui__search-clear {
		width: calc(60px * var(--pagefind-ui-scale));
		padding: 0;
		background-color: transparent;
		overflow: hidden;
	}
	#deploy__search .pagefind-ui__search-clear:focus {
		outline: 1px solid;
	}
	#deploy__search .pagefind-ui__search-clear::before {
		content: '';
		-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke-width='1.5' stroke='currentColor' %3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M6 18L18 6M6 6l12 12'%3E%3C/path%3E%3C/svg%3E")
			center / 60% no-repeat;
		mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke-width='1.5' stroke='currentColor' %3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M6 18L18 6M6 6l12 12'%3E%3C/path%3E%3C/svg%3E")
			center / 60% no-repeat;
		display: block;
		width: 100%;
		height: 100%;
	}

	#deploy__search .pagefind-ui__result {
		border: 0;
	}

	#search .pagefind-ui__result-link {
		background-size: 100% 6px;
		background-position: bottom;
		background-repeat: repeat-x;
		background-image: linear-gradient(transparent, transparent 5px);
	}

	#deploy__search .pagefind-ui__result-link:hover {
		text-decoration: none;
		background-image: linear-gradient(transparent, transparent 4px);
	}

	#search mark {
		background-color: transparent;
		font-weight: 600;
	}
</style>

<style>
	#deploy__search {
		--pagefind-ui-border: theme('colors.zinc.400');
		--pagefind-ui-border-width: 1px;
	}
</style>
