<script lang="ts">
	import { onMount } from 'svelte';
	import { Cloud, Sun, CloudRain, CloudSnow, CloudLightning, CloudDrizzle, Wind, Thermometer } from 'lucide-svelte';
	import type { ClockWeatherWidgetConfig } from '$lib/types/widget.js';

	interface Props {
		config: ClockWeatherWidgetConfig;
	}

	let { config }: Props = $props();

	let now = $state(new Date());
	let weatherData: { temp: number; condition: string; location?: string } | null = $state(null);
	let weatherError = $state(false);
	let weatherLoading = $state(false);

	const clockStyle = $derived(config.clockStyle ?? 'digital');
	const showWeather = $derived(config.showWeather ?? false);

	const timeFormatter = $derived(
		new Intl.DateTimeFormat('en-US', {
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
			hour12: clockStyle !== '24h',
			timeZone: config.timezone || undefined
		})
	);

	const dateFormatter = $derived(
		new Intl.DateTimeFormat('en-US', {
			weekday: 'short',
			month: 'short',
			day: 'numeric',
			timeZone: config.timezone || undefined
		})
	);

	const timeStr = $derived(timeFormatter.format(now));
	const dateStr = $derived(dateFormatter.format(now));

	// Analog clock hand angles
	const hours = $derived.by(() => {
		const d = new Date(now.toLocaleString('en-US', { timeZone: config.timezone || undefined }));
		return d.getHours() % 12;
	});
	const minutes = $derived.by(() => {
		const d = new Date(now.toLocaleString('en-US', { timeZone: config.timezone || undefined }));
		return d.getMinutes();
	});
	const seconds = $derived.by(() => {
		const d = new Date(now.toLocaleString('en-US', { timeZone: config.timezone || undefined }));
		return d.getSeconds();
	});

	const hourAngle = $derived((hours + minutes / 60) * 30);
	const minuteAngle = $derived((minutes + seconds / 60) * 6);
	const secondAngle = $derived(seconds * 6);

	async function fetchWeather() {
		if (!showWeather || !config.latitude || !config.longitude) return;
		weatherLoading = true;
		weatherError = false;
		try {
			const res = await fetch(
				`/api/widgets/weather?lat=${config.latitude}&lng=${config.longitude}`
			);
			if (res.ok) {
				const json = await res.json();
				if (json.success && json.data) {
					weatherData = json.data;
				}
			} else {
				weatherError = true;
			}
		} catch {
			weatherError = true;
		} finally {
			weatherLoading = false;
		}
	}

	onMount(() => {
		fetchWeather();
	});

	// Tick clock every second
	$effect(() => {
		const interval = setInterval(() => {
			now = new Date();
		}, 1000);
		return () => clearInterval(interval);
	});

	// Refresh weather every 30 minutes
	$effect(() => {
		if (!showWeather) return;
		const interval = setInterval(fetchWeather, 30 * 60 * 1000);
		return () => clearInterval(interval);
	});

	function getWeatherIcon(condition: string) {
		const c = condition.toLowerCase();
		if (c.includes('rain')) return CloudRain;
		if (c.includes('drizzle')) return CloudDrizzle;
		if (c.includes('snow')) return CloudSnow;
		if (c.includes('thunder') || c.includes('lightning')) return CloudLightning;
		if (c.includes('wind')) return Wind;
		if (c.includes('cloud') || c.includes('overcast')) return Cloud;
		return Sun;
	}
</script>

<div class="flex h-full flex-col items-center justify-center rounded-[1.4rem] border border-border bg-card shadow-[var(--shadow-soft)] p-4">
	{#if clockStyle === 'analog'}
		<!-- Analog clock face -->
		<svg viewBox="0 0 100 100" class="h-32 w-32">
			<!-- Clock face -->
			<circle cx="50" cy="50" r="48" fill="none" stroke="currentColor" stroke-width="1.5" class="text-border" />
			<!-- Hour markers -->
			<!-- eslint-disable-next-line @typescript-eslint/no-unused-vars -->
			{#each {length: 12} as _, i (i)}
				{@const angle = (i * 30 * Math.PI) / 180}
				{@const x1 = 50 + 42 * Math.sin(angle)}
				{@const y1 = 50 - 42 * Math.cos(angle)}
				{@const x2 = 50 + 46 * Math.sin(angle)}
				{@const y2 = 50 - 46 * Math.cos(angle)}
				<line {x1} {y1} {x2} {y2} stroke="currentColor" stroke-width={i % 3 === 0 ? '2' : '1'} class="text-foreground" />
			{/each}
			<!-- Hour hand -->
			<line
				x1="50" y1="50"
				x2={50 + 24 * Math.sin((hourAngle * Math.PI) / 180)}
				y2={50 - 24 * Math.cos((hourAngle * Math.PI) / 180)}
				stroke="currentColor" stroke-width="2.5" stroke-linecap="round" class="text-foreground"
			/>
			<!-- Minute hand -->
			<line
				x1="50" y1="50"
				x2={50 + 34 * Math.sin((minuteAngle * Math.PI) / 180)}
				y2={50 - 34 * Math.cos((minuteAngle * Math.PI) / 180)}
				stroke="currentColor" stroke-width="1.5" stroke-linecap="round" class="text-foreground"
			/>
			<!-- Second hand -->
			<line
				x1="50" y1="50"
				x2={50 + 38 * Math.sin((secondAngle * Math.PI) / 180)}
				y2={50 - 38 * Math.cos((secondAngle * Math.PI) / 180)}
				stroke="currentColor" stroke-width="0.8" stroke-linecap="round" class="text-primary"
			/>
			<!-- Center dot -->
			<circle cx="50" cy="50" r="2" fill="currentColor" class="text-primary" />
		</svg>
		<p class="mt-2 text-xs text-muted-foreground">{dateStr}</p>
	{:else}
		<!-- Digital clock -->
		<p class="font-display text-4xl font-semibold tabular-nums text-foreground">{timeStr}</p>
		<p class="mt-1 text-sm text-muted-foreground">{dateStr}</p>
		{#if config.timezone}
			<p class="mt-0.5 text-xs text-muted-foreground/70">{config.timezone.replace(/_/g, ' ')}</p>
		{/if}
	{/if}

	<!-- Weather section -->
	{#if showWeather}
		<div class="mt-3 flex items-center gap-2 border-t border-border pt-3">
			{#if weatherLoading}
				<div class="h-5 w-20 animate-pulse rounded bg-muted"></div>
			{:else if weatherError}
				<span class="text-xs text-muted-foreground">Weather unavailable</span>
			{:else if weatherData}
				{@const WeatherIcon = getWeatherIcon(weatherData.condition)}
				<WeatherIcon class="h-5 w-5 text-muted-foreground" />
				<span class="text-lg font-semibold text-foreground">{Math.round(weatherData.temp)}°</span>
				<span class="text-xs text-muted-foreground">{weatherData.condition}</span>
			{:else}
				<Thermometer class="h-4 w-4 text-muted-foreground" />
				<span class="text-xs text-muted-foreground">No weather data</span>
			{/if}
		</div>
	{/if}
</div>
