// Menu page — sticky anchor nav, 8 categories, real HTML.
const { useState: useStateMenu, useRef: useRefMenu, useEffect: useEffectMenu } = React;

function PageMenu({ navigate }) {
  const [active, setActive] = useStateMenu(window.MENU[0].id);
  const [query, setQuery] = useStateMenu('');
  const [filter, setFilter] = useStateMenu('all'); // all | best | vg | gf
  const sectionRefs = useRefMenu({});

  // Sticky scrollspy
  useEffectMenu(() => {
    const onScroll = () => {
      const y = window.scrollY + 220;
      let current = window.MENU[0].id;
      for (const cat of window.MENU) {
        const el = sectionRefs.current[cat.id];
        if (el && el.offsetTop <= y) current = cat.id;
      }
      setActive(current);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const jump = (id) => {
    const el = sectionRefs.current[id];
    if (el) window.scrollTo({ top: el.offsetTop - 180, behavior: 'smooth' });
  };

  const matches = (dish) => {
    if (filter === 'best' && !dish.tags.includes('best')) return false;
    if (filter === 'vg' && !dish.tags.includes('vg') && !dish.tags.includes('v')) return false;
    if (filter === 'gf' && !dish.tags.includes('gf')) return false;
    if (query) {
      const q = query.toLowerCase();
      return (dish.name + ' ' + dish.desc).toLowerCase().includes(q);
    }
    return true;
  };

  return (
    <main className="fade-enter">
      <MenuHero />
      <MenuToolbar
        categories={window.MENU}
        active={active}
        onJump={jump}
        query={query}
        setQuery={setQuery}
        filter={filter}
        setFilter={setFilter}
      />
      <section style={{ padding: '48px 0 96px' }}>
        <div className="container container--wide" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 80 }}>
          <div>
            {window.MENU.map((cat, idx) => {
              const visible = cat.items.filter(matches);
              if (visible.length === 0 && (query || filter !== 'all')) return null;
              return (
                <section
                  key={cat.id}
                  ref={el => (sectionRefs.current[cat.id] = el)}
                  style={{ paddingTop: idx === 0 ? 0 : 64, paddingBottom: 16 }}
                >
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 16, marginBottom: 4 }}>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--terracotta)', letterSpacing: '0.16em' }}>
                      0{idx + 1} / 0{window.MENU.length}
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
                    <div>
                      <h2 style={{ fontSize: 38, lineHeight: 1.05, marginTop: 6 }}>{cat.name}</h2>
                      <div className="arabic" style={{ fontSize: 22, color: 'var(--ink-2)', marginTop: 6 }}>{cat.nameAr}</div>
                    </div>
                    <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                      {visible.length} dishes
                    </div>
                  </div>
                  <p style={{ fontSize: 15, color: 'var(--ink-2)', marginTop: 12, maxWidth: '60ch' }}>{cat.intro}</p>

                  <div style={{ marginTop: 24 }}>
                    {visible.map((dish, i) => <DishCard key={i} dish={dish} />)}
                  </div>
                </section>
              );
            })}
          </div>

          {/* Side panel */}
          <aside style={{ position: 'sticky', top: 180, alignSelf: 'start', display: 'flex', flexDirection: 'column', gap: 24 }}>
            <div style={{
              background: 'var(--cream)',
              border: '1px solid var(--line)',
              borderRadius: 'var(--radius)',
              padding: 28,
            }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--terracotta)' }}>HOUSE STANDARD</div>
              <div className="serif" style={{ fontSize: 22, fontWeight: 600, color: 'var(--charcoal)', marginTop: 8, lineHeight: 1.3 }}>
                Every grill plate is served with —
              </div>
              <ul style={{ margin: '16px 0 0', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
                {['Hummus', 'Garlic paste', 'Pickles', 'Oriental salad', 'Lebanese pita', 'Fries'].map(item => (
                  <li key={item} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 14, color: 'var(--ink-2)' }}>
                    <Icon.check width="14" height="14" style={{ color: 'var(--olive-dark)' }} /> {item}
                  </li>
                ))}
              </ul>
            </div>

            <div style={{
              background: 'var(--charcoal)', color: 'var(--paper)',
              borderRadius: 'var(--radius)',
              padding: 28,
            }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--saffron)' }}>FRESH ON SITE</div>
              <div className="serif" style={{ fontSize: 22, color: 'var(--paper)', marginTop: 8, fontWeight: 500, lineHeight: 1.3 }}>
                Our Lebanese pita is baked on-site at flagship branches.
              </div>
              <div style={{ fontSize: 13, color: 'rgba(245,235,220,0.7)', marginTop: 12 }}>
                Look for the bakery window at Al Raffa, Mirdif and Jumeirah 1.
              </div>
            </div>

            <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 'var(--radius)', padding: 24 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--ink-3)' }}>ALLERGEN KEY</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 14 }}>
                <span className="tag tag--vg">VG — Vegan</span>
                <span className="tag tag--v">V — Vegetarian</span>
                <span className="tag tag--gf">GF — Gluten free</span>
                <span className="tag tag--n">Contains nuts</span>
                <span className="tag tag--best">Best-seller</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 14, lineHeight: 1.45 }}>
                Cross-contact possible; tell us about severe allergies and we'll route the prep.
              </div>
            </div>
          </aside>
        </div>
      </section>
    </main>
  );
}

function MenuHero() {
  return (
    <section style={{ background: 'var(--cream)', padding: '80px 0 56px', borderBottom: '1px solid var(--line)' }}>
      <div className="container container--wide">
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 64, alignItems: 'end' }}>
          <div>
            <div className="eyebrow">The menu</div>
            <h1 style={{ fontSize: 'clamp(48px, 6vw, 84px)', lineHeight: 1, marginTop: 16 }}>
              Eight sections. <span style={{ color: 'var(--terracotta)', fontStyle: 'italic' }}>Same recipe</span> since 1977.
            </h1>
            <p className="lede" style={{ marginTop: 20 }}>
              Cold and hot mezze, salads, shawarma off the spit, mains from the charcoal grill,
              saj sandwiches, daily specials, desserts and fresh juices. Prices in AED.
            </p>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-2)' }}>
            <div className="row"><span style={{ color: 'var(--terracotta)' }}>●</span> Prices in AED, dine-in &amp; takeaway</div>
            <div className="row"><span style={{ color: 'var(--olive-dark)' }}>●</span> Vary slightly between Talabat / Deliveroo / Careem</div>
            <div className="row"><span style={{ color: 'var(--saffron)' }}>●</span> Last updated May 2026</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function MenuToolbar({ categories, active, onJump, query, setQuery, filter, setFilter }) {
  return (
    <div style={{
      position: 'sticky',
      top: 105,
      zIndex: 30,
      background: 'rgba(255,252,246,0.95)',
      backdropFilter: 'blur(10px)',
      borderBottom: '1px solid var(--line)',
    }}>
      <div className="container container--wide" style={{ padding: '14px var(--gutter)', display: 'flex', gap: 16, alignItems: 'center' }}>
        <div style={{ display: 'flex', gap: 4, overflow: 'auto', flex: 1 }} className="anchor-scroll">
          {categories.map((c, i) => (
            <button
              key={c.id}
              className="nav__link"
              onClick={() => onJump(c.id)}
              style={{
                whiteSpace: 'nowrap',
                background: active === c.id ? 'var(--charcoal)' : 'transparent',
                color: active === c.id ? 'var(--paper)' : 'var(--ink-2)',
                fontSize: 13,
                padding: '8px 14px',
              }}
            >
              {c.name}
            </button>
          ))}
        </div>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <Icon.search width="14" height="14" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)' }} />
          <input
            placeholder="Search dishes"
            value={query}
            onChange={e => setQuery(e.target.value)}
            style={{
              padding: '8px 14px 8px 32px',
              borderRadius: 999,
              border: '1px solid var(--line-strong)',
              background: 'var(--paper)',
              fontSize: 13,
              fontFamily: 'var(--font-sans)',
              width: 200,
            }}
          />
        </div>
        <div style={{ display: 'flex', gap: 4, background: 'var(--cream)', padding: 3, borderRadius: 999 }}>
          {[['all','All'],['best','★'],['vg','VG'],['gf','GF']].map(([v, l]) => (
            <button
              key={v}
              onClick={() => setFilter(v)}
              style={{
                padding: '6px 12px', borderRadius: 999,
                background: filter === v ? 'var(--paper)' : 'transparent',
                color: filter === v ? 'var(--charcoal)' : 'var(--ink-2)',
                fontSize: 12, fontFamily: 'var(--font-mono)', letterSpacing: '0.06em',
                fontWeight: filter === v ? 600 : 400,
                boxShadow: filter === v ? '0 1px 3px rgba(31,27,23,0.08)' : 'none',
              }}
            >{l}</button>
          ))}
        </div>
      </div>
      <style>{`.anchor-scroll::-webkit-scrollbar { display: none; }`}</style>
    </div>
  );
}

window.PageMenu = PageMenu;
