"use client";

import React, { useState, useEffect } from "react";
import Image from "next/image";

const Certifications = () => {
  const [certifications, setCertifications] = useState(null);

  useEffect(() => {
    const fetchCertifications = async () => {
      try {
        const response = await fetch("/assets/data/data.json");
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        setCertifications(data.certifications || []);
      } catch (error) {
        console.error("Failed to fetch certifications data:", error);
      }
    };

    fetchCertifications();
  }, []);

  if (!certifications) {
    return (
      <div className="flex justify-center items-center h-64 bg-gray-50">
        <p className="text-xl font-medium text-gray-700">
          Loading Certifications...
        </p>
      </div>
    );
  }

  return (
    <section
      id="certificationsScroll"
      className="w-full flex flex-col items-center justify-center py-20 px-4 md:px-8 bg-gray-50 rounded-lg shadow-inner"
    >
      <h3 className="text-2xl font-poppins text-blue-500 mb-12 font-extrabold">
        Certifications
      </h3>

      <div className="w-full max-w-6xl grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
        {certifications.map((cert) => (
          <a
            key={cert.name}
            href={cert.link}
            target="_blank"
            rel="noopener noreferrer"
            title={cert.name}
            className="flex flex-col bg-white rounded-xl border border-gray-100 shadow-md overflow-hidden transition-transform duration-300 hover:scale-105 hover:shadow-xl"
          >
            <div className="relative w-full aspect-[4/3] bg-gray-50">
              <Image
                src={cert.img}
                alt={`${cert.name} certificate`}
                fill
                className="object-contain p-2"
                sizes="(max-width: 640px) 100vw, (max-width: 1280px) 50vw, 20vw"
                unoptimized
              />
            </div>
            <div className="flex flex-col items-start p-4 gap-1">
              <p className="text-sm font-semibold text-gray-800 font-poppins leading-snug">
                {cert.name}
              </p>
              <p className="text-xs text-gray-500 font-poppins">
                {cert.issuer}
              </p>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
};

export default Certifications;
