<script lang="ts">
  import ProfileBadge from '../../components/layout/ProfileBadge.svelte';
  import ReplyContext from '../../components/content/ReplyContext.svelte';
  import EventMenu from '../../components/EventMenu.svelte';
  import type { NostrEvent } from '../../types/nostr.js';
  import { getKindInfo } from '../../types/kind-lookup.js';

  interface Props {
    zapReceipt: NostrEvent; // Kind 9735 zap receipt
    parentEvent?: NostrEvent; // The event this zap receipt is for
    onReply?: (receipt: NostrEvent) => void;
  }

  let { zapReceipt, parentEvent, onReply }: Props = $props();
  let expanded = $state(false);
  let contentElement: HTMLElement | null = $state(null);
  let needsExpansion = $state(false);

  function getRelativeTime(): string {
    const now = Math.floor(Date.now() / 1000);
    const diff = now - zapReceipt.created_at;
    const hours = Math.floor(diff / 3600);
    const days = Math.floor(diff / 86400);
    const minutes = Math.floor(diff / 60);

    if (days > 0) return `${days}d ago`;
    if (hours > 0) return `${hours}h ago`;
    if (minutes > 0) return `${minutes}m ago`;
    return 'just now';
  }

  function getAmount(): number {
    const amountTag = zapReceipt.tags.find((t) => t[0] === 'amount');
    if (amountTag && amountTag[1]) {
      const amount = parseInt(amountTag[1], 10);
      return isNaN(amount) ? 0 : amount;
    }
    return 0;
  }

  function getZappedPubkey(): string | null {
    const pTag = zapReceipt.tags.find((t) => t[0] === 'p');
    return pTag?.[1] || null;
  }

  function getZappedEventId(): string | null {
    const eTag = zapReceipt.tags.find((t) => t[0] === 'e');
    return eTag?.[1] || null;
  }

  function getZapperPubkey(): string {
    return zapReceipt.pubkey;
  }

  function isReply(): boolean {
    // Check if this zap receipt is a reply (has e tag pointing to another event)
    return zapReceipt.tags.some((t) => t[0] === 'e' && t[1] !== zapReceipt.id);
  }

  $effect(() => {
    if (contentElement) {
      checkContentHeight();
      // Use ResizeObserver to detect when content changes (e.g., images loading)
      const observer = new ResizeObserver(() => {
        checkContentHeight();
      });
      observer.observe(contentElement);
      return () => observer.disconnect();
    }
  });

  function checkContentHeight() {
    if (contentElement) {
      // Use requestAnimationFrame to ensure DOM is fully updated
      requestAnimationFrame(() => {
        if (contentElement) {
          needsExpansion = contentElement.scrollHeight > 500;
        }
      });
    }
  }

  function toggleExpanded() {
    expanded = !expanded;
  }
</script>

<article class="zap-receipt-reply" id="event-{zapReceipt.id}" data-event-id={zapReceipt.id}>
  <div class="card-content" class:expanded bind:this={contentElement}>
    {#if parentEvent}
      <div class="zap-reply-context">
        <span class="text-sm text-fog-text-light dark:text-fog-dark-text-light">⚡ Zapping</span>
        <ReplyContext {parentEvent} targetId="event-{parentEvent.id}" />
      </div>
    {/if}

    <div class="zap-header flex items-center gap-2 mb-2">
      <ProfileBadge pubkey={getZapperPubkey()} />
      <span class="text-lg">⚡</span>
      <span class="text-sm font-semibold">{getAmount().toLocaleString()} sats</span>
      <span class="text-xs text-fog-text-light dark:text-fog-dark-text-light">{getRelativeTime()}</span>
      <div class="ml-auto">
        <EventMenu event={zapReceipt} />
      </div>
    </div>

    {#if zapReceipt.content}
      <div class="zap-content mb-2 text-sm text-fog-text dark:text-fog-dark-text">
        {zapReceipt.content}
      </div>
    {/if}

    <div class="zap-actions flex items-center gap-4">
      {#if onReply}
        <button
          onclick={() => onReply(zapReceipt)}
          class="text-xs text-fog-accent dark:text-fog-dark-accent hover:underline"
        >
          Reply
        </button>
      {/if}
    </div>
  </div>
  
  {#if needsExpansion}
    <button
      onclick={toggleExpanded}
      class="show-more-button text-sm text-fog-accent dark:text-fog-dark-accent hover:underline mt-2"
    >
      {expanded ? 'Show less' : 'Show more'}
    </button>
  {/if}
  
  <div class="kind-badge">
    <span class="kind-number">{getKindInfo(zapReceipt.kind).number}</span>
    <span class="kind-description">{getKindInfo(zapReceipt.kind).description}</span>
  </div>
</article>

<style>
  .zap-receipt-reply {
    padding: 1rem;
    margin-bottom: 1rem;
    background: var(--fog-post, #ffffff);
    border: 1px solid var(--fog-border, #e5e7eb);
    border-radius: 0.25rem;
    border-left: 3px solid #fbbf24; /* Gold/yellow for zaps */
    position: relative;
  }

  :global(.dark) .zap-receipt-reply {
    background: var(--fog-dark-post, #1f2937);
    border-color: var(--fog-dark-border, #374151);
    border-left-color: #fbbf24;
  }

  .zap-content {
    line-height: 1.6;
  }

  .zap-actions {
    padding-top: 0.5rem;
    padding-right: 6rem; /* Reserve space for kind badge */
    border-top: 1px solid var(--fog-border, #e5e7eb);
    margin-top: 0.5rem;
  }

  :global(.dark) .zap-actions {
    border-top-color: var(--fog-dark-border, #374151);
  }

  .card-content {
    max-height: 500px;
    overflow: hidden;
    transition: max-height 0.3s ease;
  }

  .card-content.expanded {
    max-height: none;
  }

  .show-more-button {
    width: 100%;
    text-align: center;
    padding: 0.5rem;
    background: transparent;
    border: none;
    cursor: pointer;
  }

  .kind-badge {
    position: absolute;
    bottom: 0.5rem;
    right: 0.5rem;
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 0.25rem;
    font-size: 0.625rem;
    line-height: 1;
    color: var(--fog-text-light, #9ca3af);
  }

  :global(.dark) .kind-badge {
    color: var(--fog-dark-text-light, #6b7280);
  }

  .kind-number {
    font-weight: 600;
  }

  .kind-description {
    font-size: 0.625rem;
    opacity: 0.8;
  }
</style>
