<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 8px 0 8px;
  min-width: 0;
  cursor: pointer;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: #141414;
  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-muted);
  font-weight: 600;
  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: 800;
  color: var(--primary-light);
  white-space: nowrap;
  line-height: 1.15;
}

.chevron {
  font-size: 10px;
  color: var(--primary-light);
  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);
  border-radius: var(--radius-sm);
  background: #141414;
  box-shadow: var(--shadow);
}

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

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

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

.panel-row.highlight {
  color: var(--primary-light);
  font-weight: 800;
  font-size: 14px;
}

.panel-divider {
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--border-gold-soft), transparent);
  margin: 4px 0;
}

.panel-recharge-btn {
  width: 100%;
  padding: 8px 0;
  margin-top: 4px;
  border-radius: 6px;
  border: 1px solid var(--primary, #c8a84e);
  background: rgba(200, 168, 78, 0.12);
  color: var(--primary-light, #c8a84e);
  font-size: 13px;
  font-weight: 700;
  cursor: pointer;
  transition: background 0.2s;
}

.panel-recharge-btn:active {
  background: rgba(200, 168, 78, 0.24);
}

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