<script setup lang="ts">
import { ref, onActivated, onMounted, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n';
import api from '../api';
import BetHistoryCard, { type BetHistoryItem } from '../components/BetHistoryCard.vue';
import BetStatsPanel from '../components/BetStatsPanel.vue';
import GoldSpinner from '../components/GoldSpinner.vue';
import { useOnLocaleChange } from '../composables/useOnLocaleChange';
import { usePullToRefresh } from '../composables/usePullToRefresh';

const { t } = useI18n();

const items = ref<BetHistoryItem[]>([]);
const total = ref(0);
const page = ref(1);
const loading = ref(false);
const initialLoading = ref(true);
const hasMore = ref(true);
const statusFilter = ref('');

const sentinel = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;

const STATUS_FILTERS = [
  { key: '', label: 'history.filter_all' },
  { key: 'WON', label: 'history.filter_won' },
  { key: 'LOST', label: 'history.filter_lost' },
  { key: 'PENDING', label: 'history.filter_pending' },
] as const;

const PUSH_FILTER = { key: 'PUSH', label: 'history.filter_push' } as const;

async function loadPage(p: number) {
  if (loading.value) return;
  loading.value = true;
  try {
    const params: Record<string, unknown> = { page: p };
    if (statusFilter.value) params.status = statusFilter.value;
    const { data } = await api.get('/player/bets', { params });
    const result = data.data ?? { items: [], total: 0, pageSize: 20 };
    total.value = result.total ?? 0;
    const pageSize = result.pageSize ?? 20;
    if (p === 1) {
      items.value = result.items ?? [];
    } else {
      items.value = [...items.value, ...(result.items ?? [])];
    }
    hasMore.value = items.value.length < total.value && (result.items?.length ?? 0) >= pageSize;
    page.value = p;
  } finally {
    loading.value = false;
    initialLoading.value = false;
  }
}

async function reset() {
  items.value = [];
  total.value = 0;
  page.value = 1;
  hasMore.value = true;
  initialLoading.value = true;
  loadPage(1);
}

function changeFilter(key: string) {
  if (statusFilter.value === key) return;
  statusFilter.value = key;
  reset();
}

useOnLocaleChange(reset);

const { pullDistance, refreshing, spinning, progress } = usePullToRefresh({
  onRefresh: async () => { await loadPage(1); },
});

onActivated(() => { void loadPage(1); });

onMounted(() => {
  observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting && hasMore.value && !loading.value) {
        loadPage(page.value + 1);
      }
    },
    { rootMargin: '200px' },
  );
  if (sentinel.value) observer.observe(sentinel.value);
});

onUnmounted(() => {
  observer?.disconnect();
});

const pullIndicatorStyle = () => ({
  height: `${pullDistance.value}px`,
  opacity: Math.min(pullDistance.value / 48, 1),
});
</script>

<template>
  <div class="history-page">
    <div
      class="pull-indicator"
      :style="pullIndicatorStyle()"
    >
      <GoldSpinner v-if="spinning" :size="28" :progress="progress" :active="spinning" />
    </div>

    <div v-if="initialLoading" class="state">
      <GoldSpinner :size="36" />
      <span class="loading-text">{{ t('bet.loading') }}</span>
    </div>

    <template v-else>
      <BetStatsPanel :items="items" />

      <div class="filter-tabs">
        <button
          v-for="f in STATUS_FILTERS"
          :key="f.key"
          type="button"
          class="filter-tab"
          :class="{ active: statusFilter === f.key }"
          @click="changeFilter(f.key)"
        >
          {{ t(f.label) }}
        </button>
        <span class="filter-divider" aria-hidden="true" />
        <button
          type="button"
          class="filter-tab filter-tab--push"
          :class="{ active: statusFilter === PUSH_FILTER.key }"
          :title="t('history.filter_push_hint')"
          @click="changeFilter(PUSH_FILTER.key)"
        >
          {{ t(PUSH_FILTER.label) }}
        </button>
      </div>

      <template v-if="items.length">
        <BetHistoryCard v-for="bet in items" :key="bet.betNo" :bet="bet" />

        <div ref="sentinel" class="sentinel" />

        <div v-if="loading" class="load-more-spinner">
          <GoldSpinner :size="24" />
        </div>

        <div v-else-if="!hasMore && items.length > 0" class="end-hint">
          {{ t('common.no_more') }}
        </div>
      </template>

      <div v-else class="state">{{ t('history.empty') }}</div>
    </template>
  </div>
</template>

<style scoped>
.history-page {
  padding-bottom: 24px;
}

.pull-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  transition: height 0.15s ease;
}

.filter-tabs {
  display: flex;
  gap: 6px;
  margin-bottom: 12px;
  overflow-x: auto;
  align-items: center;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
}

.filter-divider {
  width: 1px;
  height: 18px;
  background: rgba(255, 255, 255, 0.14);
  flex-shrink: 0;
  margin: 0 2px;
}

.filter-tab--push {
  border-style: dashed;
}

.filter-tabs::-webkit-scrollbar { display: none; }

.filter-tab {
  flex-shrink: 0;
  padding: 7px 14px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 700;
  color: var(--text-muted);
  background: #141414;
  border: 1px solid #2a2a2a;
  transition: all 0.2s;
}

.filter-tab.active {
  color: var(--primary-light);
  background: rgba(212, 175, 55, 0.1);
  border-color: var(--border-gold-soft);
}

.state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  text-align: center;
  color: var(--text-muted);
  padding: 56px 20px;
  font-weight: 600;
  font-size: 14px;
}

.loading-text {
  font-size: 13px;
}

.sentinel {
  height: 1px;
}

.load-more-spinner {
  display: flex;
  justify-content: center;
  padding: 20px 0 8px;
}

.end-hint {
  text-align: center;
  font-size: 12px;
  color: #555;
  font-weight: 600;
  padding: 16px 0 4px;
  letter-spacing: 0.03em;
}
</style>
