---
import BaseLayout from "../layouts/BaseLayout.astro";
import ContentCard from "../components/ContentCard.astro";
import MediaModal from "../components/MediaModal.astro";
import { readContentCache } from "../lib/content/cache";
import { youtubeVideos } from "../lib/content/selectors";
import { getPublicConfig } from "../lib/config";

const cache = await readContentCache();
const videos = youtubeVideos(cache).sort(
  (a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt),
);

const cfg = getPublicConfig();
const siteUrl = (cfg.siteUrl || "http://localhost:4321").replace(/\/$/, "");
const canonicalUrl = `${siteUrl}/videos`;

const videosJsonLd = {
  "@context": "https://schema.org",
  "@type": "CollectionPage",
  name: "Videos | SanthoshJ",
  url: canonicalUrl,
  mainEntity: {
    "@type": "ItemList",
    itemListElement: videos.slice(0, 20).map((video, index) => ({
      "@type": "ListItem",
      position: index + 1,
      url: `${siteUrl}/videos/${encodeURIComponent(video.id)}`,
      item: {
        "@type": "VideoObject",
        name: video.title,
        uploadDate: video.publishedAt,
      },
    })),
  },
};
---

<BaseLayout
  title="Videos | SanthoshJ"
  description="Latest and featured YouTube videos."
  canonicalPath="/videos"
>
  <script type="application/ld+json" set:html={JSON.stringify(videosJsonLd)} />
  <section class="section">
    <div class="section-header">
      <h2 class="title-hover-line">Videos</h2>
      <span class="muted">{videos.length} items</span>
    </div>
    {
      videos.length > 0 ? (
        <div class="grid">
          {videos.map((item) => (
            <ContentCard item={item} placement="videos.list" />
          ))}
        </div>
      ) : (
        <div class="empty">
          No videos yet. Configure <code>YOUTUBE_CHANNEL_ID</code> and run{" "}
          <code>npm run fetch-content</code>.
        </div>
      )
    }
  </section>
  
  <MediaModal />
</BaseLayout>
