<script lang="ts">
  import { getBreezSDK } from "$lib/breez.svelte";
  import { getCashuAddress } from "$lib/cashu.svelte";
  import QRCode from "qrcode";

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

  const paymentMethod = $derived(
    type === "bitcoin"
      ? "bitcoinAddress"
      : type === "bolt12"
        ? "bolt12Offer"
        : type === "lightning"
          ? "bolt11Invoice"
          : "liquidAddress"
  );

  const paymentText = $derived(
    paymentMethod === "bolt11Invoice"
      ? getCashuAddress()
      : getBreezSDK().then((breezSDK) =>
          breezSDK.prepareReceivePayment({ paymentMethod }).then((prep) =>
            breezSDK.receivePayment({ prepareResponse: prep }).then((res) => {
              let destination = res.destination;
              if (destination.includes(":"))
                destination = destination.split(":")[1];
              if (destination.includes("?"))
                destination = destination.split("?")[0];
              return destination;
            })
          )
        )
  );

  const qr = $derived(
    paymentText.then((text) =>
      QRCode.toDataURL(`${type}:${text}`, {
        errorCorrectionLevel: "H",
      })
    )
  );
</script>

{#await qr}
  <div class="spinner"></div>
{:then qrDataUrl}
  <img class="qr" src={qrDataUrl} alt="${alt}" />
{/await}

{#await paymentText then paymentText}
  <pre class="addr">{paymentText}</pre>
{/await}

<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>
