/* Hero, About, Skills, Projects, Contact components */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ─── Reveal-on-scroll hook ─── */
function useReveal() {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
    }, { threshold: 0.15 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, seen];
}

/* ─── Cursor follower ─── */
function CursorGlow() {
  const ref = useRef(null);
  useEffect(() => {
    const onMove = (e) => {
      if (!ref.current) return;
      ref.current.style.left = e.clientX + 'px';
      ref.current.style.top = e.clientY + 'px';
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  return <div className="cursor-glow" ref={ref} />;
}

/* ─── Top nav ─── */
function Nav({ lang, setLang, t }) {
  const go = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 40, behavior: 'smooth' });
  };
  return (
    <nav className="nav">
      <a className="nav-logo" href="#top" onClick={go('top')}>
        <span className="dot" />
        <span>fc/</span>
      </a>
      <div className="nav-links">
        <a onClick={go('about')}>{t.nav.about}</a>
        <a onClick={go('skills')}>{t.nav.skills}</a>
        <a onClick={go('work')}>{t.nav.work}</a>
        <a onClick={go('contact')}>{t.nav.contact}</a>
      </div>
      <div className="lang-toggle">
        <button className={lang==='pt'?'active':''} onClick={()=>setLang('pt')}>PT</button>
        <button className={lang==='en'?'active':''} onClick={()=>setLang('en')}>EN</button>
      </div>
    </nav>
  );
}

/* ─── Hero with particle field ─── */
function HeroParticles({ intensity }) {
  const canvasRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let raf, w, h;
    const resize = () => {
      w = canvas.width = canvas.offsetWidth * devicePixelRatio;
      h = canvas.height = canvas.offsetHeight * devicePixelRatio;
    };
    resize();
    window.addEventListener('resize', resize);
    const count = Math.round(60 + intensity * 8);
    const pts = Array.from({ length: count }, () => ({
      x: Math.random() * w, y: Math.random() * h,
      vx: (Math.random() - .5) * .3 * devicePixelRatio,
      vy: (Math.random() - .5) * .3 * devicePixelRatio,
      r: Math.random() * 1.5 + .5,
    }));
    let mouse = { x: -9999, y: -9999 };
    const onMouse = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouse.x = (e.clientX - rect.left) * devicePixelRatio;
      mouse.y = (e.clientY - rect.top) * devicePixelRatio;
    };
    canvas.addEventListener('mousemove', onMouse);
    canvas.addEventListener('mouseleave', () => { mouse = { x: -9999, y: -9999 }; });
    const draw = () => {
      ctx.clearRect(0, 0, w, h);
      pts.forEach(p => {
        p.x += p.vx; p.y += p.vy;
        if (p.x < 0 || p.x > w) p.vx *= -1;
        if (p.y < 0 || p.y > h) p.vy *= -1;
        const dx = p.x - mouse.x, dy = p.y - mouse.y;
        const d = Math.sqrt(dx*dx + dy*dy);
        if (d < 120 * devicePixelRatio) {
          const f = (120 * devicePixelRatio - d) / (120 * devicePixelRatio);
          p.x += (dx / d) * f * 2;
          p.y += (dy / d) * f * 2;
        }
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r * devicePixelRatio, 0, Math.PI*2);
        ctx.fillStyle = 'rgba(0,229,255,.55)';
        ctx.fill();
      });
      // connect close pts
      for (let i = 0; i < pts.length; i++) {
        for (let j = i+1; j < pts.length; j++) {
          const dx = pts[i].x - pts[j].x, dy = pts[i].y - pts[j].y;
          const d = Math.sqrt(dx*dx + dy*dy);
          if (d < 100 * devicePixelRatio) {
            ctx.strokeStyle = `rgba(0,229,255,${(1 - d / (100*devicePixelRatio)) * .12})`;
            ctx.lineWidth = .5;
            ctx.beginPath();
            ctx.moveTo(pts[i].x, pts[i].y);
            ctx.lineTo(pts[j].x, pts[j].y);
            ctx.stroke();
          }
        }
      }
      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
    };
  }, [intensity]);
  return <canvas ref={canvasRef} className="hero-canvas" />;
}

function Hero({ t, intensity }) {
  const [phase, setPhase] = useState(0);
  useEffect(() => {
    const ts = [200, 600, 1100, 1700, 2300];
    const ids = ts.map((d, i) => setTimeout(() => setPhase(i + 1), d));
    return () => ids.forEach(clearTimeout);
  }, []);
  return (
    <section className="hero" id="top">
      <HeroParticles intensity={intensity} />
      <div className="hero-meta">
        <div style={{ opacity: phase >= 1 ? 1 : 0, transition: 'opacity .6s' }}>
          <span className="k">@ </span><span className="v">{t.hero.meta1}</span>
        </div>
        <div style={{ opacity: phase >= 1 ? 1 : 0, transition: 'opacity .6s .1s' }}>
          <span className="k">role · </span>{t.hero.meta2}
        </div>
        <div style={{ opacity: phase >= 1 ? 1 : 0, transition: 'opacity .6s .2s' }}>
          <span className="k">loc · </span>{t.hero.meta3}
        </div>
        <div style={{ opacity: phase >= 1 ? 1 : 0, transition: 'opacity .6s .3s' }}>
          <span className="k">status · </span><span className="v">{t.hero.meta4}</span>
        </div>
      </div>

      <h1 className="hero-name">
        <span className="line">
          <span className="word" style={{
            transform: phase >= 2 ? 'translateY(0)' : 'translateY(110%)',
            transition: 'transform 1.1s cubic-bezier(.2,.8,.2,1)',
            display: 'inline-block'
          }}>{t.hero.name1}</span>
        </span>
        <span className="line">
          <span className="word glow" style={{
            transform: phase >= 3 ? 'translateY(0)' : 'translateY(110%)',
            transition: 'transform 1.1s cubic-bezier(.2,.8,.2,1)',
            display: 'inline-block'
          }}>{t.hero.name2}</span>
        </span>
      </h1>

      <p className="hero-tagline" style={{
        opacity: phase >= 4 ? 1 : 0,
        transform: phase >= 4 ? 'none' : 'translateY(20px)',
        transition: 'all .8s cubic-bezier(.2,.8,.2,1)'
      }}>
        {t.hero.tagline.map((seg, i) => (
          (i === 2 || i === 4) ? <span key={i} className="hl">{seg}</span> : <span key={i}>{seg}</span>
        ))}
      </p>

      <div className="hero-side" style={{ opacity: phase >= 5 ? 1 : 0, transition: 'opacity .6s' }}>
        {t.hero.side}
      </div>

      <div className="hero-scroll" style={{ opacity: phase >= 5 ? 1 : 0, transition: 'opacity .8s' }}>
        <span>{t.hero.scroll}</span>
        <span className="line-down" />
      </div>
    </section>
  );
}

/* ─── About ─── */
function About({ t }) {
  const [secRef, secIn] = useReveal();
  const [logIdx, setLogIdx] = useState(0);
  useEffect(() => {
    if (!secIn) return;
    setLogIdx(0);
    const id = setInterval(() => {
      setLogIdx((i) => (i < t.about.log.length ? i + 1 : i));
    }, 380);
    return () => clearInterval(id);
  }, [secIn, t]);

  return (
    <section id="about" ref={secRef}>
      <div className={`section-tag reveal ${secIn ? 'in' : ''}`}>{t.about.tag}</div>
      <h2 className={`section-title reveal d1 ${secIn ? 'in' : ''}`}>
        {t.about.title.map((seg, i) => typeof seg === 'string' ? <span key={i}>{seg}</span> : seg)}
      </h2>

      <div className="about-grid">
        <div>
          <div className={`about-text reveal d2 ${secIn ? 'in' : ''}`}>
            <p>{t.about.p1}</p>
            <p>{t.about.p2}</p>
          </div>
          <div className={`processing-log reveal d3 ${secIn ? 'in' : ''}`}>
            {t.about.log.slice(0, logIdx).map((ln, i) => (
              <div className="ln" key={i}>
                <span className="ix">{String(i+1).padStart(2, '0')}</span>
                <span className={i === logIdx - 1 ? 'blink' : 'ok'}>{ln}</span>
              </div>
            ))}
          </div>
        </div>

        <div className={`about-stats reveal d2 ${secIn ? 'in' : ''}`}>
          {t.about.stats.map((s, i) => (
            <Stat key={i} idx={i} label={s.k} value={s.v} unit={s.u} parentIn={secIn} />
          ))}
        </div>
      </div>
    </section>
  );
}

function Stat({ idx, label, value, unit, parentIn }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    if (!parentIn) return;
    const id = setTimeout(() => setShow(true), 350 + idx * 220);
    return () => clearTimeout(id);
  }, [parentIn, idx]);
  return (
    <div className={`stat ${show ? 'in' : ''}`}>
      <div className="stat-label">{label}</div>
      <div className="stat-value">
        {value}<span className="unit">{unit}</span>
      </div>
    </div>
  );
}

window.PortfolioPart1 = { useReveal, CursorGlow, Nav, Hero, About };
