/* Mega menu data */
const MEGA_MENUS = {
  projects: {
    cols: 1,
    items: [
      { label: "FiveM Scripts", sub: "01", desc: "Server-side systems and tools. The first complete project.", href: "fivem.html" },
      { label: "Untitled Tool", sub: "02", desc: "A small utility quietly in development.", href: "#", soon: true },
      { label: "Notebook", sub: "03", desc: "Notes, experiments, and writing. Public when ready.", href: "#", soon: true },
    ],
  },
  fivem: {
    cols: 2,
    left: [
      { label: "Overview", desc: "What FiveM scripts we ship and why." },
      { label: "Faction", desc: "Group structures, ranks, shared tooling." },
      { label: "Sidejobs", desc: "Small, repeatable work for downtime." },
      { label: "Robbery", desc: "Heist and stickup systems with real friction." },
    ],
    right: [
      { label: "Core", desc: "Foundations the rest of the suite leans on." },
      { label: "Jobs", desc: "Whitelisted work — the structured side." },
      { label: "Custom work", desc: "Need something specific? Write to us." },
    ],
    footer: { label: "Browse all 18 scripts →", href: "fivem.html" },
  },
  manifesto: {
    cols: 1,
    items: [
      { label: "Why after hours?", sub: "i", desc: "Ideas breathe best without a roadmap." },
      { label: "How we build", sub: "ii", desc: "One complete thought at a time, shipped when ready." },
      { label: "Who it's for", sub: "iii", desc: "Server owners who'd rather read docs than guess." },
    ],
  },
  contact: {
    cols: 1,
    items: [
      { label: "Discord", sub: "↗", desc: "Fastest way to reach us — community + support.", href: "https://discord.gg/afterhoursofficial" },
      { label: "Email", sub: "↗", desc: "For custom work and longer conversations.", href: "#" },
      { label: "Custom work", sub: "→", desc: "After-hours builds happen after-hours — write us.", href: "#" },
    ],
  },
};

/* Single mega dropdown panel */
const MegaMenu = ({ id, data, visible }) => {
  if (!data) return null;

  return (
    <div className={`mega-menu ${visible ? "mega-menu--visible" : ""}`} role="region" aria-label={id + " menu"}>
      <div className="mega-menu-inner">
        {data.cols === 2 ? (
          <div className="mega-cols">
            <div className="mega-col">
              {data.left.map((item, i) => (
                <a key={i} className="mega-item" href={item.href || "#"} onClick={!item.href ? (e) => e.preventDefault() : undefined}>
                  <span className="mega-item-n">{String(i + 1).padStart(2, "0")}</span>
                  <span className="mega-item-body">
                    <span className="mega-item-label">{item.label}</span>
                    <span className="mega-item-desc">{item.desc}</span>
                  </span>
                </a>
              ))}
            </div>
            <div className="mega-divider" aria-hidden="true"></div>
            <div className="mega-col">
              {data.right.map((item, i) => (
                <a key={i} className="mega-item" href={item.href || "#"} onClick={!item.href ? (e) => e.preventDefault() : undefined}>
                  <span className="mega-item-n">{String(data.left.length + i + 1).padStart(2, "0")}</span>
                  <span className="mega-item-body">
                    <span className="mega-item-label">{item.label}</span>
                    <span className="mega-item-desc">{item.desc}</span>
                  </span>
                </a>
              ))}
              {data.footer && (
                <a href={data.footer.href} className="mega-footer-link">
                  <span className="mega-item-label">{data.footer.label}</span>
                </a>
              )}
            </div>
          </div>
        ) : (
          <div className="mega-col mega-col--single">
            {data.items.map((item, i) => (
              <a
                key={i}
                className={`mega-item ${item.soon ? "mega-item--soon" : ""}`}
                href={item.href || "#"}
                onClick={!item.href ? (e) => e.preventDefault() : undefined}
              >
                <span className="mega-item-n">{item.sub || String(i + 1).padStart(2, "0")}</span>
                <span className="mega-item-body">
                  <span className="mega-item-label">{item.label}{item.soon && <span className="mega-soon-tag">Soon</span>}</span>
                  <span className="mega-item-desc">{item.desc}</span>
                </span>
              </a>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

/* Top nav with theme toggle, scroll-state, and mega menus */
const Nav = ({ theme, onToggleTheme }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [openMenu, setOpenMenu] = React.useState(null);
  const closeTimer = React.useRef(null);
  const navRef = React.useRef(null);

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

  // Close on click outside
  React.useEffect(() => {
    const handler = (e) => {
      if (navRef.current && !navRef.current.contains(e.target)) {
        setOpenMenu(null);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const handleEnter = (id) => {
    clearTimeout(closeTimer.current);
    setOpenMenu(id);
  };

  const handleLeave = () => {
    closeTimer.current = setTimeout(() => setOpenMenu(null), 120);
  };

  const isFivem = typeof location !== "undefined" && /fivem/i.test(location.pathname);
  const home = isFivem ? "index.html" : "#top";
  const link = (anchor) => isFivem ? `index.html${anchor}` : anchor;
  const isDark = theme === "dark";

  const NAV_ITEMS = [
    { id: "manifesto", label: "Manifesto", href: link("#manifesto") },
    { id: "projects",  label: "Projects",  href: link("#projects") },
    { id: "fivem",     label: "FiveM",     href: "fivem.html" },
    { id: "contact",   label: "Contact",   href: link("#contact") },
  ];

  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""} ${openMenu ? "nav--menu-open" : ""}`} ref={navRef}>
      <a href={home} className="nav-brand">
        <span className="nav-mark"></span>
        <span>After-Hours</span>
      </a>

      <div className="nav-links">
        {NAV_ITEMS.map(({ id, label, href }) => (
          <div
            key={id}
            className="nav-item-wrap"
            onMouseEnter={() => handleEnter(id)}
            onMouseLeave={handleLeave}
          >
            <a
              href={href}
              className={`nav-link ${openMenu === id ? "nav-link--active" : ""}`}
              aria-expanded={openMenu === id}
              aria-haspopup="true"
            >
              {label}
              <span className="nav-link-caret" aria-hidden="true"></span>
            </a>
            <MegaMenu id={id} data={MEGA_MENUS[id]} visible={openMenu === id} />
          </div>
        ))}
      </div>

      <button
        type="button"
        className="theme-toggle"
        onClick={onToggleTheme}
        aria-label={isDark ? "Switch to light theme" : "Switch to dark theme"}
        aria-pressed={isDark}
      >
        <span className="theme-toggle-glyph" aria-hidden="true">{isDark ? "☀" : "☾"}</span>
        <span className="theme-toggle-label">{isDark ? "Light" : "Dark"}</span>
      </button>
    </nav>
  );
};

/* HERO */
const Hero = () => {
  return (
    <section className="hero" id="top">
      <div className="hero-grid" aria-hidden="true"></div>
      <div className="container" style={{ position: "relative", zIndex: 1, width: "100%" }}>
        <div className="hero-meta">
          <span><span className="dot"></span>Studio open · 24/7</span>
          <span>est. MMXXVI</span>
          <span>v 01 — fivem</span>
        </div>

        <h1 className={`hero-title in`}>
          <span className="line"><span>Built after</span></span>
          <span className="line"><span><em>hours.</em></span></span>
          <span className="line"><span>Released for everyone.</span></span>
        </h1>

        <div className="hero-bottom">
          <p className="hero-lede">
            <strong>After-Hours</strong> is a quiet studio for unusual software.
            One project at a time, made carefully, shipped without fanfare.
          </p>
          <div className="eyebrow" style={{ alignSelf: "end" }}>
            01 / Currently shipping<br />
            <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 22, color: "var(--fg)", textTransform: "none", letterSpacing: 0 }}>
              FiveM scripts
            </span>
          </div>
          <a href="fivem.html" className="hero-cta">
            View work <span className="arrow">→</span>
          </a>
        </div>
      </div>

      <div className="hero-scroll">
        <span>Scroll</span>
        <div className="hero-scroll-line"></div>
      </div>
    </section>
  );
};

/* TICKER */
const Ticker = () => {
  const items = [
    "Built after hours",
    "Released for everyone",
    "Scripts. Tools. Strange ideas.",
    "Quiet software, loud care",
    "FiveM · Vol. 01",
  ];
  const Row = () => (
    <span>
      {items.map((t, i) => (
        <React.Fragment key={i}>
          {t}
          <span className="sep" aria-hidden="true"></span>
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker-track">
        <Row />
        <Row />
      </div>
    </div>
  );
};

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