<template>
  <v-app class="bg-background">
    <v-container>
      <v-row justify="center" no-gutters>
        <v-col class="text-center" cols="12" sm="6">
          <!-- Logo 與品牌名稱 -->
          <v-card class="bg-transparent" variant="flat">
            <BrandAvatar />

            <v-card-title class="text-primary font-weight-bold">運動玩轉健康力</v-card-title>
            <v-card-subtitle class="text-primary">Taipei Masters Hub</v-card-subtitle>
          </v-card>

          <!-- 登入卡片 -->
          <v-card class="rounded-lg mt-4" color="surface">
            <v-card-title> 市民登入 </v-card-title>
            <v-card-text> 請輸入您的手機號碼或信箱 </v-card-text>
            <!-- 表單 -->
            <v-form class="pa-4" @submit.prevent="handleLogin">
              <v-alert
                v-if="errorMessage"
                class="mb-4"
                density="compact"
                type="error"
                variant="tonal"
              >
                {{ errorMessage }}
              </v-alert>

              <v-text-field
                v-model="account"
                class="mb-6"
                color="primary"
                hide-details="auto"
                label="手機號碼"
                placeholder="例如: 0910666888"
                prepend-inner-icon="mdi-cellphone-android"
                required
                rounded="lg"
                variant="outlined"
              />

              <v-btn
                block
                class="glow-sweep-button rounded-lg font-weight-bold elevation-2 mb-4"
                color="secondary"
                :loading="loading"
                type="submit"
              >
                登入健康平台
              </v-btn>

              <v-btn
                block
                class="rounded-lg font-weight-bold"
                color="primary"
                prepend-icon="mdi-clipboard-text-search"
                to="/self-assessment"
                variant="outlined"
              >
                不登入，先做線上自評
              </v-btn>
            </v-form>
            <!-- <div class="d-flex align-center justify-center my-4">
              <v-divider class="mr-3" />
              <span class="text-caption text-grey font-weight-bold">或使用以下方式快捷登入</span>
              <v-divider class="ml-3" />
            </div> -->

            <!-- LINE 一鍵登入 (高齡場景極度實用) -->
            <!-- <v-btn
              block
              class="rounded-lg font-weight-bold text-white mb-4 text-button d-flex align-center justify-center"
              color="#06C755"
              :loading="lineLoading"
              size="large"
              style="text-transform: none"
              variant="flat"
              @click="handleLineLogin"
            >
              <v-icon class="mr-2" icon="mdi-message-text" />
              使用 LINE 帳號一鍵登入
            </v-btn> -->

            <v-card-actions class="justify-center">
              <span class="text-body-small text-grey">
                登入即表示您同意本平台的
                <a class="text-accent text-decoration-none font-weight-bold" href="#">
                  個資授權條款
                </a>
              </span>
            </v-card-actions>
          </v-card>

          <!-- 版權 -->
          <div class="mt-8 text-body-small text-grey-darken-1">
            <p>© 2026 SKYTEK</p>
          </div>
        </v-col>
      </v-row>
    </v-container>
  </v-app>
</template>

<script setup lang="ts">
import { HTTPError } from 'ky'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import BrandAvatar from '@/components/BrandAvatar.vue'
import { useAppStore } from '@/stores/app'

const store = useAppStore()
const router = useRouter()

const account = ref('')
const loading = ref(false)
const lineLoading = ref(false)
const errorMessage = ref('')

/** 後端要求純數字、09 開頭、共 10 碼；允許使用者輸入時夾雜連字號或空白 */
function normalizePhone (value: string) {
  return value.replace(/\D/g, '')
}

interface ErrorResponseBody {
  /** 一般錯誤格式，例如 401 手機門號不存在 */
  message?: string
  /** 驗證失敗時（400）後端走 ASP.NET Core 的 ProblemDetails 格式 */
  errors?: Record<string, string[]>
}

/** 優先取用後端回應 body 的錯誤訊息，取不到時退回通用錯誤訊息 */
function resolveErrorMessage (error: unknown): string {
  // ky 建立 HTTPError 時已經把 body 讀進 error.data，body 已被消耗，
  // 不能再呼叫 error.response.json()（會丟 "Body has already been read"）
  if (error instanceof HTTPError && error.data && typeof error.data === 'object') {
    const body = error.data as ErrorResponseBody

    if (body.message) {
      return body.message
    }

    const firstFieldError = Object.values(body.errors ?? {})[0]?.[0]
    if (firstFieldError) {
      return firstFieldError
    }
  }

  return error instanceof Error ? error.message : '登入失敗，請稍後再試。'
}

async function handleLogin () {
  const phone = normalizePhone(account.value)

  if (!/^09\d{8}$/.test(phone)) {
    errorMessage.value = '請輸入正確的手機門號格式（09 開頭，共 10 碼）'
    return
  }

  errorMessage.value = ''
  loading.value = true

  try {
    await store.login(phone)
    router.push('/')
  } catch (error) {
    errorMessage.value = resolveErrorMessage(error)
  } finally {
    loading.value = false
  }
}

async function _handleLineLogin () {
  lineLoading.value = true

  try {
    await store.login('0910666888') // LINE 模擬登入預設手機
    router.push('/')
  } catch (error) {
    errorMessage.value = resolveErrorMessage(error)
  } finally {
    lineLoading.value = false
  }
}
</script>

<style scoped>
.glow-sweep-button {
  overflow: hidden;
  position: relative;
}

.glow-sweep-button::after {
  position: absolute;
  top: -50%;
  left: -70%;
  width: 45%;
  height: 200%;
  background: linear-gradient(
    120deg,
    transparent 0%,
    rgba(255, 255, 255, 0.15) 35%,
    rgba(255, 255, 255, 0.75) 50%,
    rgba(255, 255, 255, 0.15) 65%,
    transparent 100%
  );
  content: '';
  transform: rotate(18deg);
  animation: glow-sweep 2.4s ease-in-out infinite;
  pointer-events: none;
}

@keyframes glow-sweep {
  0% {
    left: -70%;
  }

  45%,
  100% {
    left: 125%;
  }
}

</style>
