"use client";

import { useEffect, useState } from "react";
import { isYouTubeUploadLimitError } from "@/lib/youtube/errors";
import { YouTubeLimitBanner } from "./YouTubeLimitBanner";

/** Shows a dashboard alert when a recent job hit YouTube's upload limit. */
export function RecentYouTubeLimitAlert() {
  const [show, setShow] = useState(false);

  useEffect(() => {
    let active = true;

    fetch("/api/jobs?limit=10")
      .then(async (res) => {
        if (!res.ok) return;
        const data = await res.json();
        const hit = (data.jobs ?? []).some((job: { items?: Array<{ status: string; error?: string | null }> }) =>
          (job.items ?? []).some(
            (item) => item.status === "FAILED" && item.error && isYouTubeUploadLimitError(item.error),
          ),
        );
        if (active) setShow(hit);
      })
      .catch(() => {});

    return () => {
      active = false;
    };
  }, []);

  if (!show) return null;
  return <YouTubeLimitBanner className="mb-6" />;
}
