// V3: TRAIL — a slow-scroll editorial with a glowing snail trail that draws itself between sections.

const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

const TrailPath = () => {
  // SVG trail that spans the full scroll length, drawing as you scroll.
  const pathRef = useRefT(null);
  const svgRef = useRefT(null);
  const [len, setLen] = useStateT(0);
  const [offset, setOffset] = useStateT(0);

  useEffectT(() => {
    const el = pathRef.current;
    if (!el) return;
    const L = el.getTotalLength();
    setLen(L);
    setOffset(L);

    const onScroll = () => {
      const doc = document.documentElement;
      const max = doc.scrollHeight - window.innerHeight;
      const p = Math.max(0, Math.min(1, window.scrollY / Math.max(max, 1)));
      setOffset(L * (1 - p));
    };
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <svg ref={svgRef} viewBox="0 0 1000 5000" preserveAspectRatio="none" style={{
      position: 'absolute', top: 0, left: 0, width: '100%', height: '100%',
      pointerEvents: 'none', zIndex: 1, opacity: 0.6,
    }}>
      <defs>
        <linearGradient id="trailGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--cyan)"/>
          <stop offset="50%" stopColor="var(--magenta)"/>
          <stop offset="100%" stopColor="var(--cyan)"/>
        </linearGradient>
        <filter id="glow">
          <feGaussianBlur stdDeviation="4" result="b"/>
          <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
      </defs>
      <path
        ref={pathRef}
        d="M 500 40 C 200 200, 800 400, 500 600 S 100 900, 500 1150 S 900 1400, 400 1700 S 100 2000, 500 2300 S 900 2600, 300 2900 S 800 3200, 500 3500 S 100 3800, 500 4100 S 900 4400, 500 4700 L 500 4980"
        stroke="url(#trailGrad)"
        strokeWidth="2"
        fill="none"
        strokeDasharray={len}
        strokeDashoffset={offset}
        strokeLinecap="round"
        filter="url(#glow)"
      />
    </svg>
  );
};

const Stanza = ({ number, kicker, children, align='left' }) => (
  <section style={{
    position: 'relative', zIndex: 2, minHeight: '100dvh', display: 'flex',
    alignItems: 'center', justifyContent: align === 'right' ? 'flex-end' : 'flex-start',
    padding: '80px clamp(24px, 8vw, 140px)',
  }}>
    <div style={{ maxWidth: 720, textAlign: align }}>
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.3em', color: 'var(--cyan)',
        textTransform: 'uppercase', marginBottom: 32,
        display: 'flex', alignItems: 'center', gap: 12,
        justifyContent: align === 'right' ? 'flex-end' : 'flex-start',
      }}>
        <span style={{ width: 30, height: 1, background: 'var(--cyan)' }} />
        {String(number).padStart(2,'0')} · {kicker}
      </div>
      {children}
    </div>
  </section>
);

const BigLine = ({ children }) => (
  <h2 style={{
    fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 400,
    fontSize: 'clamp(44px, 6.5vw, 104px)', lineHeight: 1.02, letterSpacing: '-0.02em',
    margin: 0, color: 'var(--fg)',
  }}>{children}</h2>
);

const TrailRoot = () => {
  return (
    <div style={{ position: 'relative', overflow: 'hidden' }}>
      <TrailPath />

      {/* Ambient glyph */}
      <div style={{
        position: 'fixed', top: 18, left: 32, zIndex: 40,
        display: 'flex', alignItems: 'center', gap: 10,
        fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.25em', textTransform: 'uppercase',
        color: 'var(--muted)',
      }}>
        <SnailGlyph size={22} stroke="var(--cyan)" />
        <span>Snail<b style={{ color: 'var(--magenta)' }}>3D</b></span>
      </div>

      {/* Hero */}
      <section style={{
        position: 'relative', zIndex: 2, minHeight: '100dvh',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: '80px 40px', textAlign: 'center',
      }}>
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.35em', color: 'var(--cyan)',
          textTransform: 'uppercase', marginBottom: 40,
        }}>
          A slow trail · Built for the Lord
        </div>
        <h1 style={{
          fontFamily: 'var(--serif)', fontWeight: 400,
          fontSize: 'clamp(70px, 13vw, 200px)', lineHeight: 0.88, letterSpacing: '-0.03em',
          margin: 0, color: 'var(--fg)', maxWidth: 1100,
        }}>
          Slow is <span style={{ fontStyle: 'italic', color: 'var(--cyan)' }}>smooth.</span><br/>
          Smooth is <span style={{ fontStyle: 'italic', color: 'var(--magenta)' }}>faithful.</span>
        </h1>
        <p style={{
          maxWidth: 540, marginTop: 40, fontSize: 18, lineHeight: 1.55,
          color: 'var(--muted)',
        }}>
          The archive of a maker, builder, father and evangelist —
          3D prints, agentic code, and a life trying to stay pointed at the Maker.
        </p>
        <div style={{ marginTop: 48, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.3em', color: 'var(--muted)', textTransform: 'uppercase' }}>
          ↓ follow the trail
        </div>
      </section>

      <Stanza number={1} kicker="Who">
        <BigLine>
          Maker of <span style={{ color: 'var(--cyan)' }}>useful things,</span><br/>
          apprentice in <span style={{ color: 'var(--magenta)' }}>everything else.</span>
        </BigLine>
        <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--muted)', marginTop: 32, maxWidth: 560 }}>
          I'm Snail3D — a 3D printer, designer, coder, husband and father. I build small and ship often,
          and I try to keep the Lord at the center of all of it. This page is the trail behind me.
        </p>
      </Stanza>

      <Stanza number={2} kicker="Builds" align="right">
        <BigLine>
          Slow <span style={{ color: 'var(--cyan)' }}>layers.</span><br/>
          Honest <span style={{ color: 'var(--magenta)' }}>prototypes.</span>
        </BigLine>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 2, marginTop: 40 }}>
          {window.PROJECTS.slice(0, 6).map((p, i) => (
            <a key={p.name} href={p.url} target={p.url.startsWith('/') ? '_self' : '_blank'} rel="noreferrer" style={{
              padding: '20px 18px', borderTop: '1px solid var(--line)', textAlign: 'left',
              textDecoration: 'none', color: 'var(--fg)', transition: 'background .2s',
            }} onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.03)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--cyan)', letterSpacing: '0.18em', marginBottom: 6 }}>0{i+1}</div>
              <div style={{ fontSize: 20, fontWeight: 500, fontFamily: 'var(--serif)', fontStyle: 'italic' }}>{p.name}</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.5, marginTop: 6 }}>{p.desc}</div>
            </a>
          ))}
        </div>
      </Stanza>

      <Stanza number={3} kicker="Transmissions">
        <BigLine>
          Words, rambles, <span style={{ color: 'var(--cyan)' }}>demos.</span>
        </BigLine>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 14, marginTop: 40 }}>
          {window.VIDEOS.slice(0, 4).map(v => (
            <a key={v.id} href={v.url} target="_blank" rel="noreferrer" style={{ textDecoration: 'none', color: 'var(--fg)' }}>
              <div style={{ aspectRatio: '16/9', borderRadius: 4, overflow: 'hidden', position: 'relative', background: '#000' }}>
                <img src={`https://i.ytimg.com/vi/${v.id}/hqdefault.jpg`} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: 0.75 }} />
                <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,20,0.85), transparent 50%)' }} />
                <div style={{ position: 'absolute', bottom: 10, left: 12, right: 12, fontSize: 12, fontWeight: 500, lineHeight: 1.35 }}>{v.title}</div>
              </div>
            </a>
          ))}
        </div>
      </Stanza>

      <Stanza number={4} kicker="Arcade · AI Benchmark" align="right">
        <BigLine>
          Games as a <span style={{ color: 'var(--magenta)' }}>benchmark.</span>
        </BigLine>
        <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--muted)', marginTop: 20, maxWidth: 520, marginLeft: 'auto' }}>
          Each cartridge is the same prompt handed to a different coding agent. As models get better,
          the arcade grows — a living scoreboard of AI progress at making something <em>actually fun to play</em>.
        </p>
        <div style={{ marginTop: 28, display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
          {window.GAMES.map(g => (
            <a key={g.name} href={g.url} target="_blank" rel="noreferrer" style={{
              padding: '8px 14px', border: '1px solid var(--line)', borderRadius: 999,
              fontSize: 12, textDecoration: 'none', color: 'var(--fg)', fontFamily: 'var(--mono)',
              letterSpacing: '0.08em',
            }}>{g.name}</a>
          ))}
        </div>
      </Stanza>

      <Stanza number={5} kicker="Faith">
        <BigLine>
          The <span style={{ color: 'var(--cyan)' }}>work</span> is <span style={{ color: 'var(--magenta)' }}>worship.</span>
        </BigLine>
        <div style={{ marginTop: 40, borderLeft: '2px solid var(--cyan)', paddingLeft: 24 }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.25em', color: 'var(--cyan)', textTransform: 'uppercase', marginBottom: 16 }}>
            Today's reading
          </div>
          <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 32, lineHeight: 1.2, color: 'var(--fg)' }}>
            "{window.DEVOTIONALS[0].quote}"
          </div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--magenta)', letterSpacing: '0.15em', marginTop: 14 }}>
            — {window.DEVOTIONALS[0].verse}
          </div>
          <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--muted)', marginTop: 20, maxWidth: 580 }}>
            {window.DEVOTIONALS[0].ref}
          </p>
        </div>
      </Stanza>

      <Stanza number={6} kicker="Transmit" align="right">
        <BigLine>
          Come say <span style={{ color: 'var(--cyan)' }}>hi.</span>
        </BigLine>
        <p style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--muted)', marginTop: 32, maxWidth: 540, marginLeft: 'auto' }}>
          Collaboration, commission, prayer request, or just want to nerd out about local LLMs and layer heights —
          jump in the Discord. That's where the community lives.
        </p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 32, flexWrap: 'wrap' }}>
          <a href={LINKS.discord} target="_blank" style={{
            padding: '14px 24px', borderRadius: 999, background: 'var(--cyan)', color: 'var(--bg)',
            textDecoration: 'none', fontWeight: 600,
          }}>Join the Discord →</a>
          <a href={LINKS.github} target="_blank" style={{
            padding: '14px 22px', borderRadius: 999, border: '1px solid var(--line)',
            color: 'var(--fg)', textDecoration: 'none',
          }}>GitHub</a>
          <a href={LINKS.youtube} target="_blank" style={{
            padding: '14px 22px', borderRadius: 999, border: '1px solid var(--line)',
            color: 'var(--fg)', textDecoration: 'none',
          }}>YouTube</a>
        </div>
      </Stanza>

      <footer style={{
        position: 'relative', zIndex: 2, padding: '80px 40px 120px',
        textAlign: 'center', borderTop: '1px solid var(--line)',
      }}>
        <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 32, color: 'var(--fg)', marginBottom: 12 }}>
          Soli Deo Gloria.
        </div>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.3em', color: 'var(--muted)', textTransform: 'uppercase' }}>
          © {new Date().getFullYear()} Snail3D · Trail v3
        </div>
      </footer>

      <ScriptureTicker />
    </div>
  );
};

window.TrailRoot = TrailRoot;
