// @ts-nocheck
"use client";
import { useState, useMemo, useEffect } from "react";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import { Search, ArrowUpRight, X } from "lucide-react";
import { posts as staticPosts } from "@/lib/blog";

const categories = ["ALL","DEVELOPMENT","INFRASTRUCTURE","CLOUD","ZYPHRON","BUSINESS","TUTORIALS","EXPERIMENTS","PERSONAL"] as const;

export default function BlogClient({ initialPosts }: { initialPosts?: any[] }) {
  const posts = (initialPosts !== undefined ? initialPosts : staticPosts) as any[];
  const allTags = Array.from(new Set(posts.flatMap((p:any)=> p.tags || []))).sort() as string[];
  const [activeCat, setActiveCat] = useState("ALL");
  const [q, setQ] = useState("");
  const [tag, setTag] = useState<string | null>(null);
  const [hovered, setHovered] = useState<string | null>(null);
  const [mouse, setMouse] = useState({x:0,y:0});
  const [showSearch, setShowSearch] = useState(false);

  useEffect(() => {
    const onMove = (e: MouseEvent) => setMouse({x:e.clientX, y:e.clientY});
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if ((e.ctrlKey||e.metaKey) && e.key.toLowerCase()==="k") { e.preventDefault(); setShowSearch(true);} if (e.key==="/" && !(e.target instanceof HTMLInputElement)) { e.preventDefault(); setShowSearch(true);} };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const filtered = useMemo(() => {
    return posts.filter(p=>{
      if (p as any as {draft?:boolean} && (p as any).draft) return false;
      const catMatch = activeCat==="ALL" ? true : [p.category, ...p.tags].join(" ").toUpperCase().includes(activeCat) || (activeCat==="ZYPHRON" && p.tags.join(" ").toUpperCase().includes("ZYPHRON")) || (activeCat==="CLOUD" && p.tags.join(" ").toUpperCase().includes("CLOUD")) || (activeCat==="TUTORIALS" && p.category==="Technology") ;
      const tagMatch = !tag ? true : p.tags.includes(tag);
      const sq = q.trim().toLowerCase();
      const searchMatch = !sq ? true : [p.title, p.excerpt, p.content, p.category, ...p.tags].join(" ").toLowerCase().includes(sq);
      return catMatch && tagMatch && searchMatch;
    });
  }, [activeCat, tag, q]);

  const featured = posts.find(p=>p.featured) || posts[0];
  const stats = {
    articles: posts.length,
    categories: new Set(posts.map(p=>p.category)).size,
    techs: allTags.length,
    reading: posts.reduce((a,p)=> a + parseInt(p.reading), 0),
  };
  const zyphronPosts = posts.filter(p=> p.tags.some(t=>t.toLowerCase().includes("zyphron")) || p.category==="Entrepreneurship");

  return (
    <div className="bg-[#07080c] overflow-hidden">
      {/* HERO */}
      <section className="relative min-h-[78vh] flex flex-col justify-center overflow-hidden">
        <div className="absolute inset-0">
          <div className="absolute inset-0 grid-pattern opacity-[0.22] [mask-image:radial-gradient(70%_50%_at_50%_0%,black,transparent)]" />
          <div className="absolute inset-0 bg-[radial-gradient(800px_500px_at_50%_-10%,rgba(59,130,246,0.12),transparent_70%)]" />
          <div className="absolute inset-0 opacity-[0.03]" style={{ backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")` }} />
          <div className="absolute top-[18%] left-[6%] hidden sm:block text-[10px] tracking-[0.2em] text-white/10 rotate-3">BUILD • LINUX • DOCKER • CLOUD</div>
          <div className="absolute bottom-[18%] right-[8%] hidden sm:block text-[10px] tracking-[0.2em] text-white/10 -rotate-2">NEXT.JS • REACT • NODE • HOSTING</div>
        </div>
        <div className="relative max-w-[1100px] mx-auto px-6 sm:px-8 pt-28 pb-10 text-center">
          <p className="text-[11px] tracking-[0.2em] font-semibold text-white/30 uppercase">Blog / Notes / Journal</p>
          <motion.h1 initial={{ opacity:0, y:16 }} animate={{ opacity:1, y:0 }} transition={{ duration:0.6, ease:[0.16,1,0.3,1] }} className="mt-3 text-[40px] sm:text-[68px] lg:text-[78px] font-[800] tracking-[-0.05em] leading-[0.85] text-white">IDEAS, BUILDS<br /><span className="bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent">& LESSONS.</span></motion.h1>
          <p className="mt-4 max-w-[640px] mx-auto text-[14px] leading-relaxed text-white/50">Notes from building software, infrastructure, products and businesses.</p>
          <button onClick={()=>setShowSearch(true)} className="mt-6 mx-auto flex items-center gap-2 rounded-full bg-white text-black px-4 py-2 text-sm font-semibold hover:bg-white/90">Search articles <Search size={14} /></button>
        </div>
        <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/30"><span className="text-[10px] tracking-[0.2em]">SCROLL TO READ</span><span className="w-px h-8 bg-gradient-to-b from-white/30 to-transparent animate-pulse" /></div>
      </section>

      {/* FEATURED */}
      {featured && (
        <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-8">
          <p className="text-[11px] tracking-[0.2em] text-blue-300 font-semibold">FEATURED</p>
          <Link href={`/blog/${featured.slug}`} className="mt-3 block group rounded-[24px] border border-white/10 bg-gradient-to-br from-white/[0.06] to-white/[0.02] overflow-hidden hover:bg-white/[0.08] transition">
            <div className="grid lg:grid-cols-[1.1fr_0.9fr] gap-0">
              <div className="p-6 sm:p-8">
                <p className="text-[11px] tracking-widest text-white/30">{featured.category.toUpperCase()} • {featured.reading} • {featured.date}</p>
                <h2 className="mt-2 text-[22px] sm:text-[28px] font-[700] tracking-tight text-white group-hover:translate-x-1 transition">{featured.title}</h2>
                <p className="mt-2 text-sm leading-relaxed text-white/60">{featured.excerpt}</p>
                <p className="mt-2 text-xs text-white/30">By Ravneet Brar • {featured.tags.join(" • ")}</p>
                <span className="mt-4 inline-flex items-center gap-1 text-sm font-semibold text-white">Read Article <ArrowUpRight size={14} className="group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition" /></span>
              </div>
              <div className="relative min-h-[220px] bg-[#0e1118] border-t lg:border-t-0 lg:border-l border-white/10 grid place-items-center overflow-hidden">
                <div className="absolute inset-0 bg-[radial-gradient(500px_300px_at_50%_0%,rgba(59,130,246,0.15),transparent_70%)]" />
                <span className="relative text-white/20 text-xs tracking-widest uppercase">Featured image • {featured.slug}</span>
                <div className="absolute inset-0 opacity-0 group-hover:opacity-100 bg-gradient-to-br from-blue-500/10 to-transparent transition" />
              </div>
            </div>
          </Link>
        </section>
      )}

      {/* SEARCH */}
      <div className="max-w-[1100px] mx-auto px-6 sm:px-8 py-4">
        <div className="relative">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-white/30" />
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Search articles, technologies and ideas..." className="w-full rounded-full bg-white/[0.06] border border-white/10 pl-9 pr-4 py-3 text-sm text-white placeholder:text-white/30 outline-none focus:border-white/20" />
          <div className="absolute right-1 top-1 bottom-1 hidden sm:flex items-center gap-1">
            <span className="text-[11px] text-white/20 px-2">/</span>
            <button onClick={()=>setShowSearch(true)} className="px-3 py-1.5 rounded-full bg-white text-black text-xs font-semibold">⌘K</button>
          </div>
        </div>
      </div>

      {/* CATEGORY FILTER sticky */}
      <div className="sticky top-[68px] z-20 backdrop-blur-xl bg-[#07080c]/80 border-y border-white/10">
        <div className="max-w-[1100px] mx-auto px-6 sm:px-8 py-3 flex gap-1.5 overflow-x-auto">
          {categories.map(c=>(
            <button key={c} onClick={()=>setActiveCat(c)} className={`shrink-0 px-4 py-1.5 rounded-full text-xs font-semibold border whitespace-nowrap transition ${activeCat===c ? "bg-white text-black border-white" : "bg-white/5 border-white/10 text-white/60 hover:text-white"}`}>{c}</button>
          ))}
        </div>
        <div className="max-w-[1100px] mx-auto px-6 sm:px-8 pb-3 flex gap-1.5 overflow-x-auto">
          <span className="text-[11px] tracking-widest text-white/20 py-1 shrink-0">TAGS:</span>
          {allTags.map(t=>(
            <button key={t} onClick={()=>setTag(tag===t?null:t)} className={`shrink-0 px-3 py-1 rounded-full text-xs font-medium border ${tag===t ? "bg-blue-500 text-white border-blue-500" : "bg-white/5 border-white/10 text-white/50 hover:text-white"}`}>{t}</button>
          ))}
          {tag && <button onClick={()=>setTag(null)} className="shrink-0 px-3 py-1 rounded-full bg-white text-black text-xs font-semibold">Clear ×</button>}
        </div>
      </div>

      {/* ARCHIVE rows */}
      <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-8">
        <div className="divide-y divide-white/10 border-y border-white/10">
          {filtered.map(p=>(
            <Link key={p.slug} href={`/blog/${p.slug}`} onMouseEnter={()=>setHovered(p.slug)} onMouseLeave={()=>setHovered(null)} className="group flex items-center gap-4 py-5 hover:bg-white/[0.03] px-2 -mx-2 transition">
              <span className="hidden sm:block text-[11px] font-mono text-white/20 w-14 shrink-0">{p.date.slice(0,7)}</span>
              <div className="flex-1 min-w-0">
                <h3 className="text-[16px] sm:text-[18px] font-semibold text-white group-hover:translate-x-0.5 transition line-clamp-1">{p.title}</h3>
                <p className="text-xs tracking-widest text-white/30 uppercase">{p.category} • {p.reading} • {p.tags.slice(0,3).join(" • ")}</p>
                <p className="text-sm text-white/50 hidden sm:block line-clamp-1 mt-0.5">{p.excerpt}</p>
              </div>
              <span className="w-8 h-8 rounded-full border border-white/10 bg-white/5 grid place-items-center text-white/40 group-hover:bg-white group-hover:text-black group-hover:translate-x-0.5 transition shrink-0"><ArrowUpRight size={14} /></span>
            </Link>
          ))}
        </div>
        {filtered.length===0 && (
          <div className="py-16 text-center">
            <h3 className="text-2xl font-bold text-white">NO MATCHES.</h3>
            <p className="text-white/50 text-sm mt-1">Try another keyword or browse the categories.</p>
            <button onClick={()=>{setQ(""); setActiveCat("ALL"); setTag(null);}} className="mt-4 px-5 py-2 rounded-full bg-white text-black font-semibold text-sm">Clear Search</button>
          </div>
        )}
        {filtered.length===0 && posts.length===0 && (
          <div className="py-16 text-center">
            <h3 className="text-2xl font-bold text-white">NOTHING HERE YET.</h3>
            <p className="text-white/50 text-sm">I&apos;m still writing. Check back soon.</p>
            <Link href="/" className="mt-4 inline-flex px-5 py-2 rounded-full bg-white text-black font-semibold text-sm">Back Home →</Link>
          </div>
        )}
      </section>

      {/* hover preview */}
      <AnimatePresence>
        {hovered && (
          <motion.div style={{ left: mouse.x + 16, top: mouse.y + 16 }} initial={{ opacity:0, scale:0.96 }} animate={{ opacity:1, scale:1 }} exit={{ opacity:0, scale:0.96 }} className="pointer-events-none fixed z-20 hidden lg:block w-[300px] rounded-2xl border border-white/15 bg-[#0f1117] overflow-hidden shadow-2xl">
            {(() => {
              const p = posts.find(x=>x.slug===hovered);
              if (!p) return null;
              return <div><div className="h-28 bg-[#0e1118] grid place-items-center border-b border-white/10"><span className="text-white/20 text-xs tracking-widest uppercase">{p.slug}</span></div><div className="p-4"><p className="font-semibold text-white text-sm">{p.title}</p><p className="text-xs text-white/40">{p.category} • {p.reading}</p></div></div>;
            })()}
          </motion.div>
        )}
      </AnimatePresence>

      {/* CARDS varying sizes */}
      <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-6">
        <div className="grid sm:grid-cols-3 gap-4">
          {filtered.slice(0,3).map((p,i)=>(
            <Link key={p.slug} href={`/blog/${p.slug}`} className={`rounded-[20px] border border-white/10 bg-white/[0.04] p-5 hover:bg-white/[0.06] group ${i===0 ? "sm:col-span-2 sm:row-span-1" : ""}`}>
              <p className="text-[11px] tracking-widest text-white/30">{p.category} • {p.reading}</p>
              <h3 className="font-semibold text-white mt-1 group-hover:translate-x-0.5 transition">{p.title}</h3>
              <p className="text-sm text-white/50 mt-1 line-clamp-2">{p.excerpt}</p>
              <span className="mt-3 inline-flex text-xs font-semibold text-white">Read →</span>
            </Link>
          ))}
        </div>
      </section>

      {/* stats */}
      <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-8">
        <div className="rounded-2xl border border-white/10 bg-white/[0.03] p-6 grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
          <div><p className="text-2xl font-bold text-white">{stats.articles}</p><p className="text-xs tracking-widest text-white/30 uppercase">Articles</p></div>
          <div><p className="text-2xl font-bold text-white">{stats.categories}</p><p className="text-xs tracking-widest text-white/30 uppercase">Categories</p></div>
          <div><p className="text-2xl font-bold text-white">{stats.techs}</p><p className="text-xs tracking-widest text-white/30 uppercase">Technologies</p></div>
          <div><p className="text-2xl font-bold text-white">{stats.reading}m</p><p className="text-xs tracking-widest text-white/30 uppercase">Reading</p></div>
        </div>
        <p className="text-[11px] text-white/20 text-center mt-2">Auto-calculated, not fabricated</p>
      </section>

      {/* tech cloud */}
      <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-8 text-center">
        <h2 className="text-xl font-bold text-white">WHAT I WRITE ABOUT</h2>
        <div className="mt-4 flex flex-wrap justify-center gap-2">
          {allTags.map(t=>(
            <button key={t} onClick={()=>{setTag(t); window.scrollTo({ top: 600, behavior:"smooth" });}} className="px-4 py-2 rounded-full bg-white/10 border border-white/10 text-white/70 hover:bg-white hover:text-black text-sm font-medium transition">{t}</button>
          ))}
        </div>
      </section>

      {/* zyphron journal */}
      <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-8 border-t border-white/10">
        <div className="flex justify-between items-end">
          <h2 className="text-xl font-bold text-white">BUILDING ZYPHRON</h2>
          <Link href="/zyphron" className="text-xs font-semibold text-blue-400 hover:text-blue-300">Explore Zyphron Journal →</Link>
        </div>
        <div className="mt-4 grid sm:grid-cols-2 gap-3">
          {zyphronPosts.slice(0,2).map(p=>(
            <Link key={p.slug} href={`/blog/${p.slug}`} className="rounded-2xl border border-blue-500/20 bg-blue-500/10 p-5 hover:bg-blue-500/15">
              <p className="text-xs tracking-widest text-blue-300">{p.category} • {p.reading}</p><p className="font-semibold text-white mt-1">{p.title}</p><p className="text-sm text-white/60 mt-1">{p.excerpt}</p>
            </Link>
          ))}
        </div>
      </section>

      {/* build log */}
      <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-8 border-t border-white/10">
        <h2 className="text-xl font-bold text-white">BUILD LOG</h2>
        <div className="mt-4 space-y-2">
          {[
            { date:"2026-02-10", what:"Shipped blog search + filters", broke:"—", learned:"Search UX matters" },
            { date:"2026-02-05", what:"Zyphron live preview", broke:"iframe CSP check", learned:"Graceful fallback" },
            { date:"2026-01-20", what:"Linux hardening", broke:"Firewall rules", learned:"Test in staging" },
          ].map(e=>(
            <div key={e.date} className="rounded-xl border border-white/10 bg-white/[0.04] px-4 py-3 flex flex-wrap gap-3 text-sm">
              <span className="font-mono text-white/40 w-24 shrink-0">{e.date}</span><span className="text-white font-medium flex-1">{e.what}</span><span className="text-white/30 hidden sm:inline">Broke: {e.broke}</span><span className="text-emerald-300 text-xs">Learned: {e.learned}</span>
            </div>
          ))}
        </div>
      </section>

      {/* newsletter + rss */}
      <section className="max-w-[1100px] mx-auto px-6 sm:px-8 py-10 border-t border-white/10 grid lg:grid-cols-2 gap-6">
        <div className="rounded-[20px] border border-white/10 bg-white/[0.04] p-6 sm:p-8">
          <h3 className="text-xl font-bold text-white">GET THE NOTES.</h3>
          <p className="text-sm text-white/50 mt-1">Occasional updates about things I&apos;m building, learning and exploring.</p>
          <form onSubmit={e=>e.preventDefault()} className="mt-4 flex gap-2">
            <input type="email" placeholder="Your email" required className="flex-1 rounded-full bg-black/40 border border-white/10 px-4 py-2.5 text-sm text-white placeholder:text-white/30 outline-none" />
            <button className="px-5 py-2.5 rounded-full bg-white text-black font-semibold text-sm">Subscribe →</button>
          </form>
          <p className="text-[11px] text-white/20 mt-2">Connect to real provider when available — no fake subscriptions.</p>
        </div>
        <div className="rounded-[20px] border border-white/10 bg-white/[0.03] p-6 sm:p-8 flex flex-col justify-center">
          <h3 className="font-semibold text-white">RSS Feed</h3><p className="text-sm text-white/50">Subscribe via RSS for updates.</p>
          <a href="/rss.xml" className="mt-3 inline-flex w-fit px-4 py-2 rounded-full bg-white text-black font-semibold text-sm">RSS Feed ↗</a>
          <p className="text-xs text-white/20 mt-2">/rss.xml • includes published articles only</p>
        </div>
      </section>

      {/* final */}
      <section className="py-16 sm:py-20 text-center border-t border-white/10 bg-gradient-to-b from-white/[0.04] to-transparent">
        <p className="text-[11px] tracking-[0.2em] text-white/30 uppercase">Keep exploring</p>
        <h2 className="mt-2 text-[32px] sm:text-[52px] font-[800] tracking-[-0.04em] text-white leading-none">BUILD. LEARN.<br />WRITE. REPEAT.</h2>
        <p className="text-white/50 mt-3 max-w-[600px] mx-auto">The best way to understand what I&apos;m building is to follow the process.</p>
        <div className="mt-6 flex flex-wrap justify-center gap-3">
          <Link href={`/blog/${filtered[0]?.slug || posts[0].slug}`} className="px-6 py-3 rounded-full bg-white text-black font-semibold">Read Latest →</Link>
          <Link href="/work" className="px-6 py-3 rounded-full border border-white/15 text-white font-semibold">Explore My Work →</Link>
          <Link href="/about" className="px-6 py-3 rounded-full border border-white/15 text-white font-semibold">About Ravneet →</Link>
        </div>
      </section>

      {/* command search modal */}
      <AnimatePresence>
        {showSearch && (
          <motion.div initial={{ opacity:0 }} animate={{ opacity:1 }} exit={{ opacity:0 }} className="fixed inset-0 z-30 flex items-start justify-center pt-[20vh] px-4">
            <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={()=>setShowSearch(false)} />
            <div className="relative w-full max-w-[640px] rounded-2xl bg-[#0f1117] border border-white/10 overflow-hidden">
              <div className="flex items-center gap-3 px-4 py-3 border-b border-white/10">
                <Search size={16} className="text-white/40" />
                <input autoFocus value={q} onChange={e=>setQ(e.target.value)} placeholder="Search articles…" className="flex-1 bg-transparent outline-none text-sm text-white placeholder:text-white/30" />
                <button onClick={()=>setShowSearch(false)} className="w-7 h-7 rounded-full bg-white/10 grid place-items-center text-white"><X size={14} /></button>
              </div>
              <div className="max-h-[40vh] overflow-auto p-2">
                {filtered.slice(0,8).map(p=>(
                  <Link key={p.slug} href={`/blog/${p.slug}`} onClick={()=>setShowSearch(false)} className="flex justify-between items-center px-3 py-2.5 rounded-xl hover:bg-white hover:text-black text-white text-sm">
                    <span><b>{p.title}</b> <span className="opacity-50 text-xs">— {p.category}</span></span><ArrowUpRight size={14} />
                  </Link>
                ))}
                {filtered.length===0 && <p className="text-center text-white/30 py-8 text-sm">NO MATCHES. Try another keyword.</p>}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
