<script lang="ts">
  import { balances, getBreezSDK } from "$lib/breez.svelte";
  import PaymentHistoryItem from "$lib/components/PaymentHistoryItem.svelte";
  import type {
    BindingLiquidSdk,
    Payment,
  } from "@breeztech/breez-sdk-liquid/web";
  import { cashuTxns } from "$lib/cashu.svelte";

  let payments = $state<Payment[]>([]);

  const combinedPayments = $derived(
    [...payments, ...$cashuTxns].sort((a, b) => b.timestamp - a.timestamp)
  );

  async function loadPayments() {
    try {
      const breezSDK = await getBreezSDK();
      const result = await breezSDK.listPayments({});
      payments = result;
    } catch (err) {
      console.error("Failed to load payments", err);
    }
  }

  $effect(() => {
    balances.tick;
    loadPayments();
  });
</script>

<div class="payment-history">
  {#if combinedPayments.length === 0}
    <p class="empty">No payments yet.</p>
  {:else}
    {#each combinedPayments as payment (payment.txId)}
      <PaymentHistoryItem {payment} />
    {/each}
  {/if}
</div>

<style>
  .payment-history {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .empty {
    text-align: center;
    font-size: 0.9rem;
    opacity: 0.8;
    margin: 0.5rem 0;
  }
</style>
