// Top nav + scrolling ticker
const Ticker = () => {
  const items = [
    "MATCHDAY: Sat 02 May vs Charnock Richard — 15:00 KO",
    "WOMEN'S 1ST: vs Burnley Belvedere — Sun 03 May, 14:00",
    "U16s into the County Cup Final — congratulations lads",
    "Become a 2026/27 Match Sponsor — limited slots remaining",
    "Follow us on Facebook for live updates from every game",
  ];
  return (
    <div style={{
      background: 'var(--ink)', color: '#fff', overflow: 'hidden',
      borderBottom: '1px solid var(--ink-3)', position: 'relative',
    }}>
      <div style={{
        display: 'flex', whiteSpace: 'nowrap', animation: 'tickermove 32s linear infinite',
        padding: '8px 0', gap: 48,
      }}>
        {[...items, ...items, ...items].map((s, i) => (
          <span key={i} className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
            <span style={{ color: 'var(--red)', marginRight: 14 }}>●</span>{s}
          </span>
        ))}
      </div>
      <style>{`@keyframes tickermove { from { transform: translateX(0) } to { transform: translateX(-33.333%) } }`}</style>
      {/* Speed override below */}
    </div>
  );
};

const Nav = ({ page, setPage, scrolled }) => {
  const links = [
    { id: 'home', label: 'Home' },
    { id: 'fixtures', label: 'Fixtures' },
    { id: 'teams', label: 'Teams' },
    { id: 'matchcentre', label: 'Match Centre' },
    { id: 'community', label: 'Join Us' },
    { id: 'sponsors', label: 'Sponsors' },
  ];
  const isMobile = useIsMobile(900);
  const [open, setOpen] = React.useState(false);

  // Lock body scroll when drawer is open. Also auto-close if the viewport
  // grows past mobile while the drawer is open.
  React.useEffect(() => {
    if (!isMobile && open) setOpen(false);
    document.body.style.overflow = (open && isMobile) ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open, isMobile]);

  // Close drawer when nav target changes
  const go = (id) => { setOpen(false); setPage(id); };

  const header = (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: scrolled ? 'rgba(14,15,18,0.96)' : 'var(--ink)',
      backdropFilter: 'blur(8px)',
      borderBottom: '1px solid var(--ink-3)',
      transition: 'all 200ms ease',
    }}>
      <div className="container" style={{
        display: 'flex', alignItems: 'center', height: isMobile ? 64 : 72, gap: isMobile ? 12 : 32,
      }}>
        <a onClick={() => go('home')} style={{
          display: 'flex', alignItems: 'center', gap: isMobile ? 10 : 14, cursor: 'pointer', flexShrink: 0,
        }}>
          <img src="assets/logo.jpg" alt="Blackpool Wren Rovers FC" style={{
            width: isMobile ? 40 : 48, height: isMobile ? 40 : 48, objectFit: 'cover',
            border: '2px solid var(--paper)', flexShrink: 0,
          }} />
          <div style={{ display: 'flex', flexDirection: 'column', whiteSpace: 'nowrap', minWidth: 0 }}>
            <div className="display" style={{
              color: '#fff', fontSize: isMobile ? 15 : 18, lineHeight: 1,
              maxWidth: isMobile ? 180 : 'none', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{isMobile ? 'WREN ROVERS' : 'BLACKPOOL WREN ROVERS'}</div>
            <div className="mono" style={{
              color: 'var(--red)', fontSize: isMobile ? 8 : 9,
              letterSpacing: isMobile ? '0.18em' : '0.28em', marginTop: 4,
            }}>EST. 1936 · LANCASHIRE</div>
          </div>
        </a>

        {/* Desktop nav */}
        {!isMobile && (
          <>
            <nav style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
              {links.map(l => (
                <a key={l.id}
                  onClick={() => go(l.id)}
                  style={{
                    color: page === l.id ? '#fff' : 'rgba(255,255,255,0.7)',
                    fontWeight: 600, fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase',
                    padding: '10px 14px', cursor: 'pointer',
                    borderTop: page === l.id ? '2px solid var(--red)' : '2px solid transparent',
                    borderBottom: page === l.id ? '2px solid var(--red)' : '2px solid transparent',
                    transition: 'all 160ms ease',
                  }}
                  onMouseEnter={(e) => { if (page !== l.id) e.currentTarget.style.color = '#fff'; }}
                  onMouseLeave={(e) => { if (page !== l.id) e.currentTarget.style.color = 'rgba(255,255,255,0.7)'; }}
                >{l.label}</a>
              ))}
            </nav>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <a href="https://facebook.com" target="_blank" rel="noopener noreferrer" style={{
                color: '#fff', fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase',
                display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 12px',
                border: '1px solid rgba(255,255,255,0.2)', fontWeight: 600,
              }}>
                <span style={{
                  display: 'inline-block', width: 14, height: 14, background: '#1877F2',
                  color: '#fff', fontSize: 9, fontWeight: 800, textAlign: 'center', lineHeight: '14px',
                }}>f</span>
                Facebook
              </a>
            </div>
          </>
        )}

        {/* Mobile hamburger button */}
        {isMobile && (
          <button
            type="button"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
            style={{
              marginLeft: 'auto', width: 44, height: 44, padding: 0,
              background: 'transparent', border: '1px solid rgba(255,255,255,0.25)',
              display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              gap: 5, cursor: 'pointer', flexShrink: 0,
              WebkitTapHighlightColor: 'rgba(200,16,46,0.3)',
            }}>
            <span aria-hidden="true" style={{
              width: 18, height: 2, background: '#fff',
              transform: open ? 'translateY(7px) rotate(45deg)' : 'none',
              transition: 'transform 200ms ease',
            }} />
            <span aria-hidden="true" style={{
              width: 18, height: 2, background: '#fff',
              opacity: open ? 0 : 1, transition: 'opacity 150ms ease',
            }} />
            <span aria-hidden="true" style={{
              width: 18, height: 2, background: '#fff',
              transform: open ? 'translateY(-7px) rotate(-45deg)' : 'none',
              transition: 'transform 200ms ease',
            }} />
          </button>
        )}
      </div>
    </header>
  );

  // Render the drawer as a portal on document.body so it escapes the
  // sticky header's containing block (Safari has bugs putting position:fixed
  // children inside a position:sticky ancestor).
  const drawer = (isMobile && open) ? (
    <div
      onClick={() => setOpen(false)}
      style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, left: 0,
        zIndex: 9999,
        background: 'rgba(14,15,18,0.98)',
        WebkitBackdropFilter: 'blur(8px)', backdropFilter: 'blur(8px)',
        overflowY: 'auto',
        animation: 'drawerSlide 240ms ease',
      }}>
      <style>{`@keyframes drawerSlide { from { transform: translateX(100%); } to { transform: translateX(0); } }`}</style>
      {/* Top bar inside drawer with its own close button */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 16px', height: 64,
        borderBottom: '1px solid rgba(255,255,255,0.08)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="assets/logo.jpg" alt="" style={{ width: 36, height: 36, objectFit: 'cover', border: '2px solid var(--paper)' }} />
          <div className="display" style={{ color: '#fff', fontSize: 15, lineHeight: 1 }}>WREN ROVERS</div>
        </div>
        <button
          onClick={(e) => { e.stopPropagation(); setOpen(false); }}
          aria-label="Close menu"
          style={{
            width: 44, height: 44, padding: 0,
            background: 'transparent', border: '1px solid rgba(255,255,255,0.18)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 22, cursor: 'pointer',
          }}>
          ✕
        </button>
      </div>
      <nav onClick={(e) => e.stopPropagation()} style={{ padding: '12px 16px 32px' }}>
        {links.map(l => (
          <a key={l.id}
            onClick={(e) => { e.stopPropagation(); go(l.id); }}
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              color: page === l.id ? '#fff' : 'rgba(255,255,255,0.9)',
              fontFamily: 'Bebas Neue, Anton, Impact, sans-serif',
              fontSize: 30, letterSpacing: '0.04em',
              padding: '18px 8px', cursor: 'pointer',
              borderBottom: '1px solid rgba(255,255,255,0.08)',
              textTransform: 'uppercase', textDecoration: 'none',
            }}>
            <span style={{
              borderLeft: page === l.id ? '3px solid var(--red)' : '3px solid transparent',
              paddingLeft: 12,
            }}>{l.label}</span>
            <span style={{ color: 'var(--red)', fontSize: 22 }}>›</span>
          </a>
        ))}
        <a href="https://facebook.com" target="_blank" rel="noopener noreferrer"
          onClick={(e) => e.stopPropagation()}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            marginTop: 28, padding: '14px 18px',
            border: '1px solid rgba(255,255,255,0.25)', color: '#fff',
            fontSize: 12, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase',
            textDecoration: 'none',
          }}>
          <span style={{
            display: 'inline-block', width: 18, height: 18, background: '#1877F2',
            color: '#fff', fontSize: 12, fontWeight: 800, textAlign: 'center', lineHeight: '18px',
          }}>f</span>
          Follow on Facebook
        </a>
        <div className="mono" style={{
          fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.4)',
          marginTop: 28, paddingTop: 20, borderTop: '1px solid rgba(255,255,255,0.08)',
          fontWeight: 700,
        }}>
          BLACKPOOL WREN ROVERS FC<br/>
          EST. 1936 · LANCASHIRE
        </div>
      </nav>
    </div>
  ) : null;

  return (
    <>
      {header}
      {drawer && (typeof document !== 'undefined'
        ? ReactDOM.createPortal(drawer, document.body)
        : drawer)}
    </>
  );
};

Object.assign(window, { Nav, Ticker });
