<!-- src/routes/register/+page.svelte -->
<script lang="ts">
	import { goto } from '$app/navigation';
	let workerName = '';
	let login_id = '';
	let password = '';
	let message = '';

	async function handleRegister(e: Event) {
		e.preventDefault();
		message = '';

		try {
			const res = await fetch('/register', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ workerName, login_id, password })
			});

			const data = await res.json();

			if (!res.ok) {
				message = `❌ ${data.error ?? '등록 실패'}`;
				return;
			}

			message = '✅ 등록 성공! 자동 로그인 중...';
			setTimeout(() => goto('/'), 800); // 0.8초 뒤 홈으로 이동
		} catch (err) {
			console.error(err);
			message = '❌ 서버 오류';
		}
	}
</script>

<div class="flex flex-col items-center mt-20">
	<h1 class="text-3xl font-bold mb-6">작업자 등록</h1>

	<form on:submit={handleRegister} class="w-80 space-y-4">
		<input
			type="text"
			bind:value={workerName}
			placeholder="이름"
			class="w-full border p-2 rounded"
			required
		/>

		<input
			type="text"
			bind:value={login_id}
			placeholder="로그인 아이디"
			class="w-full border p-2 rounded"
			required
		/>

		<input
			type="password"
			bind:value={password}
			placeholder="비밀번호"
			class="w-full border p-2 rounded"
			required
		/>

		<button
			type="submit"
			class="w-full bg-purple-600 text-white p-2 rounded hover:bg-purple-700 transition"
		>
			등록하기
		</button>
	</form>

	{#if message}
		<p class="mt-4 text-center text-sm">{message}</p>
	{/if}
</div>

<style>
	input {
		outline: none;
	}
</style>
