/* Pedro Cid — personal site */
const { useState, useEffect, useRef } = React;

// ====================== Typewriter hook ======================
function useTypewriter(text, speed = 35, startDelay = 0, enabled = true) {
  const [out, setOut] = useState('');
  useEffect(() => {
    if (!enabled) {setOut(text);return;}
    setOut('');
    let i = 0;
    let cancel = false;
    const start = setTimeout(() => {
      const tick = () => {
        if (cancel) return;
        i++;
        setOut(text.slice(0, i));
        if (i < text.length) setTimeout(tick, speed);
      };
      tick();
    }, startDelay);
    return () => {cancel = true;clearTimeout(start);};
  }, [text, speed, startDelay, enabled]);
  return out;
}

// ====================== Parallax cursor hook ======================
function useCursor() {
  const [p, setP] = useState({ x: 0.5, y: 0.5 });
  useEffect(() => {
    const onMove = (e) => setP({ x: e.clientX / window.innerWidth, y: e.clientY / window.innerHeight });
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  return p;
}

// ====================== Scroll progress hook ======================
function useScroll() {
  const [s, setS] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setS(max > 0 ? h.scrollTop / max : 0);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return s;
}

// ====================== Section reveal hook ======================
function useReveal(ref, threshold = 0.15) {
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {setSeen(true);io.disconnect();}
    }, { threshold });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [ref, threshold]);
  return seen;
}

// ====================== Hero ======================
function Hero({ tweaks, scrollP }) {
  const cursor = useCursor();
  const namedText = 'Pedro Cid';
  const subText = "I'm a programmer, a founder and a student of applied mathematics.";;
  const tagText = '> initiating sequence';

  const tag = useTypewriter(tagText, 38, 200);
  const showName = tag.length === tagText.length;
  const name = useTypewriter(namedText, 90, 0, showName);
  const showSub = name.length === namedText.length;
  const sub = useTypewriter(subText, 22, 200, showSub);

  // Parallax offsets — px translate
  const dx = (cursor.x - 0.5) * 30;
  const dy = (cursor.y - 0.5) * 24;

  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="hero-grid" style={{ opacity: "1.63", width: "1112px" }}>
        <div className="hero-statue" style={{ transform: `translate3d(${dx * -0.6}px, ${dy * -0.4}px, 0)` }}>
          <img src="assets/perseus-banner.png" alt="" draggable="false" />
          <div className="statue-vignette" />
        </div>

        <div className="hero-text">
          <div className="kicker mono" style={{ fontSize: "0px", width: "182px" }}>{tag || '\u00A0'}</div>
          <h1 className="display">
            <span className="name-line">{name}</span>
            <span className="caret-h1" style={{ opacity: showName && name.length < namedText.length ? 1 : 0 }}></span>
          </h1>
          <p className="hero-sub mono">{sub}</p>
          <div className="hero-meta mono" style={{ width: "421px" }}>
            <span>SÃO PAULO · BR</span>
            <span className="dot">·</span>
            <span>MMXXVI</span>
            <span className="dot">·</span>
            <a href="https://x.com/Pedrocidp" target="_blank" rel="noreferrer">x</a>
            <a href="https://github.com/PedroCidro" target="_blank" rel="noreferrer">github</a>
            <a href="https://www.linkedin.com/in/pedrocid-p/" target="_blank" rel="noreferrer">linkedin</a>
          </div>
        </div>

        <div className="hero-geom-wrap" style={{ transform: `translate3d(${dx * 0.35}px, ${dy * 0.25}px, 0)` }}>
          <HeroGeometry progress={Math.min(1, scrollP * 3)} accent={tweaks.accent} />
        </div>
      </div>

      <div className="scroll-cue mono">
        <span>scroll</span>
        <svg viewBox="0 0 12 40" width="10" height="32"><line x1="6" y1="2" x2="6" y2="38" stroke="currentColor" strokeWidth="0.6" /><path d="M2,32 L6,38 L10,32" fill="none" stroke="currentColor" strokeWidth="0.6" /></svg>
      </div>
    </section>);

}

// ====================== About ======================
function About({ tweaks }) {
  const ref = useRef(null);
  const seen = useReveal(ref);
  return (
    <section ref={ref} className={`section about ${seen ? 'seen' : ''}`} data-screen-label="02 About">
      <div className="section-head">
        <div className="section-num mono">§ I</div>
        <OrbitMark accent={tweaks.accent} variant={1} />
        <h2 className="section-title">On the maker</h2>
      </div>
      <div className="about-body">
        <div className="about-img">
          <div className="frame-mark tl" /><div className="frame-mark tr" /><div className="frame-mark bl" /><div className="frame-mark br" />
          <img src="assets/perseus-full.png" alt="" />
        </div>
        <div className="about-text">
          <p className="lede">
            <span className="dropcap">I</span>am Pedro, I am a programmer and founder, I studied applied mathematics & computing at the University of São Paulo, and I work for a future where AI will help students actually absorb the essence of the things that they study in class.
          

          </p>
          <p className="mono small">
            <span className="dim">// what i actually do —</span><br />
            I focus my life in building AI products to teach the regular school subjects to people who don't understand why they are studying it, and my purpose is to help them finding the meaning of this subjects without putting them through the hell that rote memorization and exam prep is <em></em> ·
            I'm building <em></em>, a Duolingo for calculus · I read more than is reasonable.
          </p>
          <ul className="kvs mono small">
            <li><span className="dim">field</span><span>applied mathematics &amp; computing</span></li>
            <li><span className="dim">institute</span><span>universidade de são paulo</span></li>
            <li><span className="dim">currently</span><span>building, studying, writing</span></li>
            <li><span className="dim">tools</span><span>Notebooks, Cards, AI and my Brain</span></li>
          </ul>
        </div>
      </div>
    </section>);

}

// ====================== Now ======================
function Now({ tweaks }) {
  const ref = useRef(null);
  const seen = useReveal(ref);
  const items = [
  { t: 'Building', b: "I'm building Centauri: the EdTech startup that help people understanding the meaning and significance of  \"boring\" things" },
  { t: 'Lifting', b: "I'm making my body get used to squatting 220/3, benching 140/3 and dead-lifting 260/3." },
  { t: 'Reading', b: "I'm reading LOTR and Cycles of Time (Roger Penrose)" },
  { t: 'Studying', b: "I'm studying the EdTech industry and the art of teaching." }];

  return (
    <section ref={ref} className={`section now ${seen ? 'seen' : ''}`} data-screen-label="03 Now">
      <div className="section-head">
        <div className="section-num mono">§ II</div>
        <OrbitMark accent={tweaks.accent} variant={0} />
        <h2 className="section-title">Now</h2>
        <div className="section-meta mono">updated · {new Date().toLocaleDateString('en-CA')}</div>
      </div>
      <div className="now-grid">
        {items.map((it, i) =>
        <div key={i} className="now-card" style={{ transitionDelay: `${i * 80}ms` }}>
            <div className="now-mark"><OrbitMark accent={tweaks.accent} variant={(i + 2) % 4} /></div>
            <div className="now-t mono">{String(i + 1).padStart(2, '0')} · {it.t}</div>
            <div className="now-b">{it.b}</div>
          </div>
        )}
      </div>
    </section>);

}

// ====================== Work ======================
function Work({ tweaks }) {
  const ref = useRef(null);
  const seen = useReveal(ref);
  const [hovered, setHovered] = useState(null);

  const projects = [
  {
    id: 'centauri',
    n: '01',
    title: 'Centauri',
    kind: 'Edtech · Founder',
    year: '2025—',
    blurb: "I'm building Justmathing — a Duolingo for calculus. Bite-sized lessons, real fluency, no PDFs.",
    tags: ['edtech', 'founder', 'product'],
    x: 18, y: 30
  },
  {
    id: 'justmathing',
    n: '02',
    title: 'Justmathing',
    kind: 'Product · Calculus',
    year: '2026',
    blurb: "I'm studying applied mathematics & computing at USP. Half developer, half mathematician,",
    tags: ['calculus', 'learning', 'product'],
    x: 62, y: 18
  },
  {
    id: 'usp',
    n: '03',
    title: 'USP',
    kind: 'Studying · BMACC',
    year: '2023—',
    blurb: "I studied applied mathematics & computing at USP. Half developer, half mathematician,",
    tags: ['analysis', '\n', '\n'],
    x: 80, y: 64
  }];


  return (
    <section ref={ref} className={`section work ${seen ? 'seen' : ''}`} data-screen-label="04 Work">
      <div className="section-head">
        <div className="section-num mono">§ III</div>
        <OrbitMark accent={tweaks.accent} variant={3} />
        <h2 className="section-title">Constellation of work</h2>
        <div className="section-meta mono">hover to draw lines</div>
      </div>

      <div className="work-wrap">
        <svg className="constellation" viewBox="0 0 100 80" preserveAspectRatio="none">
          {projects.map((p, i) => projects.slice(i + 1).map((q, j) => {
            const active = hovered != null && (hovered === p.id || hovered === q.id);
            return (
              <line key={`${p.id}-${q.id}`}
              x1={p.x} y1={p.y} x2={q.x} y2={q.y}
              stroke={tweaks.accent}
              strokeWidth={active ? 0.18 : 0.08}
              strokeDasharray={active ? '0' : '0.4 0.6'}
              opacity={active ? 0.9 : 0.25}
              style={{ transition: 'all .4s' }} />);


          }))}
          {projects.map((p) =>
          <g key={p.id}>
              <circle cx={p.x} cy={p.y} r={hovered === p.id ? 1.4 : 0.9} fill={tweaks.accent} style={{ transition: 'all .3s' }} />
              <circle cx={p.x} cy={p.y} r="3" fill="none" stroke={tweaks.accent} strokeWidth="0.1" opacity={hovered === p.id ? 0.9 : 0.3} style={{ transition: 'all .3s' }} />
            </g>
          )}
        </svg>

        <div className="projects">
          {projects.map((p) =>
          <a key={p.id}
          className={`project ${hovered === p.id ? 'on' : ''}`}
          onMouseEnter={() => setHovered(p.id)}
          onMouseLeave={() => setHovered(null)}
          href={p.id === 'justmathing' ? '#' : '#'}>
            
              <div className="proj-num mono">{p.n}</div>
              <div className="proj-main">
                <div className="proj-row">
                  <h3 className="proj-title">{p.title}</h3>
                  <span className="proj-year mono">{p.year}</span>
                </div>
                <div className="proj-kind mono dim">{p.kind}</div>
                <p className="proj-blurb">{p.blurb}</p>
                <div className="proj-tags mono">
                  {p.tags.map((t) => <span key={t} className="tag" style={{ opacity: "-2.27", fontWeight: "100", padding: "2px 10px 4px", width: "59px" }}>{t}</span>)}
                </div>
              </div>
              <div className="proj-arrow">→</div>
            </a>
          )}
        </div>
      </div>
    </section>);

}

// ====================== Footer ======================
function Footer({ tweaks }) {
  return (
    <footer className="footer" data-screen-label="05 Footer">
      <div className="footer-row">
        <OrbitMark accent={tweaks.accent} variant={2} />
        <div className="footer-text mono">
          <div>— end of transmission —</div>
          <div className="dim">pedro cid · mmxxvi · sp/br</div>
        </div>
      </div>
      <div className="footer-links mono">
        <a href="https://x.com/Pedrocidp" target="_blank" rel="noreferrer">x ↗</a>
        <a href="https://github.com/PedroCidro" target="_blank" rel="noreferrer">github ↗</a>
        <a href="https://www.linkedin.com/in/pedrocid-p/" target="_blank" rel="noreferrer">linkedin ↗</a>
        <a href="mailto:hello@pedrocid.com">email ↗</a>
      </div>
    </footer>);

}

// ====================== App + Tweaks ======================
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "vibe": "occult",
  "accent": "#c9bd9b",
  "showStarfield": true,
  "grain": true
} /*EDITMODE-END*/;

const VIBE_PRESETS = {
  occult: { accent: '#c9bd9b', bg: '#050505', muted: '#7a715b' },
  scholar: { accent: '#d8c98a', bg: '#0d0a06', muted: '#8a7c5a' }, // warmer parchment
  cybermyst: { accent: '#a8b8d8', bg: '#06080f', muted: '#5a6890' } // cold blue
};

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const scrollP = useScroll();

  // Apply preset → CSS vars
  useEffect(() => {
    const preset = VIBE_PRESETS[tweaks.vibe] || VIBE_PRESETS.occult;
    const accent = tweaks.accent || preset.accent;
    const root = document.documentElement;
    root.style.setProperty('--accent', accent);
    root.style.setProperty('--bg', preset.bg);
    root.style.setProperty('--muted', preset.muted);
    root.dataset.vibe = tweaks.vibe;
  }, [tweaks.vibe, tweaks.accent]);

  // Scroll progress to a CSS var (drives global motion if needed)
  useEffect(() => {
    document.documentElement.style.setProperty('--scrollp', scrollP.toFixed(3));
  }, [scrollP]);

  return (
    <div className={`page ${tweaks.grain ? 'grain' : ''}`}>
      {tweaks.showStarfield && <StarField />}
      <EarthBg accent={tweaks.accent} />
      <div className="vignette" />

      <header className="top mono">
        <div className="brand">Pedro Cid · ⌘</div>
        <nav className="topnav">
          <a href="#about">about</a>
          <a href="#now">now</a>
          <a href="#work">work</a>
        </nav>
        <div className="status">
          <span className="pulse" /> 2026
        </div>
      </header>

      <Hero tweaks={{ ...tweaks }} scrollP={scrollP} />
      <div id="about"><About tweaks={tweaks} /></div>
      <div id="now"><Now tweaks={tweaks} /></div>
      <div id="work"><Work tweaks={tweaks} /></div>
      <Footer tweaks={tweaks} />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Vibe">
          <TweakRadio
            label="Direction"
            value={tweaks.vibe}
            onChange={(v) => {
              const preset = VIBE_PRESETS[v];
              setTweak({ vibe: v, accent: preset.accent });
            }}
            options={[
            { value: 'occult', label: 'Occult' },
            { value: 'scholar', label: 'Scholar' },
            { value: 'cybermyst', label: 'Cyber' }]
            } />
          
          <TweakColor
            label="Accent"
            value={tweaks.accent}
            onChange={(v) => setTweak('accent', v)}
            options={['#c9bd9b', '#d8c98a', '#a8b8d8', '#b89b6f', '#8b6f4e']} />
          
        </TweakSection>
        <TweakSection title="Atmosphere">
          <TweakToggle label="Starfield" value={tweaks.showStarfield} onChange={(v) => setTweak('showStarfield', v)} />
          <TweakToggle label="Film grain" value={tweaks.grain} onChange={(v) => setTweak('grain', v)} />
        </TweakSection>
      </TweaksPanel>
    </div>);

}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);