﻿import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import FreedashCaseStudy from "@/components/work/FreedashCaseStudy";
import { prisma } from "@/lib/db";

export async function generateStaticParams() {
  try {
    const projects = await prisma.project.findMany({ where: { deletedAt: null, status: "PUBLISHED" }, select: { slug: true } });
    return projects.map(p => ({ slug: p.slug }));
  } catch { return []; }
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const p = await prisma.project.findUnique({ where: { slug } }).catch(()=>null);
  if (!p || p.deletedAt) return { title: "Not found" };
  if (p.slug === "freedash") return { title: "FreeDash â€” Ravneet Brar", description: "FreeDash is a free game server and Discord bot hosting platform built as part of the Zyphron Cloud ecosystem.", alternates: { canonical: "/work/freedash" }, openGraph: { title: "FreeDash â€” Ravneet Brar", description: "FreeDash is a free game server and Discord bot hosting platform built as part of the Zyphron Cloud ecosystem.", url: "https://ravneetbrar.in/work/freedash" } };
  return { title: `${p.title} â€” Ravneet Brar`, description: p.description };
}

export default async function ProjectPage({ params, searchParams }: { params: Promise<{ slug: string }>, searchParams?: Promise<{ preview?: string }> }) {
  const { slug } = await params;
  const preview = (await searchParams)?.preview;
  const p = await prisma.project.findUnique({ where: { slug } }).catch(()=>null);
  if (!p || p.deletedAt) notFound();
  // Draft preview: only allow if preview token present and matches env secret (simplified: allow preview if ?preview=1 and status is DRAFT and user has session? For now, require preview param to show drafts)
  if (p.status !== "PUBLISHED" && preview !== "1") {
    // Check if not published, show 404 unless preview
    // In production, verify signed token; here we just hide drafts
    notFound();
  }
  const tech = p.technologies ? JSON.parse(p.technologies) as string[] : [];
  // For next project
  const all = await prisma.project.findMany({ where: { deletedAt: null, status: "PUBLISHED" }, orderBy: { createdAt: "asc" }, select: { slug: true, title: true } });
  const idx = all.findIndex(x => x.slug === slug);
  const next = all[(idx + 1) % all.length] || all[0];

  const accent = (p as any).accent || "from-blue-600/20 via-cyan-500/10 to-transparent";
  const longDesc = (p as any).longDescription || p.description;
  const problem = (p as any).problem || "Problem details in CMS.";
  const solution = (p as any).solution || "Solution details in CMS.";
  const challenges = (p as any).challenges || "Challenges in CMS.";
  const lessons = (p as any).lessons || "Lessons in CMS.";

  return (
    <div className="pt-24 bg-[#07080c]">
      <div className="max-w-[900px] mx-auto px-6 sm:px-8 py-12">
        <Link href="/work" className="text-[12px] tracking-widest text-white/30 hover:text-white uppercase">â† Back to work</Link>
        <p className="mt-6 text-[11px] tracking-[0.15em] font-semibold text-blue-300">{p.category} â€¢ {p.year}</p>
        <h1 className="mt-2 text-[36px] sm:text-[48px] font-[800] tracking-[-0.04em] text-white">{p.title}</h1>
        <p className="mt-3 text-[16px] leading-relaxed text-white/60">{longDesc}</p>
        <div className="mt-4 flex flex-wrap gap-2">{tech.map((t:string) => <span key={t} className="px-3 py-1.5 rounded-full bg-white text-black text-[12px] font-medium">{t}</span>)}</div>

        <div className={`mt-8 h-64 rounded-[24px] bg-gradient-to-br ${accent} border border-white/10 grid place-items-center`}>
          <span className="text-white/30 text-[12px] tracking-widest uppercase">Project visual â€¢ {p.title}</span>
        </div>

        <div className="mt-10 grid sm:grid-cols-2 gap-6">
          <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-6"><h3 className="font-semibold text-white">Problem</h3><p className="text-[14px] text-white/60 mt-2 leading-relaxed">{problem}</p></div>
          <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-6"><h3 className="font-semibold text-white">Solution</h3><p className="text-[14px] text-white/60 mt-2 leading-relaxed">{solution}</p></div>
          <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-6"><h3 className="font-semibold text-white">Challenges</h3><p className="text-[14px] text-white/60 mt-2 leading-relaxed">{challenges}</p></div>
          <div className="rounded-2xl border border-blue-500/20 bg-blue-500/10 p-6"><h3 className="font-semibold text-white">Lessons</h3><p className="text-[14px] text-white/70 mt-2 leading-relaxed">{lessons}</p></div>
        </div>

        <div className="mt-10 rounded-2xl border border-white/10 bg-white/[0.04] p-6">
          <p className="text-[12px] tracking-widest text-white/30 uppercase">Architecture</p>
          <div className="mt-3 space-y-2 text-[13px] text-white/60">
            <p>Users â†’ Web/Billing â†’ Application â†’ API â†’ Infrastructure â†’ Nodes â†’ Services</p>
            <div className="flex gap-2 mt-3"><span className="h-1 flex-1 bg-blue-500 rounded-full" /><span className="h-1 flex-1 bg-cyan-400 rounded-full" /><span className="h-1 flex-1 bg-violet-400 rounded-full" /></div>
          </div>
        </div>

        {p.slug === "freedash" && (
          <div className="mt-8 flex flex-wrap gap-3">
            <a href={p.liveUrl || "https://freedash.zyphron.cloud/"} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 bg-white text-black px-5 py-2.5 rounded-full font-semibold text-sm">Visit FreeDash <span aria-hidden>â†—</span></a>
            <Link href="/work" className="inline-flex items-center gap-2 border border-white/15 text-white px-5 py-2.5 rounded-full font-semibold text-sm">Back to Work â†’</Link>
          </div>
        )}

        {p.slug === "freedash" && <FreedashCaseStudy />}

        {p.liveUrl && p.slug !== "freedash" && (
          <div className="mt-8">
            <a href={p.liveUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 bg-[#2563eb] text-white px-5 py-2.5 rounded-full font-semibold text-sm">LIVE WEBSITE â†—</a>
          </div>
        )}

        <div className="mt-10 flex justify-between items-center border-t border-white/10 pt-6">
          <span className="text-white/30 text-sm">Development Process: Research â†’ Design â†’ Development â†’ Deployment â†’ Iteration</span>
          {next && <Link href={`/work/${next.slug}`} className="px-4 py-2 rounded-full bg-white text-black text-sm font-semibold">Next: {next.title} â†’</Link>}
        </div>
      </div>
    </div>
  );
}
