
/* ============================================================
   Phils 5K — Shared Header + Footer Components
   Export to window for use across all pages
   ============================================================ */

const { useState, useEffect } = React;

/* ── SMOOTH SCROLL ───────────────────────────────── */
function smoothScrollTo(targetY, duration = 680) {
  const startY = window.scrollY;
  const distance = targetY - startY;
  if (Math.abs(distance) < 2) return;
  const startTime = performance.now();
  const easeInOutCubic = t => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  function step(now) {
    const progress = Math.min((now - startTime) / duration, 1);
    window.scrollTo(0, startY + distance * easeInOutCubic(progress));
    if (progress < 1) requestAnimationFrame(step);
  }
  requestAnimationFrame(step);
}
window.smoothScrollTo = smoothScrollTo;

/* ── NAV CONFIG ─────────────────────────────────── */
const NAV_LINKS = [
  { label: "Home",          href: "index.html#home",          anchor: "#home",          internal: true },
  { label: "Runner Info",   href: "index.html#runner-info",   anchor: "#runner-info",   internal: true },
  { label: "Beneficiaries", href: "index.html#beneficiaries", anchor: "#beneficiaries", internal: true },
  { label: "Sponsors",      href: "index.html#sponsors",      anchor: "#sponsors",      internal: true },
  { label: "Photos",        href: "photos.html",              anchor: null,             internal: false },
  // { label: "Results",       href: "results.html",             anchor: null,             internal: false },
];

/* ── HEADER ─────────────────────────────────────── */
function Header({ page = "home", scrolled: scrolledProp }) {
  const [scrolled, setScrolled] = useState(scrolledProp || false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [activeSection, setActiveSection] = useState("home");

  const isHome = page === "home";

  useEffect(() => {
    if (!isHome) { setScrolled(true); return; }
    const onScroll = () => setScrolled(window.scrollY > 60);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [isHome]);

  useEffect(() => {
    if (!isHome) return;
    const sections = ["home","runner-info","beneficiaries","sponsors"];
    const onScroll = () => {
      let current = "home";
      for (const id of sections) {
        const el = document.getElementById(id);
        if (el && window.scrollY >= el.offsetTop - 120) current = id;
      }
      setActiveSection(current);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [isHome]);

  const handleNavClick = (e, link) => {
    if (isHome && link.anchor) {
      e.preventDefault();
      const el = document.querySelector(link.anchor);
      if (el) smoothScrollTo(el.offsetTop - 72);
      setMenuOpen(false);
    }
  };

  const isActive = (link) => {
    if (!isHome) return window.location.pathname.endsWith(link.href);
    return link.anchor && "#" + activeSection === link.anchor;
  };

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 200,
      background: scrolled ? 'rgba(255,253,245,0.92)' : 'transparent',
      backdropFilter: scrolled ? 'blur(20px)' : 'none',
      borderBottom: scrolled ? '1px solid rgba(245,194,0,0.22)' : 'none',
      boxShadow: scrolled ? '0 2px 20px rgba(20,14,8,0.10)' : 'none',
      transition: 'all 0.4s cubic-bezier(0.16,1,0.3,1)',
    }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 88, padding: '0 32px' }}>
        {/* Logo */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <a href="index.html" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none' }}>
            <img src="assets/phils5k-logo.png?v=2" alt="Phils 5K" style={{ height: 80, width: 'auto' }} />
          </a>
          <a href="https://www.aarclub.com" target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center' }}>
            <img src="assets/aarc-logo.png" alt="Ambler Area Running Club" style={{ height: 52, width: 'auto' }} />
          </a>
        </div>

        {/* Desktop Nav */}
        <nav style={{ display: 'flex', gap: 2, alignItems: 'center' }}>
          {NAV_LINKS.map(link => {
            const active = isActive(link);
            const isPage = !link.internal;
            const currentPage = !isHome && (
              (page === "photos" && link.href === "photos.html") ||
              (page === "results" && link.href === "results.html")
            );
            return (
              <a key={link.label} href={link.href}
                onClick={(e) => handleNavClick(e, link)}
                style={{
                  fontFamily: "'Nunito', sans-serif", fontSize: 15, fontWeight: 700,
                  color: active || currentPage ? '#F5C200' : (scrolled ? '#1B3D8F' : '#fff'),
                  textDecoration: 'none', padding: '7px 14px', borderRadius: 9999,
                  background: active || currentPage ? (scrolled ? '#1B3D8F' : 'rgba(245,194,0,0.18)') : 'transparent',
                  transition: 'all 0.2s',
                  borderBottom: isPage && !scrolled ? '2px solid transparent' : 'none',
                }}
                onMouseEnter={e => {
                  if (!active && !currentPage) e.currentTarget.style.background = scrolled ? '#EEF2FF' : 'rgba(255,255,255,0.15)';
                }}
                onMouseLeave={e => {
                  if (!active && !currentPage) e.currentTarget.style.background = 'transparent';
                }}
              >
                {link.label}
              </a>
            );
          })}
          <a href="https://runtheday.com/register/detail/aarc-phils-tavern-5k-2026" target="_blank" rel="noopener"
            onClick={() => gtag('event', 'registration_click', { 'location': 'header_nav' })}
            style={{
              marginLeft: 10, display: 'inline-flex', alignItems: 'center',
              fontFamily: "'Fredoka', cursive", fontWeight: 600, fontSize: 16,
              background: '#F5C200', color: '#1B3D8F', padding: '10px 24px',
              borderRadius: 9999, border: 'none', cursor: 'pointer', textDecoration: 'none',
              boxShadow: '0 4px 12px rgba(245,194,0,0.35)',
              transition: 'all 0.25s cubic-bezier(0.34,1.56,0.64,1)',
            }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.05)'; e.currentTarget.style.boxShadow = '0 6px 20px rgba(245,194,0,0.55)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = '0 4px 12px rgba(245,194,0,0.35)'; }}
          >
            Register Now →
          </a>
        </nav>

        {/* Mobile hamburger */}
        <button onClick={() => setMenuOpen(!menuOpen)} style={{
          display: 'none', background: 'none', border: 'none', cursor: 'pointer',
          padding: 8,
        }}>
          <svg width="24" height="24" fill="none" stroke={scrolled ? '#1B3D8F' : '#fff'} strokeWidth="2.5" strokeLinecap="round">
            {menuOpen ? <><line x1="4" y1="4" x2="20" y2="20"/><line x1="20" y1="4" x2="4" y2="20"/></> : <><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></>}
          </svg>
        </button>
      </div>

      {/* Mobile menu */}
      {menuOpen && (
        <div style={{
          background: 'rgba(255,253,245,0.97)', backdropFilter: 'blur(20px)',
          borderTop: '1px solid rgba(245,194,0,0.2)', padding: '16px 24px 24px',
        }}>
          {NAV_LINKS.map(link => (
            <a key={link.label} href={link.href} onClick={(e) => handleNavClick(e, link)}
              style={{ display: 'block', fontFamily: "'Nunito',sans-serif", fontWeight: 700, fontSize: 17, color: '#1B3D8F', padding: '12px 0', textDecoration: 'none', borderBottom: '1px solid rgba(245,194,0,0.15)' }}>
              {link.label}
            </a>
          ))}
          <a href="https://runtheday.com/register/detail/aarc-phils-tavern-5k-2026" target="_blank"
            onClick={() => gtag('event', 'registration_click', { 'location': 'header_mobile_nav' })}
            style={{ display: 'block', marginTop: 16, textAlign: 'center', background: '#F5C200', color: '#1B3D8F', fontFamily: "'Fredoka',cursive", fontWeight: 600, fontSize: 18, padding: '13px', borderRadius: 9999, textDecoration: 'none' }}>
            Register Now →
          </a>
        </div>
      )}
    </header>
  );
}

/* ── FOOTER ─────────────────────────────────────── */
function Footer() {
  /* Social icon SVGs */
  const StravaSVG = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
      <path d="M15.387 17.944l-2.089-4.116h-3.065L15.387 24l5.15-10.172h-3.066m-7.008-5.599l2.836 5.598h4.172L10.463 0l-7 13.828h4.169"/>
    </svg>
  );
  const FacebookSVG = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
      <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
    </svg>
  );
  const InstagramSVG = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
    </svg>
  );

  const iconBtn = { display: 'flex', alignItems: 'center', justifyContent: 'center', width: 42, height: 42, borderRadius: 9999, background: 'rgba(255,255,255,0.10)', border: '1px solid rgba(255,255,255,0.20)', color: 'rgba(255,255,255,0.80)', cursor: 'pointer', textDecoration: 'none', transition: 'all 0.2s' };

  return (
    <footer style={{ background: 'linear-gradient(160deg, #1B3D8F 0%, #0E2050 100%)', color: '#fff', paddingTop: 64 }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 32px' }}>
        {/* Top grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1.4fr', gap: 48, paddingBottom: 48, borderBottom: '1px solid rgba(255,255,255,0.12)' }}>

          {/* Brand */}
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 14 }}>
              <img src="assets/phils5k-logo.png?v=2" alt="Phils 5K" style={{ height: 80, width: 'auto' }} />
              <a href="https://www.aarclub.com" target="_blank" rel="noopener" style={{ display: 'inline-flex', background: '#fff', borderRadius: 12, padding: '8px 10px', boxShadow: '0 2px 8px rgba(0,0,0,0.18)' }}>
                <img src="assets/aarc-logo.png" alt="Ambler Area Running Club" style={{ height: 56, width: 'auto' }} />
              </a>
            </div>
            <p style={{ fontFamily: "'Nunito',sans-serif", fontSize: 14, color: 'rgba(255,255,255,0.68)', lineHeight: 1.75, maxWidth: 260, marginBottom: 20 }}>
              A summer evening road running race and children's fun run hosted by the Ambler Area Running Club.
            </p>
            <div style={{ display: 'flex', gap: 10 }}>
              {[
                { href: "https://www.strava.com/clubs/119981?oq=ambler", icon: <StravaSVG />, label: "Strava" },
                { href: "https://www.facebook.com/AARCPhilsTavern5K", icon: <FacebookSVG />, label: "Facebook" },
                { href: "https://www.instagram.com/amblerarearunningclub?igsh=c2hnd3ZiOTJvOTVr&utm_source=qr", icon: <InstagramSVG />, label: "Instagram" },
              ].map(s => (
                <a key={s.label} href={s.href} target="_blank" rel="noopener" aria-label={s.label} style={iconBtn}
                  onMouseEnter={e => { e.currentTarget.style.background = '#F5C200'; e.currentTarget.style.color = '#1B3D8F'; e.currentTarget.style.borderColor = '#F5C200'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.10)'; e.currentTarget.style.color = 'rgba(255,255,255,0.80)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.20)'; }}>
                  {s.icon}
                </a>
              ))}
            </div>
          </div>

          {/* Address & Contact */}
          <div>
            <div style={{ fontFamily: "'Fredoka',cursive", fontSize: 17, fontWeight: 600, color: '#F5C200', marginBottom: 14 }}>Race Location</div>
            <div style={{ fontFamily: "'Nunito',sans-serif", fontSize: 14, color: 'rgba(255,255,255,0.70)', lineHeight: 1.8 }}>
              Shady Grove Elementary School<br/>
              351 Skippack Pike<br/>
              Ambler, PA 19002
            </div>
            <div style={{ marginTop: 18 }}>
              <div style={{ fontFamily: "'Fredoka',cursive", fontSize: 17, fontWeight: 600, color: '#F5C200', marginBottom: 10 }}>Race Director</div>
              <div style={{ fontFamily: "'Nunito',sans-serif", fontSize: 14, color: 'rgba(255,255,255,0.70)', lineHeight: 1.9 }}>
                Ken Surowitz<br/>
                <a href="mailto:phils@aarclub.com" style={{ color: '#F5C200', textDecoration: 'none' }}>phils@aarclub.com</a><br/>
                <a href="tel:9082859935" style={{ color: 'rgba(255,255,255,0.70)', textDecoration: 'none' }}>(908) 285-9935</a>
              </div>
            </div>
          </div>

          {/* Quick Links */}
          <div>
            <div style={{ fontFamily: "'Fredoka',cursive", fontSize: 17, fontWeight: 600, color: '#F5C200', marginBottom: 14 }}>Quick Links</div>
            <ul style={{ listStyle: 'none' }}>
              {[
                ["Register", "https://runtheday.com/register/detail/aarc-phils-tavern-5k-2026/"],
                ["Home", "index.html#home"],
                ["Runner Info", "index.html#runner-info"],
                ["Beneficiaries", "index.html#beneficiaries"],
                ["Sponsors", "index.html#sponsors"],
                ["Photos", "photos.html"],
                // ["Results", "results.html"],
              ].map(([label, href]) => {
                const anchor = href.includes('#') ? '#' + href.split('#')[1] : null;
                const handleClick = (e) => {
                  if (label === 'Register') gtag('event', 'registration_click', { 'location': 'footer_quick_links' });
                  if (anchor) {
                    const el = document.querySelector(anchor);
                    if (el) { e.preventDefault(); smoothScrollTo(el.offsetTop - 72); }
                  }
                };
                return (
                  <li key={label} style={{ marginBottom: 8 }}>
                    <a href={href}
                      onClick={handleClick}
                      style={{ fontFamily: "'Nunito',sans-serif", fontSize: 14, color: 'rgba(255,255,255,0.68)', textDecoration: 'none', transition: 'color 0.2s' }}
                      onMouseEnter={e => e.currentTarget.style.color = '#F5C200'}
                      onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.68)'}>
                      {label}
                    </a>
                  </li>
                );
              })}
            </ul>
          </div>

          {/* Map */}
          <div>
            <div style={{ fontFamily: "'Fredoka',cursive", fontSize: 17, fontWeight: 600, color: '#F5C200', marginBottom: 14 }}>Directions</div>
            <div style={{ borderRadius: 14, overflow: 'hidden', boxShadow: '0 4px 20px rgba(0,0,0,0.30)' }}>
              <iframe
                title="Race Location — Shady Grove Elementary School"
                width="100%" height="160"
                frameBorder="0" style={{ border: 0, display: 'block' }}
                src="https://maps.google.com/maps?q=Shady+Grove+Elementary+School,+351+Skippack+Pike,+Ambler,+PA+19002&output=embed"
                allowFullScreen loading="lazy" referrerPolicy="no-referrer-when-downgrade">
              </iframe>
            </div>
            <a href="https://maps.google.com/?q=Shady+Grove+Elementary+School,+351+Skippack+Pike,+Ambler,+PA+19002" target="_blank" rel="noopener"
              style={{ display: 'inline-block', marginTop: 10, fontFamily: "'Nunito',sans-serif", fontSize: 13, color: '#F5C200', textDecoration: 'none', fontWeight: 600 }}>
              Open in Google Maps →
            </a>
          </div>
        </div>

        {/* Bottom bar */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '24px 0', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ fontFamily: "'Nunito',sans-serif", fontSize: 13, color: 'rgba(255,255,255,0.45)' }}>
            © 2026 <a href="https://www.aarclub.com" target="_blank" rel="noopener" style={{ color: 'rgba(255,255,255,0.55)', textDecoration: 'none' }}>Ambler Area Running Club</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* Export to window */
Object.assign(window, { Header, Footer, NAV_LINKS });
