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

const NAV_ITEMS = [
  { id: "home", label: "Home", href: "/" },
  { id: "about", label: "About", href: "/about" },
  { id: "grants", label: "Grants", href: "/grants" },
  { id: "apply", label: "Apply", href: "/apply" },
];

/* ─── Theme picker (light / dark / system) ─────────────────────────── */

const THEME_KEY = "dai-theme";

function readStoredTheme() {
  try { return localStorage.getItem(THEME_KEY) || "system"; } catch { return "system"; }
}
function writeStoredTheme(v) {
  try {
    if (v === "system") localStorage.removeItem(THEME_KEY);
    else localStorage.setItem(THEME_KEY, v);
  } catch {}
}
function applyTheme(v) {
  // "system" → remove the attr so CSS @media(prefers-color-scheme) takes over
  const html = document.documentElement;
  if (v === "system") html.removeAttribute("data-theme");
  else html.setAttribute("data-theme", v);
}

// Inline icons sized to match the menu button
const SunIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
    <circle cx="8" cy="8" r="3" />
    <path d="M8 1.5v1.5M8 13v1.5M1.5 8h1.5M13 8h1.5M3.4 3.4l1 1M11.6 11.6l1 1M3.4 12.6l1-1M11.6 4.4l1-1" />
  </svg>
);
const MoonIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
    <path d="M13.5 9.5A5.5 5.5 0 0 1 6.5 2.5a5.5 5.5 0 1 0 7 7z" />
  </svg>
);
const SystemIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
    <rect x="2" y="3" width="12" height="9" rx="1" />
    <path d="M6 14h4M8 12v2" />
  </svg>
);

const ThemeToggle = () => {
  const [theme, setTheme] = useState(() => (typeof document !== "undefined" ? readStoredTheme() : "system"));
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    function onDoc(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    }
    function onKey(e) { if (e.key === "Escape") setOpen(false); }
    if (open) {
      document.addEventListener("mousedown", onDoc);
      document.addEventListener("keydown", onKey);
    }
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const choose = (v) => {
    setTheme(v);
    writeStoredTheme(v);
    applyTheme(v);
    setOpen(false);
  };

  // Show icon reflecting CURRENT effective state
  const Icon = theme === "light" ? SunIcon : theme === "dark" ? MoonIcon : SystemIcon;
  const label = theme === "system" ? "Auto" : theme === "dark" ? "Dark" : "Light";

  const opts = [
    { id: "light",  label: "Light",  Ico: SunIcon },
    { id: "dark",   label: "Dark",   Ico: MoonIcon },
    { id: "system", label: "System", Ico: SystemIcon },
  ];

  return (
    <div ref={ref} style={{ position: "relative", display: "inline-flex" }}>
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        aria-label={`Theme: ${label}`}
        aria-haspopup="menu"
        aria-expanded={open}
        className="theme-toggle-btn"
      >
        <Icon size={14} />
      </button>
      {open && (
        <div role="menu" className="theme-menu">
          <div className="theme-menu-head">Appearance</div>
          {opts.map(o => (
            <button
              key={o.id}
              role="menuitemradio"
              aria-checked={theme === o.id}
              onClick={() => choose(o.id)}
              className={"theme-menu-item" + (theme === o.id ? " is-current" : "")}
            >
              <o.Ico size={14} />
              <span>{o.label}</span>
              {theme === o.id && (
                <svg width="12" height="12" viewBox="0 0 12 12" style={{ marginLeft: "auto" }}>
                  <path d="M2 6.5 L5 9 L10 3" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const Nav = ({ current = "home" }) => {
  const [open, setOpen] = useState(false);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  return (
    <>
      <nav className="site container">
        <a href="/" style={{ borderBottom: "none" }}>
          <SproutLogo size={32} />
        </a>
        <div className="links desktop-only">
          {NAV_ITEMS.map(it => (
            <a key={it.id} href={it.href}
              style={{
                borderBottom: current === it.id ? "1px solid var(--sprout)" : "none",
                color: current === it.id ? "var(--sprout)" : "var(--ink-2)",
                paddingBottom: 2,
              }}
            >
              {it.label}
            </a>
          ))}
          <ThemeToggle />
        </div>
        <div className="nav-mobile-cluster" style={{ display: "none", alignItems: "center", gap: 10 }}>
          <ThemeToggle />
          <button className="menu-button" onClick={() => setOpen(true)} aria-label="Open menu">
            <svg width="14" height="10" viewBox="0 0 14 10">
              <line x1="0" y1="2" x2="14" y2="2" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
              <line x1="0" y1="8" x2="14" y2="8" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
            </svg>
            Menu
          </button>
        </div>
      </nav>

      <div className={"mobile-drawer" + (open ? " open" : "")}>
        <div className="drawer-head">
          <SproutLogo size={28} />
          <button className="menu-button" onClick={() => setOpen(false)} aria-label="Close menu" style={{ display: "inline-flex" }}>
            <svg width="12" height="12" viewBox="0 0 12 12">
              <line x1="1" y1="1" x2="11" y2="11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
              <line x1="11" y1="1" x2="1" y2="11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
            </svg>
            Close
          </button>
        </div>
        {NAV_ITEMS.map(it => (
          <a key={it.id} href={it.href} className={current === it.id ? "current" : ""}>
            {it.label}
          </a>
        ))}
      </div>
    </>
  );
};

const Footer = () => (
  <footer className="site">
    <div className="container">
      <div className="row">
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <SproutLogo size={28} />
          <div className="small" style={{ maxWidth: 320, lineHeight: 1.6 }}>
            A small family donor-advised fund, supporting people doing quiet, careful work in the world.
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end" }}>
          <a href="mailto:hi@thedai.org" className="small" style={{ color: "var(--ink-2)" }}>hi@thedai.org</a>
          <a href="/apply" className="small" style={{ color: "var(--ink-2)" }}>Apply for a grant</a>
          <div className="small" style={{ marginTop: 16, color: "var(--ink-3)" }}>
            thedai.org · est. 2025
          </div>
        </div>
      </div>
    </div>
  </footer>
);

window.SiteNav = Nav;
window.SiteFooter = Footer;
