<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50">
    <div class="max-w-md w-full space-y-8">
      <form class="mt-8 space-y-6 max-w-2xl mx-auto" @submit.prevent="login">
        <div>
          <input
            id="password"
            v-model="password"
            name="password"
            type="password"
            required
            class="appearance-none relative block w-full px-3 py-2 border border-black placeholder-zinc-500 text-black focus:outline-none focus:ring-indigo-500 focus:border-2 focus:z-10 sm:text-sm"
            placeholder="Password"
            :disabled="loading" />
        </div>

        <div v-if="error" class="text-red-600 text-sm text-center">
          {{ error }}
        </div>

        <div>
          <button
            type="submit"
            :disabled="loading"
            class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-black hover:bg-black focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed">
            <span v-if="loading">Signing in...</span>
            <span v-else>Sign in</span>
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  layout: false,
});

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

const login = async () => {
  if (!password.value) {
    error.value = "Password is required";
    return;
  }

  loading.value = true;
  error.value = "";

  try {
    const response = await $fetch("/api/auth/login", {
      method: "POST",
      body: {
        password: password.value,
      },
    });

    if (response.success) {
      await navigateTo("/");
    }
  } catch (err) {
    error.value = err.data?.message || "Invalid password";
  } finally {
    loading.value = false;
  }
};

// Check if already authenticated
onMounted(async () => {
  try {
    const { authenticated } = await $fetch("/api/auth/check");
    if (authenticated) {
      await navigateTo("/");
    }
  } catch (err) {
    // Not authenticated, stay on login page
  }
});
</script>
