"use client";

import { useEffect, useRef, useState } from "react";

import { BIOMASS_PROJECTS, SOLAR_PROJECTS, type Project } from "@/lib/projects";

import ProjectCard from "@/components/ProjectCard";
import ProjectModal from "@/components/ProjectModal";

type TabId = "solar" | "biomass";

const TABS: { id: TabId; label: string; count: number }[] = [
  { id: "solar", label: "Solar Energy", count: SOLAR_PROJECTS.length },
  { id: "biomass", label: "Biomass Energy", count: BIOMASS_PROJECTS.length },
];

export default function ProjectsSection() {
  const [tab, setTab] = useState<TabId>("solar");
  const [selected, setSelected] = useState<Project | null>(null);
  const lastTrigger = useRef<HTMLElement | null>(null);

  const handleOpen = (project: Project, trigger?: HTMLElement) => {
    lastTrigger.current = trigger ?? null;
    setSelected(project);
  };

  const handleClose = () => {
    setSelected(null);
    // Restore focus to the card that opened the modal.
    lastTrigger.current?.focus();
  };

  // Support /projects#solar and /projects#biomass deep links.
  useEffect(() => {
    const hash = window.location.hash.replace("#", "");
    if (hash === "solar" || hash === "biomass")
      // eslint-disable-next-line react-hooks/set-state-in-effect -- one-time init from URL
      setTab(hash);
  }, []);

  const projects = tab === "solar" ? SOLAR_PROJECTS : BIOMASS_PROJECTS;

  return (
    <>
      <div
        role="tablist"
        aria-label="Project categories"
        className="mb-10 flex w-full max-w-md flex-col gap-2 rounded-card border border-line bg-surface p-1.5 sm:flex-row"
      >
        {TABS.map((t) => {
          const active = tab === t.id;
          return (
            <button
              key={t.id}
              type="button"
              role="tab"
              aria-selected={active}
              id={`tab-${t.id}`}
              aria-controls={t.id}
              onClick={() => setTab(t.id)}
              className={`flex flex-1 items-center justify-center gap-2 rounded-xl px-4 py-3 text-sm font-semibold transition-colors ${
                active
                  ? "bg-accent text-white"
                  : "text-ink-soft hover:bg-sky hover:text-ink"
              }`}
            >
              {t.label}
              <span
                className={`rounded-full px-2 py-0.5 text-[11px] font-bold ${
                  active ? "bg-accent-deep text-white" : "bg-sky text-accent-deep"
                }`}
              >
                {t.count}
              </span>
            </button>
          );
        })}
      </div>

      {/* id matches the tab slug so /projects#solar and #biomass deep links anchor here */}
      <div
        id={tab}
        role="tabpanel"
        aria-labelledby={`tab-${tab}`}
        className="grid scroll-mt-24 gap-6 sm:grid-cols-2 lg:grid-cols-3"
      >
        {projects.map((project) => (
          <ProjectCard key={project.id} project={project} onOpen={handleOpen} />
        ))}
      </div>

      <ProjectModal project={selected} onClose={handleClose} />
    </>
  );
}
