"use client";
import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence, useScroll, useTransform } from "framer-motion";
import Link from "next/link";
import { ArrowUpRight, X, ChevronDown } from "lucide-react";
import { techs, categories } from "./data";
import Orbit from "./Orbit";
import Terminal from "./Terminal";

export default function SkillsClient() {
  const [hovered, setHovered] = useState<string | null>(null);
  const [selected, setSelected] = useState<string | null>(null);
  const [expanded, setExpanded] = useState<string | null>(null);
  const sel = techs.find(t => t.name === selected);

  // scroll progress side indicator
  const [activeSection, setActiveSection] = useState(0);
  const sectionRefs = useRef<(HTMLElement | null)[]>([]);
  useEffect(() => {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) { const idx = Number(e.target.getAttribute("data-idx")); if (!isNaN(idx)) setActiveSection(idx); }});
    }, { threshold: 0.4 });
    sectionRefs.current.forEach(el => el && obs.observe(el));
    return () => obs.disconnect();
  }, []);

  const { scrollYProgress } = useScroll();
  const wordOpacity = useTransform(scrollYProgress, [0.5, 0.65], [0, 1]);

  return (
    <div className="bg-[#07080c] pt-16">
      {/* HERO */}
      <section className="relative min-h-[90vh] flex flex-col overflow-hidden">
        <div className="absolute inset-0">
          <div className="absolute inset-0 grid-pattern opacity-[0.25] [mask-image:radial-gradient(70%_50%_at_50%_0%,black,transparent)]" />
          <div className="absolute inset-0 bg-[radial-gradient(600px_400px_at_50%_0%,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-10 right-[10%] hidden sm:block text-[10px] tracking-widest text-white/10 rotate-3">LAYER: INFRA • 12 NODES • 99.9% UPTIME</div>
          <div className="absolute bottom-10 left-[8%] hidden sm:block text-[10px] tracking-widest text-white/10 -rotate-2">STACK: REACT • NEXT • NODE • LINUX • DOCKER</div>
        </div>

        <div className="relative max-w-[1200px] w-full mx-auto px-6 sm:px-8 pt-20 sm:pt-24 text-center z-10">
          <p className="text-[11px] tracking-[0.2em] font-semibold text-white/30 uppercase">Technology / Skills</p>
          <h1 className="mt-3 text-[36px] sm:text-[64px] lg:text-[72px] font-[800] tracking-[-0.05em] leading-[0.85] text-white">I BUILD WITH<br /><span className="bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent">TECHNOLOGY.</span></h1>
          <p className="mt-4 max-w-[640px] mx-auto text-[15px] leading-relaxed text-white/55">From interfaces and applications to servers and infrastructure, I work across the stack.</p>
        </div>

        {/* orbit - desktop */}
        <div className="relative hidden md:block">
          <Orbit onSelect={setSelected} hovered={hovered} setHovered={setHovered} />
        </div>
        {/* mobile stack */}
        <div className="md:hidden relative px-6 pb-8 mt-6">
          <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-5 text-center">
            <p className="w-16 h-16 mx-auto rounded-full bg-white text-black grid place-items-center font-black text-xs">RAVNEET</p>
            <p className="text-[11px] tracking-widest text-white/30 mt-3 uppercase">Tap a technology</p>
            <div className="mt-4 flex flex-wrap justify-center gap-2">
              {techs.slice(0,12).map(t => (
                <button key={t.name} onClick={() => setSelected(t.name)} onMouseEnter={() => setHovered(t.name)} onMouseLeave={() => setHovered(null)} className={`px-3 py-1.5 rounded-full text-xs font-semibold border ${hovered===t.name ? "bg-white text-black border-white" : "bg-white/10 border-white/10 text-white/70"}`}>{t.name}</button>
              ))}
            </div>
          </div>
        </div>

        {/* marquee */}
        <div className="relative border-y border-white/10 bg-white/[0.02] overflow-hidden">
          <motion.div animate={{ x: ["0%","-50%"] }} transition={{ duration: 20, repeat: Infinity, ease:"linear" }} className="flex gap-8 py-3 whitespace-nowrap hover:[animation-play-state:paused]">
            {[...techs, ...techs].map((t,i)=>(<span key={i} className="text-[13px] tracking-[0.12em] font-semibold text-white/40">{t.name.toUpperCase()}</span>))}
          </motion.div>
          <motion.div animate={{ x: ["-50%","0%"] }} transition={{ duration: 22, repeat: Infinity, ease:"linear" }} className="flex gap-8 py-3 whitespace-nowrap border-t border-white/5">
            {[...techs.slice().reverse(), ...techs.slice().reverse()].map((t,i)=>(<span key={i} className="text-[13px] tracking-[0.12em] font-semibold text-white/25">{t.name.toUpperCase()}</span>))}
          </motion.div>
        </div>
      </section>

      {/* tooltip for hovered */}
      <AnimatePresence>
        {hovered && (
          <motion.div initial={{ opacity:0, y:8 }} animate={{ opacity:1, y:0 }} exit={{ opacity:0, y:8 }} className="fixed left-1/2 -translate-x-1/2 bottom-6 z-20 pointer-events-none hidden sm:block">
            <div className="rounded-2xl bg-[#0f1117] border border-white/15 p-4 shadow-2xl min-w-[300px]">
              {(() => {
                const t = techs.find(x=>x.name===hovered);
                if (!t) return null;
                return (
                  <>
                    <p className="text-[11px] tracking-widest text-blue-300">{t.category.toUpperCase()} • {t.level}</p>
                    <p className="font-semibold text-white">{t.name}</p>
                    <p className="text-xs text-white/60 mt-1">{t.desc}</p>
                    <p className="text-[11px] text-white/30 mt-2">Used for: {t.usedFor.join(" • ")}</p>
                    <p className="text-[11px] text-white/30">Connected: {t.related.join(", ")}</p>
                  </>
                );
              })()}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* detail panel */}
      <AnimatePresence>
        {sel && (
          <motion.div initial={{ opacity:0 }} animate={{ opacity:1 }} exit={{ opacity:0 }} className="fixed inset-0 z-40 flex justify-end">
            <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={()=>setSelected(null)} />
            <motion.div initial={{ x:"100%" }} animate={{ x:0 }} exit={{ x:"100%" }} transition={{ type:"spring", damping:28, stiffness:300 }} className="relative w-full max-w-[420px] bg-[#0f1117] border-l border-white/10 p-6 sm:p-8 overflow-auto">
              <button onClick={()=>setSelected(null)} className="absolute top-4 right-4 w-8 h-8 rounded-full bg-white/10 grid place-items-center text-white"><X size={14} /></button>
              <p className="text-[11px] tracking-widest text-blue-300">{sel.category.toUpperCase()} • {sel.level}</p>
              <h3 className="mt-1 text-2xl font-bold text-white">{sel.name}</h3>
              <p className="text-sm text-white/60 mt-2 leading-relaxed">{sel.desc}</p>
              <div className="mt-6 space-y-4">
                <div><p className="text-xs tracking-widest text-white/30 uppercase">Related projects</p><ul className="mt-2 space-y-1 text-sm text-white/70">{sel.projects.map(p=><li key={p}>• {p}</li>)}</ul></div>
                <div><p className="text-xs tracking-widest text-white/30 uppercase">Related technologies</p><div className="mt-2 flex flex-wrap gap-1.5">{sel.related.map(r=><span key={r} className="px-2.5 py-1 rounded-full bg-white text-black text-xs font-semibold">{r}</span>)}</div></div>
                <Link href="/work" onClick={()=>setSelected(null)} className="inline-flex mt-4 px-4 py-2 rounded-full bg-white text-black font-semibold text-sm">View related projects <ArrowUpRight size={14} className="ml-1" /></Link>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* categories large */}
      <div className="max-w-[1200px] mx-auto px-6 sm:px-8">
        {categories.map((cat, idx) => (
          <section key={cat.id} data-idx={idx} ref={el=>{sectionRefs.current[idx]=el}} className="py-14 sm:py-20 border-t border-white/10 grid lg:grid-cols-2 gap-8 items-center">
            <div>
              <p className="text-[11px] tracking-[0.2em] text-white/30">{cat.id}</p>
              <h2 className="mt-2 text-[28px] sm:text-[36px] font-[800] tracking-[-0.04em] text-white">{cat.title}</h2>
              <p className="mt-3 text-white/60 max-w-[480px] leading-relaxed">{cat.desc}</p>
              <div className="mt-6 flex flex-wrap gap-2">
                {cat.items.map(name => {
                  const t = techs.find(x=>x.name===name);
                  return <button key={name} onClick={()=> t && setSelected(name)} className={`px-4 py-2 rounded-full text-sm font-medium border transition ${t ? "bg-white text-black border-white hover:bg-blue-500 hover:text-white hover:border-blue-500" : "bg-white/5 border-white/10 text-white/60"}`}>{name} {t && <span className="opacity-40 text-xs ml-1">{t.level[0]}</span>}</button>;
                })}
              </div>
            </div>
            <div className="rounded-[24px] border border-white/10 bg-gradient-to-br from-white/[0.06] to-transparent p-6 min-h-[160px] grid place-items-center">
              <span className="text-white/20 text-xs tracking-widest uppercase">Interactive visual • {cat.title}</span>
            </div>
          </section>
        ))}
      </div>

      {/* constellation */}
      <section className="py-16 sm:py-20 border-t border-white/10 bg-[#07080c] overflow-hidden">
        <div className="max-w-[900px] mx-auto px-6 sm:px-8 text-center">
          <h2 className="text-[28px] sm:text-[44px] font-[800] tracking-[-0.04em] text-white">HOW EVERYTHING CONNECTS</h2>
          <div className="mt-8 rounded-[24px] border border-white/10 bg-white/[0.03] p-6 sm:p-10 font-mono text-[12px] leading-relaxed">
            <div className="flex flex-col items-center gap-1 text-white/70">
              <span className="px-3 py-1 rounded-full bg-white text-black font-bold">React</span>
              <span className="w-px h-4 bg-white/20" />
              <div className="flex gap-4"><span className="px-3 py-1 rounded-full bg-white/10 border border-white/10">Next.js</span><span className="px-3 py-1 rounded-full bg-white/10 border border-white/10">TypeScript</span></div>
              <span className="w-px h-4 bg-white/20" />
              <span className="px-3 py-1 rounded-full bg-blue-500 text-white">Node.js</span>
              <span className="w-px h-4 bg-white/20" />
              <div className="flex gap-4"><span className="px-3 py-1 rounded-full bg-white/10 border border-white/10">PostgreSQL</span><span className="px-3 py-1 rounded-full bg-white/10 border border-white/10">Redis</span></div>
              <span className="w-px h-4 bg-white/20" />
              <span className="px-3 py-1 rounded-full bg-emerald-500/20 border border-emerald-500/30 text-emerald-300">Linux</span>
              <span className="w-px h-4 bg-white/20" />
              <span className="px-3 py-1 rounded-full bg-white/10 border border-white/10">Docker</span>
              <span className="w-px h-4 bg-white/20" />
              <span className="px-3 py-1 rounded-full bg-white/10 border border-white/10">Pterodactyl</span>
              <span className="w-px h-4 bg-blue-500/50" />
              <span className="px-6 py-2 rounded-full bg-[#2563eb] text-white font-bold tracking-widest">ZYPHRON CLOUD</span>
            </div>
            <div className="mt-6 h-1 rounded-full bg-white/10 overflow-hidden flex"><span className="flex-1 bg-blue-500 animate-pulse" /><span className="flex-1 bg-cyan-400" /><span className="flex-1 bg-emerald-400" /></div>
          </div>
        </div>
      </section>

      {/* zyphron connection */}
      <section className="py-16 border-t border-white/10 max-w-[800px] mx-auto px-6 sm:px-8 text-center">
        <h2 className="text-2xl font-bold text-white">Where the skills become a product.</h2>
        <div className="mt-6 flex flex-col items-center gap-2 text-sm text-white/70">
          {["Development","Backend","Databases","Linux","Docker","Server Infrastructure","Pterodactyl","ZYPHRON CLOUD"].map((s,i)=>(
            <motion.div key={s} initial={{ opacity:0, y:12 }} whileInView={{ opacity:1, y:0 }} viewport={{ once:true }} transition={{ delay:i*0.06 }} className={`px-4 py-2 rounded-full ${s==="ZYPHRON CLOUD" ? "bg-[#2563eb] text-white font-bold" : "bg-white/10 border border-white/10"}`}>{s}</motion.div>
          ))}
        </div>
      </section>

      {/* matrix */}
      <section className="py-12 border-t border-white/10 max-w-[1000px] mx-auto px-6 sm:px-8">
        <h2 className="text-2xl font-bold text-white">MY STACK</h2>
        <p className="text-white/40 text-sm mt-1">Click a row to expand • Authentic, no fake percentages</p>
        <div className="mt-6 rounded-2xl border border-white/10 overflow-hidden divide-y divide-white/10 bg-white/[0.03]">
          <div className="grid grid-cols-[1.2fr_0.8fr_0.8fr_0.6fr] gap-2 px-4 py-3 text-[11px] tracking-widest text-white/30 uppercase bg-white/[0.04]"><span>Technology</span><span>Category</span><span>Projects</span><span>Level</span></div>
          {techs.map(t=>(
            <div key={t.name}>
              <button onClick={()=> setExpanded(expanded===t.name?null:t.name)} className="w-full grid grid-cols-[1.2fr_0.8fr_0.8fr_0.6fr] gap-2 px-4 py-3 text-left hover:bg-white/[0.04] items-center">
                <span className="font-medium text-white text-sm flex items-center gap-2"><span className={`w-1.5 h-1.5 rounded-full ${t.level==="PRIMARY" ? "bg-blue-400" : t.level==="WORKING" ? "bg-emerald-400" : "bg-amber-400"}`} />{t.name}</span>
                <span className="text-xs text-white/50">{t.category}</span>
                <span className="text-xs text-white/40">{t.projects.length} Projects</span>
                <span className="flex items-center gap-1 text-xs font-semibold text-white/60">{t.level} <ChevronDown size={12} className={`transition ${expanded===t.name ? "rotate-180" : ""}`} /></span>
              </button>
              <AnimatePresence>
                {expanded===t.name && (
                  <motion.div initial={{ height:0, opacity:0 }} animate={{ height:"auto", opacity:1 }} exit={{ height:0, opacity:0 }} className="overflow-hidden bg-black/20">
                    <div className="px-4 py-3 text-sm text-white/60">{t.desc} • Used for: {t.usedFor.join(", ")} • <Link href="/work" className="text-white underline">Explore projects</Link></div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          ))}
        </div>
      </section>

      {/* currently exploring */}
      <section className="py-12 border-t border-white/10 max-w-[1000px] mx-auto px-6 sm:px-8">
        <h2 className="text-2xl font-bold text-white">CURRENTLY EXPLORING</h2>
        <div className="mt-6 grid sm:grid-cols-3 gap-4">
          {[
            { name:"Kubernetes", why:"Orchestration at scale", status:"Exploring" },
            { name:"Edge Functions", why:"Low-latency compute", status:"Working" },
            { name:"Observability", why:"Better logs & traces", status:"Exploring" },
          ].map(c=>(
            <motion.div key={c.name} whileHover={{ y:-4 }} className="rounded-2xl border border-white/10 bg-white/[0.04] p-6">
              <p className="font-semibold text-white">{c.name}</p><p className="text-sm text-white/50 mt-1">{c.why}</p><span className="mt-3 inline-flex text-xs px-2 py-1 rounded-full bg-blue-500/20 border border-blue-500/30 text-blue-300">{c.status}</span>
            </motion.div>
          ))}
        </div>
      </section>

      {/* terminal + code */}
      <section className="py-12 border-t border-white/10 grid lg:grid-cols-2 gap-6 max-w-[1100px] mx-auto px-6 sm:px-8">
        <Terminal />
        <div className="rounded-[18px] border border-white/10 bg-[#0a0d12] p-6 font-mono text-sm">
          <p className="text-white/30 text-xs tracking-widest uppercase">BUILD • LEARN • IMPROVE • REPEAT</p>
          <pre className="mt-4 text-[13px] leading-relaxed">
            <span className="text-white/40">const</span> <span className="text-cyan-300">build</span> <span className="text-white/40">=</span> <span className="text-white/40">()</span> <span className="text-white/40">=&gt;</span> <span className="text-white/40">{`{`}</span>{'\n'}
            <span className="text-violet-400">  learn</span><span className="text-white/40">();</span>{'\n'}
            <span className="text-violet-400">  create</span><span className="text-white/40">();</span>{'\n'}
            <span className="text-violet-400">  deploy</span><span className="text-white/40">();</span>{'\n'}
            <span className="text-violet-400">  improve</span><span className="text-white/40">();</span>{'\n'}
            <span className="text-white/40">{`}`};</span>
          </pre>
        </div>
      </section>

      {/* timeline */}
      <section className="py-12 border-t border-white/10 max-w-[800px] mx-auto px-6 sm:px-8">
        <h2 className="text-2xl font-bold text-white text-center">HOW MY STACK EVOLVED</h2>
        <div className="mt-6 space-y-3">
          {[
            { label:"Learning", tech:"HTML • CSS • JS" },
            { label:"Building websites", tech:"React • Next.js" },
            { label:"Programming", tech:"Node.js • PHP • Laravel" },
            { label:"Servers", tech:"Linux • Ubuntu" },
            { label:"Hosting", tech:"Docker • Pterodactyl" },
            { label:"Infrastructure", tech:"Redis • PostgreSQL • Networking" },
            { label:"Zyphron Cloud", tech:"All of the above, in prod" },
          ].map((s,i)=><div key={s.label} className="flex gap-4 items-center rounded-xl bg-white/[0.04] border border-white/10 px-4 py-3"><span className="text-xs font-bold text-white/40 w-28 shrink-0">{s.label}</span><span className="w-px h-6 bg-white/10" /><span className="text-sm text-white/70">{s.tech}</span></div>)}
        </div>
      </section>

      {/* master scroll animation */}
      <section className="relative py-20 border-t border-white/10 overflow-hidden text-center">
        <div className="sticky top-1/2 -translate-y-1/2">
          <motion.div style={{ opacity: wordOpacity }} className="text-[48px] sm:text-[80px] font-[800] tracking-[-0.05em] text-white leading-none">
            CODE<br />SERVERS<br />INFRASTRUCTURE<br />PRODUCTS<br /><span className="bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent">ZYPHRON CLOUD</span>
          </motion.div>
        </div>
        <div className="h-[40vh]" />
      </section>

      {/* final */}
      <section className="py-16 sm:py-24 text-center border-t border-white/10">
        <h2 className="text-[28px] sm:text-[48px] font-[800] tracking-[-0.04em] text-white leading-none">TECHNOLOGY IS THE TOOL.<br /><span className="text-white/20">BUILDING IS THE GOAL.</span></h2>
        <div className="mt-6 flex flex-wrap justify-center gap-3">
          <Link href="/work" className="px-6 py-3 rounded-full bg-white text-black font-semibold">View My Work <ArrowUpRight size={14} className="inline ml-1" /></Link>
          <a href="https://zyphron.cloud" target="_blank" rel="noopener noreferrer" className="px-6 py-3 rounded-full bg-[#2563eb] text-white font-semibold">Visit Zyphron Cloud ↗</a>
          <Link href="/contact" className="px-6 py-3 rounded-full border border-white/15 text-white font-semibold">Contact Ravneet</Link>
        </div>
      </section>

      {/* side progress */}
      <div className="fixed right-4 top-1/2 -translate-y-1/2 hidden xl:flex flex-col gap-2 z-20">
        {["Hero","Dev","Infra","DB","Tools","Arch","Zyphron","Learning"].map((s,i)=>(
          <span key={s} className={`w-1.5 h-6 rounded-full transition ${activeSection===i ? "bg-white" : "bg-white/20"}`} title={s} />
        ))}
      </div>
    </div>
  );
}
