// Masthead.jsx — institutional nav with responsive hamburger drawer.
//
// Behavior:
//   - ≥769px: logo lockup left, three links right
//   - ≤768px: logo lockup left, brass hamburger right → slides Navy drawer in from right
//   - Drawer: full-height, ~88vw wide, Navy ground, Cormorant Garamond nav at editorial scale,
//             gold hairline divider, "Skills · Lifestyle · Culture." footer mark
//   - Close on: link tap, backdrop tap, Esc
//   - Body scroll locked while open
//
// Visual doctrine: hairlines not boxes, no SaaS-pill toggle, no aggressive 3-bar hamburger.
// Two hairlines reads as a quiet brass mark, in keeping with the brand's restraint.

const Masthead = ({ activePage = 'home', defaultOpen = false, forceMobile = false, contained = false }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen]         = React.useState(defaultOpen);
  const detected = useIsMobile();
  const isMobile = forceMobile || detected;

  // Scroll → solidify on Pearl ground
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Close drawer if viewport widens past mobile breakpoint
  React.useEffect(() => {
    if (!isMobile) setOpen(false);
  }, [isMobile]);

  // Scroll lock + Esc to close
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  // Shared styles
  const navLinkBase = {
    fontFamily: 'Montserrat, sans-serif',
    fontWeight: 600, fontSize: 11,
    letterSpacing: '0.22em', textTransform: 'uppercase',
    color: 'var(--ld-navy)',
    borderBottom: 'none',
    padding: '4px 0',
    textDecoration: 'none',
  };
  const navLinkActive = {
    ...navLinkBase,
    borderBottom: '1px solid var(--ld-gold)',
    paddingBottom: 3,
  };

  // ── Mobile drawer link (Garamond, editorial scale) ──
  const drawerLinkBase = {
    fontFamily: 'Cormorant Garamond, serif',
    fontVariantCaps: 'all-small-caps',
    letterSpacing: '0.12em',
    fontSize: 30,
    fontWeight: 400,
    color: 'var(--ld-pearl-100)',
    textDecoration: 'none',
    borderBottom: 'none',
    display: 'flex',
    alignItems: 'baseline',
    gap: 18,
    paddingBlock: 14,
  };
  const drawerLinkActive = {
    ...drawerLinkBase,
    color: 'var(--ld-gold)',
  };

  // Eyebrow numeral for each drawer link — quiet ordinal
  const Numeral = ({ children, active }) => (
    <span style={{
      fontFamily: 'Montserrat, sans-serif', fontWeight: 600,
      fontSize: 10, letterSpacing: '0.22em',
      color: active ? 'var(--ld-gold)' : 'rgba(235,221,197,0.55)',
      minWidth: 28,
    }}>{children}</span>
  );

  return (
    <React.Fragment>
      <header style={{
        position: 'sticky', top: 0, zIndex: 30,
        background: scrolled || open ? 'rgba(251,246,236,0.96)' : 'transparent',
        borderBottom: scrolled
          ? '1px solid var(--ld-line)'
          : '1px solid transparent',
        backdropFilter: scrolled ? 'saturate(1.05)' : 'none',
        transition: 'all 320ms cubic-bezier(0.32,0.08,0.24,1)',
      }}>
        <div className="container" style={{
          padding: isMobile
            ? '18px clamp(20px, 5vw, 32px)'
            : '22px clamp(24px, 5vw, 80px)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 24,
        }}>
          {/* Logo lockup */}
          <a href="/" aria-label="The Art of Living Digitally — Home" style={{
            display: 'flex', alignItems: 'center',
            gap: isMobile ? 10 : 14,
            borderBottom: 'none',
            minWidth: 0,
          }}>
            <img
              src="assets/crest-simple-navy.png"
              alt=""
              style={{ height: isMobile ? 32 : 38, width: 'auto', flexShrink: 0 }}
            />
            <span style={{
              fontFamily: 'Cormorant Garamond, serif',
              fontVariantCaps: 'all-small-caps',
              letterSpacing: isMobile ? '0.08em' : '0.1em',
              fontSize: isMobile ? 15 : 17,
              color: 'var(--ld-navy)', fontWeight: 500,
              lineHeight: 1.1,
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
            }}>
              The Art of Living Digitally
              <sup style={{ fontSize: 9, marginLeft: 1, fontVariant: 'normal', letterSpacing: 0 }}>™</sup>
            </span>
          </a>

          {/* Desktop nav */}
          {!isMobile && (
            <nav style={{ display: 'flex', gap: 40 }}>
              <a href="/"        style={activePage === 'home'    ? navLinkActive : navLinkBase}>Home</a>
              <a href="/access"  style={activePage === 'access'  ? navLinkActive : navLinkBase}>ACCESS<sup style={{ fontSize: 7, letterSpacing: 0 }}>™</sup></a>
              <a href="/founder" style={activePage === 'founder' ? navLinkActive : navLinkBase}>Meet the Founder</a>
            </nav>
          )}

          {/* Mobile — brass hamburger */}
          {isMobile && (
            <button
              type="button"
              aria-label={open ? 'Close menu' : 'Open menu'}
              aria-expanded={open}
              aria-controls="ld-mobile-drawer"
              onClick={() => setOpen(o => !o)}
              style={{
                background: 'transparent',
                border: 'none',
                padding: 8,
                margin: -8,
                cursor: 'pointer',
                display: 'flex',
                flexDirection: 'column',
                gap: 7,
                width: 36, height: 36,
                alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}
            >
              {/* Two hairlines — the brand's hairline doctrine, not a 3-bar SaaS hamburger.
                  Animate to a quiet X. */}
              <span aria-hidden="true" style={{
                display: 'block', width: 22, height: 1,
                background: 'var(--ld-navy)',
                transformOrigin: 'center',
                transform: open ? 'translateY(4px) rotate(45deg)' : 'none',
                transition: 'transform 320ms cubic-bezier(0.32,0.08,0.24,1)',
              }} />
              <span aria-hidden="true" style={{
                display: 'block', width: 22, height: 1,
                background: 'var(--ld-navy)',
                transformOrigin: 'center',
                transform: open ? 'translateY(-4px) rotate(-45deg)' : 'none',
                transition: 'transform 320ms cubic-bezier(0.32,0.08,0.24,1)',
              }} />
            </button>
          )}
        </div>
      </header>

      {/* ── Mobile drawer + backdrop ── */}
      {isMobile && (
        <React.Fragment>
          {/* Backdrop — soft navy wash, not a SaaS dim */}
          <div
            aria-hidden="true"
            onClick={() => setOpen(false)}
            style={{
              position: contained ? 'absolute' : 'fixed', inset: 0, zIndex: 28,
              background: 'rgba(13,27,61,0.55)',
              opacity: open ? 1 : 0,
              pointerEvents: open ? 'auto' : 'none',
              transition: 'opacity 320ms cubic-bezier(0.32,0.08,0.24,1)',
            }}
          />

          {/* Drawer panel */}
          <aside
            id="ld-mobile-drawer"
            role="dialog"
            aria-modal="true"
            aria-label="Site navigation"
            style={{
              position: contained ? 'absolute' : 'fixed',
              top: 0, right: 0, bottom: 0,
              zIndex: 29,
              width: 'min(88vw, 420px)',
              background: 'var(--ld-navy)',
              color: 'var(--ld-pearl-100)',
              boxShadow: '-28px 0 64px rgba(13,27,61,0.40), -8px 0 16px rgba(13,27,61,0.20)',
              transform: open ? 'translateX(0)' : 'translateX(102%)',
              transition: 'transform 520ms cubic-bezier(0.32,0.08,0.24,1)',
              display: 'flex', flexDirection: 'column',
              willChange: 'transform',
            }}
          >
            {/* Drawer header — crest + close, mirrors masthead lockup */}
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '22px clamp(20px, 5vw, 32px)',
              borderBottom: '1px solid rgba(235,221,197,0.18)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <img src="assets/crest-simple-gold.png" alt="" style={{ height: 32, width: 'auto' }} />
                <span style={{
                  fontFamily: 'Cormorant Garamond, serif',
                  fontVariantCaps: 'all-small-caps',
                  letterSpacing: '0.1em',
                  fontSize: 15,
                  color: 'var(--ld-pearl-100)',
                  fontWeight: 500,
                  lineHeight: 1.1,
                }}>
                  Living Digitally
                  <sup style={{ fontSize: 8, marginLeft: 1, fontVariant: 'normal', letterSpacing: 0, color: 'var(--ld-gold)' }}>™</sup>
                </span>
              </div>
              <button
                type="button"
                aria-label="Close menu"
                onClick={() => setOpen(false)}
                style={{
                  background: 'transparent',
                  border: 'none',
                  padding: 8, margin: -8,
                  cursor: 'pointer',
                  color: 'var(--ld-pearl-100)',
                  fontFamily: 'Montserrat, sans-serif',
                  fontWeight: 600, fontSize: 10,
                  letterSpacing: '0.22em', textTransform: 'uppercase',
                }}
              >Close</button>
            </div>

            {/* Drawer nav */}
            <nav style={{
              padding: 'clamp(40px, 8vw, 56px) clamp(24px, 6vw, 36px) 24px',
              flex: 1,
              display: 'flex', flexDirection: 'column',
            }}>
              <div style={{
                fontFamily: 'Montserrat, sans-serif', fontWeight: 600,
                fontSize: 10, letterSpacing: '0.24em', textTransform: 'uppercase',
                color: 'var(--ld-gold)',
                marginBottom: 28,
              }}>
                Index
              </div>

              <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {[
                  { id: 'home',    label: 'Home',             href: '/',         no: 'I' },
                  { id: 'access',  label: <React.Fragment>ACCESS<sup style={{ fontSize: 9, fontVariant: 'normal', letterSpacing: 0, color: 'var(--ld-gold)' }}>™</sup></React.Fragment>, href: '/access',  no: 'II' },
                  { id: 'founder', label: 'Meet the Founder', href: '/founder', no: 'III' },
                ].map((item, i, arr) => {
                  const active = activePage === item.id;
                  return (
                    <li key={item.id} style={{
                      borderBottom: i < arr.length - 1 ? '1px solid rgba(235,221,197,0.12)' : 'none',
                    }}>
                      <a
                        href={item.href}
                        onClick={() => setOpen(false)}
                        style={active ? drawerLinkActive : drawerLinkBase}
                      >
                        <Numeral active={active}>{item.no}</Numeral>
                        <span style={{ flex: 1 }}>{item.label}</span>
                        {active && (
                          <span aria-hidden="true" style={{
                            display: 'inline-block',
                            width: 24, height: 1,
                            background: 'var(--ld-gold)',
                            transform: 'translateY(-8px)',
                          }} />
                        )}
                      </a>
                    </li>
                  );
                })}
              </ul>

              {/* Footer doctrine mark — pinned bottom */}
              <div style={{ marginTop: 'auto', paddingTop: 48 }}>
                <hr style={{
                  border: 'none', borderTop: '1px solid var(--ld-gold)',
                  width: 40, margin: '0 0 20px',
                }} />
                <div style={{
                  fontFamily: 'Cormorant Garamond, serif',
                  fontStyle: 'italic',
                  fontSize: 16,
                  lineHeight: 1.4,
                  color: 'rgba(235,221,197,0.78)',
                  maxWidth: 280,
                }}>
                  Skills. Lifestyle. Culture.
                </div>
                <div style={{
                  marginTop: 6,
                  fontFamily: 'Cormorant Garamond, serif',
                  fontStyle: 'italic',
                  fontSize: 13,
                  lineHeight: 1.5,
                  color: 'rgba(235,221,197,0.55)',
                  maxWidth: 280,
                }}>
                  Digital literacy as inheritance, not interruption.
                </div>
              </div>
            </nav>
          </aside>
        </React.Fragment>
      )}
    </React.Fragment>
  );
};

window.Masthead = Masthead;
