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

  interface Props {
    reply: NostrEvent;
    parentEvent?: NostrEvent; // The event this is replying to
    onReply?: (post: NostrEvent) => void;
  }

  let { reply, 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 - reply.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 getClientName(): string | null {
    const clientTag = reply.tags.find((t) => t[0] === 'client');
    return clientTag?.[1] || null;
  }

  function getParentPreview(): string {
    if (parentEvent) {
      return parentEvent.content.slice(0, 100) + (parentEvent.content.length > 100 ? '...' : '');
    }
    // Try to extract from reply tags
    const eTag = reply.tags.find((t) => t[0] === 'e' && t[3] === 'reply');
    if (eTag) {
      return 'Replying to...';
    }
    return '';
  }

  $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="Feed-reply">
  <div class="card-content" class:expanded bind:this={contentElement}>
    {#if parentEvent}
      <div class="reply-context mb-2 p-2 bg-fog-highlight dark:bg-fog-dark-highlight rounded text-xs text-fog-text-light dark:text-fog-dark-text-light">
        <span class="font-semibold">Replying to:</span> {getParentPreview()}
      </div>
    {/if}

    <div class="reply-header flex items-center gap-2 mb-2">
      <ProfileBadge pubkey={reply.pubkey} />
      <span class="text-xs text-fog-text-light dark:text-fog-dark-text-light">{getRelativeTime()}</span>
      {#if getClientName()}
        <span class="text-xs text-fog-text-light dark:text-fog-dark-text-light">via {getClientName()}</span>
      {/if}
      <div class="ml-auto">
        <EventMenu event={reply} showContentActions={reply.kind === 1} />
      </div>
    </div>

    <div class="reply-content mb-2">
      <MarkdownRenderer content={reply.content} />
    </div>

    <div class="reply-actions flex items-center gap-4">
      <FeedReactionButtons event={reply} />
      <ZapButton event={reply} />
      <ZapReceipt eventId={reply.id} pubkey={reply.pubkey} />
      {#if onReply}
        <button
          onclick={() => onReply(reply)}
          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(reply.kind).number}</span>
    <span class="kind-description">{getKindInfo(reply.kind).description}</span>
  </div>
</article>

<style>
  .Feed-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 var(--fog-accent, #64748b);
    position: relative;
  }

  :global(.dark) .Feed-reply {
    background: var(--fog-dark-post, #1f2937);
    border-color: var(--fog-dark-border, #374151);
    border-left-color: var(--fog-dark-accent, #64748b);
  }

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

  .reply-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) .reply-actions {
    border-top-color: var(--fog-dark-border, #374151);
  }

  .reply-context {
    cursor: pointer;
    transition: opacity 0.2s;
  }

  .reply-context:hover {
    opacity: 0.8;
  }

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