<template>
  <div class="page-wrapper">
    <Spinner :loading="loading" />
    <div v-html="output" />
    <!-- 👇 Only show form if access is allowed -->
    <div v-if="allowAccess" class="login-container">
      <form @submit.prevent="submitForm" class="login-form">
        <h2 class="title">Login</h2>
         <!-- Include Captcha -->
        <Captcha v-model:captcha="captchaValue" />
        <button type="submit" :disabled="loading || !captchaValue" class="btn">
          <span v-if="!loading">Login</span>
          <span v-else>Loading...</span>
        </button>
        <br/>
        <p v-if="captchaError" class="error-text">{{ captchaError }}</p>
      </form>
    </div>
    <!-- 👇 Show this if the user did not come from an approved source -->
    <div v-else class="login-container">
      <h2 class="title">Access Denied</h2>
      <p>You must access this page through the proper login flow.</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import Spinner from '@/components/Spinner.vue';
import Captcha from '@/components/Captcha.vue';

const output = ref('');
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const captchaValue = ref('');
const captchaError = ref('');
const redirectTo = ref('/');
const allowAccess = ref(false) // 🔐 This controls what to show
// 🟡 Grab redirect param on load
onMounted(() => {
  const redirectParam = route.query.redirect;
  const authParam = route.query.auth;
  if (redirectParam && typeof redirectParam === 'string') {
    redirectTo.value = decodeURIComponent(redirectParam);
  }
  // ✅ More reliable than document.referrer
  if (authParam === 'ok') {
    allowAccess.value = true;
  }
});

const submitForm = async () => {
  loading.value = true;
  output.value = '';
  const config = useRuntimeConfig();

  try {
    const res = await $fetch(`${window.location.origin}/api/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: {
        source: 'login',
        panswer: captchaValue.value,
        redirect: redirectTo.value,
      },
      credentials: 'include',
      throwHttpErrors: false, // important: do NOT throw on 401/4xx
    });

    if (res.status === 'success') {
      captchaError.value = '';
      if (redirectTo.value.startsWith('http://') || redirectTo.value.startsWith('https://')) {
        window.location.href = redirectTo.value;
      } else {
        router.push(redirectTo.value);
      }
    } else if (res.status === 'error' && res.message === 'Invalid CAPTCHA') {
      captchaError.value = '❌ Invalid CAPTCHA. Please try again.';
    } else {
      captchaError.value = res.message || 'Login failed. Please try again.';
    }
  } catch (error) {
    // This should rarely happen now because throwHttpErrors is false
    captchaError.value = error.message || 'Network error.';
  } finally {
    loading.value = false;
  }
};
</script>


<style scoped>
.page-wrapper {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin: 0;
  text-align: center;
}
.login-container {
  max-width: 100%;
  width: 400px;
  margin: 5rem auto;
  padding: 2rem;
  border-radius: 8px;
  background: #f9fafb;
  box-shadow: 0 4px 10px rgb(0 0 0 / 0.1);
}

.title {
  text-align: center;
  margin-bottom: 1.5rem;
  font-weight: 700;
  font-size: 1.8rem;
  color: #222;
}
.input-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 1.2rem;
}
.btn {
  width: 100%;
  padding: 0.8rem;
  font-weight: 600;
  font-size: 1.1rem;
  background-color: #3b82f6; /* blue-500 */
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn:hover:not(:disabled) {
  background-color: #2563eb; /* blue-600 */
}

.btn:disabled {
  background-color: #93c5fd; /* blue-300 */
  cursor: not-allowed;
}
.error-text {
  color: red;
  font-size: 0.95rem;
  margin-bottom: 1rem;
  text-align: center;
}
</style>
