<template>
  <div class="login-container">
    <div class="login-box">
      <img :src="siteLogo" alt="Site logo" class="login-logo" />
      <h1>ShopDB</h1>

      <div v-if="error" class="error-message">{{ error }}</div>

      <!-- First run: no users yet - create the first admin -->
      <template v-if="mode === 'createadmin'">
        <p class="first-run-note">First run - create your admin account.</p>
        <form @submit.prevent="handleCreateAdmin">
          <div class="form-group">
            <label for="newusername">Username <span class="hint">(your SSO)</span></label>
            <input id="newusername" v-model="username" type="text" class="form-control" required autofocus />
          </div>
          <div class="form-group">
            <label for="email">Email</label>
            <input id="email" v-model="email" type="email" class="form-control" required />
          </div>
          <div class="form-group">
            <label for="newpassword">Password</label>
            <input id="newpassword" v-model="password" type="password" class="form-control" required minlength="8" />
          </div>
          <button type="submit" class="btn btn-primary" :disabled="loading">
            {{ loading ? 'Creating...' : 'Create admin & continue' }}
          </button>
        </form>
      </template>

      <!-- Normal login -->
      <form v-else @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">Username</label>
          <input id="username" v-model="username" type="text" class="form-control" required autofocus />
        </div>
        <div class="form-group">
          <label for="password">Password</label>
          <input id="password" v-model="password" type="password" class="form-control" required />
        </div>
        <button type="submit" class="btn btn-primary" :disabled="loading">
          {{ loading ? 'Logging in...' : 'Login' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { setupApi } from '../api'
import { clearNeedsAdmin } from '../composables/setupState'
import { getSiteLogo } from '../utils/siteSettings'
import { withBase, stripBase } from '../utils/basePath'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// Where to land after login: the guard-supplied ?redirect target, else the
// dashboard. Only accept same-site absolute paths to avoid open redirects.
function postLoginTarget() {
  const redirect = route.query.redirect
  if (typeof redirect === 'string' && redirect.startsWith('/') && !redirect.startsWith('//')) {
    // Tolerate a redirect that still carries the mount base (old bookmarks,
    // pre-fix interceptor URLs): router paths must be base-free.
    return stripBase(redirect)
  }
  return '/'
}

const siteLogo = ref(withBase('/ge-aerospace-logo.svg'))
const mode = ref('login')
const username = ref('')
const email = ref('')
const password = ref('')
const error = ref('')
const loading = ref(false)

onMounted(async () => {
  getSiteLogo().then(logo => { siteLogo.value = logo })

  // If the instance has no users yet, offer to create the first admin.
  try {
    const response = await setupApi.needsAdmin()
    if (response.data?.data?.needsadmin) mode.value = 'createadmin'
  } catch (err) { /* fall back to normal login */ }
})

async function handleLogin() {
  error.value = ''
  loading.value = true
  const result = await authStore.login(username.value, password.value)
  loading.value = false
  if (result.success) router.push(postLoginTarget())
  else error.value = result.message
}

async function handleCreateAdmin() {
  error.value = ''
  loading.value = true
  try {
    await setupApi.createAdmin({ username: username.value, email: email.value, password: password.value })
    clearNeedsAdmin()   // an admin now exists; stop the first-run gate firing
    // Log straight in with the new credentials, then on to the setup wizard.
    const result = await authStore.login(username.value, password.value)
    if (result.success) router.push('/setup')
    else { mode.value = 'login'; error.value = 'Admin created - please sign in.' }
  } catch (err) {
    error.value = err.response?.data?.data?.error?.message || err.response?.data?.message || 'Could not create admin'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.first-run-note { color: var(--text-light); font-size: 0.9rem; margin-bottom: 1rem; }
.hint { color: var(--text-light); font-weight: normal; font-size: 0.85em; }
</style>
