// components.jsx — UI primitives + sections
const { useState, useEffect, useRef, useMemo, useCallback, useLayoutEffect } = React;

/* ============================================================
   Visual primitives
   ============================================================ */

function Arrow({ size = 14, dir = "ne" }) {
  const rotations = { ne: -45, e: 0, s: 90, sw: 135, nw: -135, n: -90, w: 180 };
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none"
         style={{ transform: `rotate(${rotations[dir]}deg)` }}>
      <path d="M2 7 H12 M8 3 L12 7 L8 11" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function CircleMotif({ top, left, right, bottom, size, opacity = 0.25, dashed }) {
  return (
    <div style={{
      position: "absolute",
      top, left, right, bottom,
      width: size, height: size,
      borderRadius: "50%",
      border: `1px ${dashed ? "dashed" : "solid"} currentColor`,
      opacity,
      pointerEvents: "none",
    }} />
  );
}

function HairlineRow({ children, style }) {
  return (
    <div style={{
      borderTop: "1px solid var(--hairline)",
      display: "flex",
      alignItems: "baseline",
      gap: 24,
      padding: "20px 0",
      ...style,
    }}>{children}</div>
  );
}

/* ============================================================
   Navbar
   ============================================================ */

function Navbar({ route, navigate, lang, setLang, t }) {
  const linkStyle = (k) => ({
    fontSize: 14,
    letterSpacing: "0.02em",
    cursor: "pointer",
    position: "relative",
    color: route === k ? "var(--ink)" : "var(--muted)",
    transition: "color 0.3s",
  });
  return (
    <nav style={{
      position: "fixed", top: 0, left: 0, right: 0,
      zIndex: 100,
      padding: "22px var(--gutter)",
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      mixBlendMode: "difference",
      color: "#f6f5f2",
    }}>
      <a onClick={() => navigate("home")} style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
        <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
          <circle cx="11" cy="11" r="10.25" stroke="currentColor" strokeWidth="1"/>
          <circle cx="11" cy="11" r="5.25" stroke="currentColor" strokeWidth="1"/>
          <line x1="0.5" y1="11" x2="21.5" y2="11" stroke="currentColor" strokeWidth="1" opacity="0.6"/>
        </svg>
        <span style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-0.01em" }}>Fabrício Parra</span>
        <span className="mono" style={{ marginLeft: 12, opacity: 0.6, fontSize: 11 }}>— Product Designer</span>
      </a>

      <div style={{ display: "flex", alignItems: "center", gap: 36 }}>
        <a onClick={() => navigate("home")} style={linkStyle("home")}>{lang === "pt" ? "Home" : "Home"}</a>
        <a onClick={() => navigate("work")} style={linkStyle("work")}>{t.nav.work}</a>
        <a onClick={() => navigate("about")} style={linkStyle("about")}>{t.nav.about}</a>
        <a onClick={() => navigate("contact")} style={linkStyle("contact")}>{t.nav.contact}</a>
        <LangToggle lang={lang} setLang={setLang} />
      </div>
    </nav>
  );
}

function LangToggle({ lang, setLang }) {
  return (
    <div style={{
      display: "inline-flex",
      alignItems: "center",
      gap: 0,
      border: "1px solid currentColor",
      borderRadius: 999,
      padding: 3,
      fontSize: 11,
      letterSpacing: "0.06em",
      textTransform: "uppercase",
    }}>
      {["pt", "en"].map(l => (
        <button key={l}
          onClick={() => setLang(l)}
          style={{
            padding: "5px 11px",
            borderRadius: 999,
            background: lang === l ? "currentColor" : "transparent",
            color: lang === l ? "var(--ink)" : "currentColor",
            mixBlendMode: lang === l ? "difference" : "normal",
            transition: "background 0.3s, color 0.3s",
            cursor: "pointer",
            fontFamily: "JetBrains Mono, monospace",
          }}>
          {l}
        </button>
      ))}
    </div>
  );
}

/* ============================================================
   Hero / Home
   ============================================================ */

function Home({ t, navigate, lang }) {
  const heroRef = useRef(null);
  const nameRef = useRef(null);

  useEffect(() => {
    const lines = heroRef.current?.querySelectorAll('[data-reveal]') || [];
    gsap.set(lines, { yPercent: 110 });
    gsap.to(lines, { yPercent: 0, duration: 1.2, ease: "expo.out", stagger: 0.08, delay: 0.2 });
    // marquee animation
    const marquee = document.querySelector('[data-marquee-track]');
    if (marquee) {
      gsap.to(marquee, { xPercent: -50, duration: 40, ease: "none", repeat: -1 });
    }
  }, [lang]);

  return (
    <section data-screen-label="home" ref={heroRef} style={{ position: "relative", paddingTop: 0 }}>
      {/* Hero */}
      <div style={{
        minHeight: "100vh",
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        padding: "120px var(--gutter) 40px",
        position: "relative",
        overflow: "hidden",
      }}>
        <CircleMotif top="15%" right="-200px" size={600} opacity={0.18} />
        <CircleMotif top="40%" right="-100px" size={400} opacity={0.12} />
        <CircleMotif bottom="-120px" left="-80px" size={300} opacity={0.18} />

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 24 }}>
          <div className="mono" style={{ color: "var(--muted)", maxWidth: 240 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#16a34a", boxShadow: "0 0 0 4px rgba(22,163,74,0.18)" }}></span>
              {t.hero.eyebrow}
            </span>
          </div>
          <div className="mono" style={{ color: "var(--muted)", textAlign: "right" }}>
            <div>(2021 — 2026)</div>
            <div style={{ marginTop: 6 }}>v.{lang === "pt" ? "PT" : "EN"} · 01</div>
          </div>
        </div>

        <div ref={nameRef} style={{ marginTop: "auto" }}>
          <h1 style={{
            fontSize: "var(--t-display)",
            fontWeight: 500,
            letterSpacing: "-0.04em",
            lineHeight: 0.95,
          }}>
            <span style={{ display: "block", overflow: "hidden", paddingBottom: "0.05em" }}>
              <span data-reveal style={{ display: "inline-block" }}>{t.hero.name1}</span>
            </span>
            <span style={{ display: "block", overflow: "hidden", paddingBottom: "0.05em" }}>
              <span data-reveal style={{ display: "inline-flex", alignItems: "baseline", gap: "0.3em" }}>
                <span className="italic-serif">{t.hero.name2}</span>
                <span style={{ display: "inline-block", width: "0.4em", height: "0.4em", borderRadius: "50%", background: "currentColor", alignSelf: "center" }}></span>
              </span>
            </span>
          </h1>

          <div style={{
            display: "grid",
            gridTemplateColumns: "1fr 1fr",
            gap: 40,
            marginTop: 60,
            alignItems: "end",
            paddingTop: 28,
            borderTop: "1px solid var(--hairline)",
          }}>
            <div style={{ maxWidth: 480 }}>
              <div className="reveal-line"><span data-reveal style={{ fontSize: "var(--t-h3)", lineHeight: 1.3, letterSpacing: "-0.01em" }}>{t.hero.tagline}</span></div>
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 16 }}>
              <button className="btn btn-solid" onClick={() => navigate("work")}>
                <span>{t.nav.work}</span><span className="arrow"><Arrow/></span>
              </button>
              <button className="btn" onClick={() => navigate("contact")}>
                <span>{t.nav.contact}</span>
              </button>
            </div>
          </div>
        </div>

        <div style={{ position: "absolute", bottom: 40, left: "var(--gutter)", display: "flex", alignItems: "center", gap: 10 }}>
          <span className="mono" style={{ color: "var(--muted)" }}>{t.hero.scroll}</span>
          <span style={{ display: "inline-block", animation: "scrollHint 1.6s ease-in-out infinite" }}>
            <Arrow dir="s"/>
          </span>
        </div>
      </div>

      {/* Marquee */}
      <Marquee t={t} lang={lang} />

      {/* Featured projects glimpse */}
      <FeaturedProjects t={t} navigate={navigate} lang={lang} />
    </section>
  );
}

function Marquee({ t, lang }) {
  const items = lang === "pt"
    ? ["Product Design", "UX Strategy", "Interface Craft", "Prototipação", "Design System", "AI Workflow"]
    : ["Product Design", "UX Strategy", "Interface Craft", "Prototyping", "Design System", "AI Workflow"];
  const repeated = [...items, ...items, ...items, ...items];
  return (
    <div style={{ borderTop: "1px solid var(--hairline)", borderBottom: "1px solid var(--hairline)", overflow: "hidden", padding: "26px 0", whiteSpace: "nowrap" }}>
      <div data-marquee-track style={{ display: "inline-flex", gap: 60, willChange: "transform" }}>
        {repeated.map((it, i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 60, fontSize: "clamp(28px, 4vw, 56px)", fontWeight: 400, letterSpacing: "-0.02em" }}>
            <span className={i % 2 === 1 ? "italic-serif" : ""}>{it}</span>
            <span style={{ width: 10, height: 10, borderRadius: "50%", background: "currentColor", opacity: 0.5 }}></span>
          </span>
        ))}
      </div>
    </div>
  );
}

function FeaturedProjects({ t, navigate, lang }) {
  useEffect(() => {
    // preload all project cover images so hover previews don't flash a dark bg
    PROJECTS.forEach(p => { if (p.cover) { const img = new Image(); img.src = p.cover; } });
    // refresh ScrollTrigger after layout settles (fonts/images load)
    const refresh = () => ScrollTrigger.refresh();
    const timer = setTimeout(refresh, 100);
    window.addEventListener("load", refresh);
    return () => { clearTimeout(timer); window.removeEventListener("load", refresh); };
  }, []);
  return (
    <div style={{ padding: "120px var(--gutter)" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 60, flexWrap: "wrap", gap: 16 }}>
        <h2 style={{ fontSize: "var(--t-h2)", fontWeight: 500, letterSpacing: "-0.02em" }}>
          {t.work.title}<span className="italic-serif" style={{ marginLeft: 6 }}>.</span>
        </h2>
        <div className="mono" style={{ color: "var(--muted)" }}>{t.work.subtitle}</div>
      </div>
      <div>
        {PROJECTS.map((p, i) => (
          <ProjectListRow key={p.id} p={p} index={i} t={t} lang={lang} onClick={() => navigate("project", { id: p.id })}/>
        ))}
      </div>
    </div>
  );
}

function ProjectListRow({ p, index, t, lang, onClick }) {
  const ref = useRef(null);
  const imgRef = useRef(null);
  const [hover, setHover] = useState(false);

  useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;
    gsap.fromTo(el,
      { yPercent: 40, opacity: 0 },
      {
        yPercent: 0, opacity: 1, duration: 0.9, ease: "expo.out",
        scrollTrigger: { trigger: el, start: "top 100%", toggleActions: "play none none none" },
      }
    );
  }, []);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const handleMouse = (e) => {
      if (!imgRef.current) return;
      const rect = el.getBoundingClientRect();
      gsap.to(imgRef.current, { x: e.clientX - rect.left - 180, y: e.clientY - rect.top - 110, duration: 0.6, ease: "power3.out" });
    };
    el.addEventListener("mousemove", handleMouse);
    return () => el.removeEventListener("mousemove", handleMouse);
  }, []);

  return (
    <div ref={ref}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "relative",
        display: "grid",
        gridTemplateColumns: "60px 1.4fr 1fr 200px 60px",
        alignItems: "center",
        padding: "32px 0",
        borderTop: "1px solid var(--hairline)",
        cursor: "pointer",
        transition: "padding 0.5s var(--ease)",
        paddingLeft: hover ? 24 : 0,
      }}>
      <span className="mono" style={{ color: "var(--muted)" }}>{p.n}</span>
      <span style={{
        fontSize: "clamp(28px, 3.2vw, 44px)",
        fontWeight: 500,
        letterSpacing: "-0.02em",
        display: "inline-flex", alignItems: "baseline", gap: 12,
      }}>
        {p.name}
        <span className="italic-serif" style={{ fontSize: "0.5em", color: "var(--muted)" }}>— {p.type[lang]}</span>
      </span>
      <span className="mono" style={{ color: "var(--muted)" }}>{p.role[lang]}</span>
      <span className="mono" style={{ color: "var(--muted)", textAlign: "right" }}>{p.year}</span>
      <span style={{
        display: "inline-flex", justifyContent: "flex-end",
        transform: hover ? "translateX(0)" : "translateX(-8px)",
        opacity: hover ? 1 : 0.4,
        transition: "all 0.4s var(--ease)",
      }}>
        <Arrow size={18}/>
      </span>

      <div style={{
        position: "absolute",
        top: 0, left: 0,
        width: 360, height: 220,
        pointerEvents: "none",
        zIndex: 10,
        opacity: hover ? 1 : 0,
        transition: "opacity 0.3s var(--ease)",
        willChange: "opacity",
      }}>
        <div ref={imgRef} style={{
          width: "100%",
          height: "100%",
          borderRadius: 8,
          overflow: "hidden",
          boxShadow: "0 30px 60px rgba(0,0,0,0.18)",
          willChange: "transform",
        }}>
          <ProjectArt p={p} compact/>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   Work index page
   ============================================================ */

function Work({ t, navigate, lang }) {
  useEffect(() => {
    PROJECTS.forEach(p => { if (p.cover) { const img = new Image(); img.src = p.cover; } });
  }, []);
  return (
    <section data-screen-label="work" style={{ padding: "var(--gutter)" }}>
      <div style={{ paddingTop: 40, paddingBottom: 60 }}>
        <div className="mono" style={{ color: "var(--muted)", marginBottom: 30 }}>{t.nav.index} · 01 / {String(PROJECTS.length).padStart(2, "0")}</div>
        <h1 style={{ fontSize: "clamp(60px, 10vw, 160px)", fontWeight: 500, letterSpacing: "-0.04em", lineHeight: 0.9 }}>
          {t.work.title.split(" ")[0]} <span className="italic-serif">{t.work.title.split(" ").slice(1).join(" ")}</span>
        </h1>
      </div>

      <div>
        {PROJECTS.map((p, i) => (
          <WorkBigRow key={p.id} p={p} t={t} lang={lang} onClick={() => navigate("project", { id: p.id })}/>
        ))}
      </div>
    </section>
  );
}

function WorkBigRow({ p, t, lang, onClick }) {
  const [hover, setHover] = useState(false);
  const imgRef = useRef(null);
  const rowRef = useRef(null);

  useEffect(() => {
    const el = rowRef.current;
    if (!el) return;
    const handleMouse = (e) => {
      if (!imgRef.current) return;
      const rect = el.getBoundingClientRect();
      gsap.to(imgRef.current, { x: e.clientX - rect.left - 200, y: e.clientY - rect.top - 130, duration: 0.6, ease: "power3.out" });
    };
    el.addEventListener("mousemove", handleMouse);
    return () => el.removeEventListener("mousemove", handleMouse);
  }, []);

  return (
    <div ref={rowRef}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "relative",
        display: "grid",
        gridTemplateColumns: "80px 1fr 200px 60px",
        alignItems: "center",
        padding: "44px 0",
        borderTop: "1px solid var(--hairline)",
        cursor: "pointer",
      }}>
      <span className="mono" style={{ color: "var(--muted)" }}>{p.n}</span>
      <span style={{ fontSize: "clamp(40px, 6vw, 88px)", fontWeight: 500, letterSpacing: "-0.03em", lineHeight: 1 }}>
        {p.name.includes(" ") ? <>
          {p.name.split(" ")[0]} <span className="italic-serif">{p.name.split(" ").slice(1).join(" ")}</span>
        </> : p.name}
      </span>
      <span className="mono" style={{ color: "var(--muted)", textAlign: "right" }}>{p.type[lang]}</span>
      <span style={{ display: "inline-flex", justifyContent: "flex-end" }}>
        <Arrow size={20}/>
      </span>

      <div style={{
        position: "absolute",
        top: 0, left: 0,
        width: 400, height: 260,
        pointerEvents: "none",
        zIndex: 10,
        opacity: hover ? 1 : 0,
        transition: "opacity 0.3s var(--ease)",
        willChange: "opacity",
      }}>
        <div ref={imgRef} style={{
          width: "100%",
          height: "100%",
          borderRadius: 8,
          overflow: "hidden",
          willChange: "transform",
        }}>
          <ProjectArt p={p} compact/>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Arrow, CircleMotif, HairlineRow, Navbar, Home, Work, Marquee, FeaturedProjects, ProjectListRow, WorkBigRow });
