<template>
  <div class="page-wrapper">
    <Spinner :loading="loading" />
    <div v-html="output" />
    <div v-if="!loading">
      <div v-if="allowAccess" class="login-container">
        <form @submit.prevent="submitForm" class="login-form" autocomplete="on">
          <h2 class="title">Login</h2>

          <div class="input-group">
            <input
              type="text"
              placeholder="Username"
              v-model="username"
              required
              autocomplete="username"
              inputmode="email"
            />
          </div>

          <div class="input-group">
            <input
              type="password"
              placeholder="Password"
              v-model="password"
              required
              autocomplete="current-password"
            />
          </div>

          <Captcha ref="captchaRef" v-model:captcha="captchaValue" />
          <button type="submit" :disabled="loading || !captchaValue" class="btn">
            <span v-if="!loading">Login</span>
            <span v-else>Loading...</span>
          </button>
          <p v-if="captchaError" class="error-text">{{ captchaError }}</p>
        </form>
      </div>

      <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>
  </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(true)
const username = ref('')
const password = ref('')
const captchaRef = ref(null)
const captchaValue = ref('')
const captchaError = ref('')
const allowAccess = ref(false)

const ALLOWED_REDIRECTS = new Set(['/', '/login', '/signin'])
function sanitizeRedirect(raw) {
  if (typeof raw !== 'string') return '/login'
  if (raw.startsWith('http://') || raw.startsWith('https://')) return '/login'
  if (!raw.startsWith('/')) return '/login'
  const pathOnly = raw.split('?')[0]
  return ALLOWED_REDIRECTS.has(pathOnly) ? raw : '/login'
}

onMounted(() => {
  allowAccess.value = true
  loading.value = false
})

const submitForm = async () => {
  loading.value = true
  output.value = ''
  captchaError.value = ''

  // Read optional redirect from query but sanitize strictly
  const requested = sanitizeRedirect(String(route.query.redirect || '/login'))

  try {
    // Optional CSRF token if you set one in a meta tag
    const csrf = document.querySelector('meta[name="csrf-token"]')?.content

    const res = await $fetch(`${window.location.origin}/api/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(csrf ? { 'X-CSRF-Token': csrf } : {})
      },
      credentials: 'include',
      body: {
        username: username.value,
        password: password.value,
        source: 'login',
        panswer: captchaValue.value,
        redirect: requested
      },
      throwHttpErrors: false
    })

    if (res?.status === 'success' && res?.redirect) {
      router.push(res.redirect)     // e.g. /waiting?name=...&handoff=...&path=/login
    } else {
      captchaError.value = res?.message || 'Login failed'
      loading.value = false
    }
  } catch (error) {
    captchaError.value = error?.data?.message || 'Internal server error!'
    loading.value = false
  } finally {
    // scrub sensitive inputs
    password.value = ''
    captchaRef.value?.refreshCaptcha()
    captchaValue.value = ''
  }
}
</script>

<style scoped>
.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);
}
.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;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.btn:hover:not(:disabled) { background-color: #2563eb; }
.btn:disabled { background-color: #93c5fd; cursor: not-allowed; }
.input-group input {
  padding: 0.8rem;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 1rem;
}
.input-group input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59,130,246,.3);
}
.error-text { color: #b91c1c; margin-top: .5rem; }
</style> 