// V1: SHELL — a literal 3D shell spiral drives the layout.
// Each section is a "chamber" of the spiral; scroll pulls deeper in.

const { useState, useEffect, useRef } = React;

const ShellSpiral = () => {
  const [t, setT] = useState(0);
  useEffect(() => {
    let raf, last = performance.now();
    const loop = (now) => {
      const mo = (+(document.body.dataset.motion ?? 80)) / 100;
      const dt = (now - last) / 1000; last = now;
      setT(v => v + dt * 0.15 * mo);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Build a log spiral
  const pts = [];
  const turns = 4.2;
  const steps = 220;
  for (let i = 0; i <= steps; i++) {
    const p = i / steps;
    const angle = p * Math.PI * 2 * turns + t;
    const r = 6 + Math.pow(p, 1.35) * 300;
    const x = 400 + Math.cos(angle) * r;
    const y = 400 + Math.sin(angle) * r;
    pts.push(`${x.toFixed(2)},${y.toFixed(2)}`);
  }

  return (
    <svg viewBox="0 0 800 800" style={{ width: '100%', height: '100%', overflow: 'visible' }}>
      <defs>
        <radialGradient id="shellGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--cyan)" stopOpacity="0.35"/>
          <stop offset="70%" stopColor="var(--cyan)" stopOpacity="0"/>
        </radialGradient>
        <linearGradient id="shellStroke" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="var(--cyan)"/>
          <stop offset="100%" stopColor="var(--magenta)"/>
        </linearGradient>
      </defs>
      <circle cx="400" cy="400" r="340" fill="url(#shellGlow)" />
      {/* Chambers — concentric arcs */}
      {[0,1,2,3,4].map(i => {
        const r = 40 + i * 55;
        return <circle key={i} cx="400" cy="400" r={r} fill="none" stroke="url(#shellStroke)" strokeWidth={0.8} opacity={0.15 + i * 0.08} />;
      })}
      <polyline points={pts.join(' ')} fill="none" stroke="url(#shellStroke)" strokeWidth="1.4" opacity="0.85" />
      {/* Ticks */}
      {Array.from({length: 36}).map((_, i) => {
        const a = (i / 36) * Math.PI * 2 + t * 0.5;
        const x1 = 400 + Math.cos(a) * 345, y1 = 400 + Math.sin(a) * 345;
        const x2 = 400 + Math.cos(a) * 360, y2 = 400 + Math.sin(a) * 360;
        return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--cyan)" strokeWidth="0.6" opacity="0.45" />;
      })}
      {/* Center eye */}
      <circle cx="400" cy="400" r="3" fill="var(--magenta)" />
      <circle cx="400" cy="400" r="10" fill="none" stroke="var(--cyan)" strokeWidth="0.8" opacity="0.6" />
    </svg>
  );
};

const ChamberNav = ({ active, onGo }) => {
  const items = [
    { id: 'hero',    label: 'Entry' },
    { id: 'about',   label: 'About' },
    { id: 'builds',  label: 'Builds' },
    { id: 'arcade',  label: 'Arcade' },
    { id: 'videos',  label: 'Videos' },
    { id: 'faith',   label: 'Faith' },
    { id: 'contact', label: 'Contact' },
  ];
  return (
    <nav className="chamber-nav" style={{
      position: 'fixed', left: 24, top: '50%', transform: 'translateY(-50%)', zIndex: 60,
      display: 'flex', flexDirection: 'column', gap: 2, fontFamily: 'var(--mono)', fontSize: 10,
      letterSpacing: '0.14em', textTransform: 'uppercase',
    }}>
      {items.map((it, i) => (
        <a key={it.id} href={`#${it.id}`} onClick={() => onGo?.(it.id)} style={{
          display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0',
          color: active === it.id ? 'var(--cyan)' : 'var(--muted)', textDecoration: 'none', transition: 'color .3s',
        }}>
          <span style={{ width: 20, textAlign: 'right', opacity: .6 }}>{String(i+1).padStart(2,'0')}</span>
          <span style={{ width: 1, height: 14, background: active === it.id ? 'var(--cyan)' : 'var(--line)' }} />
          <span>{it.label}</span>
        </a>
      ))}
    </nav>
  );
};

const ShellHero = () => {
  return (
    <section id="hero" className="shell-hero" style={{
      position: 'relative', minHeight: '100dvh', display: 'grid', gridTemplateColumns: '1fr 1fr',
      alignItems: 'center', padding: '120px 80px 80px', gap: 40,
    }}>
      <div style={{ position: 'relative', zIndex: 10 }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 10, padding: '6px 14px',
          borderRadius: 999, background: 'rgba(0,240,255,0.06)', border: '1px solid var(--line)',
          fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--cyan)', marginBottom: 32,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--cyan)', animation: 'blink 1.8s infinite' }} />
          Shell v3 · Evangelism Mode
        </div>
        <h1 style={{
          fontFamily: 'var(--sans)', fontSize: 'clamp(52px, 7.2vw, 120px)', fontWeight: 700,
          lineHeight: 0.95, letterSpacing: '-0.03em', margin: 0, color: 'var(--fg)',
        }}>
          Build<br/>
          <span style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 400, color: 'var(--cyan)' }}>slowly,</span><br/>
          ship<br/>
          <span style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 400, color: 'var(--magenta)' }}>faithfully.</span>
        </h1>
        <p style={{ maxWidth: 460, marginTop: 28, fontSize: 17, lineHeight: 1.55, color: 'var(--muted)' }}>
          Snail3D is a maker, builder, father and evangelist. 3D printing, agentic code, and
          work for the Lord — kept at the center of every chamber we build.
        </p>
        <div style={{ display: 'flex', gap: 12, marginTop: 32, flexWrap: 'wrap' }}>
          <a href="#builds" style={btnPrimary}>Enter the shell →</a>
          <a href="/gita/" style={btnGhost}>Meet GITA</a>
        </div>
      </div>
      <div style={{ position: 'relative', height: '80vh', minHeight: 520 }}>
        <ShellSpiral />
        <div style={{
          position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
          fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.3em', color: 'var(--muted)',
          textTransform: 'uppercase', pointerEvents: 'none', marginTop: 160,
        }}>
          Scroll inward
        </div>
      </div>
    </section>
  );
};

const ShellSection = ({ id, kicker, title, children }) => (
  <section id={id} className="shell-section" style={{ padding: '140px 80px', maxWidth: 1400, margin: '0 auto', position: 'relative' }}>
    <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 60, alignItems: 'start' }}>
      <div style={{ position: 'sticky', top: 120 }}>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.2em', color: 'var(--cyan)', textTransform: 'uppercase', marginBottom: 8 }}>{kicker}</div>
        <h2 style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 400, fontSize: 44, lineHeight: 1, margin: 0, color: 'var(--fg)' }}>{title}</h2>
      </div>
      <div>{children}</div>
    </div>
  </section>
);

const ProjectCard = ({ p }) => (
  <a href={p.url} target={p.url.startsWith('/') ? '_self' : '_blank'} rel="noreferrer" style={{
    display: 'block', padding: 24, border: '1px solid var(--line)', borderRadius: 18,
    background: p.featured ? 'linear-gradient(135deg, rgba(0,240,255,0.06), rgba(255,0,255,0.03))' : 'rgba(255,255,255,0.02)',
    textDecoration: 'none', color: 'var(--fg)', transition: 'all .3s',
    minHeight: 170, display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
  }}
  onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--cyan)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
  onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.transform = 'translateY(0)'; }}>
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: 10 }}>
        <h3 style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em' }}>{p.name}</h3>
        {p.featured && <span style={{ fontSize: 9, fontFamily: 'var(--mono)', color: 'var(--cyan)', letterSpacing: '0.2em' }}>◆ FEATURED</span>}
      </div>
      <p style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--muted)', margin: 0 }}>{p.desc}</p>
    </div>
    <div style={{ fontSize: 10, fontFamily: 'var(--mono)', letterSpacing: '0.15em', color: 'var(--magenta)', textTransform: 'uppercase', marginTop: 16 }}>{p.lang} →</div>
  </a>
);

const FaithPanel = () => {
  const [i, setI] = useState(0);
  const d = window.DEVOTIONALS[i];
  return (
    <div style={{
      border: '1px solid var(--line)', borderRadius: 22, padding: 40,
      background: 'radial-gradient(ellipse at top left, rgba(0,240,255,0.04), transparent 60%)',
    }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.25em', color: 'var(--cyan)', textTransform: 'uppercase', marginBottom: 24 }}>
        Daily Chamber · {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
      </div>
      <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 36, lineHeight: 1.15, color: 'var(--fg)', marginBottom: 20 }}>
        "{d.quote}"
      </div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.15em', color: 'var(--magenta)', marginBottom: 28 }}>— {d.verse}</div>
      <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--muted)', margin: 0, maxWidth: 580 }}>{d.ref}</p>
      <div style={{ display: 'flex', gap: 8, marginTop: 32 }}>
        {window.DEVOTIONALS.map((_, j) => (
          <button key={j} onClick={() => setI(j)} style={{
            width: j === i ? 28 : 8, height: 8, borderRadius: 8, border: 0,
            background: j === i ? 'var(--cyan)' : 'var(--line)', cursor: 'pointer', transition: 'all .3s',
          }} aria-label={`Devotional ${j+1}`} />
        ))}
      </div>
    </div>
  );
};

const VideoStrip = () => (
  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14 }}>
    {window.VIDEOS.slice(0, 6).map(v => (
      <a key={v.id} href={v.url} target="_blank" rel="noreferrer" style={{
        display: 'block', borderRadius: 14, overflow: 'hidden', border: '1px solid var(--line)',
        textDecoration: 'none', color: 'var(--fg)', background: 'rgba(255,255,255,0.02)',
      }}>
        <div style={{ aspectRatio: '16/9', position: 'relative', overflow: 'hidden', background: '#000' }}>
          <img src={`https://i.ytimg.com/vi/${v.id}/hqdefault.jpg`} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: 0.75 }} />
          {v.new && <div style={{ position: 'absolute', top: 10, left: 10, background: 'var(--magenta)', color: 'var(--bg)', fontSize: 9, fontFamily: 'var(--mono)', padding: '3px 8px', borderRadius: 999, letterSpacing: '0.15em', fontWeight: 700 }}>NEW</div>}
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,20,0.8), transparent 50%)' }} />
        </div>
        <div style={{ padding: 14, fontSize: 13, lineHeight: 1.35, fontWeight: 500 }}>{v.title}</div>
      </a>
    ))}
  </div>
);

const ContactBlock = () => (
  <div style={{ border: '1px solid var(--line)', borderRadius: 20, padding: 36 }}>
    <p style={{ fontSize: 18, lineHeight: 1.5, color: 'var(--muted)', marginTop: 0 }}>
      Got a build to share, a collaboration idea, or a prayer request? Come say hi in the Discord —
      the chamber's open.
    </p>
    <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 24 }}>
      <a href={LINKS.discord} target="_blank" style={btnPrimary}>Join the Discord →</a>
      <a href={LINKS.github} target="_blank" style={btnGhost}>GitHub</a>
      <a href={LINKS.youtube} target="_blank" style={btnGhost}>YouTube</a>
    </div>
  </div>
);

const btnPrimary = {
  display: 'inline-flex', alignItems: 'center', gap: 10, padding: '14px 22px',
  background: 'var(--cyan)', color: 'var(--bg)', borderRadius: 999, textDecoration: 'none',
  fontWeight: 600, fontSize: 14, letterSpacing: '0.02em', transition: 'transform .2s',
};
const btnGhost = {
  display: 'inline-flex', alignItems: 'center', gap: 10, padding: '14px 22px',
  background: 'rgba(255,255,255,0.04)', color: 'var(--fg)', borderRadius: 999, textDecoration: 'none',
  fontWeight: 500, fontSize: 14, border: '1px solid var(--line)',
};

const ShellRoot = () => {
  const [active, setActive] = useState('hero');
  useEffect(() => {
    const onScroll = () => {
      const ids = ['hero','about','builds','arcade','videos','faith','contact'];
      let cur = 'hero';
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top < window.innerHeight * 0.45) cur = id;
      }
      setActive(cur);
    };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <>
      <ChamberNav active={active} onGo={setActive} />
      <header style={{ position: 'fixed', top: 18, right: 24, zIndex: 60, display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--muted)' }}>
        <SnailGlyph size={22} stroke="var(--cyan)" />
        <span>Snail<b style={{ color: 'var(--magenta)', fontWeight: 700 }}>3D</b></span>
      </header>
      <ShellHero />
      <ShellSection id="about" kicker="Chamber 01" title="What I'm about.">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 24 }}>
          {[
            { h: "3D Printing",     p: "Practical prints, public designs, and open MakerWorld files." },
            { h: "Agentic Code",    p: "Local-first AI tools, voice dashboards, honest prototypes." },
            { h: "Faith & Family",  p: "The Lord first, family close, work for His glory." },
          ].map((b, i) => (
            <div key={i} style={{ padding: '24px 0', borderTop: '1px solid var(--line)' }}>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--cyan)', letterSpacing: '0.2em', marginBottom: 10 }}>0{i+1}</div>
              <h3 style={{ fontSize: 22, margin: '0 0 10px', fontWeight: 600 }}>{b.h}</h3>
              <p style={{ color: 'var(--muted)', fontSize: 14, lineHeight: 1.55, margin: 0 }}>{b.p}</p>
            </div>
          ))}
        </div>
      </ShellSection>
      <ShellSection id="builds" kicker="Chamber 02" title="Featured builds.">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
          {window.PROJECTS.slice(0, 9).map(p => <ProjectCard key={p.name} p={p} />)}
        </div>
      </ShellSection>
      <ShellSection id="arcade" kicker="Chamber 03" title="Arcade benchmark.">
        <p style={{ color: 'var(--muted)', fontSize: 15, margin: '0 0 24px', maxWidth: 620 }}>
          Same prompt, different coding agents. The Snail Arcade is a living scoreboard of how well
          AI can build something actually fun to play — updated as the frontier moves.
        </p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 10 }}>
          {window.GAMES.map(g => (
            <a key={g.name} href={g.url} target="_blank" rel="noreferrer" style={{
              padding: 16, border: '1px solid var(--line)', borderRadius: 12, textDecoration: 'none',
              color: 'var(--fg)', background: 'rgba(255,0,255,0.03)', transition: 'border-color .2s',
            }} onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--magenta)'}
              onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line)'}>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>{g.name}</div>
              <div style={{ fontSize: 11, color: 'var(--muted)', lineHeight: 1.4 }}>{g.desc}</div>
              <div style={{ fontSize: 9, fontFamily: 'var(--mono)', color: 'var(--magenta)', letterSpacing: '0.2em', marginTop: 10, textTransform: 'uppercase' }}>{g.tag}</div>
            </a>
          ))}
        </div>
      </ShellSection>
      <ShellSection id="videos" kicker="Chamber 04" title="Recent transmissions.">
        <VideoStrip />
      </ShellSection>
      <ShellSection id="faith" kicker="Chamber 05" title="Faith at the center.">
        <FaithPanel />
      </ShellSection>
      <ShellSection id="contact" kicker="Chamber 06" title="Transmit.">
        <ContactBlock />
      </ShellSection>
      <footer style={{ padding: '40px 80px', borderTop: '1px solid var(--line)', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', display: 'flex', justifyContent: 'space-between', letterSpacing: '0.15em', textTransform: 'uppercase' }}>
        <span>© {new Date().getFullYear()} Snail3D · Soli Deo Gloria</span>
        <span>Built slowly. Shipped faithfully.</span>
      </footer>
      <ScriptureTicker />
    </>
  );
};

window.ShellRoot = ShellRoot;
