<template>
  <LoginView
    :company-name="LOGIN_BRAND_NAME"
    :submitting="loginSubmitting"
    :error-message="loginError"
    @login="submitLogin"
    @recover-password="handleRecoverPassword"
    @sso-login="handleSsoLogin"
  />
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'

import { useSystemState } from '../composables/useSystemState.js'
import { markLoginEntryTransition } from '../utils/loginEntryTransition.js'
import LoginView from './LoginView.vue'

const route = useRoute()
const router = useRouter()
const {
  handleLogin,
  handleRecoverPassword,
  handleSsoLogin,
  loginError,
  loginSubmitting,
  resolveEntryRoute
} = useSystemState()

const LOGIN_ENTRY_ROUTE_DELAY_MS = 140
const LOGIN_BRAND_NAME = '易财费控'

function waitForLoginEntryReady() {
  return new Promise((resolve) => {
    window.setTimeout(resolve, LOGIN_ENTRY_ROUTE_DELAY_MS)
  })
}

async function submitLogin(credentials) {
  const passed = await handleLogin(credentials)

  if (!passed) {
    return
  }

  markLoginEntryTransition()
  await waitForLoginEntryReady()

  const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : ''

  if (redirect.startsWith('/app/')) {
    router.replace(redirect)
    return
  }

  router.replace(resolveEntryRoute())
}
</script>
