/* global React, Common, Motion */
const { BrandMark, detectOS, OSLogo, useGitHubStars, formatStars, useLatestRelease } = Common;
const { useTheme, useGlobalMouse } = Motion;
const GH_REPO = "KonradDallaOrg/dimmy";

// Mini-waveform that responds to mouse X. A soft "breathing" ribbon of bars.
// Each bar's height = base + ripple wave that pulses outward from the cursor.
function NavWave({ bars = 11 }) {
  const { x } = useGlobalMouse();
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf, last = performance.now();
    const tick = (now) => {
      setT((p) => p + (now - last) / 1000);
      last = now;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <span className="nav-wave" style={{
      display: "inline-flex", alignItems: "center", gap: 2,
      height: 18, padding: "0 8px",
      borderLeft: "1px solid var(--line)",
      marginLeft: 4,
    }} aria-hidden="true">
      {Array.from({ length: bars }).map((_, i) => {
        const pos = i / (bars - 1); // 0..1
        const dist = Math.abs(pos - x); // distance from mouse x
        // Height: base + ripple that decays with distance + soft sine breath
        const ripple = Math.max(0, 1 - dist * 3);
        const breath = 0.5 + 0.5 * Math.sin(t * 1.4 + i * 0.6);
        const h = 3 + ripple * 11 + breath * 2 * (0.4 + ripple);
        return (
          <i key={i} style={{
            display: "block",
            width: 2, height: h,
            background: ripple > 0.4
              ? `linear-gradient(180deg, #34D399, #38BDF8 60%, #818CF8)`
              : "var(--fg-faint)",
            borderRadius: 99,
            transition: "background 200ms",
            opacity: 0.35 + ripple * 0.65,
          }}/>
        );
      })}
    </span>
  );
}

function ThemeToggle() {
  const { theme, toggle } = useTheme();
  const isDark = theme === "dark";
  return (
    <button onClick={toggle} aria-label="Toggle theme" style={{
      width: 32, height: 32, borderRadius: 8,
      border: "1px solid var(--line)",
      background: "transparent",
      color: "var(--fg-muted)",
      cursor: "pointer",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      position: "relative", overflow: "hidden",
    }}>
      <span style={{
        position: "absolute", inset: 0,
        display: "flex", alignItems: "center", justifyContent: "center",
        transform: isDark ? "translateY(0)" : "translateY(120%)",
        opacity: isDark ? 1 : 0,
        transition: "transform 400ms cubic-bezier(0.5,1.6,0.4,1), opacity 200ms",
      }}>
        {/* moon */}
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
      </span>
      <span style={{
        position: "absolute", inset: 0,
        display: "flex", alignItems: "center", justifyContent: "center",
        transform: !isDark ? "translateY(0)" : "translateY(-120%)",
        opacity: !isDark ? 1 : 0,
        transition: "transform 400ms cubic-bezier(0.5,1.6,0.4,1), opacity 200ms",
      }}>
        {/* sun */}
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
      </span>
    </button>
  );
}

function Hamburger({ open }) {
  return (
    <span aria-hidden="true" style={{
      position: "relative", display: "inline-block", width: 16, height: 12,
    }}>
      {[0, 1, 2].map((i) => (
        <span key={i} style={{
          position: "absolute", left: 0, right: 0, height: 2, borderRadius: 1,
          background: "currentColor",
          top: open ? 5 : i * 5,
          transform: open
            ? `rotate(${i === 1 ? 0 : (i === 0 ? 45 : -45)}deg)`
            : "none",
          opacity: open && i === 1 ? 0 : 1,
          transition: "transform 200ms cubic-bezier(0.2,0.8,0.2,1), top 200ms, opacity 150ms",
        }}/>
      ))}
    </span>
  );
}

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const { theme } = useTheme();
  const stars = useGitHubStars(GH_REPO);
  const starsLabel = formatStars(stars);
  const release = useLatestRelease(GH_REPO);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  // Lock body scroll while the mobile menu is open
  React.useEffect(() => {
    if (mobileOpen) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = prev; };
    }
  }, [mobileOpen]);
  // Close on hash change (link click) or resize back to desktop
  React.useEffect(() => {
    const onHash = () => setMobileOpen(false);
    const onResize = () => { if (window.innerWidth > 760) setMobileOpen(false); };
    window.addEventListener("hashchange", onHash);
    window.addEventListener("resize", onResize);
    return () => {
      window.removeEventListener("hashchange", onHash);
      window.removeEventListener("resize", onResize);
    };
  }, []);
  const os = detectOS();
  const links = [
    ["Features", "#features"],
    ["How it works", "#how"],
    ["Speed", "#speed"],
    ["Styles", "#styles"],
    ["Pricing", "#pricing"],
  ];
  const navBg = theme === "dark"
    ? (scrolled ? "rgba(5,5,5,0.78)" : "rgba(5,5,5,0)")
    : (scrolled ? "rgba(250,250,247,0.85)" : "rgba(250,250,247,0)");
  return (
    <nav style={{
      position: "sticky", top: 0, zIndex: 50,
      borderBottom: scrolled ? "1px solid var(--line)" : "1px solid transparent",
      background: navBg,
      backdropFilter: scrolled ? "blur(20px) saturate(1.4)" : "none",
      WebkitBackdropFilter: scrolled ? "blur(20px) saturate(1.4)" : "none",
      transition: "background 200ms, border-color 200ms",
    }}>
      <div style={{
        maxWidth: 1200, margin: "0 auto",
        display: "flex", alignItems: "center", gap: 24,
        padding: "16px 32px",
      }}>
        <a href="#" style={{
          display: "flex", alignItems: "center", gap: 10,
          textDecoration: "none", color: "var(--fg)",
        }}>
          <BrandMark size={26}/>
          <strong style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700, letterSpacing: "-0.01em" }}>Dimmy</strong>
          {release && <span style={{
            fontFamily: "var(--font-mono)", fontSize: 10,
            color: "var(--fg-faint)", marginLeft: 4,
            padding: "2px 6px", borderRadius: 4,
            border: "1px solid var(--line)",
          }}>{release}</span>}
        </a>
        <NavWave/>
        <div style={{
          display: "flex", gap: 24, fontSize: 14, color: "var(--fg-muted)",
          marginLeft: 16,
        }} className="nav-links">
          {links.map(([l, h]) => (
            <a key={l} href={h} style={{
              color: "inherit", textDecoration: "none",
              transition: "color 200ms",
              position: "relative",
            }}
              onMouseEnter={(e) => e.currentTarget.style.color = "var(--fg)"}
              onMouseLeave={(e) => e.currentTarget.style.color = "var(--fg-muted)"}
            >{l}</a>
          ))}
        </div>
        <div style={{ flex: 1 }}/>
        <ThemeToggle/>
        <a className="nav-desktop-cta" href={`https://github.com/${GH_REPO}`} target="_blank" rel="noopener" style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          fontFamily: "var(--font-mono)", fontSize: 12,
          color: "var(--fg-muted)", textDecoration: "none",
          padding: "6px 10px", borderRadius: 8,
          border: "1px solid var(--line)",
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.111.82-.261.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.4 3-.405 1.02.005 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
          {starsLabel && <span>{starsLabel}</span>}
        </a>
        <a className="nav-desktop-cta" href="#download" style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          background: theme === "dark" ? "white" : "var(--bg-deep)",
          color: theme === "dark" ? "var(--bg-deep)" : "white",
          padding: "8px 14px", borderRadius: 8,
          textDecoration: "none", fontSize: 13, fontWeight: 600,
          fontFamily: "var(--font-sans)",
        }}>
          <OSLogo os={os} size={13}/>
          Download free
        </a>

        {/* Mobile-only hamburger */}
        <button
          className="nav-mobile-toggle"
          onClick={() => setMobileOpen((v) => !v)}
          aria-label={mobileOpen ? "Close menu" : "Open menu"}
          aria-expanded={mobileOpen}
          style={{
            width: 36, height: 36, borderRadius: 8,
            border: "1px solid var(--line)",
            background: "transparent",
            color: "var(--fg)",
            cursor: "pointer",
            display: "none", alignItems: "center", justifyContent: "center",
          }}>
          <Hamburger open={mobileOpen}/>
        </button>
      </div>

      {/* Mobile menu panel, slides down from the nav */}
      <div className={`nav-mobile-panel ${mobileOpen ? "open" : ""}`} style={{
        position: "fixed", left: 0, right: 0, top: 64,
        bottom: 0,
        background: theme === "dark" ? "rgba(5,5,5,0.96)" : "rgba(250,250,247,0.96)",
        backdropFilter: "blur(24px) saturate(1.4)",
        WebkitBackdropFilter: "blur(24px) saturate(1.4)",
        zIndex: 49,
        padding: "24px 20px 32px",
        display: "flex", flexDirection: "column", gap: 4,
        transform: mobileOpen ? "translateY(0)" : "translateY(-8px)",
        opacity: mobileOpen ? 1 : 0,
        pointerEvents: mobileOpen ? "auto" : "none",
        transition: "transform 240ms cubic-bezier(0.2,0.8,0.2,1), opacity 200ms",
        visibility: mobileOpen ? "visible" : "hidden",
        overflowY: "auto",
      }}>
        {links.map(([l, h]) => (
          <a key={l} href={h} onClick={() => setMobileOpen(false)} style={{
            display: "block",
            padding: "14px 8px",
            color: "var(--fg)", textDecoration: "none",
            fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600,
            letterSpacing: "-0.01em",
            borderBottom: "1px solid var(--line)",
          }}>{l}</a>
        ))}
        <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 12 }}>
          <a href={`https://github.com/${GH_REPO}`} target="_blank" rel="noopener" style={{
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10,
            padding: "12px 16px", borderRadius: 10,
            border: "1px solid var(--line-strong)",
            color: "var(--fg)", textDecoration: "none",
            fontFamily: "var(--font-mono)", fontSize: 13,
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.111.82-.261.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.4 3-.405 1.02.005 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
            <span>GitHub{starsLabel ? ` · ${starsLabel}★` : ""}</span>
          </a>
          <a href="#download" onClick={() => setMobileOpen(false)} style={{
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10,
            background: theme === "dark" ? "white" : "var(--bg-deep)",
            color: theme === "dark" ? "var(--bg-deep)" : "white",
            padding: "14px 18px", borderRadius: 10,
            textDecoration: "none", fontSize: 15, fontWeight: 600,
            fontFamily: "var(--font-sans)",
          }}>
            <OSLogo os={os} size={16}/>
            Download for {os === "mac" ? "macOS" : os === "win" ? "Windows" : "Linux"}
          </a>
        </div>
      </div>
    </nav>
  );
}

window.Nav = Nav;
