/* Common Works — chrome: nav, footer, reveal */
const { useState, useEffect, useRef } = React;

/* Scroll/rect-based reveal — robust inside preview iframes where
   IntersectionObserver / rAF / CSS transitions can be frame-throttled.
   The visible state is ALWAYS reached, even if transitions never advance,
   by self-healing any element that is still hidden after it should have shown. */
const _revealEls = new Set();      // not yet in viewport
const _armed = new Set();          // "in" added, awaiting transition / self-heal
let _revealBound = false;

function _forceVisible(el) {
  // jump straight to the visible end-state without relying on a transition
  el.style.opacity = "1";
  el.style.transform = "none";
  if (el.classList.contains("stagger")) {
    for (const c of el.children) { c.style.opacity = "1"; c.style.transform = "none"; }
  }
}
function _reveal(el) {
  el.classList.add("in");
  _revealEls.delete(el);
  _armed.add(el);
  // backstop: if the CSS transition can't run (frozen compositor), the element
  // would stay at opacity 0 — after the transition window, force it visible.
  setTimeout(() => {
    if (!_armed.has(el)) return;
    _armed.delete(el);
    const probe = el.classList.contains("stagger") ? (el.children[0] || el) : el;
    if (parseFloat(getComputedStyle(probe).opacity) < 0.9) {
      // transitions are not advancing in this environment — drop animation globally
      document.documentElement.classList.add("no-anim");
      _forceVisible(el);
    }
  }, 1000);
}
function _checkReveals() {
  const vh = window.innerHeight || document.documentElement.clientHeight;
  _revealEls.forEach((el) => {
    const r = el.getBoundingClientRect();
    if (r.top < vh * 0.9 && r.bottom > 0) _reveal(el);
  });
}
function _bindReveals() {
  if (_revealBound) return;
  _revealBound = true;
  const handler = () => window.requestAnimationFrame(_checkReveals);
  window.addEventListener("scroll", handler, { passive: true });
  window.addEventListener("resize", handler, { passive: true });
  // final safety: reveal (and guarantee-visible) everything regardless after load
  setTimeout(() => {
    _revealEls.forEach((el) => _reveal(el));
  }, 2000);
}

function Reveal({ children, className = "", as = "div", stagger = false, ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    _bindReveals();
    _revealEls.add(el);
    _checkReveals();
    const t = setTimeout(_checkReveals, 60);
    return () => { clearTimeout(t); _revealEls.delete(el); _armed.delete(el); };
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className={(stagger ? "stagger " : "reveal ") + className} {...rest}>
      {children}
    </Tag>
  );
}

function BrandMark() {
  return (
    <span className="brand-mark" aria-hidden="true">
      <span style={{ left: 0, top: 0, width: 7, height: 7 }} />
      <span style={{ right: 0, top: 0, width: 7, height: 7, opacity: .55 }} />
      <span style={{ left: 0, bottom: 0, width: 7, height: 7, opacity: .55 }} />
      <span style={{ right: 0, bottom: 0, width: 7, height: 7 }} />
    </span>
  );
}

function TopNav({ route, go }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  function navigate(id) { setMenuOpen(false); go(id); }

  return (
    <>
      <nav className={"nav" + (scrolled ? " scrolled" : "")}>
        <div className="wrap-wide nav-in">
          <a className="brand" href="#/" onClick={(e) => { e.preventDefault(); navigate("home"); }}>
            <BrandMark />
            <span className="wordmark">Common <b>Works</b></span>
          </a>
          <div className="nav-links">
            {window.CW.nav.map((n) => (
              <a key={n.id} className={"nav-link" + (route === n.id ? " active" : "")}
                 href={"#/" + n.id}
                 onClick={(e) => { e.preventDefault(); go(n.id); }}>
                {n.label}
              </a>
            ))}
          </div>
          <div className="nav-cta">
            <a className="btn btn-primary nav-talk" href={"mailto:" + window.CW.email}>
              Talk to us <Arrow />
            </a>
            <button className="nav-burger" aria-label={menuOpen ? "Close menu" : "Open menu"}
                    aria-expanded={menuOpen} onClick={() => setMenuOpen(o => !o)}>
              {menuOpen
                ? <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M4 4l12 12M16 4L4 16" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
                : <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M3 6h14M3 10h14M3 14h14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
              }
            </button>
          </div>
        </div>
      </nav>
      {menuOpen && (
        <div className="mobile-menu">
          <nav>
            {window.CW.nav.map((n) => (
              <a key={n.id}
                 className={"mobile-nav-link" + (route === n.id ? " active" : "")}
                 href={"#/" + n.id}
                 onClick={(e) => { e.preventDefault(); navigate(n.id); }}>
                {n.label}
              </a>
            ))}
          </nav>
          <a className="btn btn-primary mobile-menu-cta" href={"mailto:" + window.CW.email}>
            Talk to us <Arrow />
          </a>
        </div>
      )}
    </>
  );
}

function Footer({ go }) {
  const CW = window.CW;
  return (
    <footer className="footer">
      <div className="wrap-wide footer-top">
        <div className="footer-grid">
          <div>
            <span className="wordmark">Common Works</span>
            <p className="footer-desc">{CW.tagline}</p>
            <p className="footer-location">{CW.location}</p>
          </div>
          <div className="footer-col">
            <h4>Firm</h4>
            <ul>
              <li><a href="#/what" onClick={(e)=>{e.preventDefault();go("what");}}>What We Do</a></li>
              <li><a href="#/careers" onClick={(e)=>{e.preventDefault();go("careers");}}>Join Us</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Contact</h4>
            <ul>
              <li><a href={"mailto:" + CW.email}>{CW.email}</a></li>
              <li><a href={"https://" + CW.domain}>{CW.domain}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Legal</h4>
            <ul>
              <li><a href="#/terms" onClick={(e)=>{e.preventDefault();go("terms");}}>Terms of Service</a></li>
              <li><a href="#/privacy" onClick={(e)=>{e.preventDefault();go("privacy");}}>Privacy Policy</a></li>
            </ul>
          </div>
        </div>
      </div>
      <div className="wrap-wide footer-bottom">
        <span>© {new Date().getFullYear()} Common Works<span className="footer-loc-sep"> · </span><span className="footer-loc">{CW.location}</span></span>
        <span><a href={"mailto:" + CW.email}>{CW.email}</a></span>
      </div>
    </footer>
  );
}

Object.assign(window, { Reveal, TopNav, Footer, BrandMark });
