<script setup lang="ts">
import { ref, onMounted, onActivated, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, RouterLink } from 'vue-router';
import GoldSpinner from '../../components/GoldSpinner.vue';
import DesktopWalletPageHeader from '../../components/desktop/DesktopWalletPageHeader.vue';
import LocaleFlag from '../../components/LocaleFlag.vue';
import { useAuthStore } from '../../stores/auth';
import { useAppLocale } from '../../composables/useAppLocale';
import { usePlayerProfile } from '../../composables/usePlayerProfile';
import { formatMoney } from '../../utils/localeDisplay';
import { parseCashbackApiData, sumCashbackAmount } from '../../utils/cashback';
import api from '../../api';

const { t, locale } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const { locales, setLocale, initFromUser } = useAppLocale();
const { profileRaw, refreshProfile } = usePlayerProfile();

const cashbackTotal = ref('0');
const loading = ref(true);

async function fetchCashbackTotal() {
  try {
    const { data } = await api.get('/player/cashbacks');
    cashbackTotal.value = sumCashbackAmount(parseCashbackApiData(data.data)).toString();
  } catch {
    try {
      const { data } = await api.get('/player/wallet/transactions/stats');
      const byType = data.data?.byType ?? [];
      let sum = 0;
      for (const g of byType) {
        if (['CASHBACK', 'CASHBACK_DEPOSIT'].includes(g.transactionType?.toUpperCase())) {
          sum += Math.abs(parseFloat(g.totalAmount ?? '0'));
        }
      }
      cashbackTotal.value = sum.toString();
    } catch {
      // ignore
    }
  }
}

async function loadPage() {
  loading.value = true;
  try {
    await refreshProfile();
    initFromUser(profileRaw.value?.locale);
    await fetchCashbackTotal();
  } finally {
    loading.value = false;
  }
}

function logout() {
  auth.logout();
  router.push('/');
}

const balanceDisplay = computed(() =>
  formatMoney(profileRaw.value?.wallet?.availableBalance, locale.value),
);

onMounted(loadPage);
onActivated(loadPage);
</script>

<template>
  <div class="desktop-records-page wallet-overview-page">
    <DesktopWalletPageHeader />

    <div v-if="loading" class="wallet-loading">
      <GoldSpinner :size="36" />
    </div>

    <template v-else>
      <div class="wallet-overview-content">
      <section class="wallet-hero">
        <div class="wallet-hero-top">
          <div class="wallet-hero-brand">
            <img src="/logo.png" alt="" class="wallet-hero-logo" />
            <span class="wallet-hero-brand-text">THEBET365</span>
          </div>
          <RouterLink to="/wallet/recharge" class="wallet-hero-recharge">
            + {{ t('recharge.title') }}
          </RouterLink>
        </div>
        <div class="wallet-hero-body">
          <span class="wallet-hero-label">{{ t('wallet.my_balance') }}</span>
          <p class="wallet-hero-balance">{{ balanceDisplay }}</p>
        </div>
      </section>

      <div class="wallet-stat-grid">
        <div class="wallet-stat-card">
          <span class="wallet-stat-label">{{ t('profile.username') }}</span>
          <span class="wallet-stat-value">{{ profileRaw?.username || '-' }}</span>
        </div>
        <div class="wallet-stat-card">
          <span class="wallet-stat-label">{{ t('wallet.cashback_total') }}</span>
          <span class="wallet-stat-value">{{ formatMoney(cashbackTotal, locale) }}</span>
        </div>
        <div class="wallet-stat-card">
          <span class="wallet-stat-label">{{ t('wallet.frozen') }}</span>
          <span class="wallet-stat-value">{{ formatMoney(profileRaw?.wallet?.frozenBalance, locale) }}</span>
        </div>
      </div>

      <section class="wallet-panel">
        <div class="wallet-panel-row">
          <div class="wallet-panel-label">{{ t('profile.account') }}</div>
          <div class="wallet-panel-content">
            <div class="wallet-info-line">
              <span class="wallet-info-key">{{ t('profile.username') }}</span>
              <span class="wallet-info-val">{{ profileRaw?.username }}</span>
            </div>
            <div class="wallet-info-line">
              <span class="wallet-info-key">{{ t('profile.phone') }}</span>
              <span class="wallet-info-val">{{ profileRaw?.preferences?.phone || '-' }}</span>
            </div>
            <RouterLink to="/profile/edit" class="wallet-panel-link">
              {{ t('profile.edit') }}
              <span aria-hidden="true">›</span>
            </RouterLink>
          </div>
        </div>

        <div class="wallet-panel-row">
          <div class="wallet-panel-label">{{ t('profile.language') }}</div>
          <div class="wallet-panel-content">
            <div class="wallet-lang-group" role="group" :aria-label="t('profile.language')">
              <button
                v-for="item in locales"
                :key="item.code"
                type="button"
                class="wallet-lang-btn"
                :class="{ active: locale === item.code }"
                @click="setLocale(item.code)"
              >
                <LocaleFlag :locale="item.code" :size="14" />
                <span>{{ item.label }}</span>
              </button>
            </div>
          </div>
        </div>

        <div class="wallet-panel-row wallet-panel-row--actions">
          <button type="button" class="wallet-logout-btn" @click="logout">
            {{ t('auth.logout') }}
          </button>
        </div>
      </section>
      </div>
    </template>
  </div>
</template>

<style scoped>
.wallet-overview-page {
  gap: 14px;
  flex: 0 1 auto !important;
  height: auto !important;
  overflow: visible;
}

.wallet-overview-content {
  display: flex;
  flex-direction: column;
  gap: 14px;
  width: 100%;
  max-width: 640px;
  margin: 0 auto;
}

.wallet-loading {
  display: flex;
  justify-content: center;
  padding: 48px 0;
}

.wallet-hero {
  padding: 20px 22px;
  border-radius: 14px;
  background: linear-gradient(135deg, #003D6B 0%, #005B9F 52%, #002847 100%);
  box-shadow: 0 4px 16px rgba(0, 61, 107, 0.16);
  color: #fff;
}

.wallet-hero-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 18px;
}

.wallet-hero-brand {
  display: flex;
  align-items: center;
  gap: 8px;
}

.wallet-hero-logo {
  width: 22px;
  height: 22px;
  object-fit: contain;
}

.wallet-hero-brand-text {
  font-size: 12px;
  font-weight: 800;
  letter-spacing: 0.14em;
  color: rgba(255, 255, 255, 0.88);
}

.wallet-hero-recharge {
  display: inline-flex;
  align-items: center;
  padding: 8px 16px;
  border-radius: 999px;
  border: 1px solid rgba(255, 255, 255, 0.32);
  background: rgba(255, 255, 255, 0.12);
  color: #fff;
  font-size: 13px;
  font-weight: 700;
  text-decoration: none;
  white-space: nowrap;
}

.wallet-hero-recharge:hover {
  background: rgba(255, 255, 255, 0.2);
}

.wallet-hero-label {
  display: block;
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  color: rgba(255, 255, 255, 0.72);
  margin-bottom: 6px;
}

.wallet-hero-balance {
  margin: 0;
  font-family: 'SF Mono', 'Consolas', monospace;
  font-size: clamp(30px, 3.2vw, 42px);
  font-weight: 700;
  line-height: 1.1;
}

.wallet-stat-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.wallet-stat-card {
  padding: 14px 16px;
  border-radius: 10px;
  border: 1px solid var(--border);
  background: var(--bg-card);
}

.wallet-stat-label {
  display: block;
  font-size: 11px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.04em;
  margin-bottom: 6px;
}

.wallet-stat-value {
  display: block;
  font-size: 16px;
  font-weight: 800;
  color: var(--primary);
  font-variant-numeric: tabular-nums;
  word-break: break-all;
}

.wallet-panel {
  border: 1px solid var(--border);
  border-radius: 12px;
  background: var(--bg-card);
  overflow: hidden;
}

.wallet-panel-row {
  display: grid;
  grid-template-columns: 88px minmax(0, 1fr);
  gap: 16px;
  padding: 16px 18px;
  border-bottom: 1px solid var(--border);
  align-items: start;
}

.wallet-panel-row:last-child {
  border-bottom: none;
}

.wallet-panel-row--actions {
  display: flex;
  justify-content: flex-end;
  grid-template-columns: none;
}

.wallet-panel-label {
  font-size: 12px;
  font-weight: 800;
  color: var(--text-muted);
  padding-top: 2px;
}

.wallet-panel-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-width: 0;
}

.wallet-info-line {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
}

.wallet-info-key {
  width: 64px;
  flex-shrink: 0;
  color: var(--text-muted);
  font-weight: 600;
}

.wallet-info-val {
  flex: 1;
  font-weight: 700;
  color: var(--text);
  word-break: break-all;
}

.wallet-panel-link {
  align-self: flex-start;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid var(--border-active);
  color: var(--primary-light);
  font-size: 12px;
  font-weight: 700;
  text-decoration: none;
}

.wallet-panel-link:hover {
  background: rgba(0, 102, 204, 0.06);
}

.wallet-lang-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.wallet-lang-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 7px 12px;
  border-radius: 999px;
  border: 1px solid var(--border);
  background: var(--bg-body);
  color: var(--text-muted);
  font-size: 12px;
  font-weight: 700;
  cursor: pointer;
}

.wallet-lang-btn.active {
  border-color: var(--border-active);
  color: var(--primary-light);
  background: rgba(0, 102, 204, 0.08);
}

.wallet-logout-btn {
  padding: 8px 18px;
  border-radius: 8px;
  border: 1px solid rgba(220, 38, 38, 0.35);
  background: transparent;
  color: var(--danger);
  font-size: 13px;
  font-weight: 700;
  cursor: pointer;
}

.wallet-logout-btn:hover {
  background: rgba(220, 38, 38, 0.06);
}

@media (max-width: 720px) {
  .wallet-stat-grid {
    grid-template-columns: 1fr;
  }

  .wallet-panel-row {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}
</style>
