import type { Metadata } from "next";
import Link from "next/link";
import Header from "@/components/Header";
import Footer from "@/components/Footer";

export const metadata: Metadata = {
  title: "From the Vault — On-Camera Archive · AV Beat",
  description:
    "Highlights from a decade of AV Beat on-camera coverage — booth walkthroughs, product demos, and exec interviews from NAB Show, IBC, SVG, and the trade circuit (2014–2021). Today our coverage runs through written reporting; this page is a permanent archive of the video era.",
  alternates: { canonical: "/video-archive" },
  openGraph: {
    title: "From the Vault — On-Camera Archive · AV Beat",
    description:
      "A decade of on-camera coverage from the NAB Show floor, IBC, SVG, and beyond — archived, not deprecated.",
    type: "website",
    url: "https://avbeat.com/video-archive",
  },
};

// Server-side fetch with revalidation so we don't hammer YouTube and the page
// stays static-fast. RSS only returns ~15 latest videos but that's fine for
// an archive landing — "See full library" link takes them to YouTube.
export const revalidate = 21600;  // 6 hours

type Video = {
  videoId: string;
  title: string;
  description: string;
  publishedYear: number;
  thumbnail: string;
};

async function fetchArchive(): Promise<Video[]> {
  try {
    const r = await fetch(
      "https://www.youtube.com/feeds/videos.xml?channel_id=UC_eyQjdiEtNjNE67KDWzQug",
      { next: { revalidate: 21600 }, headers: { "User-Agent": "Mozilla/5.0 avbeat.com archive" } },
    );
    if (!r.ok) return [];
    const xml = await r.text();
    // Lightweight XML parsing — every <entry>…</entry> block is one video.
    const entries = xml.split("<entry>").slice(1);
    return entries.map((block) => {
      const get = (re: RegExp) => (block.match(re)?.[1] ?? "").trim();
      const videoId = get(/<yt:videoId>([^<]+)<\/yt:videoId>/);
      const title = get(/<title>([^<]+)<\/title>/);
      const description = get(/<media:description>([\s\S]*?)<\/media:description>/);
      const published = get(/<published>([^<]+)<\/published>/);
      const publishedYear = published ? new Date(published).getFullYear() : 2018;
      return {
        videoId,
        title,
        description: description.slice(0, 200),
        publishedYear,
        thumbnail: `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`,
      };
    }).filter(v => v.videoId);
  } catch {
    return [];
  }
}

export default async function VideoArchive() {
  const videos = await fetchArchive();

  return (
    <>
      <Header />
      <main className="bg-[var(--color-bg,#0a0a0c)] text-[var(--color-text,#e7e7ea)] min-h-screen">
        {/* Archive intro — frames the section explicitly as historical so users
            don't read "old videos" as "stale publication". */}
        <section className="border-b border-white/8 bg-gradient-to-b from-[#11111a] to-transparent">
          <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <div className="inline-flex items-center gap-2 bg-amber-500/10 border border-amber-500/30 text-amber-300 text-[10px] font-bold uppercase tracking-[0.2em] px-3 py-1 rounded mb-5">
              <span className="w-1.5 h-1.5 rounded-full bg-amber-400" /> From the Vault · 2014 – 2021
            </div>
            <h1 className="text-3xl md:text-5xl font-black text-white tracking-tight mb-4" style={{ fontFamily: "'Barlow Condensed', sans-serif", letterSpacing: '-0.01em' }}>
              ON-CAMERA ARCHIVE
            </h1>
            <p className="text-white/65 text-base md:text-lg leading-relaxed max-w-3xl">
              For seven years our team carried cameras through NAB Show, IBC, SVG, and dozens of regional production gatherings,
              capturing booth walkthroughs, product unveils, and exec interviews on the show floor. Today our coverage is
              all written reporting — but the video archive lives on, preserved as a record of an industry that moves
              faster than memory.
            </p>
            <p className="text-white/40 text-sm mt-4">
              These clips are kept for reference. We&apos;re not producing new video at this time.
            </p>
          </div>
        </section>

        {/* Video grid */}
        <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
          {videos.length === 0 ? (
            <div className="bg-[#111118] border border-white/8 rounded-xl p-12 text-center">
              <p className="text-white/40 text-sm">Archive feed is temporarily unavailable. Browse the full library directly on{" "}
                <a href="https://youtube.com/@avbeat" target="_blank" rel="noopener noreferrer" className="text-[var(--color-text-info,#60a5fa)] hover:underline">YouTube</a>.
              </p>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-[11px] uppercase tracking-[0.2em] text-white/40 font-bold">Selected clips</h2>
                <a
                  href="https://youtube.com/@avbeat"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs text-white/50 hover:text-white transition uppercase tracking-wider"
                >
                  See full library on YouTube →
                </a>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                {videos.map((v) => (
                  <a
                    key={v.videoId}
                    href={`https://www.youtube.com/watch?v=${v.videoId}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="group bg-[#111118] border border-white/8 rounded-lg overflow-hidden hover:border-white/25 transition-all"
                  >
                    <div className="aspect-video bg-black relative overflow-hidden">
                      <img
                        src={v.thumbnail}
                        alt={v.title}
                        loading="lazy"
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 opacity-90 group-hover:opacity-100"
                      />
                      {/* Subtle aged-archive tint so the thumbnail signals "vault" */}
                      <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent pointer-events-none" />
                      {/* Play badge */}
                      <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                        <div className="w-14 h-14 rounded-full bg-black/60 border border-white/30 flex items-center justify-center group-hover:bg-[var(--color-brand,#cc0000)]/80 transition">
                          <svg className="w-5 h-5 text-white ml-0.5" fill="currentColor" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
                        </div>
                      </div>
                    </div>
                    <div className="p-4">
                      <h3 className="text-white font-semibold text-sm leading-snug line-clamp-2 group-hover:text-[var(--color-text-info,#60a5fa)] transition">
                        {v.title}
                      </h3>
                      <p className="text-white/35 text-xs mt-2 uppercase tracking-wider">From the BB vault</p>
                    </div>
                  </a>
                ))}
              </div>
            </>
          )}
        </section>

        {/* Why no recent videos — meta-explanation that turns "old" into "deliberate choice" */}
        <section className="border-t border-white/8 bg-[#0d0d14]">
          <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <h2 className="text-white font-bold text-xl mb-3" style={{ fontFamily: "'Barlow Condensed', sans-serif" }}>
              Why we stopped shooting video
            </h2>
            <p className="text-white/55 text-sm leading-relaxed mb-3">
              The video era — bullpens of camera crews on the NAB floor, B-roll runs through manufacturer booths,
              same-day edits uploaded from press rooms — produced thousands of hours of footage. It also produced a
              very specific kind of coverage: surface-level, sponsor-friendly, optimized for trade-show buzz.
            </p>
            <p className="text-white/55 text-sm leading-relaxed mb-3">
              We made the call to step away from on-camera coverage and rebuild AV Beat as a written publication —
              deeper reporting, more original analysis, fewer canned booth tours. Most of our peers in the trade press
              are doing the opposite. We think the readers (and the industry) are better served this way.
            </p>
            <p className="text-white/55 text-sm leading-relaxed">
              The vault stays online so the work isn&apos;t lost. If you&apos;re looking for what&apos;s next from BB,
              head to the{" "}
              <Link href="/" className="text-[var(--color-text-info,#60a5fa)] hover:underline">homepage</Link>{" "}
              or subscribe to the{" "}
              <Link href="/newsletter" className="text-[var(--color-text-info,#60a5fa)] hover:underline">daily newsletter</Link>.
            </p>
          </div>
        </section>
      </main>
      <Footer />
    </>
  );
}
