<script>
  import { createEventDispatcher } from 'svelte';
  import { fly, fade } from 'svelte/transition';

  export let isOpen = false;
  export let onClose = () => {};
  export let onConfirm = (payload) => {};
  export let rateBRLPerEasyCoin = 1;

  const dispatch = createEventDispatcher();

  let pixKey = '';
  let amount = '';

  $: numericAmount = Number(amount) || 0;
  $: totalBRL = numericAmount * Number(rateBRLPerEasyCoin || 1);

  function close() {
    onClose();
    dispatch('close');
  }

  function confirm() {
    if (!pixKey || !numericAmount) return;
    const payload = { pixKey, amount: numericAmount, totalBRL };
    onConfirm(payload);
    dispatch('confirm', payload);
  }

  function formatBRL(n) {
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(Number(n || 0));
  }
</script>

{#if isOpen}
  <div class="fixed inset-0 z-50" aria-modal="true" role="dialog" aria-label="Vender EasyCoin">
    <div
      class="absolute inset-0 bg-black/40"
      role="button"
      tabindex="0"
      aria-label="Fechar menu de venda"
      on:click={close}
      on:keydown={(event) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          close();
        }
      }}
      transition:fade
    ></div>

    <div
      class="absolute inset-y-0 right-0 w-full max-w-md bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 shadow-xl flex flex-col"
      transition:fly={{ x: 24, duration: 200 }}
    >
      <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
        <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">Vender EasyCoin</h3>
        <button
          class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
          aria-label="Fechar"
          on:click={close}
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
               fill="none" stroke="currentColor" stroke-width="1.5" class="w-5 h-5">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <div class="p-6 space-y-4 overflow-auto">
        <div class="rounded-lg border border-amber-200 bg-amber-50 text-amber-900 px-4 py-3 text-sm">
          <p class="font-semibold">Função não implementada ainda</p>
          <p>
            Este formulário permite simular a venda e preencher os campos (PIX e quantidade),
            mas o envio ainda não está conectado ao backend/pagamentos reais.
          </p>
        </div>
        <div class="space-y-1">
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300" for="sell-pix-key">Chave Pix</label>
          <input
            id="sell-pix-key"
            class="w-full px-3 py-2 rounded-md bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
            bind:value={pixKey}
            placeholder="Informe sua chave Pix" />
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300" for="sell-amount">Quantidade (EasyCoin)</label>
            <input
              id="sell-amount"
              type="number" min="0" step="0.01"
              class="w-full px-3 py-2 rounded-md bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
              bind:value={amount}
              placeholder="0,00" />
          </div>
          <div class="space-y-1">
            <p class="block text-sm font-medium text-gray-700 dark:text-gray-300">Valor em Reais</p>
            <div class="w-full px-3 py-2 rounded-md bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-900 dark:text-gray-100">
              {formatBRL(totalBRL)}
            </div>
          </div>
        </div>

        <div class="text-xs text-gray-500 dark:text-gray-400">
          Taxa de conversão: 1 EasyCoin = {formatBRL(rateBRLPerEasyCoin)}
        </div>
      </div>

      <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex items-center justify-end gap-3">
        <button
          class="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={close}
        >
          Cancelar
        </button>
        <button
          class="px-4 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white disabled:opacity-50"
          disabled={!pixKey || !numericAmount}
          on:click={confirm}
        >
          Confirmar
        </button>
      </div>
    </div>
  </div>
{/if}