<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { formatMoney } from '../utils/localeDisplay';
import { usePlayerProfile } from '../composables/usePlayerProfile';

const { locale, t } = useI18n();
const { profileRaw, refreshProfile } = usePlayerProfile();
const router = useRouter();
const open = ref(false);
const root = ref<HTMLElement | null>(null);

const wallet = computed(() => profileRaw.value?.wallet ?? null);

function amountValue(value: unknown): number {
  if (value == null) return 0;
  if (typeof value === 'number') return Number.isFinite(value) ? value : 0;
  if (typeof value === 'string') {
    const n = Number(value);
    return Number.isFinite(n) ? n : 0;
  }
  if (typeof value === 'object' && typeof (value as { toString?: () => string }).toString === 'function') {
    const n = Number((value as { toString: () => string }).toString());
    return Number.isFinite(n) ? n : 0;
  }
  return 0;
}

const available = computed(() => formatMoney(wallet.value?.availableBalance, locale.value));
const frozen = computed(() => formatMoney(wallet.value?.frozenBalance, locale.value));

const total = computed(() =>
  formatMoney(
    amountValue(wallet.value?.availableBalance) + amountValue(wallet.value?.frozenBalance),
    locale.value,
  ),
);

function toggle() {
  const next = !open.value;
  open.value = next;
  if (next) void refreshProfile();
}

function close() {
  open.value = false;
}

function goRecharge() {
  close();
  router.push('/wallet/recharge');
}

function onOutsideClick(e: Event) {
  if (!root.value?.contains(e.target as Node)) open.value = false;
}

onMounted(() => {
  document.addEventListener('click', onOutsideClick);
  document.addEventListener('touchend', onOutsideClick);
});

onUnmounted(() => {
  document.removeEventListener('click', onOutsideClick);
  document.removeEventListener('touchend', onOutsideClick);
});
</script>

<template>
  <div ref="root" class="cash-chip-wrap">
    <button type="button" class="cash-chip" @click="toggle">
      <span class="chip-body">
        <span class="chip-label">{{ t('wallet.cash_balance') }}</span>
        <span class="chip-amount">{{ available }}</span>
      </span>
      <span class="chevron" :class="{ open }">▾</span>
    </button>

    <div v-if="open" class="cash-panel">
      <div class="panel-row">
        <span>{{ t('wallet.cash_balance') }}</span>
        <span>{{ total }}</span>
      </div>
      <div class="panel-divider" />
      <div class="panel-row muted">
        <span>{{ t('wallet.unsettled') }}</span>
        <span>{{ frozen }}</span>
      </div>
      <div class="panel-row highlight">
        <span>{{ t('wallet.available') }}</span>
        <span>{{ available }}</span>
      </div>
      <div class="panel-divider" />
      <button type="button" class="panel-recharge-btn" @click="goRecharge">
        {{ t('recharge.title') }}
      </button>
    </div>

    <div v-if="open" class="backdrop" @click="close" />
  </div>
</template>

<style scoped>
.cash-chip-wrap {
  position: relative;
  z-index: 120;
}

.cash-chip {
  display: flex;
  align-items: center;
  gap: 4px;
  height: 36px;
  padding: 0 10px;
  min-width: 0;
  cursor: pointer;
  border: 1px solid var(--border);
  border-radius: var(--radius-sm);
  background: var(--bg-card);
  box-sizing: border-box;
}

.chip-body {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  min-width: 0;
}

.chip-label {
  font-size: 8px;
  color: var(--text-dim);
  font-weight: 500;
  letter-spacing: 0.02em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  line-height: 1.15;
}

.chip-amount {
  font-size: 11px;
  font-weight: 600;
  color: var(--text);
  white-space: nowrap;
  line-height: 1.15;
  font-variant-numeric: tabular-nums;
}

.chevron {
  font-size: 10px;
  color: var(--text-muted);
  transition: transform 0.2s;
  margin-left: 0;
}

.chevron.open {
  transform: rotate(180deg);
}

.cash-panel {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  width: min(260px, 78vw);
  padding: 12px 14px;
  z-index: 130;
  border: 1px solid var(--border-strong);
  border-radius: var(--radius-sm);
  background: var(--dropdown-bg);
  backdrop-filter: none;
  -webkit-backdrop-filter: none;
  box-shadow: var(--shadow);
}

.cash-panel::before {
  display: none;
}

.panel-row {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  font-size: 13px;
  font-weight: 500;
  padding: 6px 0;
  font-variant-numeric: tabular-nums;
}

.panel-row.muted {
  color: var(--text-muted);
}

.panel-row.highlight {
  color: var(--text);
  font-weight: 600;
  font-size: 14px;
}

.panel-divider {
  height: 1px;
  background: var(--border);
  margin: 4px 0;
}

.panel-recharge-btn {
  width: 100%;
  padding: 8px 0;
  margin-top: 4px;
  border-radius: var(--radius-sm);
  border: none;
  background: var(--primary);
  color: var(--on-primary);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: opacity 0.15s ease;
}

.panel-recharge-btn:active {
  opacity: 0.88;
}

.backdrop {
  position: fixed;
  inset: 0;
  z-index: 110;
}
</style>
