<script setup lang="ts">
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { useMarketStore } from '@/stores/market'
import MarketRow from './MarketRow.vue'
import type { MarketType, MarketItem } from '@/types'

const { t } = useI18n()
const store = useMarketStore()
const { filteredList, activeTab, searchQuery, loading } = storeToRefs(store)
const { setTab, setSearch } = store

const tabs = computed<{ label: string; value: MarketType }[]>(() => [
  { label: t('nav.futures'), value: 'futures' },
  { label: t('nav.spot'), value: 'spot' },
])

type SortKey = keyof Pick<MarketItem, 'symbol' | 'price' | 'change24h' | 'high24h' | 'low24h' | 'volume24h'>
type SortDir = 'asc' | 'desc'

const sortKey = ref<SortKey | null>(null)
const sortDir = ref<SortDir>('desc')

const columns = computed<{ key: SortKey; label: string }[]>(() => [
  { key: 'symbol', label: t('market.name') },
  { key: 'price', label: t('market.price') },
  { key: 'change24h', label: t('market.change24hShort') },
  { key: 'high24h', label: t('market.high24h') },
  { key: 'low24h', label: t('market.low24h') },
  { key: 'volume24h', label: t('market.volume24hLabel') },
])

function toggleSort(key: SortKey) {
  if (sortKey.value === key) {
    sortDir.value = sortDir.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortKey.value = key
    sortDir.value = 'desc'
  }
}

const sortedList = computed(() => {
  if (!sortKey.value) return filteredList.value
  const key = sortKey.value
  const dir = sortDir.value === 'asc' ? 1 : -1
  return [...filteredList.value].sort((a, b) => {
    const va = a[key]
    const vb = b[key]
    if (typeof va === 'string') return dir * (va as string).localeCompare(vb as string)
    return dir * ((va as number) - (vb as number))
  })
})
</script>

<template>
  <div class="market-table-wrap">
    <!-- Tab + 搜索 -->
    <div class="market-table-toolbar">
      <div class="tabs">
        <button
          v-for="tab in tabs"
          :key="tab.value"
          class="tab"
          :class="{ 'is-active': activeTab === tab.value }"
          @click="setTab(tab.value)"
        >
          {{ tab.label }}
        </button>
      </div>

      <div class="search-box">
        <input
          class="search-input"
          :value="searchQuery"
          :placeholder="t('market.searchPair')"
          @input="setSearch(($event.target as HTMLInputElement).value)"
        />
        <svg class="search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
        </svg>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <table class="table">
        <thead>
          <tr>
            <th
              v-for="col in columns"
              :key="col.key"
              class="th"
              :class="{ 'th-right': col.key !== 'symbol', 'th-active': sortKey === col.key }"
              @click="toggleSort(col.key)"
            >
              {{ col.label }}
              <span class="sort-icon">
				<span class="sort-up" :class="{ active: sortKey === col.key && sortDir === 'desc' }">↑</span>
                <span class="sort-down" :class="{ active: sortKey === col.key && sortDir === 'asc' }">↓</span>
              </span>
            </th>
          </tr>
        </thead>
        <tbody>
          <template v-if="loading">
            <tr v-for="i in 8" :key="i" class="skeleton-row">
              <td colspan="6"><div class="skeleton" /></td>
            </tr>
          </template>
          <template v-else-if="sortedList.length">
            <MarketRow v-for="item in sortedList" :key="`${item.symbol}-${item.type}`" :item="item" />
          </template>
          <tr v-else>
            <td colspan="6" class="empty">{{ t('common.noData') }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped>
/* Toolbar */
.market-table-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-4);
}

.tabs { display: flex; gap: 0; }
.tab {
  padding: var(--space-2) var(--space-4);
  font-size: var(--text-body);
  color: var(--color-text-secondary);
  border-bottom: 2px solid transparent;
  transition: color var(--transition), border-color var(--transition);
}
.tab:hover { color: var(--color-text-primary); }
.tab.is-active {
  color: var(--color-text-primary);
  font-weight: var(--fw-semibold);
  border-bottom-color: var(--color-primary);
}

.search-box { position: relative; }
.search-input {
  height: 36px;
  padding: 0 var(--space-3) 0 var(--space-8);
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: 18px;
  color: var(--color-text-primary);
  font-size: var(--text-small);
  width: 160px;
  transition: border-color var(--transition);
}
.search-input::placeholder { color: var(--color-text-muted); }
.search-input:focus { border-color: var(--color-border-focus); }
.search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-text-muted);
  pointer-events: none;
}

/* Table */
.table-container { overflow-x: auto; }
.table { width: 100%; border-collapse: collapse; }

.th {
  padding: var(--space-3) var(--space-4);
  font-size: var(--text-small);
  font-weight: var(--fw-medium);
  color: var(--color-text-secondary);
  text-align: left;
  border-bottom: 1px solid var(--color-border);
  white-space: nowrap;
  cursor: pointer;
  user-select: none;
  transition: color var(--transition);
}
.th:hover { color: var(--color-text-primary); }
.th.th-active { color: var(--color-primary); }
.th-right { text-align: right; }

.sort-icon {
  margin-left: 4px;
  font-size: 10px;
  opacity: 0.4;
  display: inline-flex;
  flex-direction: column;
  line-height: 1;
  gap: 1px;
  vertical-align: middle;
}
.th:hover .sort-icon { opacity: 0.8; }
/* .sort-up, .sort-down { opacity: 1 !important; color: var(--color-primary); } */
.sort-up, .sort-down {
  opacity: 0.2;
}
.sort-up.active, .sort-down.active {
  opacity: 1 !important;
  color: var(--color-primary);
}

/* Loading skeleton */
.skeleton-row td { padding: var(--space-3) var(--space-4); }
.skeleton {
  height: 20px;
  background: linear-gradient(90deg, var(--color-bg-card) 25%, rgba(255,255,255,0.06) 50%, var(--color-bg-card) 75%);
  background-size: 200% 100%;
  border-radius: var(--radius-sm);
  animation: shimmer 1.2s infinite;
}
@keyframes shimmer { to { background-position: -200% 0; } }

.empty {
  padding: var(--space-12);
  text-align: center;
  color: var(--color-text-muted);
  font-size: var(--text-small);
}

/* ── 移动端 ── */
@media (max-width: 768px) {
  .market-table-toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: var(--space-3);
  }
  .search-input { width: 100%; }
  .search-box { width: 100%; }
}
</style>
