import { useEffect, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import { useTheme } from "../../app/useTheme";

const NAV_ITEMS = [
  { label: "Tools", to: "/tools" },
  { label: "How it works", to: "/how-it-works" },
  { label: "Contribute", to: "/contribute" },
];

function isNavActive(to: string, pathname: string): boolean {
  if (to === "/tools") return pathname.startsWith("/tools");
  return pathname === to;
}

function PlimiMark({ size = 28 }: { size?: number }) {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "baseline",
        gap: 6,
        fontFamily: "Geist, system-ui, sans-serif",
        fontWeight: 700,
        fontSize: size,
        letterSpacing: "-0.04em",
        color: "var(--p-text)",
        position: "relative",
      }}
    >
      <span style={{ position: "relative" }}>
        plimi
        <span
          style={{
            position: "absolute",
            left: "74%",
            top: "-0.12em",
            width: "0.32em",
            height: "0.32em",
            borderRadius: "50%",
            background: "var(--p-accent)",
            transform: "rotate(-12deg)",
          }}
        />
      </span>
    </span>
  );
}



function ThemeToggle({ dark, onClick }: { dark: boolean; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      aria-label="Toggle theme"
      className="flex items-center justify-center w-9 h-8 rounded-lg bg-[var(--p-surface)] border border-[var(--p-border)] text-[var(--p-text)] cursor-pointer"
    >
      {dark ? (
        <svg
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="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>
      ) : (
        <svg
          width="16"
          height="16"
          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>
      )}
    </button>
  );
}

function MenuToggle({ open, onClick }: { open: boolean; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      aria-label={open ? "Close menu" : "Open menu"}
      aria-expanded={open}
      className="md:hidden flex items-center justify-center w-9 h-8 rounded-lg bg-[var(--p-surface)] border border-[var(--p-border)] text-[var(--p-text)] cursor-pointer"
    >
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
        {open ? (
          <path d="M6 6l12 12M18 6L6 18" />
        ) : (
          <path d="M3 6h18M3 12h18M3 18h18" />
        )}
      </svg>
    </button>
  );
}

export function Header() {
  const { dark, toggleTheme } = useTheme();
  const location = useLocation();
  const [menuOpen, setMenuOpen] = useState(false);

  // Close the mobile menu whenever the route changes.
  useEffect(() => {
    setMenuOpen(false);
  }, [location.pathname]);

  // Lock body scroll while the mobile menu sheet is open.
  useEffect(() => {
    if (!menuOpen) return;
    const previous = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = previous;
    };
  }, [menuOpen]);

  return (
    <header className="sticky top-0 z-40 border-b border-[var(--p-border)] bg-[color-mix(in_oklab,var(--p-bg)_85%,transparent)] backdrop-blur-md pt-safe">
      <div className="flex items-center justify-between px-6 py-4 md:px-8 md:py-5">
        <Link to="/" aria-label="Plimi home">
          <PlimiMark size={26} />
        </Link>

        <nav className="hidden md:flex gap-6">
          {NAV_ITEMS.map((item) => {
            const active = isNavActive(item.to, location.pathname);
            return (
              <Link
                key={item.label}
                to={item.to}
                className={`font-sans text-[13px] no-underline transition-colors ${
                  active
                    ? "text-[var(--p-text)] font-semibold"
                    : "text-[var(--p-muted)] hover:text-[var(--p-text)] font-normal"
                }`}
              >
                {item.label}
              </Link>
            );
          })}
        </nav>

        <div className="flex items-center gap-2.5">
          <ThemeToggle dark={dark} onClick={toggleTheme} />
          <MenuToggle open={menuOpen} onClick={() => setMenuOpen((o) => !o)} />
        </div>
      </div>

      {menuOpen && (
        <>
          {/* Tap-away backdrop below the bar */}
          <button
            aria-hidden="true"
            tabIndex={-1}
            onClick={() => setMenuOpen(false)}
            className="md:hidden fixed inset-0 top-[var(--plimi-header-h,56px)] z-30 bg-[color-mix(in_oklab,var(--p-bg)_55%,transparent)]"
          />
          <nav className="md:hidden relative z-40 flex flex-col gap-1 border-t border-[var(--p-border)] bg-[var(--p-surface)] px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] animate-plimi-drop">
            {NAV_ITEMS.map((item) => {
              const active = isNavActive(item.to, location.pathname);
              return (
                <Link
                  key={item.label}
                  to={item.to}
                  className={`flex items-center justify-between rounded-xl px-4 py-3.5 font-sans text-[15px] no-underline transition-colors ${
                    active
                      ? "bg-[var(--p-accent)] text-[var(--p-accent-ink)] font-semibold"
                      : "text-[var(--p-text)] hover:bg-[var(--p-chip)]"
                  }`}
                >
                  {item.label}
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="opacity-50">
                    <path d="M9 18l6-6-6-6" />
                  </svg>
                </Link>
              );
            })}
          </nav>
        </>
      )}
    </header>
  );
}
