<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import {
  fetchStakingDirectList,
  fetchStakingTeamOverview,
  type StakingDirectMember,
  type StakingTeamOverview,
} from '@/api/staking'
import { stakingNodeLevelI18nKey } from '@/utils/stakingNodeLevel'

const { t, te } = useI18n()
const router = useRouter()

const PAGE_SIZE = 20

const loading = ref(true)
const error = ref<string | null>(null)
const overview = ref<StakingTeamOverview | null>(null)

const directList = ref<StakingDirectMember[]>([])
const listLoading = ref(false)
const listPage = ref(1)
const listHasMore = ref(false)

function fmtNum(n: string | number | undefined, maxFrac = 2) {
  const v = Number(n)
  if (!Number.isFinite(v)) return '0'
  return v.toLocaleString('en-US', {
    minimumFractionDigits: 0,
    maximumFractionDigits: maxFrac,
  })
}

function levelLabel(level: string | undefined) {
  const key = stakingNodeLevelI18nKey(level)
  return te(key) ? t(key) : t('finance.nodeLevelNormal')
}

const nodeLevelText = computed(() => levelLabel(overview.value?.nodeLevel))

const statCards = computed(() => {
  const o = overview.value
  return [
    { label: t('finance.directNumLabel'), value: fmtNum(o?.directNum ?? 0, 0) },
    { label: t('finance.teamNumLabel'), value: fmtNum(o?.teamNum ?? 0, 0) },
    { label: t('finance.teamPerformanceLabel'), value: fmtNum(o?.teamPerformance ?? 0) },
    { label: t('finance.totalRevenueLabel'), value: fmtNum(o?.totalRevenue ?? 0) },
  ]
})

function goBack() {
  if (window.history.length > 1) {
    router.back()
    return
  }
  router.push({ name: 'finance-ido' })
}

async function loadOverview() {
  overview.value = await fetchStakingTeamOverview()
}

async function loadDirectList(page = 1, append = false) {
  listLoading.value = true
  try {
    const pageData = await fetchStakingDirectList(page, PAGE_SIZE)
    const rows = Array.isArray(pageData?.content) ? pageData.content : []
    directList.value = append ? [...directList.value, ...rows] : rows
    listPage.value = page
    listHasMore.value = pageData?.last === false
  } catch {
    if (!append) {
      directList.value = []
    }
    listHasMore.value = false
  } finally {
    listLoading.value = false
  }
}

async function loadAll() {
  loading.value = true
  error.value = null
  try {
    await Promise.all([loadOverview(), loadDirectList(1, false)])
  } catch (e) {
    error.value = e instanceof Error ? e.message : t('common.loadFailed')
    overview.value = null
    directList.value = []
  } finally {
    loading.value = false
  }
}

function loadMoreDirect() {
  if (listLoading.value || !listHasMore.value) return
  void loadDirectList(listPage.value + 1, true)
}

onMounted(() => {
  void loadAll()
})
</script>

<template>
  <main class="team-page page-main">
    <header class="team-topbar page-container">
      <button type="button" class="team-back" aria-label="back" @click="goBack">‹</button>
      <h1 class="team-title">{{ t('finance.myTeam') }}</h1>
      <span class="team-topbar-spacer" aria-hidden="true" />
    </header>

    <div v-if="loading" class="team-loading page-container">
      <div class="spinner" />
    </div>

    <div v-else-if="error" class="team-error page-container">
      <p>{{ error }}</p>
      <button type="button" class="retry-btn" @click="loadAll">{{ t('common.retry') }}</button>
    </div>

    <template v-else>
      <div class="page-container team-body">
        <div class="node-banner">
          <span class="node-banner-label">{{ t('finance.currentNodeLevel') }}</span>
          <span class="node-banner-value">{{ nodeLevelText }}</span>
        </div>

        <div class="stats-grid">
          <div v-for="(card, i) in statCards" :key="i" class="stat-card dark-card">
            <p class="stat-value">{{ card.value }}</p>
            <p class="stat-label">{{ card.label }}</p>
          </div>
        </div>

        <h2 class="section-title">{{ t('finance.directListTitle') }}</h2>

        <div v-if="listLoading && !directList.length" class="list-loading">
          <div class="spinner sm" />
        </div>
        <div v-else-if="!directList.length" class="list-empty">{{ t('common.noData') }}</div>
        <div v-else class="direct-table-wrap">
          <table class="direct-table">
            <thead>
              <tr>
                <th>{{ t('finance.directAddress') }}</th>
                <th>{{ t('finance.levelCol') }}</th>
                <th>{{ t('finance.buyAmountCol') }}</th>
                <th>{{ t('finance.myRewardCol') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, idx) in directList" :key="`${row.directAddress}-${idx}`">
                <td class="direct-addr">{{ row.directAddress || '—' }}</td>
                <td>{{ levelLabel(row.level) }}</td>
                <td class="num">{{ fmtNum(row.buyAmount) }}</td>
                <td class="num">{{ fmtNum(row.reward) }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div v-if="listHasMore" class="load-more-row">
          <button
            type="button"
            class="load-more-btn"
            :disabled="listLoading"
            @click="loadMoreDirect"
          >
            {{ listLoading ? t('common.loading') : t('finance.teamLoadMore') }}
          </button>
        </div>
      </div>
    </template>
  </main>
</template>

<style scoped>
.team-page {
  padding-bottom: var(--space-16);
  min-height: 60vh;
}

.team-topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: calc(var(--header-height) + var(--space-4));
  padding-bottom: var(--space-4);
}

.team-back {
  width: 40px;
  height: 40px;
  border: none;
  background: transparent;
  color: var(--color-text-primary);
  font-size: 28px;
  line-height: 1;
  cursor: pointer;
  padding: 0;
}

.team-title {
  margin: 0;
  font-size: 18px;
  font-weight: var(--fw-semibold);
  color: var(--color-text-primary);
}

.team-topbar-spacer {
  width: 40px;
}

.team-body {
  max-width: 960px;
}

.team-loading,
.team-error {
  padding-top: var(--space-16);
  text-align: center;
  color: var(--color-text-secondary);
}

.spinner {
  width: 36px;
  height: 36px;
  margin: 0 auto;
  border-radius: 50%;
  border: 2px solid var(--color-border);
  border-top-color: var(--color-primary);
  animation: spin 0.8s linear infinite;
}

.spinner.sm {
  width: 24px;
  height: 24px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.retry-btn {
  margin-top: var(--space-4);
  padding: var(--space-2) var(--space-6);
  border-radius: var(--radius-md);
  border: 1px solid var(--color-primary);
  background: transparent;
  color: var(--color-primary);
  cursor: pointer;
}

.node-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-4);
  padding: var(--space-5) var(--space-6);
  margin-bottom: var(--space-4);
  border-radius: 12px;
  background: linear-gradient(90deg, #c9a227 0%, #e8c547 50%, #c9a227 100%);
  color: #1a1408;
}

.node-banner-label {
  font-size: 15px;
  font-weight: var(--fw-medium);
}

.node-banner-value {
  font-size: 16px;
  font-weight: var(--fw-bold);
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--space-3);
  margin-bottom: var(--space-8);
}

.stat-card {
  padding: var(--space-5) var(--space-4);
  text-align: center;
}

.stat-value {
  margin: 0 0 var(--space-2);
  font-size: 22px;
  font-weight: var(--fw-bold);
  color: var(--color-primary);
  font-family: var(--font-family-num);
  line-height: 1.2;
}

.stat-label {
  margin: 0;
  font-size: 13px;
  color: var(--color-text-secondary);
  line-height: 1.4;
}

.section-title {
  margin: 0 0 var(--space-4);
  font-size: 18px;
  font-weight: var(--fw-semibold);
  color: var(--color-text-primary);
}

.list-loading,
.list-empty {
  text-align: center;
  padding: var(--space-8) 0;
  color: var(--color-text-secondary);
  font-size: var(--text-small);
}

.direct-table-wrap {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.direct-table {
  width: 100%;
  min-width: 560px;
  border-collapse: collapse;
  font-size: 13px;
}

.direct-table th {
  padding: var(--space-3) var(--space-2);
  font-weight: var(--fw-normal);
  font-size: 12px;
  color: var(--color-text-muted);
  text-align: left;
  white-space: nowrap;
  border-bottom: 1px solid var(--color-border);
}

.direct-table td {
  padding: var(--space-4) var(--space-2);
  color: var(--color-text-primary);
  vertical-align: middle;
  border-bottom: 1px solid rgba(255, 255, 255, 0.04);
}

.direct-table td.num {
  font-family: var(--font-family-num);
  white-space: nowrap;
}

.direct-addr {
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.load-more-row {
  display: flex;
  justify-content: center;
  padding: var(--space-6) 0;
}

.load-more-btn {
  padding: var(--space-2) var(--space-8);
  border-radius: 999px;
  border: 1px solid var(--color-border);
  background: transparent;
  color: var(--color-text-secondary);
  font-size: var(--text-small);
  cursor: pointer;
}

.load-more-btn:hover:not(:disabled) {
  border-color: var(--color-primary);
  color: var(--color-primary);
}

.load-more-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

@media (max-width: 640px) {
  .stat-value {
    font-size: 20px;
  }
}
</style>
