// menu.jsx — Full pizza menu page with hover preview + Liste/Galerie toggle
const { useState: useStateMenu, useMemo, useRef: useRefMenu } = React;

// Curated Unsplash food photos cycled by pizza id.
// Used as default images; user can override per-pizza later via data.
const PIZZA_IMG_POOL = [
  "https://images.unsplash.com/photo-1574071318508-1cdbab80d002?w=600&h=600&fit=crop",
  "https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?w=600&h=600&fit=crop",
  "https://images.unsplash.com/photo-1571407970349-bc81e7e96d47?w=600&h=600&fit=crop",
  "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=600&h=600&fit=crop",
  "https://images.unsplash.com/photo-1604068549290-dea0e4a305ca?w=600&h=600&fit=crop",
  "https://images.unsplash.com/photo-1590947132387-155cc02f3212?w=600&h=600&fit=crop",
  "https://images.unsplash.com/photo-1593504049359-74330189a345?w=600&h=600&fit=crop",
  "https://images.unsplash.com/photo-1548369937-47519962c11a?w=600&h=600&fit=crop",
];
const imgFor = (pizzaOrId) => {
  if (pizzaOrId && typeof pizzaOrId === 'object' && pizzaOrId.image) return pizzaOrId.image;
  const id = typeof pizzaOrId === 'object' ? pizzaOrId.id : pizzaOrId;
  return PIZZA_IMG_POOL[(id - 1) % PIZZA_IMG_POOL.length];
};

function CategoryNav({ active, onPick, categories, mode, onMode }) {
  return (
    <div className="fp-catnav-wrap">
      <nav className="fp-catnav">
        <button
          className={`fp-catnav__chip ${active === 'all' ? 'is-active' : ''}`}
          onClick={() => onPick('all')}
        >
          Tout <span>· 22</span>
        </button>
        {categories.map(c => (
          <button
            key={c.slug}
            className={`fp-catnav__chip ${active === c.slug ? 'is-active' : ''}`}
            onClick={() => onPick(c.slug)}
          >
            {c.name} <span>· {c.pizzas.length}</span>
          </button>
        ))}
        <button
          className={`fp-catnav__chip ${active === 'sweet' ? 'is-active' : ''}`}
          onClick={() => onPick('sweet')}
        >
          Desserts & Boissons <span>· 8</span>
        </button>
      </nav>

      <div className="fp-mode" role="tablist" aria-label="Affichage">
        <button
          className={`fp-mode__btn ${mode === 'list' ? 'is-active' : ''}`}
          onClick={() => onMode('list')}
          aria-label="Vue liste"
        >
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 6h16M4 12h16M4 18h16"/></svg>
          <span>Liste</span>
        </button>
        <button
          className={`fp-mode__btn ${mode === 'grid' ? 'is-active' : ''}`}
          onClick={() => onMode('grid')}
          aria-label="Vue galerie"
        >
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2"><rect x="4" y="4" width="7" height="7"/><rect x="13" y="4" width="7" height="7"/><rect x="4" y="13" width="7" height="7"/><rect x="13" y="13" width="7" height="7"/></svg>
          <span>Galerie</span>
        </button>
      </div>
    </div>
  );
}

function PizzaRow({ pizza, onAdd, idx, onPreview, onPreviewMove, onPreviewLeave }) {
  return (
    <article
      className="fp-pizza"
      style={{'--i': idx}}
      onMouseEnter={(e) => onPreview(pizza, e)}
      onMouseMove={onPreviewMove}
      onMouseLeave={onPreviewLeave}
    >
      <div className="fp-pizza__num">N°{String(pizza.id).padStart(2,'0')}</div>
      <div className="fp-pizza__main">
        <header className="fp-pizza__head">
          <h3 className="fp-pizza__name">
            {pizza.name}
            {pizza.signature && <span className="fp-pizza__badge">★ signature</span>}
            {pizza.vege && <span className="fp-pizza__badge fp-pizza__badge--vege">végé</span>}
          </h3>
          <div className="fp-pizza__dots" aria-hidden="true"></div>
          <div className="fp-pizza__price">{pizza.price.toFixed(2).replace('.', ',')}€</div>
        </header>
        <p className="fp-pizza__desc"><em>{pizza.desc}</em></p>
        <ul className="fp-pizza__ings">
          {pizza.ingredients.map((ing, k) => (
            <li key={k}>{ing}</li>
          ))}
        </ul>
      </div>
      <button className="fp-pizza__add" onClick={() => onAdd(pizza)} aria-label={`Ajouter ${pizza.name}`}>
        <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
        <span>Ajouter</span>
      </button>
    </article>
  );
}

function PizzaCard({ pizza, onAdd, idx }) {
  return (
    <article className="fp-pcard" style={{'--i': idx}}>
      <div className="fp-pcard__media">
        <img src={imgFor(pizza)} alt={pizza.name} loading="lazy" />
        <span className="fp-pcard__num">N°{String(pizza.id).padStart(2,'0')}</span>
        {pizza.signature && <span className="fp-pcard__sig">★ signature</span>}
      </div>
      <div className="fp-pcard__body">
        <header className="fp-pcard__head">
          <h3 className="fp-pcard__name">{pizza.name}</h3>
          <span className="fp-pcard__price">{pizza.price.toFixed(2).replace('.', ',')}€</span>
        </header>
        <p className="fp-pcard__desc"><em>{pizza.desc}</em></p>
        <ul className="fp-pcard__ings">
          {pizza.ingredients.slice(0, 4).map((ing, k) => <li key={k}>{ing}</li>)}
          {pizza.ingredients.length > 4 && <li className="fp-pcard__more">+{pizza.ingredients.length - 4}</li>}
        </ul>
        <button className="fp-pcard__add" onClick={() => onAdd(pizza)}>
          Ajouter
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
        </button>
      </div>
    </article>
  );
}

function HoverPreview({ pizza, x, y }) {
  if (!pizza) return null;
  return (
    <div
      className="fp-hover"
      style={{ left: x + 'px', top: y + 'px' }}
      aria-hidden="true"
    >
      <div className="fp-hover__plate">
        <img src={imgFor(pizza)} alt="" />
      </div>
      <div className="fp-hover__stamp">N°{String(pizza.id).padStart(2,'0')}</div>
    </div>
  );
}

function Menu({ onAdd }) {
  const [filter, setFilter] = useStateMenu('all');
  const [mode, setMode] = useStateMenu('list');
  const [hover, setHover] = useStateMenu({ pizza: null, x: 0, y: 0 });
  const cats = window.pizzaCategories;

  const visibleCats = useMemo(() => {
    if (filter === 'all') return cats;
    if (filter === 'sweet') return [];
    return cats.filter(c => c.slug === filter);
  }, [filter]);

  const showPreview = (pizza, e) => {
    setHover({ pizza, x: e.clientX, y: e.clientY });
  };
  const movePreview = (e) => {
    setHover(h => h.pizza ? { ...h, x: e.clientX, y: e.clientY } : h);
  };
  const hidePreview = () => setHover({ pizza: null, x: 0, y: 0 });

  const renderCategoryList = (cat) => (
    <div className="fp-menu__list">
      {cat.pizzas.map((p, i) => (
        <PizzaRow
          key={p.id}
          pizza={p}
          onAdd={onAdd}
          idx={i}
          onPreview={showPreview}
          onPreviewMove={movePreview}
          onPreviewLeave={hidePreview}
        />
      ))}
    </div>
  );

  const renderCategoryGrid = (cat) => (
    <div className="fp-menu__grid">
      {cat.pizzas.map((p, i) => (
        <PizzaCard key={p.id} pizza={p} onAdd={onAdd} idx={i} />
      ))}
    </div>
  );

  return (
    <main className="fp-menu" data-mode={mode}>
      <header className="fp-menu__hd">
        <span className="fp-eyebrow">La carte</span>
        <h1 className="fp-menu__title">
          22 <em>pizzas</em>,<br/>
          3 <em>desserts</em>,<br/>
          5 <em>boissons</em>.
        </h1>
        <p className="fp-menu__lede">
          Toutes nos pizzas sont en taille unique (∅ 31 cm). Pâte au levain, 48h de
          fermentation. Cuisson au four à pierre.
        </p>
      </header>

      <CategoryNav
        active={filter}
        onPick={setFilter}
        categories={cats}
        mode={mode}
        onMode={setMode}
      />

      {filter !== 'sweet' && visibleCats.map(cat => (
        <section key={cat.slug} className="fp-menu__cat">
          <header className="fp-menu__cat-hd">
            <span className="fp-menu__cat-icon">{cat.icon}</span>
            <h2 className="fp-menu__cat-title">{cat.name}</h2>
            <span className="fp-menu__cat-count">{cat.pizzas.length} pizzas</span>
          </header>
          {mode === 'list' ? renderCategoryList(cat) : renderCategoryGrid(cat)}
        </section>
      ))}

      {(filter === 'all' || filter === 'sweet') && (
        <>
          <section className="fp-menu__cat">
            <header className="fp-menu__cat-hd">
              <span className="fp-menu__cat-icon">🍮</span>
              <h2 className="fp-menu__cat-title">Desserts</h2>
              <span className="fp-menu__cat-count">{window.desserts.length} desserts</span>
            </header>
            <div className="fp-menu__list">
              {window.desserts.map((d, i) => (
                <article key={d.id} className="fp-pizza" style={{'--i': i}}>
                  <div className="fp-pizza__num">·</div>
                  <div className="fp-pizza__main">
                    <header className="fp-pizza__head">
                      <h3 className="fp-pizza__name">{d.name}</h3>
                      <div className="fp-pizza__dots" aria-hidden="true"></div>
                      <div className="fp-pizza__price">{d.price.toFixed(2).replace('.', ',')}€</div>
                    </header>
                    <p className="fp-pizza__desc"><em>{d.desc}</em></p>
                  </div>
                  <button className="fp-pizza__add" onClick={() => onAdd(d)}>
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
                    <span>Ajouter</span>
                  </button>
                </article>
              ))}
            </div>
          </section>

          <section className="fp-menu__cat">
            <header className="fp-menu__cat-hd">
              <span className="fp-menu__cat-icon">🥤</span>
              <h2 className="fp-menu__cat-title">Boissons</h2>
              <span className="fp-menu__cat-count">{window.beverages.length} boissons</span>
            </header>
            <div className="fp-menu__bevs">
              {window.beverages.map((b) => (
                <button key={b.id} className="fp-bev" onClick={() => onAdd(b)}>
                  <div className="fp-bev__name">
                    {b.name}<span> · {b.size}</span>
                  </div>
                  <div className="fp-bev__row">
                    <span className="fp-bev__price">{b.price.toFixed(2).replace('.', ',')}€</span>
                    <span className="fp-bev__plus">+</span>
                  </div>
                </button>
              ))}
            </div>
          </section>
        </>
      )}

      <footer className="fp-menu__foot">
        <p>
          Allergènes, cuissons, base sans gluten ?<br/>
          <a href="tel:+33613851153">Appelle-nous au <b>06 13 85 11 53</b></a> — on adore parler bouffe.
        </p>
      </footer>

      <HoverPreview pizza={hover.pizza} x={hover.x} y={hover.y} />
    </main>
  );
}

window.Menu = Menu;
