<template>
    <div class="flex items-center justify-center min-h-screen bg-[#0c4b66]">
        <div class="bg-white p-8 rounded-2xl shadow-xl w-80 text-center">
            <!-- Logo + Title -->
            <div class="mb-6">
                <img :src="logo" alt="Logo" class="mx-auto w-34 py-5" />
            </div>

            <!-- Input -->
            <div>
                <InputField
                    v-model="username"
                    type="text"
                    placeholder="Username"
                    class="mb-4"
                />
                <PasswordInput v-model="password" placeholder="Password" />
            </div>

            <!-- Button -->
            <button
                @click="handleLogin"
                :disabled="loading"
                class="w-full py-2 bg-sky-400 hover:bg-sky-500 rounded font-bold text-gray-800 transition disabled:opacity-50"
            >
                {{ loading ? "Loading..." : "Login" }}
            </button>
        </div>
    </div>
</template>

<script setup>
import { ref } from "vue";
import logo from '@/../images/logo.png'
import InputField from "@/components/InputField.vue";
import PasswordInput from "@/components/InputPassword.vue";
import axios from "axios";

const username = ref("");
const password = ref("");
const loading = ref(false);

const handleLogin = async () => {
  if (!username.value || !password.value) {
    alert("Harap isi username dan password!");
    return;
  }

  loading.value = true;
  try {
    const res = await axios.post("/api/login", {
      nama: username.value,
      password: password.value,
    });

    const data = res.data;

    // Simpan token & role
    localStorage.setItem("token", data.token);
    localStorage.setItem("role", data.role);

    // Redirect sesuai role
    window.location.href = data.redirect;

  } catch (error) {
    console.error(error);
    alert("Login gagal. Periksa username atau password.");
  } finally {
    loading.value = false;
  }
};
</script>
