<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/stores/account'
import { useBrokerEntry } from '@/composables/useBrokerEntry'
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 store = useAccountStore()
const { info, loading } = storeToRefs(store)
const toast = useToast()
const {
  isBroker,
  showNotBrokerTip: showNotBroker,
  applySubmitting,
  applyError,
  handleBrokerClick,
  goApplyList,
  handleApply,
} = useBrokerEntry()

const avatarLoadError = ref(false)

watch(
  () => info.value?.avatar,
  () => {
    avatarLoadError.value = false
  },
)

onMounted(() => store.fetchInfo())

const scoreLabel = computed<Record<string, string>>(() => ({
  low: t('account.scoreLow'),
  medium: t('account.scoreMedium'),
  high: t('account.scoreHigh'),
}))
const scoreColor: Record<string, string> = { low: '#ff4d4f', medium: '#F0B90B', high: '#00d084' }

const emailDisplay = computed(() =>
  info.value ? maskEmailForDisplay(info.value.email) : '',
)

async function handleApplyWithToast() {
  const ok = await handleApply()
  if (ok) toast.success(t('account.applySubmitted'))
}

const quickLinks = computed(() => [
  { icon: '🔒', labelKey: 'account.security', to: '/account/security', descKey: 'account.securityDesc' },
  { icon: '💰', labelKey: 'account.assets',   to: '/assets',           descKey: 'account.assetsDesc' },
  { icon: '🎁', labelKey: 'account.inviteFriends', to: '/invite',      descKey: 'account.inviteDesc' },
  { icon: '❓', labelKey: 'account.helpSupport',   to: '/help',        descKey: 'account.helpDesc' },
])

async function copyUid() {
  if (!info.value) return
  await navigator.clipboard.writeText(info.value.uid)
  toast.success(t('common.copied'))
}

const showSupport = ref(false)
</script>

<template>
  <main class="page-main">
    <div class="page-container content">
      <div class="page-head">
        <h1 class="page-title">{{ t('account.title') }}</h1>
      </div>

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

      <template v-else-if="info">
        <!-- 账户概览卡片 -->
        <div class="overview-card dark-card">
          <div class="overview-left">
            <div class="avatar">
              <img
                v-if="info.avatar && !avatarLoadError"
                :src="info.avatar"
                alt=""
                class="avatar-img"
                width="64"
                height="64"
                referrerpolicy="no-referrer"
                @error="avatarLoadError = true"
              >
              <span v-else>{{ info.email[0]?.toUpperCase() ?? '?' }}</span>
            </div>
            <div class="account-info">
              <p class="account-email">{{ emailDisplay }}</p>
              <p class="account-uid">
                {{ t('account.uid') }}: {{ info.uid }}
                <button class="copy-uid" :title="`${t('common.copied')} UID`" @click="copyUid">⎘</button>
              </p>
            </div>
          </div>
          <div class="overview-right">
            <RouterLink to="/account/security" class="score-block">
              <span class="score-label">{{ t('account.securityScore') }}</span>
              <span class="score-value" :style="{ color: scoreColor[info.securityScore] }">
                {{ scoreLabel[info.securityScore] }}
              </span>
            </RouterLink>
            <div class="twofa-block">
              <span class="twofa-label">{{ t('account.twofa') }}</span>
              <span class="twofa-status" :class="info.googleAuthEnabled ? 'enabled' : 'disabled'">
                {{ info.googleAuthEnabled ? t('common.on') : t('common.off') }}
              </span>
            </div>
          </div>
        </div>

        <!-- 快捷功能入口 -->
        <div class="quick-grid">
          <RouterLink
            v-for="link in quickLinks"
            :key="link.to"
            :to="link.to"
            class="quick-card dark-card"
          >
            <div class="quick-icon">{{ link.icon }}</div>
            <div>
              <p class="quick-title">{{ t(link.labelKey) }}</p>
              <p class="quick-desc">{{ t(link.descKey) }}</p>
            </div>
            <span class="quick-arrow">›</span>
          </RouterLink>

          <!-- 经纪商（经纪商跳转，非经纪商弹提示） -->
          <button class="quick-card dark-card" @click="() => void handleBrokerClick()">
            <div class="quick-icon">🏦</div>
            <div>
              <p class="quick-title">
                {{ t('account.broker') }}
                <span v-if="isBroker" class="broker-dot">●</span>
              </p>
              <p class="quick-desc">{{ t('account.brokerDesc') }}</p>
            </div>
            <span class="quick-arrow">›</span>
          </button>

          <!-- 联系客服（弹窗，不跳转） -->
          <button v-if="CUSTOMER_SERVICE_ENTRIES_VISIBLE" class="quick-card dark-card" @click="showSupport = true">
            <div class="quick-icon">💬</div>
            <div>
              <p class="quick-title">{{ t('account.supportTitle') }}</p>
              <p class="quick-desc">{{ t('account.supportHours') }}</p>
            </div>
            <span class="quick-arrow">›</span>
          </button>
        </div>
      </template>
    </div>

    <!-- 联系客服弹窗 -->
    <Teleport to="body">
      <div v-if="CUSTOMER_SERVICE_ENTRIES_VISIBLE && showSupport" class="modal-overlay" @click.self="showSupport = false">
        <div class="modal dark-card">
          <div class="modal-header">
            <h3 class="modal-title">{{ t('account.supportTitle') }}</h3>
            <button class="modal-close" @click="showSupport = false">✕</button>
          </div>
          <p class="support-hours">🕐 {{ t('account.supportHours') }}</p>
          <div class="support-list">
            <a
              class="support-item"
              :href="CUSTOMER_SERVICE_URL || '#'"
              target="_blank"
              rel="noopener"
            >
              <span class="support-ico">💬</span>
              <div>
                <p class="support-name">{{ t('account.onlineSupport') }}</p>
                <p class="support-hint">{{ t('account.instantChat') }}</p>
              </div>
              <span class="support-arrow">›</span>
            </a>
            <a class="support-item" href="https://t.me/ibit_support" target="_blank" rel="noopener">
              <span class="support-ico">✈️</span>
              <div>
                <p class="support-name">{{ t('account.telegramSupport') }}</p>
                <p class="support-hint">@ibit_support</p>
              </div>
              <span class="support-arrow">›</span>
            </a>
            <a class="support-item" href="mailto:support@ibit.com">
              <span class="support-ico">✉️</span>
              <div>
                <p class="support-name">{{ t('account.emailSupport') }}</p>
                <p class="support-hint">support@ibit.com</p>
              </div>
              <span class="support-arrow">›</span>
            </a>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 非经纪商提示 -->
    <Teleport to="body">
      <div v-if="showNotBroker" class="modal-overlay" @click.self="showNotBroker = false">
        <div class="modal dark-card" style="text-align:center;">
          <div style="font-size:36px;margin-bottom:var(--space-4);">🏦</div>
          <h3 class="modal-title" style="margin-bottom:var(--space-3);">{{ t('header.brokerApplyTitle') }}</h3>
          <p style="font-size:var(--text-small);color:var(--color-text-secondary);line-height:1.6;margin-bottom:var(--space-6);">
            {{ t('header.brokerApplyDesc') }}
          </p>
          <p v-if="applyError" style="font-size:var(--text-small);color:var(--color-down);margin-bottom:var(--space-4);">{{ applyError }}</p>
          <button type="button" class="btn-apply-list-tip" @click="goApplyList">{{ t('header.viewApplyList') }}</button>
          <div style="display:flex;gap:var(--space-3);">
            <button class="btn-cancel-tip" @click="showNotBroker = false">{{ t('common.cancel') }}</button>
            <button class="btn-apply-tip" :disabled="applySubmitting" @click="handleApplyWithToast">
              {{ applySubmitting ? t('header.submitting') : t('header.applyNow') }}
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </main>
</template>

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

.page-head {
  display: flex;
  align-items: center;
  margin-bottom: var(--space-8);
}

.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); } }

/* ── 概览卡片 ── */
.overview-card {
  padding: var(--space-6) var(--space-8);
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--space-8);
  margin-bottom: var(--space-6);
}
.overview-left { display: flex; align-items: center; gap: var(--space-5); }
.avatar {
  width: 64px; height: 64px;
  border-radius: 50%;
  background: var(--color-primary);
  display: flex; align-items: center; justify-content: center;
  font-size: 28px; font-weight: var(--fw-bold);
  color: #000; flex-shrink: 0;
  overflow: hidden;
}
.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
.account-email {
  font-size: var(--text-body);
  font-weight: var(--fw-semibold);
  color: var(--color-text-primary);
  margin-bottom: var(--space-1);
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  max-width: 240px;
}
.account-uid {
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  margin-bottom: 2px;
  display: flex; align-items: center; gap: var(--space-2);
}
.copy-uid {
  background: transparent; border: none;
  color: var(--color-text-muted);
  font-size: 14px; cursor: pointer;
  transition: color var(--transition); line-height: 1;
  padding: 0 2px;
}
.copy-uid:hover { color: var(--color-primary); }

.overview-right {
  display: flex; flex-direction: column;
  gap: var(--space-3); align-items: flex-end;
}
.score-block {
  display: flex; align-items: center; gap: var(--space-3);
  text-decoration: none;
}
.score-block:hover .score-value { opacity: 0.8; }
.score-label, .twofa-label {
  font-size: var(--text-small); color: var(--color-text-secondary);
}
.score-value {
  font-size: var(--text-small); font-weight: var(--fw-semibold);
}
.twofa-block { display: flex; align-items: center; gap: var(--space-3); }
.twofa-status {
  font-size: var(--text-small); font-weight: var(--fw-semibold);
  padding: 2px 8px; border-radius: var(--radius-sm);
}
.twofa-status.enabled  { color: var(--color-up);         background: rgba(0,208,132,0.1); }
.twofa-status.disabled { color: var(--color-text-muted); background: var(--color-bg-card); }

/* ── 快捷入口 ── */
.quick-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--space-4);
}
.quick-card {
  display: flex; align-items: center;
  gap: var(--space-4);
  padding: var(--space-5) var(--space-6);
  cursor: pointer;
  transition: border-color var(--transition), transform var(--transition);
  text-decoration: none; text-align: left;
  width: 100%;
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
}
.quick-card:hover { border-color: var(--color-primary); transform: translateY(-2px); }
.quick-icon { font-size: 28px; flex-shrink: 0; }
.quick-title {
  font-size: var(--text-body); font-weight: var(--fw-semibold);
  color: var(--color-text-primary); margin-bottom: 4px;
}
.quick-desc { font-size: var(--text-small); color: var(--color-text-secondary); }
.quick-arrow { font-size: 24px; color: var(--color-text-muted); margin-left: auto; }
.broker-dot { color: var(--color-primary); font-size: 8px; vertical-align: middle; margin-left: var(--space-1); }
.btn-apply-list-tip {
  width: 100%;
  margin-bottom: var(--space-4);
  padding: var(--space-3);
  background: transparent;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  color: var(--color-text-secondary);
  font-size: var(--text-small);
  cursor: pointer;
}
.btn-apply-list-tip:hover { border-color: var(--color-primary); color: var(--color-primary); }
.btn-cancel-tip {
  flex: 1;
  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;
}
.btn-apply-tip {
  flex: 2;
  padding: var(--space-3);
  background: var(--color-primary);
  border: none;
  border-radius: var(--radius-md);
  color: #000;
  font-weight: var(--fw-semibold);
  cursor: pointer;
}
.btn-apply-tip:disabled { opacity: .5; cursor: not-allowed; }

/* ── 客服弹窗 ── */
.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; transition: color var(--transition);
}
.modal-close:hover { color: var(--color-text-primary); }

.support-hours {
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  margin-bottom: var(--space-5);
}
.support-list { display: flex; flex-direction: column; gap: 2px; }
.support-item {
  display: flex; align-items: center; gap: var(--space-4);
  padding: var(--space-4);
  border-radius: var(--radius-md);
  text-decoration: none;
  transition: background var(--transition);
}
.support-item:hover { background: var(--color-bg-card-hover); }
.support-ico { font-size: 24px; flex-shrink: 0; width: 32px; text-align: center; }
.support-name {
  font-size: var(--text-body); color: var(--color-text-primary);
  font-weight: var(--fw-medium); margin-bottom: 2px;
}
.support-hint { font-size: var(--text-small); color: var(--color-text-secondary); }
.support-arrow { font-size: 20px; color: var(--color-text-muted); margin-left: auto; }

/* ── 移动端 ── */
@media (max-width: 768px) {
  .overview-card {
    flex-direction: column; align-items: flex-start;
    gap: var(--space-4); padding: var(--space-5);
  }
  .overview-right { align-items: flex-start; }
  .quick-grid { grid-template-columns: 1fr; }
  .account-email { max-width: 200px; }
}
</style>
