<script lang="ts">
	import { fade } from 'svelte/transition';
	import type { WiFiNetwork } from '../network';
	import Icon from '@iconify/svelte';

	let {
		network,
		selectedNetwork = $bindable(),
		onSelect = (network) => {}
	}: {
		network: WiFiNetwork;
		selectedNetwork?: WiFiNetwork;
		onSelect?: (network: WiFiNetwork) => void;
	} = $props();

	function getSignalStrength(signal: number): string {
		if (signal >= 70) return 'excellent';
		if (signal >= 50) return 'good';
		if (signal >= 30) return 'fair';
		return 'poor';
	}

	function getSignalIcon(signal: number): string {
		if (signal >= 70) return 'mdi:wifi-strength-4';
		if (signal >= 50) return 'mdi:wifi-strength-3';
		if (signal >= 30) return 'mdi:wifi-strength-2';
		return 'mdi:wifi-strength-1';
	}

	function getSecurityIcon(security: string): string {
		if (security.includes('WPA3')) return 'mdi:shield-check';
		if (security.includes('WPA2')) return 'mdi:shield';
		if (security.includes('WPA')) return 'mdi:shield-outline';
		return 'mdi:shield-off';
	}

	function formatFrequency(freq: number): string {
		return `${(freq / 1000).toFixed(1)} GHz`;
	}

	function select() {
		selectedNetwork = network;
		onSelect?.(network);
	}

	let signalColor = $derived(
		network.signal >= 70 ? 'text-success' : network.signal >= 30 ? 'text-warning' : 'text-error'
	);
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
	class="card bg-base-200 hover:bg-base-300 transition-colors cursor-pointer"
	class:ring-2={selectedNetwork?.bssid === network.bssid}
	class:ring-primary={selectedNetwork?.bssid === network.bssid}
	onclick={select}
	in:fade={{ duration: 300 }}
>
	<div class="card-body p-4">
		<div class="flex items-center justify-between">
			<div class="flex items-center gap-3 flex-1">
				<Icon
					icon={getSignalIcon(network.signal)}
					class="w-5 h-5 text-base-content {signalColor}"
				/>
				<div class="flex-1">
					<div class="flex items-center gap-2">
						<h3 class="font-medium text-base-content">
							{network.ssid || 'Hidden Network'}
						</h3>
						{#if network.active}
							<div class="badge badge-success badge-sm">Connected</div>
						{/if}
					</div>
					<div class="flex items-center gap-4 text-xs text-base-content/70 mt-1">
						<span>Channel {network.chan}</span>
						<span>{formatFrequency(network.freq)}</span>
						<span>{network.rate}</span>
						<span>{network.security}</span>
					</div>
				</div>
			</div>
			<div class="flex items-center gap-2">
				<Icon icon={getSecurityIcon(network.security)} class="w-4 h-4 text-base-content/70" />
				<div class="text-right">
					<div class="text-sm font-medium text-base-content">
						{network.signal}%
					</div>
					<div class="text-xs text-base-content/70 capitalize">
						{getSignalStrength(network.signal)}
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
