﻿import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import ShareButtons from "@/components/ShareButtons";
import { ReadingProgress, CodeBlock, TOC, Lightbox, Callout } from "@/components/blog/ArticleExtras";
import { prisma } from "@/lib/db";

export async function generateStaticParams(){
  try {
    const posts = await prisma.blogPost.findMany({ where: { deletedAt: null, status: "PUBLISHED" }, select: { slug: true } });
    return posts.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.blogPost.findUnique({ where: { slug } }).catch(()=>null);
  if(!p || p.deletedAt) return {title:"Not found"};
  if (p.status !== "PUBLISHED") return { title: "Not found" };
  return {title:`${p.title} â€” Ravneet Brar`, description:p.description, alternates: { canonical: `/blog/${p.slug}` }};
}
function readingTime(content: string) {
  const words = content.trim().split(/\s+/).length;
  const mins = Math.max(1, Math.round(words / 200));
  return `${mins} min`;
}
export default async function PostPage({params, searchParams}:{params:Promise<{slug:string}>, searchParams?: Promise<{ preview?: string }> }){
  const {slug}=await params;
  const preview = (await searchParams)?.preview;
  const p = await prisma.blogPost.findUnique({ where: { slug } }).catch(()=>null);
  if(!p || p.deletedAt) notFound();
  if (p.status !== "PUBLISHED" && preview !== "1") notFound();
  const tags = p.tags ? JSON.parse(p.tags) as string[] : [];
  const reading = readingTime(p.content);
  const date = (p.publishedAt || p.createdAt).toISOString().slice(0,10);
  // prev/next
  const all = await prisma.blogPost.findMany({ where: { deletedAt: null, status: "PUBLISHED" }, orderBy: { publishedAt: "asc" }, select: { slug:true, title:true } });
  const idx = all.findIndex(x=>x.slug===slug);
  const prev = all[idx-1];
  const nxt = all[idx+1];
  const related = all.filter(x=>x.slug!==slug).slice(0,3);
  return (
    <div className="pt-24 bg-[#07080c]">
      <ReadingProgress />
      <TOC items={["Introduction","The Problem","Implementation","Infrastructure","Challenges","Lessons","Conclusion"]} />
      <article className="max-w-[760px] mx-auto px-6 sm:px-8 py-12">
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify({ "@context":"https://schema.org", "@type":"Article", headline: p.title, description: p.description, author: { "@type":"Person", name:"Ravneet Brar" }, datePublished: date, image: `https://ravneetbrar.in/blog/${p.slug}` }) }} />
        <Link href="/blog" className="text-[12px] tracking-widest text-white/30 hover:text-white uppercase">â† Blog</Link>
        <p className="mt-6 text-[11px] tracking-widest text-blue-300 uppercase">{p.category} â€¢ {date} â€¢ {reading} â€¢ By Ravneet Brar</p>
        <h1 className="mt-2 text-[30px] sm:text-[42px] font-[800] tracking-[-0.04em] leading-[0.95] text-white">{p.title}</h1>
        <p className="mt-3 text-white/60">{p.description}</p>
        <div className="mt-4 flex flex-wrap gap-2">{tags.map((t:string)=> <span key={t} className="px-2.5 py-1 rounded-full bg-white/10 border border-white/10 text-[11px] text-white/60">{t}</span>)}</div>
        <Lightbox src={`Hero image â€¢ ${p.title}`} caption="Hero image â€” click to open lightbox (prev/next/zoom via Esc)" />
        <div className="mt-8 prose prose-invert max-w-none">
          <p id="introduction" className="text-[15px] leading-[1.8] text-white/70">{p.content}</p>
          <h2 id="implementation" className="text-white font-bold mt-8">Implementation</h2>
          <CodeBlock code={`const server = await deploy({\n  region: "in",\n  stack: ["linux","docker","pterodactyl"]\n});\nconsole.log("active", server.status);`} lang="TypeScript" />
          <div className="mt-6 rounded-xl bg-black/40 border border-white/10 p-4 font-mono text-[12px] text-white/60">$ systemctl status nginx<br />â— nginx.service â€” Active: active (running)</div>
          <Callout kind="TIP">Useful advice: keep deploys idempotent and observable.</Callout>
          <Callout kind="NOTE">Status: {p.status} â€” only published articles appear in sitemap & RSS.</Callout>
          <Lightbox src="Diagram â€¢ architecture" caption="Zyphron Cloud infrastructure dashboard" />
          <p className="text-[13px] text-white/40 mt-6">Live project embed (if permitted): <a href="https://zyphron.cloud/" target="_blank" rel="noopener noreferrer" className="underline text-blue-400">zyphron.cloud</a> â€” iframe respects CSP.</p>
          <div className="mt-6 rounded-xl border border-white/10 bg-white/[0.03] h-32 grid place-items-center"><span className="text-white/20 text-xs">Live embed preview â€” uses iframe only if allowed</span></div>
        </div>
        <ShareButtons title={p.title} slug={p.slug} />
        <div className="mt-8 rounded-2xl border border-white/10 bg-white/[0.03] p-4 flex justify-between items-center">
          <span className="text-sm text-white">Ravneet Brar</span><span className="text-xs text-white/40">Founder â€¢ Developer â€¢ Builder</span>
          <Link href="/about" className="text-xs font-semibold text-white underline">About Ravneet â†’</Link>
        </div>
        <div className="mt-4 flex gap-2 text-xs">
          <span className="px-2 py-1 rounded-full bg-white/10 border border-white/10 text-white/60">â¤ï¸</span>
          <span className="px-2 py-1 rounded-full bg-white/10 border border-white/10 text-white/60">ðŸ”¥</span>
          <span className="px-2 py-1 rounded-full bg-white/10 border border-white/10 text-white/60">ðŸ’¡</span>
          <span className="px-2 py-1 rounded-full bg-white/10 border border-white/10 text-white/60">ðŸš€</span>
          <span className="text-white/20 ml-2">Reactions â€” no login required</span>
        </div>
        <div className="mt-10 flex justify-between border-t border-white/10 pt-6 text-sm">
          {prev ? <Link href={`/blog/${prev.slug}`} className="text-white/60 hover:text-white">â† PREVIOUS<br />{prev.title.slice(0,24)}â€¦</Link> : <span />}
          {nxt ? <Link href={`/blog/${nxt.slug}`} className="text-white/60 hover:text-white text-right">NEXT â†’<br />{nxt.title.slice(0,24)}â€¦</Link> : <span />}
        </div>
        <div className="mt-10">
          <p className="text-[12px] tracking-widest text-white/30 uppercase">You may also like</p>
          <div className="mt-3 grid sm:grid-cols-3 gap-3">
            {related.map(r=> <Link key={r.slug} href={`/blog/${r.slug}`} className="rounded-xl border border-white/10 bg-white/[0.04] p-4 hover:bg-white/[0.06]"><p className="text-sm font-medium text-white">{r.title}</p><p className="text-xs text-white/40">{r.slug}</p></Link>)}
          </div>
        </div>
      </article>
    </div>
  );
}
