// Top navigation — sticky behavior, mobile drawer
const { useState, useEffect, useRef } = React;

function Nav({ onOpenDrawer, active }) {
  const [scrolled, setScrolled] = useState(false);
  const [loginOpen, setLoginOpen] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 24);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  useEffect(() => {
    const openLogin = () => setLoginOpen(true);
    window.addEventListener("gf:openLogin", openLogin);
    return () => window.removeEventListener("gf:openLogin", openLogin);
  }, []);
  const links = [
    { id: "topics", label: "Topics", href: "topics.html" },
    { id: "book", label: "Book", href: "book.html" },
    { id: "coaching", label: "Coaching", href: "coaching.html" },
    { id: "get-guide", label: "Get Free Guide", action: "lead" },
  ];
  const scrollTo = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) el.scrollIntoView ? window.scrollTo({ top: el.offsetTop - 72, behavior: "smooth" }) : null;
  };
  const onLinkClick = (l) => (e) => {
    if (l.action === "lead") {
      e.preventDefault();
      window.dispatchEvent(new CustomEvent("gf:openLead"));
      return;
    }
    if (l.href) { /* let it navigate */ return; }
    scrollTo(l.id)(e);
  };
  return (
    <>
    <header
      style={{
        position: "fixed", top: 0, left: 0, right: 0, zIndex: 40,
        transition: "background .25s ease, border-color .25s ease, backdrop-filter .25s ease",
        background: scrolled ? "rgba(7,7,10,.78)" : "rgba(7,7,10,0)",
        backdropFilter: scrolled ? "blur(14px) saturate(130%)" : "none",
        WebkitBackdropFilter: scrolled ? "blur(14px) saturate(130%)" : "none",
        borderBottom: `1px solid ${scrolled ? "rgba(214,189,122,.16)" : "transparent"}`,
      }}
    >
      <div className="nav-inner" style={{ display: "flex", alignItems: "center", height: 72, gap: 24, position: "relative", width: "100%", maxWidth: 1280, margin: "0 auto", padding: "0 32px", boxSizing: "border-box" }}>
        <a href="index.html" onClick={(e) => {
          const p = window.location.pathname;
          if (p === "/" || p.endsWith("index.html")) {
            e.preventDefault();
            window.scrollTo({ top: 0, behavior: "smooth" });
          }
        }} style={{ display: "flex", alignItems: "center", gap: 12, letterSpacing: ".02em" }}>
          <Monogram />
          <span style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
            <span className="serif" style={{ fontSize: 18, fontWeight: 600, letterSpacing: ".01em" }}>George Farah</span>
            <span className="mono" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: ".24em", marginTop: 4 }}>PhD · MASTER COACH</span>
          </span>
        </a>
        <nav className="desktop-nav" style={{
          display: "flex", gap: 28,
          position: "absolute", left: "50%", top: "50%", transform: "translate(-50%, -50%)",
        }}>
          {links.map(l => (
            <a key={l.id} href={l.href || `#${l.id}`} onClick={onLinkClick(l)}
              style={{
                fontSize: 13, letterSpacing: ".04em", color: active === l.id ? "var(--gold-2)" : "var(--soft)",
                position: "relative", paddingBottom: 4,
              }}>
              {l.label}
              {active === l.id && <span style={{ position: "absolute", left: 0, right: 0, bottom: -2, height: 1, background: "var(--gold)" }} />}
            </a>
          ))}
        </nav>
        <div className="desktop-nav" style={{ display: "flex", gap: 10, alignItems: "center", marginLeft: "auto" }}>
          <a href="membership.html"
            style={{
              fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase",
              padding: "12px 18px", border: "1px solid var(--gold)", color: "var(--bone)",
              background: "linear-gradient(180deg,rgba(201,169,97,.14),rgba(201,169,97,.04))",
            }}>Become a Member</a>
          <button onClick={() => setLoginOpen(true)}
            style={{
              fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase",
              padding: "12px 18px", color: "var(--soft)", background: "transparent",
              border: "1px solid var(--line-strong)",
              transition: "color .15s, border-color .15s",
            }}
            onMouseEnter={e => { e.currentTarget.style.color = "var(--gold-2)"; e.currentTarget.style.borderColor = "var(--gold-3)"; }}
            onMouseLeave={e => { e.currentTarget.style.color = "var(--soft)"; e.currentTarget.style.borderColor = "var(--line-strong)"; }}
          >Login</button>
        </div>
        <button className="mobile-only" onClick={onOpenDrawer} aria-label="Open menu"
          style={{ marginLeft: "auto", width: 44, height: 44, display: "none", placeItems: "center" }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M3 6h16M3 11h16M3 16h16" stroke="#f2eee4" strokeWidth="1.4" strokeLinecap="round" /></svg>
        </button>
      </div>
      <style>{`
        @media (max-width: 960px) {
          .desktop-nav { display: none !important; }
          .mobile-only { display: grid !important; }
        }
        @media (max-width: 760px) {
          .nav-inner { padding: 0 20px !important; }
        }
      `}</style>
    </header>
    {window.LoginModal && <window.LoginModal open={loginOpen} onClose={() => setLoginOpen(false)} />}
    </>
  );
}

function Monogram() {
  const [svg, setSvg] = React.useState("");
  React.useEffect(() => {
    fetch("assets/gf-logo.svg").then(r => r.text()).then(t => {
      // Paint the outlined paths gold
      const painted = t
        .replace(/fill="#8E1214"/gi, 'fill="currentColor"')
        .replace(/fill="none"/g, 'fill="currentColor"')
        .replace(/<svg /, '<svg style="color:#d9bd7a" ');
      setSvg(painted);
    });
  }, []);
  return (
    <div style={{ width: 56, height: 30, display: "grid", placeItems: "center", color: "#d9bd7a" }}
      dangerouslySetInnerHTML={{ __html: svg.replace(/width="[^"]+"/, 'width="100%"').replace(/height="[^"]+"/, 'height="100%"') }}
    />
  );
}

function MobileDrawer({ open, onClose }) {
  useEffect(() => {
    document.body.classList.toggle("scroll-lock", open);
    return () => document.body.classList.remove("scroll-lock");
  }, [open]);
  const links = [
    { id: "topics", label: "Topics", href: "topics.html" },
    { id: "book", label: "Book", href: "book.html" },
    { id: "coaching", label: "Coaching", href: "coaching.html" },
    { id: "membership", label: "Membership", href: "membership.html" },
    { id: "get-guide", label: "Get Free Guide", action: "lead" },
  ];
  const go = (id) => () => {
    onClose();
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) window.scrollTo({ top: el.offsetTop - 64, behavior: "smooth" });
    }, 220);
  };
  return (
    <>
      <div onClick={onClose}
        style={{
          position: "fixed", inset: 0, zIndex: 60,
          background: "rgba(0,0,0,.6)", backdropFilter: "blur(6px)",
          opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none",
          transition: "opacity .3s ease",
        }} />
      <aside
        style={{
          position: "fixed", top: 0, right: 0, bottom: 0, width: "min(420px, 86vw)", zIndex: 70,
          background: "linear-gradient(180deg,#0b0c10 0%,#07070a 100%)",
          borderLeft: "1px solid var(--line-strong)",
          transform: open ? "translateX(0)" : "translateX(100%)", transition: "transform .35s cubic-bezier(.2,.8,.2,1)",
          display: "flex", flexDirection: "column",
        }}
        aria-hidden={!open}
      >
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
          <a href="index.html" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <Monogram />
            <span className="serif" style={{ fontSize: 17 }}>George Farah</span>
          </a>
          <button onClick={onClose} aria-label="Close menu"
            style={{ width: 40, height: 40, display: "grid", placeItems: "center" }}>
            <svg width="18" height="18" viewBox="0 0 18 18"><path d="M3 3l12 12M15 3L3 15" stroke="#f2eee4" strokeWidth="1.4" strokeLinecap="round" /></svg>
          </button>
        </div>
        <div style={{ padding: "12px 12px", display: "flex", flexDirection: "column" }}>
          {links.map((l, i) => (
            <button key={l.id} onClick={
              l.action === "lead"
                ? (() => {
                    onClose();
                    setTimeout(() => window.dispatchEvent(new Event("gf:openLead")), 220);
                  })
                : l.href
                ? (() => { onClose(); setTimeout(() => { window.location.href = l.href; }, 220); })
                : go(l.id)
            }
              style={{
                textAlign: "left", padding: "20px 16px", borderBottom: "1px solid var(--line)",
                display: "flex", justifyContent: "space-between", alignItems: "baseline",
              }}>
              <span className="serif" style={{ fontSize: 24 }}>{l.label}</span>
              <span className="mono" style={{ fontSize: 11, color: "var(--gold)", letterSpacing: ".24em" }}>{String(i + 1).padStart(2, "0")}</span>
            </button>
          ))}
        </div>
        <div style={{ marginTop: "auto", padding: 24, borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 16 }}>
          <button onClick={() => { onClose(); setTimeout(() => window.dispatchEvent(new Event("gf:openLogin")), 220); }}
            style={{
              textAlign: "center", padding: "16px 24px", letterSpacing: ".18em", fontSize: 12, textTransform: "uppercase",
              border: "1px solid var(--line-strong)", color: "var(--soft)",
            }}>Login</button>
          <a href="membership.html"
            style={{
              textAlign: "center", padding: "18px 24px", letterSpacing: ".18em", fontSize: 12, textTransform: "uppercase",
              border: "1px solid var(--gold)",
              background: "linear-gradient(180deg,rgba(201,169,97,.18),rgba(201,169,97,.04))",
            }}>Become a Member</a>
          <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
            {[
              { label: "Instagram", href: "https://www.instagram.com/georgefarah_guru/", icon: (
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="3" width="18" height="18" rx="5" />
                  <circle cx="12" cy="12" r="4" />
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
                </svg>
              ) },
              { label: "Twitter", href: "https://x.com/gvfarah", icon: (
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M18.244 2H21.5l-7.5 8.57L22.5 22h-6.8l-5.33-6.97L4.2 22H.94l8.02-9.16L.5 2h6.97l4.82 6.37L18.244 2Zm-1.19 18h1.88L7.03 4H5.04l12.014 16Z" />
                </svg>
              ) },
              { label: "LinkedIn", href: "https://www.linkedin.com/in/george-farah-phd-59a94486", icon: (
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M4.98 3.5A2.5 2.5 0 1 1 4.98 8.5a2.5 2.5 0 0 1 0-5ZM3 9.75h4V21H3V9.75ZM9.5 9.75h3.83v1.54h.05c.53-.95 1.83-1.95 3.77-1.95 4.03 0 4.78 2.53 4.78 5.82V21h-4v-4.98c0-1.19-.02-2.72-1.66-2.72-1.66 0-1.91 1.29-1.91 2.63V21h-4V9.75Z" />
                </svg>
              ) },
            ].map(s => (
              <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.label}
                style={{
                  width: 40, height: 40, display: "grid", placeItems: "center",
                  border: "1px solid var(--line-strong)", color: "var(--soft)",
                  transition: "color .15s, border-color .15s, background .15s",
                }}
                onMouseEnter={e => { e.currentTarget.style.color = "var(--gold-2)"; e.currentTarget.style.borderColor = "var(--gold)"; e.currentTarget.style.background = "rgba(201,169,97,.06)"; }}
                onMouseLeave={e => { e.currentTarget.style.color = "var(--soft)"; e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.background = "transparent"; }}
              >{s.icon}</a>
            ))}
          </div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { Nav, MobileDrawer, Monogram });
