/* global React */
const { useState, useEffect, useRef } = React;

// ============================================================
// Cursor crosshair + coordinates (lots of motion)
// ============================================================
function Cursor() {
  const [pos, setPos] = useState({ x: -100, y: -100 });
  const [over, setOver] = useState(false);

  useEffect(() => {
    const move = (e) => setPos({ x: e.clientX, y: e.clientY });
    const enter = (e) => {
      if (e.target.closest && e.target.closest("a,button,.hover-target"))
        setOver(true);
    };
    const leave = (e) => {
      if (e.target.closest && e.target.closest("a,button,.hover-target"))
        setOver(false);
    };
    window.addEventListener("mousemove", move);
    document.addEventListener("mouseover", enter);
    document.addEventListener("mouseout", leave);
    return () => {
      window.removeEventListener("mousemove", move);
      document.removeEventListener("mouseover", enter);
      document.removeEventListener("mouseout", leave);
    };
  }, []);

  if (window.matchMedia && window.matchMedia("(max-width: 720px)").matches)
    return null;

  return (
    <React.Fragment>
      <div
        className={"cursor " + (over ? "dot" : "")}
        style={{ transform: `translate(${pos.x}px, ${pos.y}px) translate(-50%, -50%)` }}
      />
      <div className="cursor-coords" style={{ left: pos.x, top: pos.y }}>
        x{String(pos.x).padStart(4, "0")} · y{String(pos.y).padStart(4, "0")}
      </div>
    </React.Fragment>
  );
}

// ============================================================
// Status bar (fake "build status" / time)
// ============================================================
function StatusBar() {
  const [time, setTime] = useState("");
  useEffect(() => {
    const tick = () => {
      const d = new Date();
      const fmt = (n) => String(n).padStart(2, "0");
      setTime(`${fmt(d.getHours())}:${fmt(d.getMinutes())}:${fmt(d.getSeconds())}`);
    };
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="statusbar">
      <span className="dot" />
      <span>arman.chaudhary / portfolio.v2</span>
      <span className="seg hide-sm">build 0024 · main</span>
      <span className="seg hide-sm">chandigarh, in · utc+5:30</span>
      <span className="spacer" />
      <span className="seg hide-sm">status: shipping</span>
      <span className="seg">{time}</span>
    </div>
  );
}

// ============================================================
// Nav
// ============================================================
const NAV = [
  { id: "home", label: "Index", num: "00" },
  { id: "about", label: "About", num: "01" },
  { id: "skills", label: "Stack", num: "02" },
  { id: "projects", label: "Projects", num: "03" },
  { id: "experience", label: "Experience", num: "04" },
  { id: "hackathons", label: "Hackathons", num: "05" },
  { id: "contact", label: "Connect", num: "06" },
];

function Nav() {
  const [active, setActive] = useState("home");
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + window.innerHeight * 0.35;
      let cur = "home";
      for (const n of NAV) {
        const el = document.getElementById(n.id);
        if (el && el.offsetTop <= y) cur = n.id;
      }
      setActive(cur);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    if (!open) return undefined;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);
  const go = (e, id) => {
    e.preventDefault();
    setOpen(false);
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  const current = NAV.find((n) => n.id === active) || NAV[0];
  return (
    <React.Fragment>
      <nav className={"nav " + (open ? "nav-open" : "")}>
        <div className="nav-inner">
          <button
            type="button"
            className="nav-toggle mono hover-target"
            onClick={() => setOpen((o) => !o)}
            aria-expanded={open}
            aria-label="Toggle navigation"
          >
            <span className="num">{current.num}</span>
            <span className="nav-toggle-label">{current.label}</span>
            <span className="nav-toggle-icon" aria-hidden="true">{open ? "×" : "≡"}</span>
          </button>
          <div className="nav-links">
            {NAV.map((n) => (
              <a
                key={n.id}
                href={"#" + n.id}
                onClick={(e) => go(e, n.id)}
                className={"nav-link mono " + (active === n.id ? "active" : "")}
              >
                <span className="num">{n.num}</span>
                {n.label}
              </a>
            ))}
          </div>
        </div>
      </nav>
      {open && <div className="nav-scrim" onClick={() => setOpen(false)} />}
    </React.Fragment>
  );
}

// ============================================================
// Reveal hook
// ============================================================
function useReveal(enabled = true) {
  useEffect(() => {
    if (!enabled) return undefined;

    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );

    document.querySelectorAll(".reveal:not(.in)").forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [enabled]);
}

Object.assign(window, { Cursor, StatusBar, Nav, NAV, useReveal });
