<script lang="ts">
	import { onMount } from 'svelte';
	import Icon from '@iconify/svelte';
	import LiquidGlass from '$lib/components/LiquidGlass.svelte';
	import Combobox from '$lib/components/PublicComponents/Combobox.svelte';

	let selectedTz: string = $state('');
	let tzList: string[] = $state([]);

	onMount(() => {
		selectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
		tzList = [...Intl.supportedValuesOf('timeZone')];
	});

	function formatTimezone(tz: string): string {
		return tz.replace(/_/g, ' ');
	}

	function handleTimezoneSelect(event: CustomEvent<string>) {
		selectedTz = event.detail;
	}

	$effect(() => {
		if (selectedTz) {
			fetch('http://localhost:4269/systemapi/timezone', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({ timezone: selectedTz })
			});
		}
	});
</script>

<LiquidGlass class="rounded-xl p-6">
	<div class="flex items-center gap-3 mb-4">
		<Icon icon="mdi:clock-time-four-outline" class="w-6 h-6 text-base-content" />
		<div>
			<h2 class="text-xl font-semibold text-base-content">Timezone</h2>
			<p class="text-base-content/70 text-sm">Type a city to filter and select your zone</p>
		</div>
	</div>

	{#if selectedTz}
		<Combobox
			items={tzList}
			bind:value={selectedTz}
			displayValue={formatTimezone(selectedTz)}
			placeholder="Search city…"
			on:select={handleTimezoneSelect}
		>
			<svelte:fragment slot="item" let:item>
				{formatTimezone(item)}
			</svelte:fragment>
			<svelte:fragment slot="empty">No timezones found</svelte:fragment>
		</Combobox>
	{/if}

	{#if selectedTz}
		<div class="mt-3 text-sm text-base-content/70">
			Current: <span class="font-medium">{selectedTz}</span>
		</div>
	{/if}
</LiquidGlass>
