<script setup lang="ts">
import { useAccount, useConnect, useDisconnect } from '@harb/web3';
import { ref } from 'vue';

const { address, isConnected } = useAccount();
const { connectors, connect } = useConnect();
const { disconnect } = useDisconnect();
const showConnectors = ref(false);

function shortAddress(addr: string) {
  return `${addr.slice(0, 6)}…${addr.slice(-4)}`;
}

function handleConnect(connector: (typeof connectors)[number]) {
  connect({ connector });
  showConnectors.value = false;
}
</script>

<template>
  <div class="wallet-button">
    <template v-if="isConnected && address">
      <button class="wallet-button__connected" aria-label="Disconnect wallet" @click="disconnect()">
        {{ shortAddress(address) }}
      </button>
    </template>
    <template v-else>
      <button class="wallet-button__connect" aria-label="Connect wallet" @click="showConnectors = !showConnectors">
        Connect Wallet
      </button>
      <div v-if="showConnectors" class="wallet-button__dropdown">
        <button
          v-for="connector in connectors"
          :key="connector.uid"
          class="wallet-button__option"
          :aria-label="`Connect with ${connector.name}`"
          @click="handleConnect(connector)"
        >
          {{ connector.name }}
        </button>
      </div>
    </template>
  </div>
</template>

<style lang="sass" scoped>
.wallet-button
  position: relative

  &__connect, &__connected
    padding: 0.5rem 1rem
    border-radius: 8px
    border: 1px solid rgba(255, 255, 255, 0.2)
    background: rgba(255, 255, 255, 0.08)
    color: #fff
    cursor: pointer
    font-size: 0.9rem
    transition: background 0.2s

    &:hover
      background: rgba(255, 255, 255, 0.15)

  &__connect
    background: #3b82f6
    border-color: #3b82f6

    &:hover
      background: #2563eb

  &__dropdown
    position: absolute
    top: 100%
    right: 0
    margin-top: 0.5rem
    background: #1a1a2e
    border: 1px solid rgba(255, 255, 255, 0.15)
    border-radius: 8px
    padding: 0.5rem
    min-width: 200px
    z-index: 100

  &__option
    display: block
    width: 100%
    padding: 0.5rem 0.75rem
    background: none
    border: none
    color: #fff
    cursor: pointer
    text-align: left
    border-radius: 4px
    font-size: 0.85rem

    &:hover
      background: rgba(255, 255, 255, 0.1)
</style>
