// app/Projects/[id]/page.tsx
"use client";

import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import Link from "next/link";

interface Project {
  id: string;
  title: string;
  description: string;
  link: string;
}

export default function ProjectDetail() {
  const params = useParams();
  const { id } = params as { id: string };
  const [project, setProject] = useState<Project | null>(null);

  useEffect(() => {
    if (id) {
      fetch("/data/projects.json")
        .then((res) => res.json())
        .then((data: Project[]) => {
          const found = data.find((proj) => proj.id === id);
          setProject(found || null);

          // Log the project view
          fetch("/api/stats", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ type: "project_view", projectId: id }),
          }).catch((err) => console.error("Failed to log project view", err));
        });
    }
  }, [id]);

  if (!project) {
    return <div className="p-10 text-center">Loading...</div>;
  }

  return (
    <div className="p-10 bg-gray-100 dark:bg-gray-800 min-h-screen">
      <h1 className="text-4xl font-bold text-gray-800 dark:text-white">
        {project.title}
      </h1>
      <p className="mt-4 text-gray-600 dark:text-gray-300">
        {project.description}
      </p>
      <Link
        href={project.link}
        className="mt-4 inline-block text-blue-500 hover:underline"
      >
        Visit Project
      </Link>
    </div>
  );
}
