// Nav + Hero - Clean Institutional system.
// Nav: thin top bar, live timezone strip, Have a chat CTA.
// Hero: left-aligned, word-stagger reveal, locked copy.
const { useEffect, useRef, useState } = React;

function Arrow({ size = 14 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="M2 8h11M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// Three-city timezone strip. Ticks every second silently.
// Minute-boundary → one 300ms opacity fade ("tick" class).
const CITIES = [
  { label: "DXB", tz: "Asia/Dubai" },
  { label: "NYC", tz: "America/New_York" },
];

function formatTime(tz, date) {
  // 24-hour HH:MM, locale-agnostic.
  return new Intl.DateTimeFormat("en-GB", {
    timeZone: tz,
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(date);
}

function TimezoneStrip() {
  const [times, setTimes] = useState(() => {
    const now = new Date();
    return CITIES.map(c => ({ ...c, time: formatTime(c.tz, now), tick: false }));
  });
  const prevMinute = useRef(times.map(t => t.time));

  useEffect(() => {
    const id = setInterval(() => {
      const now = new Date();
      const next = CITIES.map((c, i) => {
        const t = formatTime(c.tz, now);
        const didTick = t !== prevMinute.current[i];
        if (didTick) prevMinute.current[i] = t;
        return { ...c, time: t, tick: didTick };
      });
      setTimes(next);
      if (next.some(n => n.tick)) {
        setTimeout(() => {
          setTimes(curr => curr.map(x => ({ ...x, tick: false })));
        }, 300);
      }
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="tz" aria-label="Our time zones">
      {times.map((c, i) => (
        <React.Fragment key={c.label}>
          <span className={"tz-city" + (c.tick ? " tick" : "")}>
            <span className="tz-label">{c.label}</span>
            <span className="tz-time">{c.time}</span>
          </span>
          {i < times.length - 1 && <span className="tz-dot" aria-hidden="true"/>}
        </React.Fragment>
      ))}
    </div>
  );
}

function BurgerIcon({ open }) {
  return (
    <svg className={"burger-icon"} width="22" height="22" viewBox="0 0 22 22" fill="none" aria-hidden="true">
      {open ? (
        <>
          <line x1="4" y1="4" x2="18" y2="18" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"/>
          <line x1="18" y1="4" x2="4" y2="18" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"/>
        </>
      ) : (
        <>
          <line x1="3" y1="7" x2="19" y2="7" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"/>
          <line x1="3" y1="11" x2="19" y2="11" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"/>
          <line x1="3" y1="15" x2="19" y2="15" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"/>
        </>
      )}
    </svg>
  );
}

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const path = typeof window !== "undefined" ? window.location.pathname : "";
  const isWho = /who(\.html)?$/.test(path);
  const isWork = /work(\.html)?$/.test(path);
  const isSub = isWho || isWork;

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

  useEffect(() => {
    document.body.classList.toggle("menu-open", menuOpen);
    return () => document.body.classList.remove("menu-open");
  }, [menuOpen]);

  const closeMenu = () => setMenuOpen(false);

  return (
    <>
      <nav className={"nav" + (scrolled ? " scrolled" : "") + (menuOpen ? " menu-is-open" : "")} aria-label="Primary">
        <a href={isSub ? "/" : "#top"} className="nav-logo" onClick={closeMenu}>Agent Ventures</a>
        <div className="nav-links">
          <a href="/work" className={isWork ? "is-active" : ""}>Built</a>
          <a href="/who" className={isWho ? "is-active" : ""}>Who we are</a>
        </div>
        <div className="nav-right">
          <TimezoneStrip/>
          <a href="https://calendar.app.google/pr4sprutBxycHg9d7" target="_blank" rel="noopener" className="nav-cta">Have a chat</a>
          <button
            className="nav-burger"
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen(o => !o)}
          >
            <BurgerIcon open={menuOpen}/>
          </button>
        </div>
      </nav>
      {menuOpen && (
        <div className="mobile-menu" role="dialog" aria-label="Navigation menu">
          <nav className="mobile-menu-nav" aria-label="Mobile primary">
            <a href={isSub ? "/" : "#top"} className={"mobile-menu-link" + (!isSub ? " is-active" : "")} onClick={closeMenu}>Home</a>
            <a href="/work" className={"mobile-menu-link" + (isWork ? " is-active" : "")} onClick={closeMenu}>Built</a>
            <a href="/who" className={"mobile-menu-link" + (isWho ? " is-active" : "")} onClick={closeMenu}>Who we are</a>
          </nav>
          <div className="mobile-menu-footer">
            <a href="https://calendar.app.google/pr4sprutBxycHg9d7" target="_blank" rel="noopener" className="btn btn-primary mobile-menu-cta" onClick={closeMenu}>
              Have a chat <Arrow size={16}/>
            </a>
          </div>
        </div>
      )}
    </>
  );
}

// Hero - extreme scale (Hanken 900), rotating domain word on "business".
const ROTATE_WORDS = ["business", "company", "clinic", "operation", "team"];

function RotatingWord({ startDelay = 1500, interval = 1800 }) {
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    let id;
    const start = setTimeout(() => {
      id = setInterval(() => {
        setI(prev => (prev + 1) % ROTATE_WORDS.length);
      }, interval);
    }, startDelay);
    return () => { clearTimeout(start); if (id) clearInterval(id); };
  }, [startDelay, interval]);
  return (
    <span className="rotate-word">
      {ROTATE_WORDS.map((w, idx) => (
        <span key={w} className={"rw-option" + (idx === i ? " is-active" : "")}>{w}</span>
      ))}
    </span>
  );
}

function Hero() {
  // H1 split into tokens. "business" is the rotating domain word.
  const tokens = [
    "We", "build", "what", "the", "next", "decade", "of", "your",
    { rotate: true },
    "should", "run", "on.",
  ];

  const wordDelay = 40;
  const subheadDelay = tokens.length * wordDelay + 160;
  const actionsDelay = subheadDelay + 180;
  const tagsDelay = actionsDelay + 140;

  return (
    <section className="hero" id="top">
      <div className="hero-inner">
        <h1>
          {tokens.map((tok, i) => (
            <React.Fragment key={i}>
              <span className="word" style={{ animationDelay: `${i * wordDelay}ms` }}>
                {tok && tok.rotate ? <RotatingWord/> : tok}
              </span>
              {i < tokens.length - 1 && " "}
            </React.Fragment>
          ))}
        </h1>
        <p className="hero-subhead" style={{ animationDelay: `${subheadDelay}ms` }}>
          We build the AI agents and AI products that run it - shipped in weeks, not quarters.
        </p>
        <div className="hero-actions" style={{ animationDelay: `${actionsDelay}ms` }}>
          <a href="https://calendar.app.google/pr4sprutBxycHg9d7" target="_blank" rel="noopener" className="btn btn-primary">Have a chat <Arrow/></a>
          <a href="#work" className="btn btn-ghost">See the work</a>
        </div>
        <div className="hero-tags" style={{ animationDelay: `${tagsDelay}ms` }}>
          <span className="tag">for businesses</span>
          <span className="tag-sep" aria-hidden="true"/>
          <span className="tag">for founders</span>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Arrow });
