---
import BaseLayout from "../../layouts/BaseLayout.astro";
import { readContentCache } from "../../lib/content/cache";
import { podcastEpisodes } from "../../lib/content/selectors";

export async function getStaticPaths() {
  const cache = await readContentCache();
  const eps = podcastEpisodes(cache);
  return eps.map((e) => ({ params: { id: e.id }, props: { episode: e } }));
}

const { episode } = Astro.props;

const jsonLd = {
  "@context": "https://schema.org",
  "@type": "PodcastEpisode",
  name: episode.title,
  datePublished: episode.publishedAt,
  url: episode.url,
};

let episodeDomain = "";
try {
  episodeDomain = new URL(episode.url).hostname;
} catch {
  episodeDomain = "";
}

function truncate(s: string, n: number) {
  const t = (s || "").trim();
  if (t.length <= n) return t;
  return `${t.slice(0, Math.max(0, n - 1)).trimEnd()}…`;
}
---

<BaseLayout
  title={`${episode.title} | Irregular Mind`}
  description={`Listen: ${episode.title}`}
  canonicalPath={`/podcast/${encodeURIComponent(episode.id)}`}
  ogImageUrl={episode.thumbnailUrl}
>
  <script type="application/ld+json" set:html={JSON.stringify(jsonLd)} />
  <section class="section">
    <div class="section-header">
      <h2>{episode.title}</h2>
      <a
        class="muted"
        href="/podcast"
        data-umami-event="click"
        data-umami-event-target_id="podcast_detail.back_to_podcast"
        data-umami-event-placement="section_header"
        data-umami-event-target_url="/podcast"
      >
        Back to podcast →
      </a>
    </div>
    <div class="empty">
      <p style="margin-top: 0;">
        This page exists for SEO and sharing. Listening happens on your platform.
      </p>
      <p>
        <a
          class="cta primary"
          href={episode.url}
          target="_blank"
          rel="noopener noreferrer"
          data-umami-event="outbound_click"
          data-umami-event-target_id={`podcast_detail.open.${episode.id}`}
          data-umami-event-placement="podcast_detail"
          data-umami-event-target_url={episode.url}
          data-umami-event-title={truncate(episode.title, 160)}
          data-umami-event-type="podcast_episode"
          data-umami-event-domain={episodeDomain || "unknown"}
          data-umami-event-source="podcast"
          data-umami-event-ui_placement="podcast_detail"
        >
          Open episode
        </a>
      </p>
    </div>
  </section>
</BaseLayout>
