// Header — emergency announce bar + sticky main bar with Services + Industries mega menus
const SFHeader = ({ lang, setLang, dark, setDark, accent, page, setPage }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [openMenu, setOpenMenu] = React.useState(null); // 'services' | 'industries' | null
  const closeTimer = React.useRef(null);

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

  const t = (en, zh) => sfT(lang, en, zh);

  const enter = (k) => { if (closeTimer.current) clearTimeout(closeTimer.current); setOpenMenu(k); };
  const leave = () => { closeTimer.current = setTimeout(() => setOpenMenu(null), 140); };

  const items = [
    { k:'home',       en:'Home',       zh:'主頁' },
    { k:'services',   en:'Services',   zh:'服務',   mega:true },
    { k:'industries', en:'Industries', zh:'行業',   mega:true },
    { k:'contact',    en:'Contact',    zh:'聯絡' },
  ];

  const isActive = (k) =>
    page===k ||
    (k==='services'   && page.startsWith('pillar:')) ||
    (k==='industries' && page.startsWith('industry:'));

  return (
    <header style={{ position:'sticky', top:0, zIndex:50 }}>
      {/* Emergency / IR hotline strip */}
      <div style={{
        background:'var(--navy-700)', color:'#fff',
        fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.04em',
        padding:'7px 24px', display:'flex', alignItems:'center', gap:12, flexWrap:'wrap',
      }}>
        <span style={{ display:'inline-flex', alignItems:'center', gap:8 }}>
          <span style={{ width:6, height:6, background:'var(--orange-500)', borderRadius:'50%',
            animation:'sfpulse 2s infinite' }}/>
          {t('NOC operational · 24/7 incident response', 'NOC 運作中 · 24/7 緊急應變')}
        </span>
        <a href="tel:+85265520772" style={{
          marginLeft:'auto', display:'inline-flex', alignItems:'center', gap:8,
          background:'var(--orange-500)', color:'#fff', padding:'5px 12px',
          fontWeight:700, letterSpacing:'.06em',
        }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M6.62 10.79c1.44 2.83 3.76 5.15 6.59 6.59l2.2-2.2a1 1 0 0 1 1.02-.24c1.12.37 2.33.57 3.57.57a1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A17 17 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.25.2 2.45.57 3.57a1 1 0 0 1-.25 1.02z"/></svg>
          {t('Call Support Now', '即時聯絡支援')}
        </a>
        <style>{`@keyframes sfpulse{0%,100%{opacity:1}50%{opacity:.4}}`}</style>
      </div>

      <div style={{
        background: scrolled ? 'color-mix(in srgb, var(--bg-default) 80%, transparent)' : 'var(--bg-default)',
        backdropFilter: scrolled ? 'blur(16px) saturate(160%)' : 'none',
        WebkitBackdropFilter: scrolled ? 'blur(16px) saturate(160%)' : 'none',
        borderBottom:'1px solid var(--border-subtle)',
        transition:'all 180ms ease',
        position:'relative',
      }}>
      <div className="container" style={{ display:'flex', alignItems:'center', justifyContent:'space-between', height:64 }}>
        <div style={{ display:'flex', alignItems:'center', gap:32 }}>
          <a onClick={()=>setPage('home')} style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer' }}>
            <SFLogo height={36}/>
          </a>
          <nav style={{ display:'flex', gap:2 }}>
            {items.map(n => (
              <div key={n.k}
                onMouseEnter={()=> n.mega ? enter(n.k) : null}
                onMouseLeave={()=> n.mega ? leave() : null}
                style={{ position:'static' }}>
                <a onClick={()=> n.mega ? setPage(n.k) : setPage(n.k)} style={{
                  fontSize:13, fontWeight:500, cursor:'pointer', padding:'8px 12px',
                  display:'inline-flex', alignItems:'center', gap:5,
                  color: isActive(n.k) ? 'var(--fg-default)' : 'var(--fg-muted)',
                  borderBottom: isActive(n.k) ? `1px solid ${accent}` : '1px solid transparent',
                }}>
                  {t(n.en, n.zh)}
                  {n.mega && (
                    <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                      strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"
                      style={{ opacity:.5, transform: openMenu===n.k ? 'rotate(180deg)' : 'none', transition:'transform 160ms' }}>
                      <polyline points="6 9 12 15 18 9"/>
                    </svg>
                  )}
                </a>
              </div>
            ))}
          </nav>
        </div>
        <div style={{ display:'flex', gap:6, alignItems:'center' }}>
          <button
            onClick={()=>setLang(lang==='en'?'zh':'en')}
            role="switch" aria-checked={lang==='zh'} aria-label="Language"
            title={lang==='en' ? 'Switch to 繁體中文' : 'Switch to English'}
            style={{
              display:'inline-flex', alignItems:'center', gap:0, padding:0, height:28,
              background:'var(--bg-card)', border:'1px solid var(--border-subtle)',
              borderRadius:0, cursor:'pointer', overflow:'hidden',
              fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.04em',
            }}>
            <span style={{
              padding:'0 10px', height:'100%', display:'inline-flex', alignItems:'center',
              background: lang==='en' ? accent : 'transparent',
              color:    lang==='en' ? '#fff'  : 'var(--fg-muted)',
              fontWeight: lang==='en' ? 700 : 500,
            }}>EN</span>
            <span style={{
              padding:'0 10px', height:'100%', display:'inline-flex', alignItems:'center',
              background: lang==='zh' ? accent : 'transparent',
              color:    lang==='zh' ? '#fff'  : 'var(--fg-muted)',
              fontWeight: lang==='zh' ? 700 : 500,
              borderLeft:'1px solid var(--border-subtle)',
            }}>繁</span>
          </button>
          <button onClick={()=>setDark(!dark)} className="btn btn-ghost btn-sm" aria-label="Theme" title="Theme">
            {dark ? (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" 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>
            )}
          </button>
          <button onClick={()=>setPage('contact')} className="btn btn-primary btn-sm">
            {t('Book site survey', '預約勘察')} →
          </button>
        </div>
      </div>

      {/* MEGA MENU PANELS */}
      {openMenu==='services' && (
        <div onMouseEnter={()=>enter('services')} onMouseLeave={leave}
          style={{
            position:'absolute', left:0, right:0, top:'100%',
            background:'var(--bg-default)', borderBottom:'1px solid var(--border-subtle)',
            boxShadow:'0 24px 48px -16px rgba(0,0,0,.18)', zIndex:40,
          }}>
          <div className="container" style={{ paddingTop:28, paddingBottom:28 }}>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:24 }}>
              {SF_PILLAR_GROUPS.map(grp => (
                <div key={grp.en}>
                  <div className="mono" style={{
                    fontSize:10, color:accent, letterSpacing:'.1em',
                    paddingBottom:10, marginBottom:10,
                    borderBottom:'1px solid var(--border-subtle)',
                  }}>
                    {t(grp.en, grp.zh).toUpperCase()}
                  </div>
                  {grp.ids.map(pid => {
                    const pp = SF_PILLARS[pid]; if (!pp) return null;
                    const pt = lang==='en' ? pp.en : pp.zh;
                    return (
                      <a key={pid} onClick={()=>setPage(`pillar:${pid}`)} style={{
                        display:'block', padding:'8px 0', cursor:'pointer',
                        borderBottom:'1px solid var(--border-faint, transparent)',
                      }}>
                        <div style={{ fontSize:13, fontWeight:600, color:'var(--fg-default)', marginBottom:2 }}>
                          {pt.kicker}
                        </div>
                        <div style={{ fontSize:11, color:'var(--fg-muted)', lineHeight:1.4 }}>
                          {pt.title}
                        </div>
                      </a>
                    );
                  })}
                </div>
              ))}
            </div>
            <div style={{
              marginTop:20, paddingTop:16, borderTop:'1px solid var(--border-subtle)',
              display:'flex', alignItems:'center', justifyContent:'space-between', gap:16,
            }}>
              <span className="mono" style={{ fontSize:11, color:'var(--fg-muted)', letterSpacing:'.04em' }}>
                {t('10 capabilities · usually a few, working together',
                   '10 項能力 · 通常幾項並用')}
              </span>
              <a onClick={()=>setPage('services')} style={{
                fontSize:12, color:accent, cursor:'pointer', fontWeight:600,
                fontFamily:'var(--font-mono)',
              }}>{t('See all services →','查看全部服務 →')}</a>
            </div>
          </div>
        </div>
      )}

      {openMenu==='industries' && (
        <div onMouseEnter={()=>enter('industries')} onMouseLeave={leave}
          style={{
            position:'absolute', left:0, right:0, top:'100%',
            background:'var(--bg-default)', borderBottom:'1px solid var(--border-subtle)',
            boxShadow:'0 24px 48px -16px rgba(0,0,0,.18)', zIndex:40,
          }}>
          <div className="container" style={{ paddingTop:28, paddingBottom:28 }}>
            <div className="mono" style={{
              fontSize:10, color:accent, letterSpacing:'.1em', marginBottom:14,
            }}>
              {t('INDUSTRIES WE SERVE','服務行業')}
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:0,
              border:'1px solid var(--border-subtle)' }}>
              {SF_INDUSTRY_LIST.map((id, i) => {
                const ind = SF_INDUSTRY_PAGES[id]; const x = lang==='en'?ind.en:ind.zh;
                return (
                  <a key={id} onClick={()=>setPage(`industry:${id}`)} style={{
                    padding:'18px 18px', cursor:'pointer', background:'var(--bg-card)',
                    borderRight: (i+1)%4!==0 ? '1px solid var(--border-subtle)' : 'none',
                    borderBottom: i < SF_INDUSTRY_LIST.length-4 ? '1px solid var(--border-subtle)' : 'none',
                    transition:'background 160ms',
                  }}
                  onMouseEnter={e=>e.currentTarget.style.background='var(--bg-fill-1)'}
                  onMouseLeave={e=>e.currentTarget.style.background='var(--bg-card)'}>
                    <div className="mono" style={{ fontSize:9, color:accent, letterSpacing:'.08em', marginBottom:6 }}>
                      {String(i+1).padStart(2,'0')}
                    </div>
                    <div style={{ fontSize:14, fontWeight:600, color:'var(--fg-default)', marginBottom:4 }}>
                      {x.name}
                    </div>
                    <div style={{ fontSize:11, color:'var(--fg-muted)', lineHeight:1.4 }}>
                      {x.title}
                    </div>
                  </a>
                );
              })}
            </div>
            <div style={{
              marginTop:16, display:'flex', alignItems:'center', justifyContent:'space-between',
            }}>
              <span className="mono" style={{ fontSize:11, color:'var(--fg-muted)', letterSpacing:'.04em' }}>
                {t('Each industry has different best-fit capabilities',
                   '每個行業適合不同的服務組合')}
              </span>
              <a onClick={()=>setPage('industries')} style={{
                fontSize:12, color:accent, cursor:'pointer', fontWeight:600,
                fontFamily:'var(--font-mono)',
              }}>{t('See all industries →','查看全部行業 →')}</a>
            </div>
          </div>
        </div>
      )}
      </div>
    </header>
  );
};

const SFMark = ({ accent='#D9931C', dark=false, size=32 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <rect x="0.5" y="0.5" width="31" height="31" rx="2" stroke="currentColor" strokeOpacity="0.25"/>
    <circle cx="22" cy="10" r="3.5" fill={accent}/>
    <path d="M6 24 L10 14 L14 24 Z" fill="currentColor"/>
    <path d="M12 24 L16 12 L20 24 Z" fill="currentColor" opacity="0.7"/>
    <path d="M18 24 L22 16 L26 24 Z" fill="currentColor" opacity="0.45"/>
  </svg>
);

window.SFHeader = SFHeader;
window.SFMark = SFMark;
