<script setup lang="ts">
import { ref, computed, onMounted, onActivated } from 'vue'
import { storeToRefs } from 'pinia'
import { useSecurityStore } from '@/stores/security'
import { useToast } from '@/composables/useToast'
import { useI18n } from 'vue-i18n'
import { CUSTOMER_SERVICE_URL, CUSTOMER_SERVICE_ENTRIES_VISIBLE } from '@/utils/customerService'
import { maskEmailForDisplay } from '@/utils/maskEmail'

const { t } = useI18n()
const securityStore = useSecurityStore()
const { auth, loading } = storeToRefs(securityStore)
const toast = useToast()

const showGoogleHelp = ref(false)

function loadSetting() {
  securityStore.fetchSecuritySetting().catch(() => {
    toast.error(securityStore.error ?? t('error.loadFailed'))
  })
}

onMounted(loadSetting)
onActivated(loadSetting)

const emailMasked = computed(() => maskEmailForDisplay(auth.value?.email ?? ''))
const emailVerified = computed(() => Number(auth.value?.emailVerified) === 1)
const googleBound = computed(() => Number(auth.value?.googleStatus) === 1)
const fundSet = computed(() => Number(auth.value?.fundsVerified) === 1)

function openGoogleHelp() {
  showGoogleHelp.value = true
}

async function refresh() {
  try {
    await securityStore.fetchSecuritySetting()
    toast.success(t('error.statusUpdated'))
  } catch {
    toast.error(securityStore.error ?? t('error.refreshFailed'))
  }
}
</script>

<template>
  <main class="page-main">
    <div class="page-container content">
      <div class="page-header">
        <RouterLink to="/account" class="back-link">{{ t('security.back') }}</RouterLink>
        <h1 class="page-title">{{ t('security.title') }}</h1>
      </div>

      <div v-if="loading && !auth" class="loading-state">
        <div class="spinner" />
      </div>

      <template v-else>
        <div class="warn-banner dark-card">
          <span class="warn-icon">⚠️</span>
          <span>{{ t('security.warningBanner') }}</span>
        </div>

        <div class="section-card dark-card">
          <h2 class="section-heading">{{ t('security.accountSecurity') }}</h2>

          <!-- 登录密码 -->
          <div class="security-row">
            <div class="security-row-left">
              <div class="security-icon">🔑</div>
              <div>
                <p class="security-label">{{ t('security.loginPassword') }}</p>
                <p class="security-desc">{{ t('security.loginPasswordDesc') }}</p>
              </div>
            </div>
            <div class="row-right">
              <span class="badge badge-on">{{ t('security.set') }}</span>
              <RouterLink to="/account/security/change-password" class="action-btn">{{ t('security.change') }}</RouterLink>
            </div>
          </div>

          <div class="row-divider" />

          <!-- 邮箱认证 -->
          <div class="security-row">
            <div class="security-row-left">
              <div class="security-icon">✉️</div>
              <div>
                <p class="security-label">{{ t('security.emailVerify') }}</p>
                <p class="security-desc">{{ emailMasked }}</p>
              </div>
            </div>
            <div class="row-right">
              <span :class="emailVerified ? 'badge badge-on' : 'badge badge-off'">
                {{ emailVerified ? t('security.bound') : t('security.notBound') }}
              </span>
            </div>
          </div>

          <div class="row-divider" />

          <!-- 谷歌认证 -->
          <div class="security-row">
            <div class="security-row-left">
              <div class="security-icon">🛡</div>
              <div>
                <p class="security-label">{{ t('security.googleAuth') }}</p>
                <p class="security-desc">{{ t('security.googleAuthDesc') }}</p>
              </div>
            </div>
            <div class="row-right">
              <span :class="googleBound ? 'badge badge-on' : 'badge badge-off'">
                {{ googleBound ? t('security.bound') : t('security.notBound') }}
              </span>
              <RouterLink v-if="!googleBound" to="/account/security/google-auth" class="action-btn">
                {{ t('security.bind') }}
              </RouterLink>
              <button v-else type="button" class="action-btn" @click="openGoogleHelp">{{ t('common.more') }}</button>
            </div>
          </div>

          <div class="row-divider" />

          <!-- 资金密码 -->
          <div class="security-row">
            <div class="security-row-left">
              <div class="security-icon">💳</div>
              <div>
                <p class="security-label">{{ t('security.fundPassword') }}</p>
                <p class="security-desc">{{ t('security.fundPasswordDesc') }}</p>
              </div>
            </div>
            <div class="row-right">
              <span :class="fundSet ? 'badge badge-on' : 'badge badge-off'">
                {{ fundSet ? t('security.set') : t('security.notSet') }}
              </span>
              <RouterLink to="/account/security/fund-password" class="action-btn">
                {{ fundSet ? t('security.change') : t('security.set2') }}
              </RouterLink>
            </div>
          </div>
        </div>

        <div class="footer-actions">
          <button type="button" class="link-refresh" @click="refresh">{{ t('security.refresh') }}</button>
        </div>
      </template>
    </div>

    <Teleport to="body">
      <div v-if="showGoogleHelp" class="modal-overlay" @click.self="showGoogleHelp = false">
        <div class="modal dark-card">
          <div class="modal-header">
            <h3 class="modal-title">{{ t('security.googleHelpTitle') }}</h3>
            <button class="modal-close" type="button" @click="showGoogleHelp = false">✕</button>
          </div>
          <p class="modal-text">{{ t('security.googleHelpDesc') }}</p>
          <a
            v-if="CUSTOMER_SERVICE_URL && CUSTOMER_SERVICE_ENTRIES_VISIBLE"
            class="btn-confirm btn-full"
            :href="CUSTOMER_SERVICE_URL"
            target="_blank"
            rel="noopener"
          >{{ t('common.contactService') }}</a>
          <button type="button" class="btn-cancel btn-full" @click="showGoogleHelp = false">{{ t('common.close') }}</button>
        </div>
      </div>
    </Teleport>
  </main>
</template>

<style scoped>
.content {
  padding-top: var(--space-8);
  padding-bottom: var(--space-16);
  max-width: 800px;
}

.page-header {
  margin-bottom: var(--space-8);
}
.back-link {
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  display: inline-block;
  margin-bottom: var(--space-3);
  transition: color var(--transition);
}
.back-link:hover {
  color: var(--color-primary);
}

.page-title {
  font-size: var(--text-h1);
  font-weight: var(--fw-bold);
  color: var(--color-text-primary);
}

.loading-state {
  display: flex;
  justify-content: center;
  padding: var(--space-16);
}
.spinner {
  width: 32px;
  height: 32px;
  border: 2px solid var(--color-border);
  border-top-color: var(--color-primary);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.warn-banner {
  display: flex;
  align-items: flex-start;
  gap: var(--space-3);
  padding: var(--space-4) var(--space-5);
  margin-bottom: var(--space-6);
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  border: 1px solid rgba(240, 185, 11, 0.35);
}
.warn-icon {
  flex-shrink: 0;
}

.section-card {
  padding: var(--space-6);
  margin-bottom: var(--space-6);
}
.section-heading {
  font-size: var(--text-body);
  font-weight: var(--fw-semibold);
  color: var(--color-text-primary);
  margin-bottom: var(--space-5);
}

.security-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-4);
  padding: var(--space-4) 0;
}
.security-row-left {
  display: flex;
  align-items: center;
  gap: var(--space-4);
}
.security-icon {
  font-size: 24px;
  flex-shrink: 0;
}
.security-label {
  font-size: var(--text-body);
  font-weight: var(--fw-medium);
  color: var(--color-text-primary);
  margin-bottom: 2px;
}
.security-desc {
  font-size: var(--text-small);
  color: var(--color-text-secondary);
}
.row-right {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  flex-shrink: 0;
}
.row-divider {
  height: 1px;
  background: var(--color-border);
}

.badge {
  font-size: var(--text-caption);
  font-weight: var(--fw-semibold);
  padding: 2px 8px;
  border-radius: var(--radius-sm);
}
.badge-on {
  color: var(--color-up);
  background: rgba(0, 208, 132, 0.1);
}
.badge-off {
  color: var(--color-text-muted);
  background: var(--color-bg-card);
}

.action-btn {
  font-size: var(--text-small);
  color: var(--color-primary);
  border: 1px solid var(--color-primary);
  border-radius: var(--radius-sm);
  padding: var(--space-1) var(--space-4);
  cursor: pointer;
  background: transparent;
  transition: background var(--transition);
  white-space: nowrap;
  text-decoration: none;
  display: inline-block;
  text-align: center;
}
.action-btn:hover {
  background: rgba(240, 185, 11, 0.1);
}

.footer-actions {
  text-align: center;
}
.link-refresh {
  background: none;
  border: none;
  color: var(--color-text-muted);
  font-size: var(--text-small);
  cursor: pointer;
  text-decoration: underline;
}

.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}
.modal {
  width: 400px;
  max-width: calc(100vw - var(--space-8));
  padding: var(--space-6);
}
.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-4);
}
.modal-title {
  font-size: var(--text-h3);
  font-weight: var(--fw-semibold);
  color: var(--color-text-primary);
}
.modal-close {
  background: transparent;
  border: none;
  color: var(--color-text-muted);
  font-size: 18px;
  cursor: pointer;
}
.modal-text {
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  line-height: 1.6;
  margin-bottom: var(--space-5);
}
.btn-full {
  width: 100%;
  margin-bottom: var(--space-3);
}
.btn-confirm {
  display: block;
  text-align: center;
  padding: var(--space-3);
  background: var(--color-primary);
  border-radius: var(--radius-md);
  color: #000;
  font-weight: var(--fw-semibold);
  text-decoration: none;
}
.btn-cancel {
  width: 100%;
  padding: var(--space-3);
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  color: var(--color-text-secondary);
  cursor: pointer;
}

@media (max-width: 768px) {
  .security-row {
    flex-direction: column;
    align-items: flex-start;
  }
  .row-right {
    margin-left: 40px;
  }
}
</style>
