<script lang="ts">
  import { Post } from "./pdsfetch";
  import { Config } from "../../config";
  import { onMount, onDestroy } from "svelte";
  import moment from "moment";
  import { blueskyHandleFromDid } from "./pdsfetch";
  import Hls from "hls.js";
  let { post }: { post: Post } = $props();

  // State for image carousel
  let currentImageIndex = $state(0);

  // Local state for reply handle text
  let replyingHandle: string | null = $state(null);

  // Video element ref and HLS instance
  let videoEl: HTMLVideoElement | null = $state(null);
  let hls: Hls | null = null;

  // Update replying handle when replyingUri changes
  $effect(() => {
    if (post.replyingUri?.repo) {
      // fire and forget; update when resolved
      blueskyHandleFromDid(post.replyingUri.repo)
        .then((h) => {
          replyingHandle = h || null;
        })
        .catch(() => {
          replyingHandle = null;
        });
    } else {
      replyingHandle = null;
    }
  });

  // Functions to navigate carousel
  function nextImage() {
    if (post.imagesCid && currentImageIndex < post.imagesCid.length - 1) {
      currentImageIndex++;
    }
  }

  function prevImage() {
    if (currentImageIndex > 0) {
      currentImageIndex--;
    }
  }

  // Function to preload an image
  function preloadImage(index: number): void {
    if (!post.imagesCid || index < 0 || index >= post.imagesCid.length) return;

    const img = new Image();
    img.src = `https://cdn.bsky.app/img/feed_thumbnail/plain/${post.authorDid}/${post.imagesCid[index]}@jpeg`;
  }

  // Initialize HLS playback when mounted if there's a video
  onMount(() => {
    // Preload the next image if it exists
    if (post.imagesCid && post.imagesCid.length > 1) {
      if (post.imagesCid.length > 1) {
        preloadImage(1);
      }
    }

    if (post.videosLinkCid && videoEl) {
      const src = `https://video.cdn.bsky.app/hls/${post.authorDid}/${post.videosLinkCid}/playlist.m3u8`;
      try {
        if (Hls.isSupported()) {
          hls = new Hls();
          hls.loadSource(src);
          hls.attachMedia(videoEl);
        } else if (videoEl.canPlayType("application/vnd.apple.mpegurl")) {
          // Safari / iOS native HLS
          videoEl.src = src;
        } else {
          // As a basic fallback, set src; some browsers may still handle it
          videoEl.src = src;
        }
      } catch (_) {
        // Ignore init errors; controls will remain and user can retry
      }
    }
  });

  onDestroy(() => {
    if (hls) {
      hls.destroy();
      hls = null;
    }
  });
</script>

<div id="postContainer">
  <div id="postHeader">
    {#if post.authorAvatarCid}
      <img
        id="avatar"
        src="https://cdn.bsky.app/img/feed_thumbnail/plain/{post.authorDid}/{post.authorAvatarCid}@jpeg"
        alt="avatar of {post.displayName}"
      />
    {/if}
    <div id="headerText">
      <a id="displayName" href="{Config.FRONTEND_PROFILE_URL}/{post.authorDid}"
        >{post.displayName}</a
      >
      <p id="handle">
        <a href="{Config.FRONTEND_URL}/profile/{post.authorHandle}"
          >@{post.authorHandle}</a
        >

        <a
          id="postLink"
          style="text-decoration: underline;"
          href="{Config.FRONTEND_URL}/profile/{post.authorDid}/post/{post.recordName}"
          >{moment(post.timenotstamp).isBefore(moment().subtract(1, "month"))
            ? moment(post.timenotstamp).format("MMM D, YYYY")
            : moment(post.timenotstamp).fromNow()}</a
        >
      </p>
    </div>
  </div>
  <div id="postContent">
    {#if post.replyingUri}
      <a
        id="replyingText"
        style="text-decoration: underline;"
        href="{Config.FRONTEND_URL}/profile/{post.replyingUri.repo}/post/{post
          .replyingUri.rkey}"
        >replying to {replyingHandle
          ? `@${replyingHandle}`
          : post.replyingUri.repo}</a
      >
    {/if}
    {#if post.quotingUri}
      <a
        id="quotingText"
        href="{Config.FRONTEND_URL}/profile/{post.quotingUri.repo}/post/{post
          .quotingUri.rkey}">quoting {post.quotingUri.repo}</a
      >
    {/if}
    <div id="postText">
      {#each post.richText.segments() as segment}
        {#if segment.mention}
          <a href="{Config.FRONTEND_URL}/profile/{segment.mention.did}"
            >{segment.text}</a
          >
        {:else if segment.link}
          <a style="text-decoration: underline" href={segment.link.uri}
            >{segment.text}</a
          >
        {:else if segment.text}
          {segment.text}
        {/if}
      {/each}
    </div>
    {#if post.imagesCid && post.imagesCid.length > 0}
      <div id="carouselContainer">
        <img
          id="embedImages"
          alt="Post Image {currentImageIndex + 1} of {post.imagesCid.length}"
          src="https://cdn.bsky.app/img/feed_thumbnail/plain/{post.authorDid}/{post
            .imagesCid[currentImageIndex]}@jpeg"
        />

        {#if post.imagesCid.length > 1}
          <div id="carouselControls">
            <button
              id="prevBtn"
              onclick={prevImage}
              disabled={currentImageIndex === 0}>←</button
            >
            <div id="carouselIndicators">
              {#each post.imagesCid as _, i}
                <div
                  class="indicator {i === currentImageIndex ? 'active' : ''}"
                ></div>
              {/each}
            </div>
            <button
              id="nextBtn"
              onclick={nextImage}
              disabled={currentImageIndex === post.imagesCid.length - 1}
              >→</button
            >
          </div>
        {/if}
      </div>
    {/if}
    {#if post.videosLinkCid}
      <!-- svelte-ignore a11y_media_has_caption -->
      <video id="embedVideo" bind:this={videoEl} controls></video>
    {/if}
    {#if post.gifLink}
      <img id="embedVideo" src={post.gifLink} alt="Post GIF" />
    {/if}
  </div>
</div>

<style>
</style>
