"use client";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";
import VideoCard from "@/components/VideoCard";

// Shared fetch, cached at module level so the three separate section
// components (which get interleaved at different points in the feed) don't
// each independently re-fetch the same video lists.
let cachedVideos: { topChoices: any[]; latest: any[] } | null = null;
let fetchPromise: Promise<{ topChoices: any[]; latest: any[] }> | null = null;

function getVideos() {
  if (cachedVideos) return Promise.resolve(cachedVideos);
  if (!fetchPromise) {
    fetchPromise = fetch("/api/community-videos")
      .then((r) => r.json())
      .then((d) => {
        cachedVideos = { topChoices: d.topChoices || [], latest: d.latest || [] };
        return cachedVideos;
      })
      .catch(() => ({ topChoices: [], latest: [] }));
  }
  return fetchPromise;
}

function VideoRow({ videos }: { videos: any[] }) {
  return (
    <div className="flex gap-3 overflow-x-auto no-scrollbar pb-2 min-w-0">
      {videos.map((v) => (
        <div key={v.id} className="shrink-0" style={{ width: "160px" }}>
          <VideoCard video={v} />
        </div>
      ))}
    </div>
  );
}

export function TopChoicesSection() {
  const [videos, setVideos] = useState<any[]>([]);
  useEffect(() => {
    getVideos().then((d) => setVideos(d.topChoices));
  }, []);
  if (videos.length === 0) return null;
  return (
    <div className="min-w-0 w-full my-6">
      <h3 className="font-bold mb-3">🏆 Top Choices</h3>
      <VideoRow videos={videos} />
    </div>
  );
}

export function LatestVideosSection() {
  const [videos, setVideos] = useState<any[]>([]);
  useEffect(() => {
    getVideos().then((d) => setVideos(d.latest));
  }, []);
  if (videos.length === 0) return null;
  return (
    <div className="min-w-0 w-full my-6">
      <h3 className="font-bold mb-3">🆕 Latest Videos</h3>
      <VideoRow videos={videos} />
    </div>
  );
}

export function MembershipUpsellSection() {
  const { data: session } = useSession();
  const tier = (session?.user as any)?.tier;
  const isPaidMember = tier && tier !== "free";

  if (isPaidMember) return null;

  return (
    <div className="card p-5 text-center bg-gradient-to-br from-red-950/40 to-transparent border-red-900/40 my-6">
      <p className="font-semibold mb-1">Enjoying the community?</p>
      <p className="text-sm text-neutral-400 mb-4">Become a member to unlock exclusive devotionals and support this community.</p>
      <Link href="/subscription/plans" className="btn-primary inline-block px-6 py-2.5 text-sm">
        View Membership Plans →
      </Link>
    </div>
  );
}
