// v5 — Nav + Hero
// Adopts v2's bespoke kinetic vocabulary: ambient arcs, traveling photons,
// hover-state typography (wire underline + headline hover lift).

const WordReveal = ({ text, stagger = 60, className = "", tag: Tag = "span", startDelay = 0 }) => {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {setSeen(true);io.disconnect();}
    }, { threshold: 0.15 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const words = String(text).split(/(\s+)/);
  let wordIdx = 0;
  return (
    <Tag ref={ref} className={`v4-reveal ${seen ? "is-in" : ""} ${className}`}>
      {words.map((w, i) => {
        if (/^\s+$/.test(w)) return <span key={i}>{w}</span>;
        const d = startDelay + wordIdx * stagger;
        wordIdx += 1;
        return (
          <span key={i} className="v4-word" style={{ fontFamily: "\"Space Grotesk\"" }}><span style={{ "--d": `${d}ms`, fontFamily: "\"Hanken Grotesk\"" }}>{w}</span></span>);

      })}
    </Tag>);

};

const FadeIn = ({ children, delay = 0, className = "", as: Tag = "span", threshold = 0.15, ...rest }) => {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {setSeen(true);io.disconnect();}
    }, { threshold });
    io.observe(el);
    return () => io.disconnect();
  }, [threshold]);
  return (
    <Tag ref={ref} className={`v4-fade ${seen ? "is-in" : ""} ${className}`} style={{ transitionDelay: `${delay}ms` }} {...rest}>
      {children}
    </Tag>);

};

// NAV
const V5Nav = () => {
  const [scrolled, setScrolled] = useState(false);
  const [activeId, setActiveId] = useState("top");
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    const ids = ["showcase", "method", "about", "engagements"];
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) setActiveId(e.target.id);});
    }, { rootMargin: "-45% 0px -50% 0px" });
    ids.forEach((id) => {const el = document.getElementById(id);if (el) io.observe(el);});
    return () => io.disconnect();
  }, []);
  const links = [
  { id: "showcase", label: "Showcase" },
  { id: "method", label: "Method" },
  { id: "about", label: "About" },
  { id: "engagements", label: "Engagements" }];

  const go = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
  };
  return (
    <header className={`v4-nav ${scrolled ? "is-scrolled" : ""}`}>
      <a href="#top" className="v4-nav-brand" onClick={(e) => go(e, "top")}>
        <span className="v4-nav-mark v4-nav-mark-photo">
          <img src={typeof window !== "undefined" && window.__resources && window.__resources.chris || "src/assets/chris.png"} alt="Chris Znerold" />
        </span>
        <span className="v4-nav-brand-text">
          <span className="v4-nav-brand-name" style={{ fontFamily: "\"Instrument Serif\"", fontWeight: "400", fontSize: "21px" }}>Chris Znerold</span>
          <span className="v4-nav-brand-sub" style={{ fontFamily: "\"Hanken Grotesk\"" }}>Design Director, Author & Educator</span>
        </span>
      </a>
      <nav className="v4-nav-links">
        {links.map((l) =>
        <a key={l.id} href={`#${l.id}`} onClick={(e) => go(e, l.id)} className={`v4-nav-link ${activeId === l.id ? "is-on" : ""}`} data-cursor={`Jump to ${l.label}`} data-cursor-style="nav">{l.label}</a>
        )}
      </nav>
      <Magnetic strength={12}>
        <a href="#engagements" onClick={(e) => go(e, "engagements")} className="v4-nav-cta" data-cursor="2026 · taking introductions" style={{ fontWeight: "500", fontFamily: "\"Hanken Grotesk\"" }}>
          <span className="v4-nav-cta-dot"></span>
          Let's talk
        </a>
      </Magnetic>
    </header>);

};

// HERO — orbital signal traces (background) + carousel of outcome words
const V5Hero = () => {
  const cycleWords = ["legible", "desirable", "usable", "teachable", "buildable", "trusted"];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setIdx((i) => (i + 1) % cycleWords.length), 2200);
    return () => clearInterval(id);
  }, []);
  const today = new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }).toUpperCase();
  return (
    <section id="top" className="v4-hero v5-hero">
      {/* Ambient orbital signal traces — sun/moon/planet system, quieter background */}
      <svg className="v5-hero-arcs" viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
        <defs>
          <radialGradient id="v5-hero-photon">
            <stop offset="0%" stopColor="var(--v4-accent-hi)" stopOpacity="1" />
            <stop offset="55%" stopColor="var(--v4-accent)" stopOpacity="0.55" />
            <stop offset="100%" stopColor="var(--v4-accent)" stopOpacity="0" />
          </radialGradient>
        </defs>

        {/* SUN — large slow orbit, lower-right */}
        <circle cx="1180" cy="640" r="420" fill="none" stroke="var(--v4-accent)" strokeWidth="0.7" strokeDasharray="2 14" className="v5-hero-orbit v5-hero-orbit-sun" />
        <path id="v5-orbit-path-sun" d="M 1180 220 A 420 420 0 1 1 1179.99 220" fill="none" />

        {/* PLANET — mid-size, upper-left */}
        <circle cx="320" cy="280" r="240" fill="none" stroke="var(--v4-accent)" strokeWidth="0.8" strokeDasharray="2 10" className="v5-hero-orbit v5-hero-orbit-planet" />
        <path id="v5-orbit-path-planet" d="M 320 40 A 240 240 0 1 1 319.99 40" fill="none" />

        {/* MOON — small fast orbit, mid-right */}
        <circle cx="1340" cy="280" r="140" fill="none" stroke="var(--v4-accent)" strokeWidth="0.7" strokeDasharray="1 8" className="v5-hero-orbit v5-hero-orbit-moon" />
        <path id="v5-orbit-path-moon" d="M 1340 140 A 140 140 0 1 1 1339.99 140" fill="none" />

        {/* Photons — 3 on sun, 2 on planet, 2 on moon. Evenly distributed via begin offsets */}
        {/* Sun: 24s orbit, photons at 0s / 8s / 16s (evenly 1/3 apart) */}
        <circle r="5.5" fill="url(#v5-hero-photon)" className="v5-hero-photon">
          <animateMotion dur="24s" begin="0.6s" repeatCount="indefinite" rotate="auto"><mpath href="#v5-orbit-path-sun" /></animateMotion>
        </circle>
        <circle r="4" fill="url(#v5-hero-photon)" className="v5-hero-photon">
          <animateMotion dur="24s" begin="8.6s" repeatCount="indefinite" rotate="auto"><mpath href="#v5-orbit-path-sun" /></animateMotion>
        </circle>
        <circle r="3" fill="url(#v5-hero-photon)" className="v5-hero-photon">
          <animateMotion dur="24s" begin="16.6s" repeatCount="indefinite" rotate="auto"><mpath href="#v5-orbit-path-sun" /></animateMotion>
        </circle>

        {/* Planet: 14s orbit, photons at 0s / 7s (evenly 1/2 apart) */}
        <circle r="4.5" fill="url(#v5-hero-photon)" className="v5-hero-photon">
          <animateMotion dur="14s" begin="1.2s" repeatCount="indefinite" rotate="auto"><mpath href="#v5-orbit-path-planet" /></animateMotion>
        </circle>
        <circle r="3" fill="url(#v5-hero-photon)" className="v5-hero-photon">
          <animateMotion dur="14s" begin="8.2s" repeatCount="indefinite" rotate="auto"><mpath href="#v5-orbit-path-planet" /></animateMotion>
        </circle>

        {/* Moon: 8s orbit, photons at 0s / 4s */}
        <circle r="3.5" fill="url(#v5-hero-photon)" className="v5-hero-photon">
          <animateMotion dur="8s" begin="2s" repeatCount="indefinite" rotate="auto"><mpath href="#v5-orbit-path-moon" /></animateMotion>
        </circle>
        <circle r="2.5" fill="url(#v5-hero-photon)" className="v5-hero-photon">
          <animateMotion dur="8s" begin="6s" repeatCount="indefinite" rotate="auto"><mpath href="#v5-orbit-path-moon" /></animateMotion>
        </circle>
      </svg>

      <div className="v4-container v5-hero-container">
        <FadeIn as="div" className="v4-hero-meta-top">
          <span data-cursor="Mountain time"><span className="v4-hero-status-dot"></span>Boulder, Colorado · est. 2013</span>
          <span data-cursor="Practice · 2026">Product + Brand Systems · AI Design Engineering · Teaching + Research</span>
          <span data-cursor={`Edition 05 · ${today}`}>{today} · ed. 05</span>
        </FadeIn>

        <h1 className="v4-hero-headline v5-hero-headline" style={{ fontWeight: "400", fontFamily: "\"Hanken Grotesk\"", fontSize: "83px" }}>
          <WordReveal text="I help unfamiliar ideas become products, brands, and systems people understand, trust, and use." stagger={40} />
        </h1>

        <div className="v5-hero-tag">
          <FadeIn delay={250}>
            <span className="v5-hero-tag-mark">—</span> <span className="wire-underline always v5-hero-tag-spine" data-cursor="The spine of the practice"><SplitText text="Making new categories make sense." className="v5-hero-tag-split" /></span>
          </FadeIn>
        </div>

        <div className="v4-hero-foot v5-hero-foot">
          <div className="v4-hero-foot-block">
            <span className="v4-hero-foot-label">— The practice</span>
            <p className="v4-hero-foot-text" style={{ fontSize: "19px" }}>
              <FadeIn delay={400}>
                Design director, author, educator, and AI-native maker. I work where ideas are still becoming clear:{'\u00A0'}<span className="wire-underline emph">product, brand, research, regulated markets, and emerging technology.</span> The category changes. The job is to make it legible.
              </FadeIn>
            </p>
          </div>
          <div className="v4-hero-foot-block">
            <span className="v4-hero-foot-label">— The work</span>
            <p className="v4-hero-foot-text" style={{ fontSize: "19px" }}>
              <FadeIn delay={550}>
                Find the signal. Shape the system. Build the proof. Websites, brand systems, product concepts, packaging, social systems, AI prototypes, and teaching frameworks for ideas that need to become understandable.
              </FadeIn>
            </p>
          </div>
          <div className="v4-hero-foot-block">
            <span className="v4-hero-foot-label">— Now</span>
            <p className="v4-hero-foot-text" style={{ fontSize: "19px" }}>
              <FadeIn delay={700}>
                Open for select <span className="wire-underline emph">2026</span> work.<br />Consulting, embedded advisory, Portal studio collaborations, AI prototype sprints, workshops, teaching engagements, and leadership conversations.
              </FadeIn>
            </p>
          </div>
        </div>
      </div>
    </section>);

};

Object.assign(window, { V5Nav, V5Hero, WordReveal, FadeIn });