"use client";

import { useEffect, useState } from "react";
import { GuideCard } from "./guide-card";
import {
  emptyWebsiteGuidesPagination,
  fetchWebsiteGuides,
} from "@/lib/website-guides";
import type { Guide } from "@/lib/types";

export function FeaturedGuides() {
  const [guides, setGuides] = useState<Guide[]>([]);
  const [isLoading, setIsLoading] = useState(true);

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

    async function loadGuides() {
      try {
        const result = await fetchWebsiteGuides({
          page: 1,
          per_page: 4,
          is_trusted: "yes",
        });

        if (isMounted) {
          setGuides(result.data.slice(0, 4));
        }
      } catch {
        if (isMounted) {
          setGuides(emptyWebsiteGuidesPagination.data);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    loadGuides();

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

  if (isLoading) {
    return (
      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
        {[...Array(4)].map((_, index) => (
          <div
            key={index}
            className="h-[360px] animate-pulse rounded-lg bg-muted"
          />
        ))}
      </div>
    );
  }

  if (guides.length === 0) {
    return (
      <div className="rounded-2xl border border-border/50 bg-white py-12 text-center shadow-sm">
        <p className="text-sm font-medium text-muted-foreground">
          No featured guides available right now.
        </p>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
      {guides.map((guide) => (
        <GuideCard key={guide.id} guide={guide} />
      ))}
    </div>
  );
}
