// Sticky Header mit Logo, Nav, Telefon, Route, Live-Open-Status
// Plus: kompakter Sprachumschalter (Popover) und mobiler Burger-Drawer

function LangSwitcherCompact() {
  const { lang, setLang } = useT();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const meta = LANG_BY_CODE[lang];

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  return (
    <div ref={ref} style={{ position:'relative' }}>
      <button
        onClick={() => setOpen(o => !o)}
        className="pill lang-pill"
        aria-haspopup="listbox"
        aria-expanded={open}
        style={{ background:'var(--paper)', borderColor:'var(--line)', cursor:'pointer', gap:6 }}
      >
        <Icon name="globe" size={14} />
        <span style={{ fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.06em' }}>{meta.short}</span>
        <span style={{ fontSize:9, opacity:.6 }}>▾</span>
      </button>
      {open && (
        <div role="listbox" style={{
          position:'absolute', top:'calc(100% + 8px)', insetInlineEnd:0,
          background:'var(--paper)', border:'1px solid var(--line)', borderRadius:8,
          boxShadow:'0 16px 50px rgba(0,0,0,.18)', minWidth:160, padding:6, zIndex:80
        }}>
          {LANGS.map(l => (
            <button key={l.code} onClick={() => { setLang(l.code); setOpen(false); }}
              role="option" aria-selected={l.code===lang}
              style={{
                display:'flex', alignItems:'center', gap:10, width:'100%',
                padding:'10px 12px', border:0, borderRadius:6, minHeight:44,
                background: l.code===lang ? 'var(--bg-2)' : 'transparent',
                color:'var(--ink)', cursor:'pointer', textAlign:'start',
                fontFamily:'var(--font-body)', fontSize:14
              }}>
              <span style={{ fontSize:16 }}>{l.flag}</span>
              <span dir={l.dir} style={{ fontFamily: (l.code==='fa'||l.code==='ar') ? '"Vazirmatn","Noto Naskh Arabic",sans-serif' : 'inherit' }}>{l.native}</span>
              {l.code===lang && <span style={{ marginInlineStart:'auto', color:'var(--brick)' }}>✓</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function MobileDrawer({ open, onClose }) {
  const { t, dir } = useT();
  const status = useOpenStatus();
  const drawerRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const first = drawerRef.current && drawerRef.current.querySelector('a,button');
    if (first) first.focus();
    return () => {
      document.body.style.overflow = prev;
      document.removeEventListener('keydown', onKey);
    };
  }, [open, onClose]);

  const slideFrom = dir === 'rtl' ? 'translateX(-100%)' : 'translateX(100%)';

  const content = (
    <div aria-hidden={!open} style={{
      position:'fixed', inset:0, zIndex:100,
      pointerEvents: open ? 'auto' : 'none',
    }}>
      <div onClick={onClose} style={{
        position:'absolute', inset:0,
        background:'rgba(42,27,18,.42)',
        opacity: open ? 1 : 0,
        transition:'opacity 220ms ease',
      }}/>
      <aside
        ref={drawerRef}
        id="mobile-drawer"
        role="dialog"
        aria-modal="true"
        aria-label={t('header.langLabel')}
        style={{
          position:'absolute', top:0, height:'100%',
          insetInlineEnd:0, insetInlineStart:'auto',
          width:'min(86vw, 360px)',
          background:'var(--paper)',
          boxShadow:'0 20px 60px rgba(0,0,0,.28)',
          transform: open ? 'translateX(0)' : slideFrom,
          transition:'transform 260ms cubic-bezier(.2,.8,.2,1)',
          display:'flex', flexDirection:'column',
          paddingBlock:'18px 24px', paddingInline:20,
          overflowY:'auto',
        }}
      >
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:18 }}>
          <span className={`pill`} style={{ background:'transparent', borderColor:'var(--line)' }}>
            <span className={`live-dot ${status.open?'':'closed'}`}></span>
            <span style={{ fontSize:12 }}>{status.label}</span>
          </span>
          <button
            onClick={onClose}
            aria-label={t('common.back')}
            style={{
              width:44, height:44, border:0, background:'transparent',
              borderRadius:8, cursor:'pointer', color:'var(--ink)',
              display:'inline-flex', alignItems:'center', justifyContent:'center',
            }}>
            <Icon name="close" size={22}/>
          </button>
        </div>
        <nav style={{ display:'flex', flexDirection:'column', gap:2, marginBottom:20 }}>
          {[
            { href:'/#sortiment', label: t('header.nav.sortiment') },
            { href:'/#angebote',  label: t('header.nav.angebote') },
            { href:'/#rezept',    label: t('header.nav.rezept') },
            { href:'/#metzgerei', label: t('header.nav.metzgerei') },
            { href:'/#standort',  label: t('header.nav.standort') },
          ].map(l => (
            <a key={l.href} href={l.href} onClick={onClose}
              style={{
                fontFamily:'var(--font-display)', fontSize:22, fontWeight:700,
                color:'var(--ink)', padding:'12px 4px', minHeight:48,
                borderBottom:'1px solid var(--line)',
                display:'flex', alignItems:'center',
              }}>
              {l.label}
            </a>
          ))}
        </nav>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          <a href="tel:+4917624846057" className="btn" style={{ justifyContent:'center' }}>
            <Icon name="phone" size={14}/>
            <span className="ltr">{t('site.phoneHuman')}</span>
          </a>
          <a href="/#standort" onClick={onClose} className="btn" style={{ background:'var(--brick)', color:'var(--paper)', borderColor:'var(--brick)', justifyContent:'center' }}>
            <Icon name="route" size={14}/> <span>{t('common.planRoute')}</span>
          </a>
        </div>
        <div style={{ marginTop:'auto', paddingTop:24 }}>
          <div className="eyebrow" style={{ marginBottom:10 }}>{t('header.langLabel')}</div>
          <DrawerLangList onPick={onClose}/>
        </div>
      </aside>
    </div>
  );
  return ReactDOM.createPortal(content, document.body);
}

function DrawerLangList({ onPick }) {
  const { lang, setLang } = useT();
  return (
    <ul style={{ listStyle:'none', padding:0, margin:0, display:'grid', gap:6 }}>
      {LANGS.map(l => (
        <li key={l.code}>
          <button onClick={() => { setLang(l.code); if (onPick) onPick(); }}
            aria-current={l.code===lang ? 'true' : undefined}
            style={{
              display:'flex', alignItems:'center', gap:10, width:'100%',
              padding:'10px 10px', border:0, borderRadius:8, minHeight:44,
              background: l.code===lang ? 'var(--bg-2)' : 'transparent',
              color:'var(--ink)', cursor:'pointer', textAlign:'start',
              fontFamily:'var(--font-body)', fontSize:15,
            }}>
            <span style={{ fontSize:18 }}>{l.flag}</span>
            <span dir={l.dir} style={{ fontFamily: (l.code==='fa'||l.code==='ar') ? '"Vazirmatn","Noto Naskh Arabic",sans-serif' : 'inherit' }}>{l.native}</span>
            {l.code===lang && <span style={{ marginInlineStart:'auto', color:'var(--brick)' }}>✓</span>}
          </button>
        </li>
      ))}
    </ul>
  );
}

function Header() {
  const { t } = useT();
  const status = useOpenStatus();
  const [scrolled, setScrolled] = React.useState(false);
  const [navOpen, setNavOpen] = React.useState(false);
  React.useEffect(() => {
    const onS = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onS); onS();
    return () => window.removeEventListener('scroll', onS);
  }, []);
  return (
    <header className="sticky" style={{ borderBottom: scrolled ? '1px solid var(--line)' : '1px solid transparent' }}>
      <div className="container-wide hdr-row" style={{ display:'flex', alignItems:'center', gap:24 }}>
        <a href="#top" style={{ display:'flex', alignItems:'center', gap:12 }}>
          <img src="assets/logo.png" alt={t('site.name')} className="hdr-logo" width="48" height="48" style={{ width:48, height:48, objectFit:'contain' }} />
          <div style={{ display:'flex', flexDirection:'column', lineHeight:1 }}>
            <span className="hdr-brand" style={{ fontFamily:'var(--font-display)', fontSize:22, fontWeight:700, letterSpacing:'-.01em' }}>{t('site.name')}</span>
            <span className="eyebrow hdr-tag" style={{ fontSize:9, marginTop:4 }}>{t('site.tagline')}</span>
          </div>
        </a>
        <nav style={{ display:'flex', gap:22, marginInlineStart:32, fontSize:14, fontWeight:500 }} className="hide-md">
          <a href="#sortiment">{t('header.nav.sortiment')}</a>
          <a href="#angebote">{t('header.nav.angebote')}</a>
          <a href="#rezept">{t('header.nav.rezept')}</a>
          <a href="#metzgerei">{t('header.nav.metzgerei')}</a>
          <a href="#standort">{t('header.nav.standort')}</a>
        </nav>
        <div className="hdr-actions" style={{ marginInlineStart:'auto', display:'flex', alignItems:'center', gap:14 }}>
          <span className="pill hide-sm" style={{ background:'transparent', borderColor:'var(--line)' }}>
            <span className={`live-dot ${status.open?'':'closed'}`}></span>
            <span style={{ fontSize:12 }}>{status.label}</span>
          </span>
          <a href="tel:+4917624846057" className="pill hide-sm" style={{ background:'var(--paper)' }}>
            <Icon name="phone" size={14} />
            <span className="ltr">{t('site.phoneHuman')}</span>
          </a>
          <span className="hide-md"><LangSwitcherCompact/></span>
          <a href="#standort" className="btn hdr-route hide-md" style={{ padding:'10px 16px', fontSize:13 }}>
            <Icon name="route" size={14} /> <span className="hdr-route-label">{t('common.route')}</span>
          </a>
          <button
            type="button"
            className="hdr-burger show-md"
            aria-label="Menu"
            aria-expanded={navOpen}
            aria-controls="mobile-drawer"
            onClick={() => setNavOpen(true)}
            style={{
              display:'none',
              width:44, height:44, border:'1px solid var(--line)',
              background:'var(--paper)', borderRadius:999, cursor:'pointer',
              alignItems:'center', justifyContent:'center', color:'var(--ink)',
            }}>
            <Icon name="menu" size={20}/>
          </button>
        </div>
      </div>
      <MobileDrawer open={navOpen} onClose={() => setNavOpen(false)}/>
      <style>{`
        .hdr-row{ padding:12px 16px; }
        .hdr-burger{ display:none; }
        @media (min-width: 600px){ .hdr-row{ padding:14px 20px; } }
        @media (min-width: 981px){ .hdr-row{ padding:14px 28px; } }
        @media (max-width: 980px){
          .hide-md{ display:none !important; }
          .hdr-burger{ display:inline-flex !important; }
        }
        @media (max-width: 720px){ .hide-sm{ display:none !important; } }
        @media (max-width: 520px){
          .hdr-logo{ width:40px; height:40px; }
          .hdr-brand{ font-size:18px; }
          .hdr-tag{ display:none; }
          .hdr-actions{ gap:8px; }
        }
      `}</style>
    </header>
  );
}

window.Header = Header;
window.LangSwitcherCompact = LangSwitcherCompact;
window.MobileDrawer = MobileDrawer;
