"use client";

import { useCallback, useEffect, useState } from "react";
import Nav from "@/components/Nav";
import Hero from "@/components/Hero";
import Work from "@/components/Work";
import InstagramFeed from "@/components/InstagramFeed";
import Slideshow from "@/components/Slideshow";
import { About, Contact, Footer, KonnexShop, Recognition } from "@/components/Sections";
import type { Award, Client, Exhibition, Project } from "@/lib/data";

export default function SinglePage({
  projects,
  awards,
  exhibitions,
  clients,
}: {
  projects: Project[];
  awards: Award[];
  exhibitions: Exhibition[];
  clients: Client[];
}) {
  const [openSlug, setOpenSlug] = useState<string | null>(null);

  const openProject = useCallback((slug: string) => {
    setOpenSlug(slug);
    try {
      window.history.replaceState(null, "", `#project-${slug}`);
    } catch {
      /* sandboxed iframes may disallow history changes */
    }
  }, []);

  const close = useCallback(() => {
    setOpenSlug(null);
    try {
      window.history.replaceState(null, "", window.location.pathname);
    } catch {
      /* ignore */
    }
  }, []);

  const shift = useCallback(
    (slug: string, delta: number) => {
      const i = projects.findIndex((p) => p.slug === slug);
      if (i === -1) return;
      const next = projects[(i + delta + projects.length) % projects.length];
      setOpenSlug(next.slug);
      try {
        window.history.replaceState(null, "", `#project-${next.slug}`);
      } catch {
        /* ignore */
      }
    },
    [projects],
  );

  // Support deep links like /#project-konnex
  useEffect(() => {
    const fromHash = () => {
      const hash = window.location.hash;
      const match = /^#project-(.+)$/.exec(hash);
      if (match && projects.some((p) => p.slug === match[1])) {
        setOpenSlug(match[1]);
        return true;
      }
      return false;
    };
    fromHash();
    const onHashChange = () => fromHash();
    window.addEventListener("hashchange", onHashChange);
    return () => window.removeEventListener("hashchange", onHashChange);
  }, [projects]);

  const openProjectRecord = openSlug
    ? (projects.find((p) => p.slug === openSlug) ?? null)
    : null;
  const konnex = projects.find((p) => p.slug === "konnex");

  return (
    <>
      <Nav onNavigate={close} />
      <main>
        <Hero projects={projects} />
        <Work projects={projects} onOpen={openProject} />
        <KonnexShop project={konnex} />
        <About />
        <Recognition awards={awards} exhibitions={exhibitions} clients={clients} />
        <InstagramFeed />
        <Contact />
      </main>
      <Footer />
      <Slideshow
        key={openProjectRecord?.slug ?? "closed"}
        project={openProjectRecord}
        onClose={close}
        onPrevProject={(slug) => shift(slug, -1)}
        onNextProject={(slug) => shift(slug, 1)}
      />
    </>
  );
}
