// Menu QR Restaurant La Piste — mobile
function MenuQR() {
  const [cat, setCat] = React.useState('locaux');
  const [cart, setCart] = React.useState({});
  const [ordered, setOrdered] = React.useState(false);

  // Lecture du paramètre URL ?t=NN pour identifier la table dynamiquement
  const tableNum = React.useMemo(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      const t = params.get('t');
      return t || '08';
    } catch (e) {
      return '08';
    }
  }, []);

  const cats = [
    { id: 'pdj',     label: 'Petit-déj' },
    { id: 'entrees', label: 'Entrées' },
    { id: 'locaux',  label: 'Plats locaux' },
    { id: 'inter',   label: 'Internationaux' },
    { id: 'desserts',label: 'Desserts' },
    { id: 'boissons',label: 'Boissons' },
    { id: 'cocktails',label:'Cocktails' },
  ];

  const dishes = {
    locaux: [
      { id: 'ndole', n: 'Ndolé aux crevettes', d: 'Feuilles amères, pâte d\'arachide, crevettes fraîches', p: 5500, a: ['arachide', 'crustacés'], hot: true,
        image: '/images/unsplash-cache/photo-1567982047351-76b6f93e38ee.jpg', cat: 'POISSON' },
      { id: 'yassa', n: 'Poulet yassa', d: 'Poulet mariné, oignons confits, citron, riz blanc', p: 6000, a: ['moutarde'], chef: true,
        image: '/images/unsplash-cache/photo-1598103442097-8b74394b95c6.jpg', cat: 'POULET' },
      { id: 'saka',  n: 'Saka saka au poisson fumé', d: 'Feuilles de manioc pilées, poisson fumé, riz', p: 4500, a: ['poisson'],
        image: '/images/unsplash-cache/photo-1547592180-85f173990554.jpg', cat: 'PLAT' },
      { id: 'mab',   n: 'Maboke de capitaine', d: 'Capitaine en papillote de feuilles, sauce nokoss', p: 7000, a: ['poisson'],
        image: '/images/unsplash-cache/photo-1611273426858-450d8e3c9fce.jpg', cat: 'POISSON' },
      { id: 'braise',n: 'Poisson braisé + plantain', d: 'Tilapia entier braisé, alloko, sauce piquante', p: 8500, a: ['poisson'], hot: true,
        image: '/images/unsplash-cache/photo-1559847844-5315695dadae.jpg', cat: 'POISSON' },
    ],
    pdj: [
      { id: 'b1', n: 'Continental TARMAC', d: 'Viennoiseries, fruits, jus, café arabica', p: 8000, a: ['gluten', 'lactose'],
        image: '/images/unsplash-cache/photo-1592151450402-0d8a4c6e35d5.jpg', cat: 'PDJ' },
      { id: 'b2', n: 'Beignets congolais', d: 'Mikate maison, miel local', p: 3500, a: ['gluten'],
        image: '/images/unsplash-cache/photo-1606755456206-b25fdf8d6f1c.jpg', cat: 'PDJ' },
    ],
    entrees: [],
    inter: [],
    desserts: [],
    boissons: [],
    cocktails: [],
  };

  const list = dishes[cat] || [];
  const add = (id) => setCart({ ...cart, [id]: (cart[id] || 0) + 1 });
  const remove = (id) => {
    const c = { ...cart };
    if (c[id] > 1) c[id]--; else delete c[id];
    setCart(c);
  };

  const total = Object.entries(cart).reduce((s, [id, q]) => {
    const d = Object.values(dishes).flat().find((x) => x && x.id === id);
    return s + (d ? d.p * q : 0);
  }, 0);
  const count = Object.values(cart).reduce((s, n) => s + n, 0);

  const Pill = ({ children, color }) => (
    <span style={{
      fontFamily: TARMAC.mono, fontSize: 8, padding: '2px 5px',
      letterSpacing: '0.06em', textTransform: 'uppercase',
      border: `1px solid ${color}40`, color: color,
    }}>{children}</span>
  );

  return (
    <Phone w={360} h={760}>
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', position: 'relative' }}>
        {/* Header */}
        <div style={{
          padding: '14px 16px 12px', borderBottom: `1px solid ${TARMAC.inkLine}`,
          background: TARMAC.inkDeep, position: 'relative',
        }}>
          <button onClick={() => window.navigateBack ? window.navigateBack('home') : window.navigateTo("home")} style={{
            position: 'absolute', top: 10, left: 10, background: 'none', border: 'none',
            color: TARMAC.paperMute, fontSize: 18, cursor: 'pointer', padding: 4,
          }}>←</button>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <div className="tm-eyebrow" style={{ color: TARMAC.paperFaint, paddingLeft: 22 }}>Le TARMAC · Dolisie</div>
            <div style={{
              padding: '3px 8px', background: 'rgba(201,146,26,0.12)',
              border: `1px solid ${TARMAC.gold}`, fontFamily: TARMAC.mono,
              fontSize: 10, color: TARMAC.gold, letterSpacing: '0.1em',
            }}>
              ● TABLE {tableNum}
            </div>
          </div>
          <h1 className="tm-serif" style={{
            fontSize: 28, color: TARMAC.gold, margin: 0, fontWeight: 500, lineHeight: 1,
          }}>
            <span style={{ fontStyle: 'italic', fontWeight: 400, color: TARMAC.paper, opacity: 0.85, fontSize: 18, display: 'block' }}>Restaurant</span>
            La Piste
          </h1>
          <div style={{ fontSize: 10, color: TARMAC.paperFaint, marginTop: 6, fontFamily: TARMAC.mono, letterSpacing: '0.04em' }}>
            Service midi · 12h–15h · Chef Kévin Mboulou
          </div>
        </div>

        {/* Category tabs */}
        <div className="tm-scroll" style={{
          display: 'flex', gap: 4, padding: '12px 16px',
          overflowX: 'auto', borderBottom: `1px solid ${TARMAC.inkLine}`,
          background: TARMAC.inkSoft,
        }}>
          {cats.map((c) => (
            <button key={c.id} onClick={() => setCat(c.id)} style={{
              flexShrink: 0, padding: '7px 12px',
              background: cat === c.id ? TARMAC.gold : 'transparent',
              color: cat === c.id ? TARMAC.ink : TARMAC.paperMute,
              border: cat === c.id ? 'none' : `1px solid ${TARMAC.inkLine}`,
              fontFamily: TARMAC.sans, fontSize: 11, fontWeight: cat === c.id ? 600 : 400,
              letterSpacing: '0.04em', cursor: 'pointer',
            }}>
              {c.label}
            </button>
          ))}
        </div>

        {/* Dish list */}
        <div className="tm-scroll" style={{ flex: 1, overflowY: 'auto', padding: '10px 16px 90px' }}>
          {cat === 'locaux' && (
            <div style={{ padding: '8px 4px 14px', borderBottom: `1px solid ${TARMAC.inkLine}`, marginBottom: 10 }}>
              <div className="tm-eyebrow" style={{ color: TARMAC.gold }}>Cuisine du Niari</div>
              <p className="tm-serif" style={{ fontSize: 13, color: TARMAC.paperMute, margin: '4px 0 0', fontStyle: 'italic', lineHeight: 1.4 }}>
                Produits du marché de Dolisie · pêche du jour à Pointe-Noire.
              </p>
            </div>
          )}
          {list.map((d) => {
            const q = cart[d.id] || 0;
            const avail = window.getDishAvailability ? window.getDishAvailability(d.id, 'cuisine') : { available: true, maxOrders: Infinity, missing: [] };
            const indispo = !avail.available;
            const lowStock = avail.available && avail.maxOrders <= 5 && avail.maxOrders !== Infinity;
            const maxReached = q >= avail.maxOrders;
            return (
              <div key={d.id} style={{
                display: 'flex', gap: 12, padding: '14px 0',
                borderBottom: `1px solid ${TARMAC.inkLineSoft}`,
                opacity: indispo ? 0.45 : 1,
                transition: 'opacity 200ms ease',
              }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3, flexWrap: 'wrap' }}>
                    {d.chef && <Pill color={TARMAC.gold}>★ Chef</Pill>}
                    {d.hot && <Pill color={TARMAC.brique}>● Pimenté</Pill>}
                    {indispo && (
                      <span style={{
                        fontFamily: TARMAC.mono, fontSize: 8, padding: '2px 6px',
                        letterSpacing: '0.08em', textTransform: 'uppercase',
                        background: TARMAC.brique, color: TARMAC.paper, fontWeight: 600,
                      }}>● Indisponible · revenez bientôt</span>
                    )}
                    {lowStock && (
                      <span style={{
                        fontFamily: TARMAC.mono, fontSize: 8, padding: '2px 6px',
                        letterSpacing: '0.08em', textTransform: 'uppercase',
                        border: `1px solid ${TARMAC.gold}`, color: TARMAC.gold,
                      }}>⚠ Reste {avail.maxOrders}</span>
                    )}
                  </div>
                  <h3 className="tm-serif" style={{ fontSize: 17, color: TARMAC.paper, margin: '2px 0', fontWeight: 500, lineHeight: 1.15 }}>
                    {d.n}
                  </h3>
                  <p style={{ fontSize: 11, color: TARMAC.paperFaint, margin: '4px 0 6px', lineHeight: 1.4 }}>
                    {d.d}
                  </p>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Price value={d.p} size={14} />
                    <span style={{ fontSize: 8, color: TARMAC.paperFaint, fontFamily: TARMAC.mono, letterSpacing: '0.08em' }}>
                      ⓘ {d.a.join(' · ')}
                    </span>
                  </div>
                </div>
                <DishImage src={d.image} name={d.n} category={d.cat} w={80} h={80} dim={indispo} />
                <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
                  {q > 0 ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4, border: `1px solid ${TARMAC.gold}` }}>
                      <button onClick={() => remove(d.id)} style={{ width: 26, height: 30, background: 'transparent', border: 'none', color: TARMAC.gold, cursor: 'pointer', fontSize: 14 }}>−</button>
                      <span className="tm-num" style={{ minWidth: 14, textAlign: 'center', color: TARMAC.gold, fontSize: 12 }}>{q}</span>
                      <button
                        onClick={() => { if (!maxReached && !indispo) add(d.id); }}
                        disabled={maxReached || indispo}
                        style={{
                          width: 26, height: 30,
                          background: (maxReached || indispo) ? 'rgba(201,146,26,0.2)' : TARMAC.gold,
                          border: 'none', color: (maxReached || indispo) ? TARMAC.paperFaint : TARMAC.ink,
                          cursor: (maxReached || indispo) ? 'not-allowed' : 'pointer',
                          fontSize: 14, fontWeight: 600,
                        }}>+</button>
                    </div>
                  ) : (
                    <button
                      onClick={() => { if (!indispo) add(d.id); }}
                      disabled={indispo}
                      style={{
                        width: 32, height: 32,
                        border: `1px solid ${indispo ? TARMAC.inkLine : TARMAC.gold}`,
                        background: 'transparent',
                        color: indispo ? TARMAC.paperFaint : TARMAC.gold,
                        cursor: indispo ? 'not-allowed' : 'pointer',
                        fontSize: 18, fontWeight: 500,
                      }}>+</button>
                  )}
                </div>
              </div>
            );
          })}
          {list.length === 0 && (
            <div style={{ padding: '40px 0', textAlign: 'center' }}>
              <div className="tm-serif" style={{ fontSize: 15, fontStyle: 'italic', color: TARMAC.paperFaint }}>
                Catégorie en préparation
              </div>
              <div style={{ fontSize: 10, color: TARMAC.paperFaint, fontFamily: TARMAC.mono, marginTop: 4, letterSpacing: '0.08em' }}>
                CONSULTEZ LES PLATS LOCAUX
              </div>
            </div>
          )}
        </div>

        {/* Sticky cart */}
        {count > 0 && (
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            padding: 12, background: TARMAC.inkDeep,
            borderTop: `1px solid ${TARMAC.gold}`,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              width: 36, height: 36, background: TARMAC.gold, color: TARMAC.ink,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: TARMAC.mono, fontWeight: 700, fontSize: 14,
            }}>{count}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 9, color: TARMAC.paperFaint, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Panier · Table {tableNum}</div>
              <Price value={total} size={16} />
            </div>
            <button onClick={() => { setOrdered(true); setTimeout(() => { setOrdered(false); setCart({}); }, 2000); }} style={{
              padding: '0 18px', height: 42, background: TARMAC.gold, color: TARMAC.ink,
              border: 'none', fontFamily: TARMAC.sans, fontWeight: 700, fontSize: 12,
              letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
            }}>Commander →</button>
          </div>
        )}

        {ordered && (
          <div style={{ position: 'absolute', inset: 0, background: 'rgba(10,10,10,0.92)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', zIndex: 50 }}>
            <div style={{ fontSize: 48, color: TARMAC.gold, lineHeight: 1 }}>✓</div>
            <div style={{ fontFamily: TARMAC.serif, fontSize: 24, color: TARMAC.gold, marginTop: 12 }}>Commande envoyée</div>
            <div style={{ fontFamily: TARMAC.mono, fontSize: 12, color: TARMAC.paperFaint, marginTop: 8, letterSpacing: '0.08em' }}>En préparation · Table {tableNum}</div>
          </div>
        )}
      </div>
    </Phone>
  );
}

window.MenuQR = MenuQR;
