<script lang="ts">
  import { walletState } from "$lib/wallet.svelte";
  import Button from "$lib/components/Button.svelte";
  import QRCode from "qrcode";
  import { onMount } from "svelte";
  import LoadingIndicator from "$lib/components/LoadingIndicator.svelte";

  const { type }: { type: string } = $props();

  let paymentText = $state("");
  const loading = $derived(paymentText === "");

  const qr = $derived(
    QRCode.toDataURL(`${type}:${paymentText}`, {
      errorCorrectionLevel: "H",
    })
  );

  onMount(async () => {
    if (!$walletState.open) return;
    const paymentMethod =
      type === "bitcoin"
        ? "bitcoinAddress"
        : type === "bolt12"
          ? "bolt12Offer"
          : type === "lightning"
            ? "bolt11Invoice"
            : "liquidAddress";

    if (paymentMethod === "bolt11Invoice") {
      paymentText = $walletState.wallet.lightningAddress;
    } else {
      paymentText = await $walletState.wallet.generateAddress(paymentMethod);
    }
  });
</script>

{#if !loading}
  {#await qr}
    <LoadingIndicator size={120} />
  {:then qrDataUrl}
    <img class="qr" src={qrDataUrl} alt={paymentText} />
  {/await}

  <pre class="addr">{paymentText}</pre>
  <Button
    class="copy-btn"
    onclick={() => navigator.clipboard.writeText(paymentText)}
  >
    Copy
  </Button>
{:else}
  <LoadingIndicator />
{/if}

<style>
  img.qr {
    width: auto;
    height: auto;
    max-width: 400px;
    max-height: 400px;
    border: 2px solid var(--primary-color);
    margin-bottom: 1.5rem;
    background: #fff;
  }
  pre.addr {
    font-family: monospace;
    background: rgba(0, 0, 0, 0.2);
    padding: 0.5rem;
    border-radius: 4px;
    overflow-x: auto;
    max-width: 100%;
    margin-bottom: 0.8rem;
    color: var(--text-color);
  }
  .spinner {
    width: 120px;
    height: 120px;
    border: 10px solid var(--surface-alt-color);
    border-top: 10px solid var(--accent-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 1.5rem auto 1rem;
  }
  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
</style>
