// Shared UI helpers
const { useState, useEffect, useRef, useMemo } = React;

function Reveal({ children, delay = 0, as: Tag = "div", ...rest }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) {setTimeout(() => setVisible(true), delay);io.unobserve(el);}});
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <Tag ref={ref} {...rest} className={(rest.className || "") + " reveal" + (visible ? " is-in" : "")}>{children}</Tag>;
}

function ThemeToggle() {
  const [mode, setMode] = useState(() => {
    try {return localStorage.getItem("stz_theme") || "system";}
    catch {return "system";}
  });

  useEffect(() => {
    const root = document.documentElement;
    const apply = () => {
      let effective = mode;
      if (mode === "system") {
        effective = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
      }
      if (effective === "dark") root.setAttribute("data-theme", "dark");else
      root.removeAttribute("data-theme");
    };
    apply();
    try {localStorage.setItem("stz_theme", mode);} catch {}

    if (mode === "system") {
      const mq = window.matchMedia("(prefers-color-scheme: dark)");
      const handler = () => apply();
      mq.addEventListener?.("change", handler);
      return () => mq.removeEventListener?.("change", handler);
    }
  }, [mode]);

  const opts = [
  { val: "light", label: "Light",
    icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" /></svg>
  },
  { val: "system", label: "System",
    icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="13" rx="1.5" /><path d="M8 21h8M12 17v4" /></svg>
  },
  { val: "dark", label: "Dark",
    icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" /></svg>
  }];

  const cycle = () => {
    const i = opts.findIndex((o) => o.val === mode);
    setMode(opts[(i + 1) % opts.length].val);
  };
  const current = opts.find((o) => o.val === mode) || opts[1];

  return (
    <>
      <div className="theme-toggle theme-toggle--seg" role="group" aria-label="Theme">
        {opts.map((o) =>
        <button
          key={o.val}
          type="button"
          className={mode === o.val ? "is-active" : ""}
          onClick={() => setMode(o.val)}
          aria-label={o.label}
          aria-pressed={mode === o.val}
          title={o.label}>
            {o.icon}
          </button>
        )}
      </div>
      <button
        type="button"
        className="theme-toggle--cycle"
        onClick={cycle}
        aria-label={"Theme: " + current.label + ". Tap to change."}
        title={"Theme: " + current.label}>
        {current.icon}
      </button>
    </>);

}

function Nav({ current, onGo }) {
  const [stuck, setStuck] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setStuck(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => {document.body.style.overflow = "";};
  }, [open]);
  const isAdmin = window.isAdmin?.();
  const links = [
  ["home", "Home"],
  ["about", "About"],
  ["work", "Work"],
  ["services", "Services"],
  ["insights", "Insights"],
  ...(isAdmin ? [["publish", "Publish"]] : []),
  ["contact", "Contact"]];

  const goAndClose = (id) => {onGo(id);setOpen(false);};
  return (
    <>
    <nav className={"nav" + (stuck ? " is-stuck" : "") + (open ? " is-open" : "")}>
      <div className="wrap nav__inner">
        <button className="brand" onClick={() => goAndClose("home")}>
          <span className="brand__mark" />
          Stanzin <em>·&nbsp;growth</em>
        </button>
        <div className="nav__links">
          {links.map(([id, label]) =>
            <button key={id} className={current === id ? "is-active" : ""} onClick={() => onGo(id)}>{label}</button>
            )}
        </div>
        <div className="nav__cta">
          <span className="nav__mono"></span>
          <ThemeToggle />
          <button className="nav__hire" onClick={() => goAndClose("contact")}>Strategy call →</button>
          <button
              className="nav__burger"
              aria-label="Toggle menu"
              aria-expanded={open}
              onClick={() => setOpen((o) => !o)}>
            
            <span /><span /><span />
          </button>
        </div>
      </div>
    </nav>

    {/* Mobile drawer — sibling of nav so it escapes nav's backdrop-filter containing block */}
    <div className={"mobile-drawer" + (open ? " is-open" : "")} aria-hidden={!open} onClick={(e) => {if (e.target === e.currentTarget) setOpen(false);}}>
      <div className="mobile-drawer__inner">
        {links.map(([id, label], i) =>
          <button
            key={id}
            className={"mobile-drawer__link" + (current === id ? " is-active" : "")}
            onClick={() => goAndClose(id)}
            style={{ transitionDelay: open ? i * 40 + 100 + "ms" : "0ms" }}>
          
            <span className="mobile-drawer__num">{String(i + 1).padStart(2, "0")}</span>
            <span className="mobile-drawer__label">{label}</span>
            <span className="mobile-drawer__arr">↗</span>
          </button>
          )}
        <div className="mobile-drawer__cta">
          <button className="btn btn--accent" onClick={() => goAndClose("contact")}>
            Strategy call <span className="arr">↗</span>
          </button>
        </div>
        <div className="mobile-drawer__foot">
          <span>hello@stanzin.xyz</span>
          <span>Bengaluru · IST</span>
        </div>
      </div>
    </div>
    </>);

}

function SectionHead({ num, title, lede, titleHtml }) {
  return (
    <Reveal className="section__head">
      <div className="section__num">{num}</div>
      <div>
        {titleHtml ?
        <h2 className="section__title" dangerouslySetInnerHTML={{ __html: titleHtml }} /> :
        <h2 className="section__title">{title}</h2>
        }
        {lede && <p className="section__lede">{lede}</p>}
      </div>
    </Reveal>);

}

function Marquee({ items }) {
  const doubled = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee__track">
        {doubled.map((x, i) => <span key={i} className="marquee__item">{x}</span>)}
      </div>
    </div>);

}

function Footer({ onGo }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <h3 className="footer__big">Let's build<br />something <em>meaningful</em>.</h3>
        <div className="footer__grid">
          <div className="footer__col">
            <h4>Stanzin</h4>
            <p style={{ maxWidth: 320, color: "var(--fg-2)", lineHeight: 1.5 }}>
              Independent growth partner for founders, D2C brands, and teams hiring for growth.
            </p>
          </div>
          <div className="footer__col">
            <h4>Pages</h4>
            <a onClick={() => onGo("home")}>Home</a>
            <a onClick={() => onGo("about")}>About</a>
            <a onClick={() => onGo("work")}>Work</a>
            <a onClick={() => onGo("services")}>Services</a>
            <a onClick={() => onGo("insights")}>Insights</a>
            <a onClick={() => onGo("contact")}>Contact</a>
          </div>
          <div className="footer__col">
            <h4>Elsewhere</h4>
            <a>LinkedIn</a><a>X / Twitter</a><a>Read.cv</a><a>Substack</a>
          </div>
          <div className="footer__col">
            <h4>Direct</h4>
            <a>hello@stanzin.me</a>
            <a>Book a call ↗</a>
            <a onClick={() => alert("Resume download — placeholder")}>Download resume ↓</a>
          </div>
        </div>
        <div className="footer__bot">
          <span>© 2026 Stanzin — all rights reserved</span>
          <span>Gurugram · India</span>
          <span>v.04 · last updated apr 2026</span>
        </div>
      </div>
    </footer>);
}

Object.assign(window, { Reveal, Nav, SectionHead, Marquee, Footer });