// Shared nav + footer + magnetic / kinetic helpers
const { useEffect: useEffectNav, useState: useStateNav, useRef: useRefNav } = React;

function Nav({ current, onNav }) {
  const links = [
    { id: "top", label: "Top" },
    { id: "about", label: "About" },
    { id: "service", label: "Service" },
    { id: "contact", label: "Contact" },
  ];
  // Marquee hero (Top + Top variant) renders a dark navy background — invert the nav there.
  // We detect dark sections by reading the background color at the top of the page.
  const [onDark, setOnDark] = useStateNav(false);
  const [menuOpen, setMenuOpen] = useStateNav(false);

  // Lock body scroll while mobile menu is open.
  useEffectNav(() => {
    if (menuOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  // Close menu when navigating (current route changes).
  useEffectNav(() => { setMenuOpen(false); }, [current]);
  useEffectNav(() => {
    const probe = () => {
      const el = document.elementFromPoint(window.innerWidth / 2, 110);
      if (!el) return;
      // walk up to find a non-transparent bg
      let node = el;
      while (node && node !== document.body) {
        const bg = getComputedStyle(node).backgroundColor;
        if (bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent") {
          // parse rgb
          const m = bg.match(/\d+/g);
          if (m) {
            const [r, g, b] = m.map(Number);
            const luma = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
            setOnDark(luma < 0.5);
          }
          return;
        }
        node = node.parentElement;
      }
      setOnDark(false);
    };
    probe();
    window.addEventListener("scroll", probe, { passive: true });
    window.addEventListener("hashchange", () => setTimeout(probe, 100));
    return () => window.removeEventListener("scroll", probe);
  }, [current]);

  return (
    <header className="nav" data-on-dark={onDark ? "true" : "false"} data-menu-open={menuOpen ? "true" : "false"}>
      <a href="#top" className="nav__logo" data-cursor="hover" onClick={(e) => { e.preventDefault(); onNav("top"); setMenuOpen(false); }} aria-label="frevia">
        <img className="nav__logo-img" src="../assets/frevia-logo.png" alt="frevia" />
      </a>

      {/* Hamburger button — only visible on mobile via CSS */}
      <button
        className="nav__burger"
        aria-label={menuOpen ? "メニューを閉じる" : "メニューを開く"}
        aria-expanded={menuOpen ? "true" : "false"}
        onClick={() => setMenuOpen((v) => !v)}
        data-cursor="hover"
      >
        <span className={`nav__burger-bar nav__burger-bar--1 ${menuOpen ? "is-open" : ""}`} />
        <span className={`nav__burger-bar nav__burger-bar--2 ${menuOpen ? "is-open" : ""}`} />
        <span className={`nav__burger-bar nav__burger-bar--3 ${menuOpen ? "is-open" : ""}`} />
      </button>

      <nav className={`nav__links ${menuOpen ? "is-open" : ""}`}>
        {links.map((l) => (
          <a
            key={l.id}
            href={`#${l.id}`}
            className={`nav__link ${current === l.id ? "is-active" : ""}`}
            data-cursor="hover"
            onClick={(e) => { e.preventDefault(); onNav(l.id); setMenuOpen(false); }}
          >
            {l.label}
          </a>
        ))}
        <a
          href="#contact"
          className="nav__link nav__link--cta-mobile"
          data-cursor="hover"
          onClick={(e) => { e.preventDefault(); onNav("contact"); setMenuOpen(false); }}
        >
          Contact ↗
        </a>
      </nav>

      <a
        href="#contact"
        className="nav__cta"
        data-cursor="hover"
        onClick={(e) => { e.preventDefault(); onNav("contact"); }}
      >
        Contact ↗
      </a>
    </header>
  );
}

function Footer({ onNav }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__big">
          <img className="footer__big-img" src="../assets/frevia-logo.png" alt="frevia" />
        </div>

        <div className="footer__grid">
          <div className="footer__col">
            <h4>Mission</h4>
            <p style={{ fontSize: 18, lineHeight: 1.5, marginTop: 8 }}>
              向き合える自由を、<br />すべての人に。
            </p>
          </div>
          <div className="footer__col">
            <h4>Sitemap</h4>
            <a href="#top" data-cursor="hover" onClick={(e) => { e.preventDefault(); onNav("top"); }}>Top</a>
            <a href="#about" data-cursor="hover" onClick={(e) => { e.preventDefault(); onNav("about"); }}>About</a>
            <a href="#service" data-cursor="hover" onClick={(e) => { e.preventDefault(); onNav("service"); }}>Service</a>
            <a href="#contact" data-cursor="hover" onClick={(e) => { e.preventDefault(); onNav("contact"); }}>Contact</a>
          </div>
          <div className="footer__col">
            <h4>Contact</h4>
            <p>〒104-0061</p>
            <p>東京都中央区銀座1-12-4</p>
            <p>N&amp;E BLD. 7階</p>
          </div>
          <div className="footer__col">
            <h4>Established</h4>
            <p>2026.01.05</p>
            <p style={{ marginTop: 12 }}>代表取締役</p>
            <p>森田 伸之介</p>
          </div>
        </div>

        <div className="footer__bottom">
          <span>© 2026 frevia Inc. All rights reserved.</span>
          <span>Crafted with curiosity in Ginza, Tokyo.</span>
        </div>
      </div>
    </footer>
  );
}

// Kinetic text — splits Japanese chars and applies hover transforms.
// On mount, each char briefly shows a palette color (navy → sky → terra rotation),
// then fades to inherit (--ink) over ~1.2s, staggered per char.
const KINETIC_PALETTE = ["#335C8E", "#7BC7E2", "#C84632", "#335C8E", "#7BC7E2", "#1F3D63"];

function Kinetic({ text, className = "", style = {}, colorize = true, dotAt = null }) {
  const [colorized, setColorized] = useStateNav(colorize);
  useEffectNav(() => {
    if (!colorize) return;
    setColorized(true);
    const t = setTimeout(() => setColorized(false), 900);
    return () => clearTimeout(t);
  }, [colorize, text]);

  const chars = Array.from(text);
  return (
    <span className={`kinetic ${className}`} style={style}>
      {chars.map((c, i) => {
        const charColor = KINETIC_PALETTE[i % KINETIC_PALETTE.length];
        const isDot = dotAt !== null && i === dotAt;
        return (
          <span
            key={i}
            className="kinetic__char"
            style={{
              display: c === " " ? "inline" : "inline-block",
              whiteSpace: c === " " ? "pre" : "normal",
              color: colorized ? charColor : "inherit",
              transitionDelay: `${i * 0.06}s`,
              position: isDot ? "relative" : undefined,
            }}
          >
            {c === " " ? "\u00A0" : c}
            {isDot ? (
              <span
                aria-hidden="true"
                style={{
                  position: "absolute",
                  left: "50%",
                  top: "0.12em",
                  width: "0.22em",
                  height: "0.22em",
                  borderRadius: "50%",
                  background: "var(--terra)",
                  transform: "translate(calc(-50% + 0.02em), 0)",
                  pointerEvents: "none",
                }}
              />
            ) : null}
          </span>
        );
      })}
    </span>
  );
}

// Magnetic — element subtly follows cursor when nearby
function Magnetic({ children, strength = 0.3, className, style }) {
  const ref = useRefNav(null);
  useEffectNav(() => {
    const el = ref.current;
    if (!el) return;
    let raf;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = (e.clientX - cx) * strength;
      const dy = (e.clientY - cy) * strength;
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        el.style.transform = `translate(${dx}px, ${dy}px)`;
      });
    };
    const onLeave = () => { el.style.transform = "translate(0,0)"; };
    el.addEventListener("mousemove", onMove);
    el.addEventListener("mouseleave", onLeave);
    return () => {
      el.removeEventListener("mousemove", onMove);
      el.removeEventListener("mouseleave", onLeave);
    };
  }, [strength]);
  return (
    <span ref={ref} className={className} style={{ display: "inline-block", transition: "transform 0.4s var(--easing)", ...style }}>
      {children}
    </span>
  );
}

// Floating background shapes — playful blobs and stickers
function FloatingShapes({ palette = "default" }) {
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none", zIndex: 0 }}>
      <div className="blob shape-float" style={{ width: 360, height: 360, background: "var(--sky)", top: "10%", left: "70%", animationDelay: "0s" }} />
      <div className="blob shape-float" style={{ width: 240, height: 240, background: "var(--navy)", top: "62%", left: "8%", animationDelay: "-3s", opacity: 0.12 }} />
      <div className="blob shape-float" style={{ width: 180, height: 180, background: "var(--terra)", top: "76%", left: "82%", animationDelay: "-5s", opacity: 0.18 }} />
    </div>
  );
}

// Section heading with eyebrow
function SectionHeading({ eyebrow, title, lead, align = "left" }) {
  return (
    <div style={{ textAlign: align, maxWidth: 900, marginInline: align === "center" ? "auto" : 0, marginBottom: 60 }}>
      <span className="eyebrow">{eyebrow}</span>
      <h2 className="h-section" style={{ marginTop: 18, textWrap: "balance" }}>{title}</h2>
      {lead ? <p style={{ marginTop: 24, fontSize: 20, color: "var(--ink-2)", maxWidth: 640, lineHeight: 1.75 }}>{lead}</p> : null}
    </div>
  );
}

Object.assign(window, { Nav, Footer, Kinetic, Magnetic, FloatingShapes, SectionHeading });
