---
import { LINKS } from "../lib/links";
---

<dialog id="media-modal" aria-modal="true" aria-labelledby="media-modal-title">
  <div class="media-modal-content">
    <div class="media-modal-header">
      <div class="media-modal-header-left">
        <img class="media-modal-thumb" alt="" loading="lazy" />
        <div class="media-modal-title-wrap">
          <div class="media-modal-kicker"></div>
          <h2 id="media-modal-title" class="media-modal-title"></h2>
        </div>
      </div>
      <button type="button" class="media-modal-close" aria-label="Close" data-close-method="button">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>

    <div class="media-modal-embed-container" data-embed-kind="">
      <div class="media-modal-embed-placeholder">
        <div class="media-modal-embed-fallback-wrap" hidden></div>
      </div>
      <iframe
        class="media-modal-embed"
        title="Media embed"
        width="100%"
        frameborder="0"
        allowfullscreen
      ></iframe>
      <audio class="media-modal-audio" controls></audio>
    </div>

    <div class="media-modal-body">
      <p class="media-modal-description"></p>
      <div class="media-modal-meta">
        <span class="media-modal-date"></span>
        <span class="media-modal-views"></span>
      </div>
    </div>

    <div class="media-modal-ctas">
    </div>
  </div>
</dialog>

<script is:inline define:vars={{ youtubeChannelUrl: LINKS.youtubeChannel, podcastUrl: LINKS.podcast }}>
(function() {
  const dialog = document.getElementById("media-modal");
  const dialogContent = dialog.querySelector(".media-modal-content");
  const kickerEl = dialog.querySelector(".media-modal-kicker");
  const thumbEl = dialog.querySelector(".media-modal-thumb");
  const titleEl = dialog.querySelector(".media-modal-title");
  const embedContainer = dialog.querySelector(".media-modal-embed-container");
  const embedPlaceholder = dialog.querySelector(".media-modal-embed-placeholder");
  const embedFallbackWrap = dialog.querySelector(".media-modal-embed-fallback-wrap");
  const iframe = dialog.querySelector(".media-modal-embed");
  const audio = dialog.querySelector(".media-modal-audio");
  const descriptionEl = dialog.querySelector(".media-modal-description");
  const dateEl = dialog.querySelector(".media-modal-date");
  const viewsEl = dialog.querySelector(".media-modal-views");
  const ctasEl = dialog.querySelector(".media-modal-ctas");
  const closeBtn = dialog.querySelector(".media-modal-close");
  
  let triggerElement = null;
  let currentTargetId = null;

  function showDialog() {
    if (typeof dialog.showModal === "function") {
      dialog.showModal();
      return;
    }

    dialog.setAttribute("open", "");
  }

  function hideDialog() {
    if (typeof dialog.close === "function") {
      dialog.close();
      return;
    }

    dialog.removeAttribute("open");
  }

  // Extract video ID from YouTube URL
  function extractYoutubeId(url) {
    try {
      const u = new URL(url);
      // Handle youtube.com/watch?v=ID
      if (u.hostname.includes("youtube.com") && u.searchParams.has("v")) {
        return u.searchParams.get("v");
      }
      // Handle youtu.be/ID
      if (u.hostname.includes("youtu.be")) {
        return u.pathname.slice(1).split("/")[0];
      }
    } catch (e) {}
    return null;
  }

  // Extract Spotify episode ID from URL
  function extractSpotifyEpisodeId(input) {
    try {
      const u = new URL(String(input));
      if (!u.hostname.includes("spotify.com")) return null;
      const match = u.pathname.match(/\/episode\/([^/?]+)/);
      return match ? match[1] : null;
    } catch (e) {}
    return null;
  }

  function extractSpotifyEpisodeIdFromGuid(guid) {
    const s = String(guid || "").trim();
    if (!s) return null;

    // spotify:episode:EPISODE_ID
    if (s.startsWith("spotify:episode:")) {
      const parts = s.split(":");
      return parts.length >= 3 ? parts[2] : null;
    }

    // URL form
    const fromUrl = extractSpotifyEpisodeId(s);
    if (fromUrl) return fromUrl;

    return null;
  }

  function getEmbed(source, itemUrl, itemId) {
    if (source === "youtube") {
      const videoId = extractYoutubeId(itemUrl);
      if (!videoId) return null;
      return {
        kind: "youtube",
        src: `https://www.youtube.com/embed/${videoId}?rel=0&modestbranding=1`,
      };
    }

    if (source === "podcast") {
      const episodeId =
        extractSpotifyEpisodeId(itemUrl) ||
        extractSpotifyEpisodeIdFromGuid(itemId) ||
        extractSpotifyEpisodeId(itemId);
      if (!episodeId) return null;
      return {
        kind: "spotify",
        src: `https://open.spotify.com/embed/episode/${episodeId}`,
        height: 232,
      };
    }

    return null;
  }

  // Add UTM parameters to URL
  function withUtm(url, utmParams) {
    const u = new URL(url);
    for (const [key, value] of Object.entries(utmParams)) {
      if (value) u.searchParams.set(key, value);
    }
    return u.toString();
  }

  function withYoutubeSubscribePrompt(url) {
    try {
      const u = new URL(url);
      u.searchParams.set("sub_confirmation", "1");
      return u.toString();
    } catch {
      return url;
    }
  }

  // Stop playback by blanking the iframe
  function stopPlayback() {
    iframe.src = "about:blank";
    embedPlaceholder.style.display = "block";
    embedContainer.dataset.embedKind = "";
    iframe.style.display = "";
    embedFallbackWrap.textContent = "";
    embedFallbackWrap.hidden = true;
    audio.pause();
    audio.removeAttribute("src");
    audio.style.display = "none";
    thumbEl.removeAttribute("src");
    thumbEl.style.display = "none";
    kickerEl.textContent = "";
    iframe.removeAttribute("allow");
    iframe.removeAttribute("height");

    ctasEl.textContent = "";
  }

  // Close modal
  function closeModal(method) {
    if (!dialog.open) return;
    
    stopPlayback();
    hideDialog();

    // Emit media_preview_close event if Umami is available
    if (typeof window.umami !== "undefined" && currentTargetId) {
      window.umami.track("media_preview_close", {
        target_id: currentTargetId,
        close_method: method || "unknown"
      });
    }

    // Restore focus to trigger element
    if (triggerElement) {
      triggerElement.focus();
      triggerElement = null;
    }

    currentTargetId = null;
  }

  // Open and populate modal
  function openModal(cardEl) {
    // Store trigger for focus return
    triggerElement = cardEl;

    // Read data attributes
    const itemId = cardEl.dataset.itemId;
    const source = cardEl.dataset.itemSource;
    const url = cardEl.dataset.itemUrl;
    const audioUrl = cardEl.dataset.itemAudioUrl;
    const title = cardEl.dataset.itemTitle;
    const summary = cardEl.dataset.itemSummary;
    const publishedAt = cardEl.dataset.itemPublishedAt;
    const thumbnailUrl = cardEl.dataset.itemThumbnailUrl;
    const views = cardEl.dataset.itemViews;

    // Store target ID for close tracking
    currentTargetId = cardEl.dataset.umamiEventTargetId;

    kickerEl.textContent = source === "podcast" ? "Podcast" : source === "youtube" ? "Video" : "";
    if (source === "podcast" && thumbnailUrl) {
      thumbEl.src = thumbnailUrl;
      thumbEl.style.display = "block";
    } else {
      thumbEl.removeAttribute("src");
      thumbEl.style.display = "none";
    }

    // Populate title
    titleEl.textContent = title || "";

    // Populate description
    descriptionEl.textContent = summary || "";

    // Populate date
    if (publishedAt) {
      const d = new Date(publishedAt);
      const formatted = Number.isFinite(d.valueOf())
        ? d.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" })
        : "";
      dateEl.textContent = formatted;
      dateEl.style.display = formatted ? "" : "none";
    } else {
      dateEl.style.display = "none";
    }

    // Populate views
    if (views && views !== "") {
      const viewsNum = parseInt(views, 10);
      viewsEl.textContent = `${viewsNum.toLocaleString()} views`;
      viewsEl.style.display = "";
    } else {
      viewsEl.style.display = "none";
    }

    // Construct embed
    const embed = getEmbed(source, url, itemId);
    if (embed) {
      embedContainer.dataset.embedKind = embed.kind;
      embedPlaceholder.style.display = "block";
      embedFallbackWrap.textContent = "";
      embedFallbackWrap.hidden = true;
      iframe.style.display = "";

      if (embed.kind === "spotify") {
        iframe.setAttribute(
          "allow",
          "autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture",
        );
        if (embed.height) iframe.setAttribute("height", String(embed.height));
      } else {
        iframe.setAttribute(
          "allow",
          "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",
        );
        iframe.removeAttribute("height");
      }

      iframe.src = embed.src;
      iframe.addEventListener("load", function onLoad() {
        embedPlaceholder.style.display = "none";
        iframe.removeEventListener("load", onLoad);
      });
      embedContainer.style.display = "block";
    } else {
      // No embed available
      if (source === "podcast") {
        embedContainer.style.display = "block";
        iframe.src = "about:blank";
        iframe.style.display = "none";

        if (audioUrl) {
          embedContainer.dataset.embedKind = "audio";
          embedPlaceholder.style.display = "none";
          embedFallbackWrap.textContent = "";
          embedFallbackWrap.hidden = true;
          audio.style.display = "block";
          audio.src = audioUrl;
        } else {
          embedContainer.dataset.embedKind = "fallback";
          embedPlaceholder.style.display = "flex";
          embedFallbackWrap.textContent = "";
          embedFallbackWrap.hidden = false;
          const fallbackLink = document.createElement("a");
          fallbackLink.className = "media-modal-embed-fallback";
          fallbackLink.target = "_blank";
          fallbackLink.rel = "noopener noreferrer";
          fallbackLink.href = url;
          fallbackLink.textContent = "Listen on Spotify";
          embedFallbackWrap.appendChild(fallbackLink);
          audio.style.display = "none";
        }
      } else {
        embedContainer.style.display = "none";
      }
    }

    const platform = source === "youtube" ? "youtube" : "spotify";
    const channelUrl = source === "youtube" ? youtubeChannelUrl : podcastUrl;

    const followAction = source === "youtube" ? "subscribe" : "follow";
    const viewAction = source === "youtube" ? "view" : "listen";

    const followLabel = source === "youtube" ? "Subscribe on YouTube" : "Follow on Spotify";
    const viewLabel = source === "youtube" ? "View on YouTube" : "Listen on Spotify";

    const followBaseUrl = source === "youtube" ? withYoutubeSubscribePrompt(channelUrl) : channelUrl;

    const followUrl = withUtm(followBaseUrl, {
      utm_source: "website",
      utm_medium: "cta",
      utm_campaign: "social-acquisition",
      utm_content: `${platform}:media_modal`,
    });
    ctasEl.textContent = "";

    const followLink = document.createElement("a");
    followLink.className = "cta primary media-modal-cta-follow";
    followLink.target = "_blank";
    followLink.rel = "me noopener noreferrer";
    followLink.href = followUrl;
    followLink.textContent = followLabel;
    followLink.setAttribute("data-umami-event", "cta_click");
    followLink.setAttribute("data-umami-event-target_id", `modal.cta.${followAction}.${platform}`);
    followLink.setAttribute("data-umami-event-placement", "media_modal");
    followLink.setAttribute("data-umami-event-platform", platform);
    followLink.setAttribute("data-umami-event-target_url", channelUrl);
    ctasEl.appendChild(followLink);

    const viewUrl = withUtm(url, {
      utm_source: "website",
      utm_medium: "cta",
      utm_campaign: "social-acquisition",
      utm_content: `${platform}:media_modal`,
    });
    const viewLink = document.createElement("a");
    viewLink.className = "cta media-modal-cta-view";
    viewLink.target = "_blank";
    viewLink.rel = "me noopener noreferrer";
    viewLink.href = viewUrl;
    viewLink.textContent = viewLabel;
    viewLink.setAttribute("data-umami-event", "cta_click");
    viewLink.setAttribute("data-umami-event-target_id", `modal.cta.${viewAction}.${platform}`);
    viewLink.setAttribute("data-umami-event-placement", "media_modal");
    viewLink.setAttribute("data-umami-event-platform", platform);
    viewLink.setAttribute("data-umami-event-target_url", url);
    ctasEl.appendChild(viewLink);

    // Open the dialog
    showDialog();
  }

  // Listen for clicks on modal-trigger cards
  document.addEventListener("click", function(e) {
    const target = e.target instanceof Element ? e.target : null;
    if (!target) return;

    const card = target.closest("button.card[data-item-id]");
    if (card) {
      e.preventDefault();
      openModal(card);
    }
  });

  // Close button
  closeBtn.addEventListener("click", function() {
    closeModal("button");
  });

  // Backdrop click
  dialog.addEventListener("click", function(e) {
    if (e.target === dialog) {
      closeModal("backdrop");
    }
  });

  // Escape key (native dialog handles the close, we hook into the close event)
  dialog.addEventListener("close", function() {
    // If dialog was closed but we didn't call closeModal explicitly (i.e., Escape key)
    if (dialog.open === false && currentTargetId) {
      stopPlayback();
      if (typeof window.umami !== "undefined") {
        window.umami.track("media_preview_close", {
          target_id: currentTargetId,
          close_method: "escape"
        });
      }
      if (triggerElement) {
        triggerElement.focus();
        triggerElement = null;
      }
      currentTargetId = null;
    }
  });
})();
</script>
