<script lang="ts">
  import { goto } from '$app/navigation'

  let id = $state('')
  let password = $state('')
  let error = $state('')
  let loading = $state(false)

  async function handleLogin(e: SubmitEvent) {
    e.preventDefault()
    error = ''
    loading = true

    try {
      const form = new URLSearchParams()
      form.set('id', id)
      form.set('password', password)
      form.set('next', '/')

      const res = await fetch('/login', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: form.toString(),
        redirect: 'manual',
      })

      if (res.ok || res.status === 302 || res.type === 'opaqueredirect') {
        await goto('/')
      } else {
        error = '아이디 또는 비밀번호가 올바르지 않습니다.'
      }
    } catch {
      error = '서버 연결에 실패했습니다.'
    } finally {
      loading = false
    }
  }
</script>

<svelte:head>
  <title>로그인 - 주식 시세</title>
</svelte:head>

<div class="min-h-screen flex items-center justify-center bg-gray-900">
  <div class="w-full max-w-sm">
    <div class="text-center mb-8">
      <h1 class="text-3xl font-bold text-white">주식 시세</h1>
      <p class="text-gray-400 mt-2">로그인이 필요합니다</p>
    </div>

    <form onsubmit={handleLogin} class="bg-gray-800 rounded-xl p-8 shadow-2xl space-y-5">
      {#if error}
        <div class="bg-red-900/40 border border-red-500/50 text-red-300 text-sm rounded-lg px-4 py-3">
          {error}
        </div>
      {/if}

      <div>
        <label class="block text-sm font-medium text-gray-400 mb-1.5" for="id">아이디</label>
        <input
          id="id"
          type="text"
          bind:value={id}
          autocomplete="username"
          required
          class="w-full bg-gray-700 border border-gray-600 rounded-lg px-4 py-2.5 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
          placeholder="아이디 입력"
        />
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-400 mb-1.5" for="password">비밀번호</label>
        <input
          id="password"
          type="password"
          bind:value={password}
          autocomplete="current-password"
          required
          class="w-full bg-gray-700 border border-gray-600 rounded-lg px-4 py-2.5 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
          placeholder="비밀번호 입력"
        />
      </div>

      <button
        type="submit"
        disabled={loading}
        class="w-full bg-blue-600 hover:bg-blue-500 disabled:bg-gray-600 text-white font-semibold rounded-lg px-4 py-2.5 transition-colors"
      >
        {loading ? '로그인 중...' : '로그인'}
      </button>
    </form>
  </div>
</div>
