/* Projects — editorial showcase. One large featured project at a time
   with side index, live preview, metrics, and animated transitions. */

const ProjectPreview = ({ kind }) => {
  if (kind === 'origins') {
    return (
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute inset-0" style={{ background: 'radial-gradient(circle at 70% 30%, color-mix(in oklab, var(--accent) 30%, transparent), transparent 60%)' }}></div>
        <svg viewBox="0 0 400 280" className="absolute inset-0 w-full h-full">
          {[...Array(7)].map((_, i) => (
            <motion.circle
              key={i} cx="200" cy="140" r={26 + i * 24}
              fill="none" stroke="currentColor"
              strokeOpacity={0.45 - i * 0.05} strokeWidth="1"
              style={{ color: 'var(--accent)' }}
              initial={{ pathLength: 0, opacity: 0 }}
              animate={{ pathLength: 1, opacity: 1 }}
              transition={{ duration: 1.4, delay: i * 0.08, ease: 'easeOut' }}
            />
          ))}
          {[
            [200,140,7],[120,90,4],[285,95,5],[110,200,4],[305,195,5],
            [200,50,3],[200,230,4],[60,140,3],[340,140,4],[150,40,3],[260,240,3],
          ].map(([x,y,r], i) => (
            <motion.g key={i}>
              <motion.circle
                cx={x} cy={y} r={r+3}
                fill="var(--accent)" opacity="0.2"
                animate={{ scale: [1, 1.6, 1], opacity: [0.3, 0, 0.3] }}
                transition={{ duration: 2.4, repeat: Infinity, delay: i * 0.2 }}
                style={{ transformOrigin: `${x}px ${y}px` }}
              />
              <motion.circle
                cx={x} cy={y} r={r}
                fill="var(--accent)"
                initial={{ scale: 0 }} animate={{ scale: 1 }}
                transition={{ delay: 0.3 + i * 0.04, duration: 0.4 }}
              />
            </motion.g>
          ))}
        </svg>
        <div className="absolute bottom-4 left-5 right-5 flex items-center justify-between font-mono text-[10px]" style={{ color: 'var(--fg-dim)' }}>
          <span>community.graph</span><span>nodes: 18.4k · edges: 142k</span>
        </div>
      </div>
    );
  }
  if (kind === 'pulsejob') {
    return (
      <div className="absolute inset-0 overflow-hidden">
        <svg viewBox="0 0 400 280" className="absolute inset-0 w-full h-full" preserveAspectRatio="none">
          <defs>
            <linearGradient id="pg" x1="0" x2="1" y1="0" y2="0">
              <stop offset="0%" stopColor="var(--accent)" stopOpacity="0" />
              <stop offset="50%" stopColor="var(--accent)" stopOpacity="1" />
              <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
            </linearGradient>
          </defs>
          {[0,1,2,3].map(i => (
            <motion.path
              key={i}
              d={`M0 ${140+i*6} L80 ${140+i*6} L100 ${100+i*6} L120 ${180+i*6} L140 ${110+i*6} L160 ${140+i*6} L240 ${140+i*6} L260 ${90+i*6} L280 ${190+i*6} L300 ${140+i*6} L400 ${140+i*6}`}
              fill="none" stroke="url(#pg)"
              strokeWidth={i===0 ? 1.6 : 0.8}
              strokeOpacity={1 - i*0.25}
              initial={{ pathLength: 0 }} animate={{ pathLength: 1 }}
              transition={{ duration: 1.6, delay: i*0.12 }}
            />
          ))}
        </svg>
        <div className="absolute top-6 left-5 flex flex-wrap gap-1.5 max-w-[60%]">
          {['Senior PM','Staff Eng','Designer','ML/Ops','Founding'].map((t, i) => (
            <motion.span
              key={t}
              initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 + i*0.08 }}
              className="px-2 py-1 rounded-md font-mono text-[10px]"
              style={{ background: 'var(--bg-elev)', border: '1px solid var(--line)', color: 'var(--fg-muted)' }}
            >{t}</motion.span>
          ))}
        </div>
        <div className="absolute bottom-4 left-5 right-5 flex items-center justify-between font-mono text-[10px]" style={{ color: 'var(--fg-dim)' }}>
          <span>match.score</span><span style={{ color: 'var(--accent)' }}>0.94</span>
        </div>
      </div>
    );
  }
  return (
    <div className="absolute inset-0 overflow-hidden">
      <div className="absolute inset-0 bg-grid opacity-40"></div>
      <svg viewBox="0 0 400 280" className="absolute inset-0 w-full h-full">
        {[
          [80,80,'Plan'],[200,60,'Reason'],[320,80,'Act'],
          [80,200,'Tool'],[200,220,'Memory'],[320,200,'Output'],
        ].map(([x,y,label], i) => (
          <g key={i}>
            <motion.rect
              x={x-40} y={y-14} width="80" height="28" rx="4"
              fill="var(--bg-card)" stroke="var(--line-strong)" strokeWidth="1"
              initial={{ opacity: 0 }} animate={{ opacity: 1 }}
              transition={{ delay: 0.1*i, duration: 0.4 }}
            />
            <motion.text
              x={x} y={y+4} textAnchor="middle"
              fontSize="11" fontFamily="var(--font-mono)" fill="var(--fg)"
              initial={{ opacity: 0 }} animate={{ opacity: 1 }}
              transition={{ delay: 0.15 + 0.1*i }}
            >{label}</motion.text>
          </g>
        ))}
        {[
          ['M120,80 L160,60', 0.4],['M240,60 L280,80', 0.5],
          ['M200,74 L200,206', 0.6],['M120,200 L160,220', 0.7],
          ['M240,220 L280,200', 0.8],
        ].map(([d, delay], i) => (
          <motion.path
            key={i} d={d} stroke="var(--accent)" strokeWidth="1" fill="none"
            strokeDasharray="3 3"
            initial={{ pathLength: 0 }} animate={{ pathLength: 1 }}
            transition={{ delay, duration: 0.6 }}
          />
        ))}
      </svg>
      <div className="absolute bottom-4 left-5 right-5 flex items-center justify-between font-mono text-[10px]" style={{ color: 'var(--fg-dim)' }}>
        <span>agent.runtime</span><span>v2.1.4</span>
      </div>
    </div>
  );
};

const PROJECTS = [
  {
    kind: 'origins', name: 'Origins', role: 'Lead engineer', year: '2024',
    tagline: 'Community at scale.',
    desc: 'A community-building platform — web + mobile — that turns drive-by signups into a self-sustaining engagement loop. Every interaction strengthens the graph.',
    stack: ['React Native', 'Node.js', 'Postgres', 'Cloudflare'],
    metrics: [{ v: '18.4k', l: 'Active members' }, { v: '+312%', l: 'Retention' }, { v: '6mo', l: 'Build time' }],
    href: 'https://origins-app.com',
  },
  {
    kind: 'pulsejob', name: 'Pulsejob.ai', role: 'Founding engineer', year: '2024',
    tagline: 'Recruiting, on autopilot.',
    desc: 'AI-driven job-seeking and recruitment workflows. Embeddings, scoring rubrics, and agentic outreach that recruiters actually trust enough to send.',
    stack: ['Next.js', 'Python', 'pgvector', 'Vercel'],
    metrics: [{ v: '0.94', l: 'Match score' }, { v: '40h→12m', l: 'Triage' }, { v: '99.97%', l: 'Uptime' }],
    href: 'https://pulsejob.ai/',
  },
  {
    kind: 'aisyncso', name: 'AISyncso', role: 'Full stack + AI', year: '2025',
    tagline: 'Build your own agents.',
    desc: 'A platform to design, customize, and deploy AI agents. Visual graph, hot-reload tools, and a runtime that scales from one workflow to thousands.',
    stack: ['React', 'Node.js', 'Redis', 'DigitalOcean'],
    metrics: [{ v: '2.4k', l: 'Agents deployed' }, { v: '0.42s', l: 'Avg latency' }, { v: 'v2.1', l: 'Runtime' }],
    href: 'https://www.aisyncso.com/',
  },
];

const Projects = () => {
  const [active, setActive] = React.useState(0);
  const [direction, setDirection] = React.useState(1);
  const p = PROJECTS[active];

  const goto = (i) => {
    setDirection(i > active ? 1 : -1);
    setActive(i);
  };
  const next = () => goto((active + 1) % PROJECTS.length);
  const prev = () => goto((active - 1 + PROJECTS.length) % PROJECTS.length);

  // auto-advance
  React.useEffect(() => {
    const id = setInterval(() => setActive(a => (a + 1) % PROJECTS.length), 7000);
    return () => clearInterval(id);
  }, []);

  return (
    <Section id="work" className="border-t hairline">
      <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-12">
        <div>
          <Eyebrow index="02">Selected work</Eyebrow>
          <SectionTitle className="mt-5">
            Three products,<br />
            <span style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontWeight: 400 }}>one playbook.</span>
          </SectionTitle>
        </div>
        <p className="max-w-md text-sm leading-relaxed" style={{ color: 'var(--fg-muted)' }}>
          Each shipped to real users. Each measurably reduced a thing that used to hurt. Click through for the live product.
        </p>
      </div>

      <motion.div {...fadeUp(0)} className="card rounded-2xl overflow-hidden">
        <div className="grid lg:grid-cols-12">
          {/* LEFT — index rail */}
          <div className="lg:col-span-4 border-b lg:border-b-0 lg:border-r hairline p-5 md:p-6 flex flex-col">
            <div className="flex items-center justify-between font-mono text-[10px] uppercase tracking-[0.2em] mb-5" style={{ color: 'var(--fg-dim)' }}>
              <span>Index</span>
              <span>{String(active + 1).padStart(2, '0')} / {String(PROJECTS.length).padStart(2, '0')}</span>
            </div>

            <ul className="flex flex-col gap-1 flex-1">
              {PROJECTS.map((proj, i) => {
                const isActive = i === active;
                return (
                  <li key={proj.name}>
                    <button
                      onClick={() => goto(i)}
                      className="w-full text-left relative overflow-hidden rounded-xl transition-colors group"
                      style={{
                        background: isActive ? 'var(--accent-soft)' : 'transparent',
                        border: '1px solid ' + (isActive ? 'var(--accent)' : 'var(--line)'),
                      }}
                    >
                      <div className="px-4 py-3.5 flex items-center gap-4 relative z-10">
                        <span
                          className="font-mono text-[10px] tabular-nums"
                          style={{ color: isActive ? 'var(--accent)' : 'var(--fg-dim)' }}
                        >{String(i + 1).padStart(2, '0')}</span>
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-medium tracking-tight truncate" style={{ color: isActive ? 'var(--fg)' : 'var(--fg-muted)' }}>{proj.name}</div>
                          <div className="font-mono text-[10px] truncate" style={{ color: 'var(--fg-dim)' }}>{proj.role} · {proj.year}</div>
                        </div>
                        <motion.span
                          animate={{ x: isActive ? 0 : -6, opacity: isActive ? 1 : 0 }}
                          transition={{ duration: 0.3 }}
                          style={{ color: 'var(--accent)' }}
                        >
                          <I.ArrowRight size={14} />
                        </motion.span>
                      </div>
                      {/* progress bar on active */}
                      {isActive && (
                        <motion.div
                          key={`bar-${active}`}
                          initial={{ scaleX: 0 }}
                          animate={{ scaleX: 1 }}
                          transition={{ duration: 7, ease: 'linear' }}
                          className="absolute bottom-0 left-0 right-0 h-px origin-left"
                          style={{ background: 'var(--accent)' }}
                        />
                      )}
                    </button>
                  </li>
                );
              })}
            </ul>

            {/* prev/next */}
            <div className="flex items-center gap-2 mt-5 pt-5 border-t hairline">
              <button onClick={prev} className="grid place-items-center w-10 h-10 rounded-full transition-colors hover:bg-white/5" style={{ border: '1px solid var(--line-strong)' }} aria-label="Previous"><I.ArrowRight size={14} className="rotate-180" /></button>
              <button onClick={next} className="grid place-items-center w-10 h-10 rounded-full transition-colors hover:bg-white/5" style={{ border: '1px solid var(--line-strong)' }} aria-label="Next"><I.ArrowRight size={14} /></button>
              <div className="flex-1 h-px" style={{ background: 'var(--line)' }}></div>
              <a href={p.href} target="_blank" rel="noreferrer" className="text-[11px] font-mono flex items-center gap-1.5" style={{ color: 'var(--accent)' }}>Visit live <I.ArrowUpRight size={12} /></a>
            </div>
          </div>

          {/* RIGHT — featured */}
          <div className="lg:col-span-8 relative" style={{ background: 'var(--bg-elev)' }}>
            <AnimatePresence mode="wait" custom={direction}>
              <motion.div
                key={p.kind}
                custom={direction}
                initial={{ opacity: 0, x: direction * 40 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -direction * 40 }}
                transition={{ duration: 0.6, ease: [0.2, 0.7, 0.2, 1] }}
                className="grid grid-rows-[1fr_auto]"
              >
                {/* Preview */}
                <div className="relative h-[280px] md:h-[360px] overflow-hidden">
                  <ProjectPreview key={p.kind} kind={p.kind} />
                </div>

                {/* Meta strip */}
                <div className="p-6 md:p-8 border-t hairline">
                  <div className="flex items-baseline justify-between gap-4 mb-3">
                    <motion.h3
                      initial={{ y: 16, opacity: 0 }}
                      animate={{ y: 0, opacity: 1 }}
                      transition={{ delay: 0.15, duration: 0.6 }}
                      className="text-3xl md:text-5xl font-display font-medium tracking-tight"
                    >
                      {p.name}
                    </motion.h3>
                    <motion.a
                      href={p.href} target="_blank" rel="noreferrer"
                      whileHover={{ rotate: 0, scale: 1.08 }}
                      className="grid place-items-center w-12 h-12 rounded-full shrink-0 -rotate-12"
                      style={{ background: 'var(--accent)', color: '#fff' }}
                      aria-label={`Visit ${p.name}`}
                    >
                      <I.ArrowUpRight size={18} />
                    </motion.a>
                  </div>
                  <motion.p
                    initial={{ y: 12, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    transition={{ delay: 0.22, duration: 0.6 }}
                    className="font-display text-lg md:text-xl mb-3"
                    style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', color: 'var(--accent)' }}
                  >
                    "{p.tagline}"
                  </motion.p>
                  <motion.p
                    initial={{ y: 10, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    transition={{ delay: 0.28, duration: 0.6 }}
                    className="text-sm md:text-base leading-relaxed max-w-2xl"
                    style={{ color: 'var(--fg-muted)', textWrap: 'pretty' }}
                  >{p.desc}</motion.p>

                  {/* metrics */}
                  <div className="mt-6 grid grid-cols-3 gap-px" style={{ background: 'var(--line)' }}>
                    {p.metrics.map((m, i) => (
                      <motion.div
                        key={m.l}
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.35 + i * 0.06 }}
                        className="p-4"
                        style={{ background: 'var(--bg-elev)' }}
                      >
                        <div className="font-display text-xl md:text-2xl font-medium">{m.v}</div>
                        <div className="font-mono text-[10px] uppercase tracking-[0.18em] mt-1" style={{ color: 'var(--fg-dim)' }}>{m.l}</div>
                      </motion.div>
                    ))}
                  </div>

                  {/* stack */}
                  <div className="mt-5 flex flex-wrap gap-1.5">
                    {p.stack.map((s, i) => (
                      <motion.span
                        key={s}
                        initial={{ opacity: 0, scale: 0.9 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ delay: 0.5 + i * 0.04 }}
                        className="px-2.5 py-1 rounded-md font-mono text-[10px]"
                        style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', color: 'var(--fg-muted)' }}
                      >{s}</motion.span>
                    ))}
                  </div>
                </div>
              </motion.div>
            </AnimatePresence>
          </div>
        </div>
      </motion.div>
    </Section>
  );
};

window.Projects = Projects;
