// Header.jsx: Orbital Aerial Solutions
const OASHeader = () => {
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  // Theme state can be: 'dark' | 'light' | 'system'
  const [theme, setTheme] = React.useState('system');
  const [resolvedTheme, setResolvedTheme] = React.useState('dark');

  // Load initial theme preference
  React.useEffect(() => {
    const saved = localStorage.getItem('oas-theme');
    if (saved === 'light' || saved === 'dark' || saved === 'system') {
      setTheme(saved);
    } else {
      setTheme('system');
    }
  }, []);

  // Sync resolved theme with page and system preference
  React.useEffect(() => {
    const updateTheme = () => {
      let active = 'dark';
      if (theme === 'system') {
        const matchesLight = window.matchMedia('(prefers-color-scheme: light)').matches;
        active = matchesLight ? 'light' : 'dark';
      } else {
        active = theme;
      }
      setResolvedTheme(active);
      document.documentElement.setAttribute('data-theme', active);
      localStorage.setItem('oas-theme', theme);
    };

    updateTheme();

    if (theme === 'system') {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: light)');
      const listener = () => {
        const matchesLight = mediaQuery.matches;
        const active = matchesLight ? 'light' : 'dark';
        setResolvedTheme(active);
        document.documentElement.setAttribute('data-theme', active);
      };
      
      // Modern and fallback listeners
      if (mediaQuery.addEventListener) {
        mediaQuery.addEventListener('change', listener);
      } else {
        mediaQuery.addListener(listener);
      }

      return () => {
        if (mediaQuery.removeEventListener) {
          mediaQuery.removeEventListener('change', listener);
        } else {
          mediaQuery.removeListener(listener);
        }
      };
    }
  }, [theme]);

  const [themeHovered, setThemeHovered] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = ['Services', 'Advantage', 'Credentials', 'Contact'];

  const scrollTo = (id) => {
    const el = document.getElementById(id.toLowerCase().replace(' ', '-'));
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    setMobileOpen(false);
  };

  const navStyle = {
    position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: scrolled ? '0 40px' : '0 48px',
    // 5. Make the header height a bit larger (original 72/96 -> 84/108)
    height: scrolled ? 84 : 108,
    // 5. Make the header extra translucent (lower opacity alpha from 0.72 to 0.45)
    background: scrolled 
      ? (resolvedTheme === 'dark' ? 'rgba(9, 12, 18, 0.45)' : 'rgba(250, 250, 250, 0.45)') 
      : 'transparent',
    borderBottom: `1px solid ${scrolled 
      ? (resolvedTheme === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.08)') 
      : 'transparent'}`,
    backdropFilter: scrolled ? 'saturate(180%) blur(24px)' : 'none',
    WebkitBackdropFilter: scrolled ? 'saturate(180%) blur(24px)' : 'none',
    transition: 'height 400ms cubic-bezier(0.16, 1, 0.3, 1), background 400ms ease, border-color 400ms ease, padding 400ms cubic-bezier(0.16, 1, 0.3, 1), backdrop-filter 400ms ease',
  };

  const Logo = () => (
    <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }} onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
      {/* 5. Make the logo height a bit larger (original 48/56 -> 58/68) */}
      <img src={resolvedTheme === 'dark' ? "assets/Color%20Logo%20-%20Dark%20Theme.svg" : "assets/Color%20Logo%20-%20Light%20Theme.svg"} alt="Orbital Aerial Solutions" style={{ height: scrolled ? 58 : 68, width: 'auto', display: 'block', transition: 'height 400ms cubic-bezier(0.16, 1, 0.3, 1), filter 300ms ease' }} />
    </div>
  );

  return (
    <header>
      <nav style={navStyle} aria-label="Main Navigation">
        <Logo />
        
        {/* Desktop Navigation */}
        <div className="desktop-nav">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {links.map(l => (
              <button key={l} onClick={() => scrollTo(l)}
                 style={{ background: 'none', border: 'none', color: 'var(--fg-2)', fontSize: 14, fontWeight: 600, fontFamily: 'var(--font-body)', padding: '8px 16px', borderRadius: 6, cursor: 'pointer', transition: 'all 200ms ease' }}
                onMouseEnter={e => { e.target.style.color = 'var(--fg-1)'; e.target.style.background = 'var(--bg-elevated)'; }}
                onMouseLeave={e => { e.target.style.color = 'var(--fg-2)'; e.target.style.background = 'transparent'; }}>
                {l}
              </button>
            ))}
          </div>

          <div style={{ width: 1, height: 24, background: 'var(--border)' }}></div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {/* Theme Toggle Button with Indicator & Hover Menu */}
            <div 
              onMouseEnter={() => setThemeHovered(true)} 
              onMouseLeave={() => setThemeHovered(false)}
              style={{ position: 'relative' }}
            >
              <button style={{ background: themeHovered ? 'var(--bg-elevated)' : 'none', border: 'none', cursor: 'pointer', color: themeHovered ? 'var(--fg-1)' : 'var(--fg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '0 12px', height: 38, borderRadius: 19, transition: 'background 200ms ease, color 200ms ease' }}>
                {theme === 'system' ? (
                  <>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 600 }}>Auto</span>
                  </>
                ) : theme === 'dark' ? (
                  <>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 600 }}>Dark</span>
                  </>
                ) : (
                  <>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 600 }}>Light</span>
                  </>
                )}
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.6, transform: themeHovered ? 'rotate(180deg)' : 'none', transition: 'transform 250ms ease' }}><polyline points="6 9 12 15 18 9" /></svg>
              </button>

              {/* Dropdown Options */}
              <div 
                style={{
                  position: 'absolute',
                  top: 'calc(100% + 6px)',
                  right: 0,
                  width: 130,
                  background: resolvedTheme === 'dark' ? 'rgba(15, 21, 32, 0.95)' : 'rgba(255, 255, 255, 0.95)',
                  backdropFilter: 'blur(16px)',
                  WebkitBackdropFilter: 'blur(16px)',
                  border: '1px solid var(--border)',
                  borderRadius: 8,
                  padding: '6px 5px',
                  boxShadow: 'var(--shadow-lg)',
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 2,
                  opacity: themeHovered ? 1 : 0,
                  visibility: themeHovered ? 'visible' : 'hidden',
                  transform: themeHovered ? 'translateY(0)' : 'translateY(-10px)',
                  transition: 'opacity 250ms ease, transform 250ms cubic-bezier(0.16, 1, 0.3, 1), visibility 250ms ease',
                  zIndex: 1000,
                }}
              >
                {[
                  { key: 'system', label: 'Auto', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg> },
                  { key: 'light', label: 'Light', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg> },
                  { key: 'dark', label: 'Dark', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg> }
                ].map((opt) => {
                  const isSelected = theme === opt.key;
                  return (
                    <button
                      key={opt.key}
                      onClick={() => {
                        setTheme(opt.key);
                        setThemeHovered(false);
                      }}
                      style={{
                        background: 'none',
                        border: 'none',
                        color: isSelected ? 'var(--cyan)' : 'var(--fg-2)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        padding: '8px 10px',
                        borderRadius: 6,
                        cursor: 'pointer',
                        fontSize: 12,
                        fontWeight: isSelected ? 600 : 500,
                        fontFamily: 'var(--font-body)',
                        textAlign: 'left',
                        width: '100%',
                        transition: 'background 150ms ease, color 150ms ease'
                      }}
                      onMouseEnter={e => {
                        e.currentTarget.style.background = 'var(--bg-elevated)';
                        if (!isSelected) e.currentTarget.style.color = 'var(--fg-1)';
                      }}
                      onMouseLeave={e => {
                        e.currentTarget.style.background = 'none';
                        if (!isSelected) e.currentTarget.style.color = 'var(--fg-2)';
                      }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        {opt.icon}
                        <span>{opt.label}</span>
                      </div>
                      {isSelected && (
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="20 6 9 17 4 12" />
                        </svg>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>

            <button onClick={() => scrollTo('Contact')}
              style={{ background: 'var(--cyan)', color: 'var(--fg-on-accent)', fontSize: 14, fontWeight: 600, fontFamily: 'var(--font-body)', padding: '10px 22px', borderRadius: 6, border: 'none', cursor: 'pointer', transition: 'all 200ms ease' }}
              onMouseEnter={e => { e.target.style.background = 'var(--cyan-400)'; e.target.style.boxShadow = 'var(--shadow-glow-cyan)'; }}
              onMouseLeave={e => { e.target.style.background = 'var(--cyan)'; e.target.style.boxShadow = 'none'; }}>
              Request a Quote
            </button>
          </div>
        </div>

        {/* Mobile Menu Button */}
        <button onClick={() => setMobileOpen(!mobileOpen)} className="mobile-menu-btn" aria-label="Toggle Navigation Menu">
          {mobileOpen ? (
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          ) : (
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
          )}
        </button>
      </nav>

      {/* Mobile Navigation Drawer */}
      <nav className={`mobile-nav-overlay ${mobileOpen ? 'open' : ''}`} aria-label="Mobile Navigation">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {links.map(l => (
            <button key={l} onClick={() => scrollTo(l)} className="mobile-nav-link">
              {l}
            </button>
          ))}
        </div>

        <button onClick={() => scrollTo('Contact')}
          style={{ background: 'var(--cyan)', color: 'var(--fg-on-accent)', fontSize: 16, fontWeight: 600, fontFamily: 'var(--font-body)', padding: '14px 24px', borderRadius: 8, border: 'none', cursor: 'pointer', textAlign: 'center', width: '100%', marginTop: 12 }}>
          Request a Quote
        </button>

        {/* Mobile Touch-Friendly Theme Switcher */}
        <div style={{ marginTop: 'auto', borderTop: '1px solid var(--border)', paddingTop: 24 }}>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 600, textTransform: 'uppercase', color: 'var(--fg-3)', letterSpacing: '0.08em', marginBottom: 12 }}>Theme</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {[
              { key: 'system', label: 'Auto' },
              { key: 'light', label: 'Light' },
              { key: 'dark', label: 'Dark' }
            ].map(opt => (
              <button key={opt.key} onClick={() => setTheme(opt.key)} style={{
                background: theme === opt.key ? 'var(--cyan)' : 'var(--bg-elevated)',
                color: theme === opt.key ? 'var(--fg-on-accent)' : 'var(--fg-2)',
                border: 'none',
                borderRadius: 6,
                padding: '10px 0',
                fontFamily: 'var(--font-body)',
                fontSize: 12,
                fontWeight: 600,
                cursor: 'pointer',
                transition: 'all 200ms ease'
              }}>
                {opt.label}
              </button>
            ))}
          </div>
        </div>
      </nav>
    </header>
  );
};
Object.assign(window, { OASHeader });
