<script lang="ts">
	import { invoke } from '@tauri-apps/api/core';
	import { onMount } from 'svelte';

	// 定义与 Rust 端 InterfaceInfo 匹配的 TypeScript 类型
	interface InterfaceInfo {
		name: string;
		addr: string;
		mac?: string;
	}

	let interfaces: InterfaceInfo[] = [];
	let loading: boolean = true;
	let error: string | null = null;

	onMount(async () => {
		try {
			// 调用 Rust 后端命令
			interfaces = await invoke<InterfaceInfo[]>("get_network_interfaces");
			console.log("Network interfaces:", interfaces);
		} catch (err) {
			console.error("Failed to get network interfaces:", err);
			// 错误处理，将错误信息展示给用户
			error = (err as string) || "未知错误";
		} finally {
			loading = false;
		}
	});
</script>

<div class="network-info">
	<h2>🌐 网络接口信息</h2>

	{#if loading}
		<p>正在加载...</p>
	{:else if error}
		<p class="error-message">错误: {error}</p>
	{:else}
		<table>
			<thead>
			<tr>
				<th>名称</th>
				<th>IP 地址 (IPv4)</th>
				<th>MAC 地址</th>
			</tr>
			</thead>
			<tbody>
			{#each interfaces as iface (iface.name)}
				<tr>
					<td><strong>{iface.name}</strong></td>
					<td>{iface.addr}</td>
					<td>{iface.mac || 'N/A'}</td>
				</tr>
			{/each}
			</tbody>
		</table>
	{/if}
</div>

<style>
    /* 简单的 Svelte 样式 */
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 1em;
    }
    th, td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    th {
        background-color: var(--main-bg-color);
    }
    .error-message {
        color: red;
        font-weight: bold;
    }
</style>