import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { AssetOverview, AssetItem, TransferAccount } from '@/types'

export const useAssetsStore = defineStore('assets', () => {
  // ── State ──────────────────────────────────────────
  const overview = ref<AssetOverview | null>(null)
  const loading = ref(false)
  const hideSmall = ref(false)
  const searchQuery = ref('')

  // ── Getters ────────────────────────────────────────
  const filteredAssets = computed<AssetItem[]>(() => {
    if (!overview.value) return []
    let list = overview.value.assets
    if (hideSmall.value) list = list.filter(a => a.usdtValue >= 1)
    if (searchQuery.value) {
      const q = searchQuery.value.toLowerCase()
      list = list.filter(a => a.coin.toLowerCase().includes(q) || a.name.includes(q))
    }
    return list
  })

  // ── Actions ────────────────────────────────────────
  async function fetchOverview() {
    loading.value = true
    try {
      await mockDelay()
      overview.value = getMockOverview()
    } finally {
      loading.value = false
    }
  }

  async function transfer(
    from: TransferAccount,
    to: TransferAccount,
    coin: string,
    amount: number,
  ) {
    await mockDelay(600)
    // Mock: no-op, real impl calls API
    console.log('transfer', { from, to, coin, amount })
  }

  // ── Return ALL state ───────────────────────────────
  return {
    overview,
    loading,
    hideSmall,
    searchQuery,
    filteredAssets,
    fetchOverview,
    transfer,
  }
})

// ── Mock helpers ───────────────────────────────────────

function mockDelay(ms = 400) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function getMockOverview(): AssetOverview {
  return {
    totalUsdt: 12580.45,
    totalCny: 91332.47,
    assets: [
      { coin: 'USDT', name: 'Tether',    available: 10000,  frozen: 200,    usdtValue: 10200 },
      { coin: 'BTC',  name: '比特币',     available: 0.05,   frozen: 0,      usdtValue: 3500 },
      { coin: 'ETH',  name: '以太坊',     available: 0.8,    frozen: 0,      usdtValue: 2200 },
      { coin: 'BNB',  name: 'BNB',       available: 2.5,    frozen: 0,      usdtValue: 900 },
      { coin: 'SOL',  name: 'Solana',    available: 5,      frozen: 0,      usdtValue: 750 },
      { coin: 'DOGE', name: '狗狗币',     available: 1000,   frozen: 0,      usdtValue: 0.3 },
    ],
  }
}
