/* Sections part 1: Nav, Hero, Marquee, About */
const { useState: uS1, useEffect: uE1, useRef: uR1 } = React;

/* ---------------- NAV ---------------- */
function Nav() {
  const [scrolled, setScrolled] = uS1(false);
  uE1(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const S = window.SITE;
  const go = (e, id) => { e.preventDefault(); document.getElementById(id)?.scrollIntoView({ behavior: "smooth" }); };
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="wrap nav-inner">
        <a href="#top" className="brand" onClick={(e) => go(e, "top")}>
          <span className="brand-mark">
            <img src="uploads/avatar.png" alt="Fhillip Castillo" loading="lazy" />
          </span>
          <span className="brand-name">Fhillip Castillo</span>
        </a>
        <div className="nav-links">
          <a href="#about" onClick={(e) => go(e, "about")}>About</a>
          <a href="#experience" onClick={(e) => go(e, "experience")}>Experience</a>
          <a href="#skills" onClick={(e) => go(e, "skills")}>Stack</a>
          <a href="#education" onClick={(e) => go(e, "education")}>Education</a>
        </div>
        <div className="nav-cta">
          <a className="btn btn-primary" href="#contact" onClick={(e) => go(e, "contact")}>
            Let's talk <Icon.arrow />
          </a>
        </div>
      </div>
    </nav>
  );
}

/* ---------------- HERO ---------------- */
function CodeWindow() {
  // typewriter for the code body — a small React component "intro"
  const lines = [
    [{ t: "com", v: "// Frontend engineer, full-stack range" }],
    [{ t: "key", v: "const " }, { t: "fn", v: "engineer" }, { t: "punc", v: " = {" }],
    [{ t: "prop", v: "  name" }, { t: "punc", v: ": " }, { t: "str", v: "'Fhillip G. Castillo'" }, { t: "punc", v: "," }],
    [{ t: "prop", v: "  stack" }, { t: "punc", v: ": [" }, { t: "str", v: "'React'" }, { t: "punc", v: ", " }, { t: "str", v: "'Next.js'" }, { t: "punc", v: ", " }, { t: "str", v: "'TypeScript'" }, { t: "punc", v: "]," }],
    [{ t: "prop", v: "  focus" }, { t: "punc", v: ": " }, { t: "str", v: "'scalable, user-centric UIs'" }, { t: "punc", v: "," }],
    [{ t: "prop", v: "  shipsTo" }, { t: "punc", v: ": " }, { t: "str", v: "'production'" }, { t: "punc", v: "," }],
    [{ t: "prop", v: "  available" }, { t: "punc", v: ": " }, { t: "key", v: "true" }, { t: "punc", v: "," }],
    [{ t: "punc", v: "};" }],
  ];

  const [count, setCount] = uS1(0); // chars revealed
  const total = lines.reduce((a, l) => a + l.reduce((b, s) => b + s.v.length, 0) + 1, 0);
  const hostRef = uR1(null);

  uE1(() => {
    let id = 0;
    const startTimer = setTimeout(() => {
      let c = 0;
      id = setInterval(() => {
        c += 1;
        setCount(c);
        if (c >= total) clearInterval(id);
      }, 24);
    }, 650);
    return () => { clearTimeout(startTimer); clearInterval(id); };
  }, [total]);

  // build rendered lines based on count
  let remaining = count;
  const done = count >= total;
  return (
    <div className="code-window" ref={hostRef}>
      <div className="cw-bar">
        <span className="cw-dot r"></span><span className="cw-dot y"></span><span className="cw-dot g"></span>
        <span className="cw-file">engineer.ts</span>
      </div>
      <div className="cw-body">
        {lines.map((line, li) => {
          const out = [];
          for (const seg of line) {
            if (remaining <= 0) break;
            const take = Math.min(seg.v.length, remaining);
            out.push({ t: seg.t, v: seg.v.slice(0, take) });
            remaining -= take;
          }
          remaining -= 1; // newline cost
          const lineHasContent = out.length > 0;
          if (!lineHasContent && remaining < 0 && li > 0) return null;
          return (
            <div className="cw-line" key={li}>
              {out.map((s, si) => <span key={si} className={`tok-${s.t}`}>{s.v}</span>)}
              {!done && remaining <= 0 && lineHasContent && <span className="cw-caret"></span>}
            </div>
          );
        })}
        {done && <div className="cw-line"><span className="cw-caret"></span></div>}
      </div>
    </div>
  );
}

function Hero() {
  const S = window.SITE;
  const role = useTypewriter(S.roles, { typeSpeed: 75, deleteSpeed: 38, hold: 1700 });
  const go = (e, id) => { e.preventDefault(); document.getElementById(id)?.scrollIntoView({ behavior: "smooth" }); };
  return (
    <header className="hero" id="top">
      <div className="wrap hero-grid">
        <div className="hero-copy">
          <Reveal>
            <span className="status-pill"><span className="status-dot"></span>{S.availability}</span>
          </Reveal>
          <Reveal delay={80}>
            <h1>Hi, I'm Fhillip.<br/><span className="grad-text">I build the web.</span></h1>
          </Reveal>
          <Reveal delay={140}>
            <div className="hero-role">
              <span>I work as a</span>
              <span className="role-rotator">{role}</span>
            </div>
          </Reveal>
          <Reveal delay={200}>
            <p className="hero-tag">{S.tagline}</p>
          </Reveal>
          <Reveal delay={260}>
            <div className="hero-actions">
              <a className="btn btn-primary" href="#contact" onClick={(e) => go(e, "contact")}>Hire me <Icon.arrow /></a>
              <a className="btn btn-ghost" href="#experience" onClick={(e) => go(e, "experience")}>View experience</a>
            </div>
          </Reveal>
          <Reveal delay={320}>
            <div className="hero-meta">
              <span className="hero-meta-item"><Icon.map />{S.location}</span>
              <span className="hero-meta-item"><Icon.bolt />React · Next.js · TypeScript</span>
            </div>
          </Reveal>
        </div>
        <div className="hero-visual" style={{ position: "relative" }}>
          <Reveal delay={160} style={{ position: "relative" }}>
            <span className="float-chip fc-1"><span className="fc-dot" style={{ background: "var(--sky)" }}></span>Next.js 15</span>
            <span className="float-chip fc-2"><span className="fc-dot" style={{ background: "var(--emerald)" }}></span>TypeScript</span>
            <span className="float-chip fc-3"><span className="fc-dot" style={{ background: "#c084fc" }}></span>Design Systems</span>
            <CodeWindow />
          </Reveal>
        </div>
      </div>
    </header>
  );
}

/* ---------------- MARQUEE ---------------- */
function Marquee() {
  const items = window.SITE.marquee;
  const row = [...items, ...items];
  return (
    <div className="marquee-band" aria-hidden="true">
      <div className="marquee-track">
        {row.map((it, i) => <span className="marquee-item" key={i}>{it}</span>)}
      </div>
    </div>
  );
}

/* ---------------- ABOUT ---------------- */
function Stat({ value, suffix, label }) {
  const [ref, val] = useCountUp(value);
  return (
    <div className="stat" ref={ref}>
      <div className="stat-num">{val}{suffix}</div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

function About() {
  const S = window.SITE;
  return (
    <section className="section" id="about">
      <div className="wrap">
        <div className="about-grid">
          <Reveal className="avatar-stack">
            <div className="avatar">
              <div className="avatar-ring"></div>
              {S.avatar
                ? <img className="avatar-img" src={S.avatar} alt={S.name} loading="lazy" />
                : <span className="avatar-mono">{S.monogram}</span>}
              <div className="avatar-tag">
                <span className="at-mono">{S.monogram}</span>
                <div>
                  <div className="at-name">{S.name}</div>
                  <div className="at-role">Full-Stack · Frontend-focused</div>
                </div>
              </div>
            </div>
          </Reveal>
          <div className="about-copy">
            <Reveal><span className="eyebrow">About me</span></Reveal>
            <Reveal delay={60}><h2 className="section-title" style={{ marginBottom: 24 }}>Frontend craft,<br/>full-stack <span className="grad-text">range.</span></h2></Reveal>
            {S.about.map((p, i) => (
              <Reveal key={i} delay={120 + i * 70}><p>{p}</p></Reveal>
            ))}
            <Reveal delay={360}>
              <div className="stats">
                {S.stats.map((s, i) => <Stat key={i} {...s} />)}
              </div>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Marquee, About });
