<script>
  import Header from '$lib/layout/Header.svelte';
  import StatsCard from '$lib/components/StatsCard.svelte';
  import PaymentMenu from '$lib/components/wallet/PaymentMenu.svelte';
  import SellMenu from '$lib/components/wallet/SellMenu.svelte';
  import tokensIcon from '$lib/assets/icons/sidebar/tokens.svg?raw';
  import walletIcon from '$lib/assets/icons/sidebar/wallet.svg?raw';

  const breadcrumb = [{ label: 'Início' }, { label: 'wallet', active: true }];

  let easyTokens = [
    { id: 1, label: 'EasyToken Soja', amount: 1 },
    { id: 2, label: 'EasyToken Milho', amount: 1 },
    { id: 3, name: 'EasyToken Café', balance: 1 }
  ];
  let easyCoinBalance = 0;

  let isPaymentOpen = false;
  let isSellOpen = false;

  let rateBRLPerEasyCoin = 100;

  function openPayment() { isPaymentOpen = true; }
  function closePayment() { isPaymentOpen = false; }
  function confirmPayment(method) { isPaymentOpen = false; }

  function openSell() { isSellOpen = true; }
  function closeSell() { isSellOpen = false; }
  function confirmSell(e) {
    isSellOpen = false;
  }

  function formatToken(n) {
    return new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 6 }).format(Number(n || 0));
  }
  function formatCoin(n) {
    return new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(Number(n || 0));
  }
</script>

<div>
  <Header title="Wallet" subtitle="Saldos e operações" breadcrumb={breadcrumb} />

  <div class="p-4 space-y-6">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {#each easyTokens as t}
        <div class="rounded-lg overflow-hidden">
          <StatsCard
            title={t.label || t.name || 'EasyToken'}
            value={formatToken(t.amount || t.balance || 0)}
            change="Saldo atual"
            iconSvg={tokensIcon}
          />
        </div>
      {/each}
      <div class="rounded-lg overflow-hidden">
        <StatsCard
          title="EasyCoin"
          value={formatCoin(easyCoinBalance)}
          change="Saldo atual"
          iconSvg={walletIcon}
        />
      </div>
    </div>

    <div class="flex gap-3">
      <button
        class="inline-flex items-center gap-2 px-4 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white shadow"
        on:click={openPayment}
      >
        Comprar EasyCoins
      </button>

      <button
        class="inline-flex items-center gap-2 px-4 py-2 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-800 dark:text-gray-100"
        on:click={openSell}
      >
        Vender EasyCoins
      </button>
    </div>
  </div>

  <PaymentMenu
    isOpen={isPaymentOpen}
    onClose={closePayment}
    onConfirm={confirmPayment}
  />

  <SellMenu
    isOpen={isSellOpen}
    onClose={closeSell}
    onConfirm={(e) => confirmSell(e.detail || e)}
    rateBRLPerEasyCoin={rateBRLPerEasyCoin}
  />
</div>