// Home / Project / About pages
const { useState: _useState, useEffect: _useEffect, useRef: _useRef } = React;

/* ---------------------- Home ---------------------- */
function Home({ lang, navigate }) {
  const projects = PROJECTS.filter(p => !p.hidden);
  const [activeIdx, setActiveIdx] = React.useState(0);
  const [isHovering, setHovering] = React.useState(false);
  const H = COPY.home;
  const headlineHtml = H.headlineHtml[lang];

  React.useEffect(() => {
    let locked = false;
    let touchStartY = 0;

    const getWorkTop = () => {
      const el = document.querySelector('.work');
      const header = document.querySelector('.site-header');
      const headerH = header ? header.offsetHeight : 80;
      return el ? el.offsetTop - headerH : 0;
    };

    const snapTo = (top) => {
      locked = true;
      window.scrollTo({ top, behavior: 'smooth' });
      setTimeout(() => {locked = false;}, 900);
    };

    const onWheel = (e) => {
      if (locked) {e.preventDefault();return;}
      const wt = getWorkTop();
      if (e.deltaY > 0 && window.scrollY < wt - 10) {
        e.preventDefault();snapTo(wt);
      } else if (e.deltaY < 0 && window.scrollY <= wt + 10 && window.scrollY > 0) {
        e.preventDefault();snapTo(0);
      }
    };

    const onTouchStart = (e) => {touchStartY = e.touches[0].clientY;};
    const onTouchEnd = (e) => {
      if (locked) return;
      const dy = touchStartY - e.changedTouches[0].clientY;
      const wt = getWorkTop();
      if (dy > 40 && window.scrollY < wt - 10) snapTo(wt);else
      if (dy < -40 && window.scrollY <= wt + 10 && window.scrollY > 0) snapTo(0);
    };

    window.scrollTo(0, 0);
    window.addEventListener('wheel', onWheel, { passive: false });
    window.addEventListener('touchstart', onTouchStart, { passive: true });
    window.addEventListener('touchend', onTouchEnd, { passive: true });

    return () => {
      window.removeEventListener('wheel', onWheel);
      window.removeEventListener('touchstart', onTouchStart);
      window.removeEventListener('touchend', onTouchEnd);
    };
  }, []);

  // Fade-in on scroll for project items
  React.useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const els = document.querySelectorAll('.home .scroll-reveal');
    if (reduce) { els.forEach(el => el.classList.add('is-visible')); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('is-visible'); io.unobserve(e.target); } });
    }, { threshold: 0.02, rootMargin: '0px 0px -2% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <main className="page home">
      <section className="intro">
        <div className="intro-lede">
          <div className="intro-avatar">
            <img src="assets/RH-profile_05.png" alt="Ricardo Hirth" />
          </div>
          <div className="intro-text">
            <h1 style={{ fontSize: "28px", maxWidth: "100%" }}>
              {H.greeting[lang].split('\n').flatMap((line, i, arr) =>
              i < arr.length - 1 ? [line, <br key={i} />] : [line]
              )}
            </h1>
            <p className="availability" style={{ fontSize: "15px" }}>
              <span className="avail-dot" aria-hidden></span>
              <span style={{ color: "#908d85" }}><span style={{ color: "#5b5953" }}>{H.availability[lang]}</span></span>
            </p>
          </div>
        </div>
        <ul className="intro-taglines">
          {H.taglines.map((t, i) => <li key={i}>{t}</li>)}
        </ul>
      </section>

      <section className="work">
        <div className="work-left scroll-reveal">
          <div className="work-eyebrow" style={{ fontSize: "12px", letterSpacing: "1px" }}>
            {lang === 'pt' ? '(Trabalhos Selecionados)' : '(Selected Works)'}
          </div>
          <div className="work-desktop">
            <ul className={`project-list ${isHovering ? "is-hovering" : ""}`}
            onMouseLeave={() => setHovering(false)}>
            
            {projects.map((p, i) =>
              <li key={p.id}>
                <a
                  href={`#${p.id}`}
                  onMouseEnter={() => {setActiveIdx(i);setHovering(true);}}
                  onFocus={() => {setActiveIdx(i);setHovering(true);}}
                  onClick={(e) => {e.preventDefault();navigate({ name: "project", id: p.id });}}>
                
                                    <span className="title-block">
                    <span className="title">{pick(p.tag, lang)}</span>
                    <span className="subtitle">{p.name}</span>
                  </span>
                  <span className="arrow" aria-hidden>↗</span>
                </a>
              </li>
              )}
          </ul>
        </div>
        </div>

        <div className="preview-wrap scroll-reveal" style={{ transitionDelay: '100ms' }}>
          <a
            className="preview"
            href={`#${projects[activeIdx].id}`}
            onClick={(e) => {e.preventDefault();navigate({ name: "project", id: projects[activeIdx].id });}}
            aria-label={`Open ${projects[activeIdx].name}`}>
            
            <div className="preview-stack">
              {projects.map((p, i) =>
              <div key={p.id} className={`preview-card ${i === activeIdx ? "is-active" : ""}`}>
                  <ProjectArt project={p} variant="preview" />
                </div>
              )}
            </div>
          </a>
          <div className="preview-caption">
            <div className="cap-left">
              <strong>{pick(projects[activeIdx].tag, lang)}</strong>
              <span>{projects[activeIdx].name}</span>
            </div>
            <div className="cap-center">
              <span>{pick(projects[activeIdx].hero, lang)}</span>
            </div>
            <div className="cap-right">
              <span>{projects[activeIdx].year}</span>
            </div>
          </div>
        </div>

        <ul className="project-list-mobile">
          {projects.map((p, i) =>
          <li key={p.id} className="scroll-reveal" style={{ transitionDelay: `${i * 80}ms` }}>
              <a
              href={`#${p.id}`}
              onClick={(e) => {e.preventDefault();navigate({ name: "project", id: p.id });}}>
                
                <div className="thumb">
                  {p.image ?
                <img src={p.image} alt={pick(p.tag, lang)} style={{ width: "100%", height: "auto", display: "block", borderRadius: "12px" }} /> :
                <div style={{ aspectRatio: "16/9", borderRadius: "12px", overflow: "hidden" }}><ProjectArt project={p} variant="preview" /></div>
                }
                </div>
                <div className="meta">
                  <strong>{pick(p.tag, lang)}</strong>
                  <span>{p.name}</span>
                </div>
              </a>
            </li>
          )}
        </ul>
      </section>
    </main>);

}

/* ---------------------- Project page ---------------------- */
function ProjectPage({ lang, id, navigate }) {
  const visibleProjects = PROJECTS.filter(p => !p.hidden);
  const idx = visibleProjects.findIndex((p) => p.id === id);
  const p = visibleProjects[idx];
  const prev = visibleProjects[(idx - 1 + visibleProjects.length) % visibleProjects.length];
  const next = visibleProjects[(idx + 1) % visibleProjects.length];
  const T = COPY.project;

  React.useEffect(() => {window.scrollTo({ top: 0, behavior: "instant" });}, [id]);

  // Parallax effect on hero
  const heroRef = React.useRef(null);
  React.useEffect(() => {
    const el = heroRef.current;
    if (!el) return;
    let raf = 0;
    const apply = () => {
      raf = 0;
      const isMobile = window.innerWidth <= 720;
      const art = el.querySelector(".art");
      if (!art) return;
      if (isMobile) {
        art.style.transform = "";
        return;
      }
      art.style.display = "";
      const rect = el.getBoundingClientRect();
      if (rect.bottom < -200 || rect.top > window.innerHeight + 200) return;
      const offset = -rect.top * 0.35;
      art.style.transform = `translate3d(0, ${offset}px, 0) scale(1.3)`;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(apply); };
    apply();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
      el.style.backgroundPositionY = "";
      const art = el.querySelector(".art");
      if (art) { art.style.transform = ""; art.style.display = ""; }
    };
  }, [id]);

  // Fade-in on scroll for gallery rows
  React.useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const els = document.querySelectorAll('.project-page .scroll-reveal');
    if (reduce) { els.forEach(el => el.classList.add('is-visible')); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('is-visible'); io.unobserve(e.target); } });
    }, { threshold: 0.02, rootMargin: '0px 0px -2% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [id]);

  if (!p) return null;

  return (
    <main className="page project-page" data-screen-label={`project ${p.name}`}>
      <div className="hero" ref={heroRef} style={{ '--hero-img': p.heroImage ? `url("${p.heroImage}")` : p.image ? `url("${p.image}")` : undefined, '--hero-bg-color': p.heroBgColor || undefined, '--hero-mobile-size': p.heroMobileZoom || undefined }}>
        <ProjectArt project={p} variant="hero" />
      </div>

      <section className="project-lead">
        <div className="lead-title">
          <h2>{pick(p.tag, lang)}</h2>
          <sup className="lead-year">({p.year}) · {p.name}</sup>
        </div>
        <p className="lead-phrase" style={{ fontSize: "21px", lineHeight: "1.4" }}>{pick(p.hero, lang)}</p>
      </section>

      <section className="gallery">
        {p.gallery.map((row, ri) => {
          if (row.layout === "text") {
            return (
              <div key={ri} className="row text-block scroll-reveal" style={{ transitionDelay: `${ri * 60}ms` }}>
                <h4>{pick(row.title, lang)}</h4>
                <div className="body">
                  {pick(row.body, lang).map((t, i) => <p key={i}>{t}</p>)}
                </div>
              </div>);

          }
          return (
            <div key={ri} className={`row ${row.layout} scroll-reveal`} style={{ transitionDelay: `${ri * 60}ms` }}>
              {row.items.map((it, ii) =>
              <div key={ii} className={`frame ${it.shape && it.shape !== "default" ? it.shape : ""}`}>
                  {it.shape === "compare" ?
                <BeforeAfterSlider imageBefore={it.imageBefore} imageAfter={it.imageAfter} lang={lang} /> :
                <ProjectArt project={p} variant="gallery" label={it.label} image={it.image} />
                }
                </div>
              )}
            </div>);

        })}
      </section>

      <section className="project-context">
        <div className="ctx-left">
          <p className="ctx-label">{lang === "pt" ? "Cliente" : "Client"}</p>
          <h2>{p.name}</h2>
          <p className="ctx-category" style={{ fontSize: "17px" }}>{p.category ? pick(p.category, lang) : pick(p.tag, lang)}</p>
          {p.link &&
          <>
              <p className="ctx-label" style={{ marginTop: "40px" }}>{lang === "pt" ? "Link do projeto" : "Project link"}</p>
              <a className="ctx-category" href={p.link} target="_blank" rel="noopener noreferrer" style={{ fontSize: "17px", color: "var(--fg)", textDecoration: "none", borderBottom: "1px solid var(--fg-mute)" }}>{p.link.replace(/^https?:\/\//, "")}</a>
            </>
          }
        </div>
        <div className="ctx-body">
          {pick(p.intro.lede, lang).map((t, i) => <p key={i}>{t}</p>)}
        </div>
      </section>

      <section className="related-projects" aria-label={T.related[lang]}>
        <h2 className="related-title">{T.related[lang]}</h2>
        <div className="related-grid">
          {[prev, next].map((rp) =>
          <a
            key={rp.id}
            href={`#${rp.id}`}
            className="related-card"
            onClick={(e) => {e.preventDefault();navigate({ name: "project", id: rp.id });}}>

              <div className="related-thumb">
                <ProjectArt project={rp} variant="related" image={rp.image} />
              </div>
              <div className="related-meta">
                <h3>{pick(rp.tag, lang)}</h3>
                <p>{rp.name}</p>
              </div>
            </a>
          )}
        </div>
      </section>
    </main>);

}

/* ---------------------- About ---------------------- */
function About({ lang, navigate, anchor }) {
  const A = COPY.about;
  const contactRef = React.useRef(null);

  React.useEffect(() => {
    document.body.classList.add("theme-dark");
    return () => document.body.classList.remove("theme-dark");
  }, []);

  // Reveal-on-scroll for each <section.reveal> child of the about page
  React.useEffect(() => {
    const els = document.querySelectorAll(".about .reveal");
    if (!els.length) return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) {
      els.forEach((el) => el.classList.add("is-visible"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("is-visible");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [lang]);

  React.useEffect(() => {
    if (anchor === "contact" && contactRef.current) {
      const y = contactRef.current.getBoundingClientRect().top + window.scrollY - 80;
      window.scrollTo({ top: y, behavior: "smooth" });
    } else {
      window.scrollTo({ top: 0, behavior: "instant" });
    }
  }, [anchor]);

  // Contact title supports a simple <br/> separator between sentences.
  const raw = A.contactTitle[lang];
  const channels = A.channels;
  const contactLines = raw.split(/<br\s*\/?>/i);

  return (
    <main className="page about">
      <section className="about-intro reveal">
        <div>
          <div className="eyebrow" style={{ fontSize: 13, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 24 }}>{A.eyebrow[lang]}</div>
          <h1 style={{ fontSize: "54px" }}>{pick(A.title, lang)}</h1>
          <div className="copy" style={{ marginTop: 36 }}>
            {pick(A.body, lang).map((t, i) => <p key={i} style={{ fontSize: "17px" }}>{t}</p>)}
          </div>
        </div>
        <div>
          <div className="portrait">
            <ProjectArt
              project={{ id: "portrait", name: "Portrait", swatch: ["#2a2620", "#4d3f30", "#dccfae"], image: "assets/RH-profile_01.jpg" }}
              variant="portrait" />
          </div>
        </div>
      </section>

      <hr className="about-rule" />

      <section className="expertise reveal">
        <div className="ex-col">
          <small>{A.expertises.label[lang]}</small>
          <ul>
            {A.expertises.items[lang].map((it, i) => <li key={i}>{it}</li>)}
          </ul>
        </div>
        <div className="ex-col">
          <small>{A.tools.label[lang]}</small>
          <ul className="ex-list-desc">
            {A.tools.items[lang].map((it, i) =>
            <li key={lang + '-' + i}>
                <strong>{it.name}</strong>
                <span>{it.desc}</span>
              </li>
            )}
          </ul>
        </div>
        <div className="ex-stamp">
          <StampSVG />
        </div>
      </section>

      <hr className="about-rule" />

      <section className="methodology reveal">
        <h2 className="methodology-title">{A.methodologyLabel[lang]}</h2>
        <div className="methodology-grid">
          {A.methodology.map((m, i) =>
          <div className="method-card" key={i}>
              <small className="num" style={{ fontFamily: "Geist" }}>{String(i + 1).padStart(2, "0")}</small>
              <strong>{pick(m.label, lang)}</strong>
              <p>{pick(m.body, lang)}</p>
            </div>
          )}
        </div>
      </section>

      <section id="contact" className="contact reveal" ref={contactRef}>
        <h2 style={{ fontSize: "54px" }}>
          {contactLines.map((line, i) =>
          <React.Fragment key={i}>
              {i > 0 && <br />}
              <span>{line}</span>
            </React.Fragment>
          )}
        </h2>
      </section>

    </main>);
}