<script lang="ts">
	import '../app.css';

	import type { LayoutData } from './$types'; // data 타입 (user와 menuItems 포함)
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';

	export let data: LayoutData; // 서버로부터 user와 menuItems를 받음

	let selectedPage = '';

	// [삭제] Svelte 파일에 있던 하드코딩된 menuItems 배열을 삭제합니다.
	// const menuItems = [ ... ]; // <-- 이 부분 삭제

	// [수정] data.menuItems를 사용하도록 변경
	$: {
		if (data.menuItems && data.menuItems.length > 0) {
			const currentItem = data.menuItems.find((item) => $page.url.pathname.startsWith(item.path));
			selectedPage = currentItem ? currentItem.path : '';
		} else {
			selectedPage = '';
		}
	}

	function handleNavigate(event: Event) {
		const target = event.target as HTMLSelectElement;
		if (target.value && target.value !== selectedPage) {
			// [선택적] 현재 페이지와 다를 때만 이동
			goto(target.value);
		}
	}

	// 로그아웃 함수 (동일)
	async function handleLogout() {
		await fetch('/api/logout', {
			method: 'POST'
		});
		window.location.href = '/login';
	}
</script>

<div class="flex flex-col h-screen">
	<header
		class="w-full bg-slate-800 text-white p-3 flex justify-between items-center shadow-md z-10"
	>
		<div class="flex items-center space-x-4">
			<h1 class="text-xl font-bold">BigData Server</h1>

			{#if data.user}
				<select
					value={selectedPage} on:change={handleNavigate}
					class="bg-slate-700 text-white text-sm rounded-md py-1.5 px-3 border border-slate-600 
                           focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer"
				>
					<option value="" disabled>-- 페이지 선택 --</option>

					{#each data.menuItems as item (item.path)}
						<option value={item.path}>{item.title}</option>
					{/each}
				</select>
			{/if}
		</div>

		<div class="flex items-center space-x-2">
			{#if data.user}
				<span class="text-xs uppercase text-cyan-400">[{data.user.role}]</span>
				<span>{data.user.name}</span>
				<button
					on:click={handleLogout}
					type="button"
					class="text-sm text-gray-300 hover:text-white cursor-pointer bg-transparent border-none p-0"
				>
					(로그아웃)
				</button>
			{:else}
				<a href="/login" class="text-sm hover:text-white">로그인</a>
			{/if}
		</div>
	</header>

	<main class="flex-1 overflow-auto bg-gray-100">
		<slot />
	</main>
</div>