// RIVA — Sections du site : la maison, les avis, nous trouver, commander, pied de page
const { useState: useState2, useEffect: useEffect2, useMemo: useMemo2 } = React;

// ====== L'HISTOIRE ======
function Story() {
  const { menu } = getEffectiveMenu();
  const cats = Object.values(menu);
  const nbPlats = cats.reduce((s, c) => s + c.items.length, 0);
  // Deux plats en vitrine : leurs photos si elles existent, sinon les vignettes
  const vitrine = useMemo2(() => {
    const signatures = menu.signature?.items || [];
    const autres = cats.flatMap(c => c.items).filter(i => i.badges?.includes('signature'));
    return [...signatures, ...autres].slice(0, 2);
  }, [menu]);

  return (
    <section id="histoire" className="feuillage py-20 md:py-28 bg-[var(--bg-2)] relative overflow-hidden">
      <div className="noise"/>
      <div className="relative max-w-[1400px] mx-auto px-5 md:px-8 grid lg:grid-cols-12 gap-10 items-center">
        <div className="lg:col-span-5 relative">
          <div className="grid grid-cols-2 gap-3">
            <PlatVisuel item={vitrine[0]} className="rounded-2xl aspect-[3/4] w-full"/>
            <PlatVisuel item={vitrine[1]} className="rounded-2xl aspect-[3/4] w-full mt-12"/>
          </div>
          <div className="absolute -bottom-4 -left-4 bg-[var(--vert)] text-[var(--bg)] p-4 rounded-2xl rotate-[-4deg] max-w-[180px]">
            <div className="font-display text-4xl leading-none">100%</div>
            <div className="text-[10px] uppercase tracking-wider mt-1 font-bold">Frais, fait minute</div>
          </div>
        </div>

        <div className="lg:col-span-7">
          <div className="kicker mb-4">La maison</div>
          <h2 className="font-display text-[2.6rem] sm:text-5xl md:text-7xl text-[var(--cream)] leading-[0.9]">
            Gua bao, sushis<br/>et <span className="text-[var(--jade-2)]">plats thaï.</span>
          </h2>
          <p className="mt-8 text-[var(--cream-2)] text-lg leading-relaxed max-w-2xl">
            Chez Bao Thaï, les rolls sont roulés à la commande et les plats thaï partent du wok à la minute. Le gua bao, petit pain vapeur garni, est la spécialité de la maison. <span className="text-[var(--vert)] font-semibold">Sur place, à emporter ou en livraison à Denain.</span>
          </p>
          <p className="mt-4 text-[var(--cream-2)]/70 leading-relaxed max-w-2xl">
            Sushis, makis, california, signatures roulées maison, poke bowls à composer, pad thaï, crousty, bo bun, bao burgers, formules et plateaux à partager : une carte large parce que chacun n'a pas envie de la même chose.
          </p>

          <div className="mt-10 grid grid-cols-2 sm:grid-cols-4 gap-6">
            {[
              { n: String(nbPlats), l: 'plats à la carte' },
              { n: String(cats.length), l: 'familles de plats' },
              { n: '6 j/7', l: 'midi et soir' },
              { n: '100%', l: 'frais' },
            ].map((s, i) => (
              <div key={i} className="border-l-2 border-[var(--vert)] pl-3">
                <div className="font-display text-3xl text-[var(--cream)]">{s.n}</div>
                <div className="text-[11px] uppercase tracking-wider text-[var(--muted)] mt-1">{s.l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ====== REVIEWS ======
function Reviews() {
  const [reviews, setReviews] = useState2([]);
  const [showForm, setShowForm] = useState2(false);
  const [showLocalForm, setShowLocalForm] = useState2(false);
  const [visible, setVisible] = useState2(6);
  // Les avis Google automatiques (Imad, 17/10/2026) : tant que le serveur
  // n'en a pas, la partie reste comme avant.
  const [google, setGoogle] = useState2(null);
  useEffect2(() => {
    fetch(urlServeur('/api/avis')).then(r => r.json())
      .then(d => { if (d && d.actif && d.avis && d.avis.length) setGoogle(d); })
      .catch(() => {});
  }, []);

  useEffect2(() => {
    let stored = [];
    try { stored = JSON.parse(localStorage.getItem('bt-reviews') || '[]'); } catch(e) {}
    setReviews([...stored, ...SEED_REVIEWS]);
  }, []);

  const addReview = (r) => {
    const newR = { ...r, id: 'r' + Date.now(), date: new Date().toISOString().slice(0,10), source: 'Site', verified: false };
    const userReviews = [newR, ...reviews.filter(x => !SEED_REVIEWS.find(s => s.id === x.id))];
    try { localStorage.setItem('bt-reviews', JSON.stringify(userReviews.slice(0, 20))); } catch(e) {}
    setReviews([newR, ...reviews]);
    setShowForm(false);
  };

  // Note affichée : on part de la vraie note Google renseignée dans config.js,
  // à laquelle s'ajoutent les avis postés sur le site. Tant que la note Google
  // n'est pas renseignée, on n'affiche AUCUNE note plutôt qu'une note inventée.
  const submittedReviews = reviews.filter(r => r.source === 'Site');
  const aNoteGoogle = typeof SHOP.googleRating === 'number' && typeof SHOP.googleReviews === 'number';
  const totalReviews = google && typeof google.total === 'number' ? google.total
    : (aNoteGoogle ? SHOP.googleReviews : 0) + submittedReviews.length;
  const totalScore = (aNoteGoogle ? SHOP.googleRating * SHOP.googleReviews : 0)
    + submittedReviews.reduce((s, r) => s + r.rating, 0);
  const avgRating = google && typeof google.note === 'number' ? google.note.toFixed(1).replace('.', ',')
    : totalReviews > 0 ? (totalScore / totalReviews).toFixed(1).replace('.', ',') : null;
  const lienTousLesAvis = (google && google.lien) || SHOP.mapsLink;
  const formatDate = (iso) => {
    try {
      const d = new Date(iso);
      const diff = Math.floor((Date.now() - d.getTime()) / 86400000);
      if (diff === 0) return 'Aujourd\'hui';
      if (diff === 1) return 'Hier';
      if (diff < 7) return `Il y a ${diff} jours`;
      if (diff < 30) return `Il y a ${Math.floor(diff/7)} sem.`;
      return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
    } catch (e) { return iso; }
  };

  return (
    <section className="py-20 md:py-28 bg-[var(--bg)]">
      <div className="max-w-[1400px] mx-auto px-5 md:px-8">
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-12">
          <div>
            <div className="kicker mb-4">Ce qu'on dit de nous</div>
            {avgRating ? (
              <>
                <h2 className="font-display text-5xl md:text-7xl text-[var(--cream)] flex items-baseline gap-4 flex-wrap">
                  <span className="text-[var(--vert)]">{avgRating}★</span>
                  <span className="text-3xl md:text-5xl text-[var(--cream-2)]">sur {totalReviews} avis</span>
                </h2>
                <div className="flex gap-1 text-[var(--vert)] mt-5">
                  {[...Array(5)].map((_, i) => <Icon.Star key={i} className={`w-6 h-6 ${i < Math.round(parseFloat(String(avgRating).replace(',', '.'))) ? '' : 'opacity-25'}`}/>)}
                </div>
                {google && <p className="text-[var(--muted)] text-sm mt-3">Note Google</p>}
              </>
            ) : (
              <>
                <h2 className="font-display text-5xl md:text-7xl text-[var(--cream)]">
                  Vous avez mangé ici ?<br/><span className="text-[var(--vert)]">Dites-le.</span>
                </h2>
                <p className="text-[var(--muted)] mt-4 max-w-md">
                  Un avis Google, c'est deux minutes, et c'est ce qui fait découvrir le restaurant aux gens du coin.
                </p>
              </>
            )}
          </div>
          <div className="flex flex-wrap gap-3 shrink-0">
            <a href={lienAvisGoogle()} target="_blank" rel="noopener noreferrer" className="btn btn-primary">
              <Icon.Star className="w-4 h-4"/> Les avis Google
            </a>
            <button onClick={() => setShowForm(true)} className="btn btn-ghost">
              Laisser un mot ici
            </button>
          </div>
        </div>

        {google && (
          <>
            <div className={`grid md:grid-cols-2 gap-4 ${google.avis.length >= 4 ? 'lg:grid-cols-4' : google.avis.length === 3 ? 'lg:grid-cols-3' : ''}`}>
              {google.avis.map((r, i) => (
                <div key={i} className="review-card flex flex-col">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex gap-0.5 text-[var(--vert)]">
                      {[...Array(5)].map((_, j) => <Icon.Star key={j} className={`w-4 h-4 ${j < r.note ? '' : 'opacity-20'}`}/>)}
                    </div>
                    <span className="pill !text-[10px] flex items-center gap-1">
                      {typeof GoogleG === 'function' && <GoogleG className="w-3 h-3"/>} Google
                    </span>
                  </div>
                  <p className="text-[var(--cream-2)] leading-relaxed flex-1">
                    {r.texte.length > 260 ? r.texte.slice(0, 250).replace(/\s+\S*$/, '') + '…' : r.texte}
                  </p>
                  <div className="mt-4 pt-4 border-t border-[var(--line)] flex items-center justify-between gap-2">
                    {r.profil
                      ? <a href={r.profil} target="_blank" rel="noopener noreferrer" className="font-semibold text-sm hover:underline">{r.nom}</a>
                      : <span className="font-semibold text-sm">{r.nom}</span>}
                    <span className="text-xs text-[var(--muted)] text-right">{r.quand}</span>
                  </div>
                </div>
              ))}
            </div>
            <p className="text-xs text-[var(--muted)] text-center mt-6">
              Sélection d'avis Google récents (4 et 5 étoiles, avec commentaire). Tous les avis sont sur Google.
            </p>
          </>
        )}

        {!google && reviews.length === 0 && (
          <div className="review-card text-center py-12">
            <Icon.Star className="w-10 h-10 text-[var(--vert)] mx-auto opacity-40"/>
            <p className="text-[var(--cream-2)] mt-4 max-w-md mx-auto leading-relaxed">
              Aucun avis affiché pour l'instant. Soyez le premier à donner le vôtre.
            </p>
          </div>
        )}

        {!google && <div className="grid md:grid-cols-3 gap-4">
          {reviews.slice(0, visible).map((r) => (
            <div key={r.id} className="review-card">
              <div className="flex items-center justify-between mb-3">
                <div className="flex gap-0.5 text-[var(--vert)]">
                  {[...Array(5)].map((_, j) => <Icon.Star key={j} className={`w-4 h-4 ${j < r.rating ? '' : 'opacity-20'}`}/>)}
                </div>
                <span className="pill !text-[10px]">{r.source}</span>
              </div>
              <p className="text-[var(--cream-2)] leading-relaxed">{r.text}</p>
              <div className="mt-4 pt-4 border-t border-[var(--line)] flex items-center justify-between">
                <span className="font-semibold text-sm flex items-center gap-1.5">
                  {r.name}
                  {r.verified && <span title="Avis vérifié"><Icon.Check className="w-3.5 h-3.5 text-[var(--jade)]"/></span>}
                </span>
                <span className="text-xs text-[var(--muted)]">{formatDate(r.date)}</span>
              </div>
            </div>
          ))}
        </div>}

        {/* Voir plus + lien Google */}
        <div className="mt-8 flex flex-col sm:flex-row items-center justify-center gap-3 flex-wrap">
          {!google && visible < reviews.length && (
            <button onClick={() => setVisible(v => Math.min(v + 6, reviews.length))}
                    className="btn btn-ghost">
              Voir plus d'avis ({reviews.length - visible} restants)
            </button>
          )}
          <a href={lienTousLesAvis} target="_blank" rel="noopener noreferrer"
             className="btn btn-primary">
            <Icon.Star className="w-4 h-4"/>
            {google && google.total ? `Voir les ${google.total} avis sur Google`
              : SHOP.googleReviews ? `Tous les ${SHOP.googleReviews} avis sur Google` : 'Voir les avis sur Google'}
          </a>
        </div>

        {showForm && (
          <ReviewChoice
            onClose={() => setShowForm(false)}
            onLocal={() => { setShowForm(false); setShowLocalForm(true); }}
          />
        )}
        {showLocalForm && <ReviewForm onSubmit={addReview} onClose={() => setShowLocalForm(false)}/>}
      </div>
    </section>
  );
}

function ReviewChoice({ onClose, onLocal }) {
  useEffect2(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);
  return (
    <div className="fixed inset-0 voile-fonce backdrop-blur-sm z-[200] flex items-center justify-center p-4" onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()}
           className="w-full max-w-[460px] bg-[var(--bg-2)] rounded-3xl border border-[var(--line)] overflow-hidden">
        <div className="px-6 py-5 border-b border-[var(--line)] flex items-center justify-between">
          <div>
            <div className="kicker">Avis</div>
            <h3 className="font-display text-3xl mt-1">Merci d'avance ! 🙏</h3>
          </div>
          <button onClick={onClose} className="w-10 h-10 rounded-full bg-[var(--bg)] flex items-center justify-center">
            <Icon.Close className="w-5 h-5"/>
          </button>
        </div>
        <div className="p-6">
          <p className="text-[var(--cream-2)] text-sm leading-relaxed mb-5">
            Tu peux partager ton avis directement sur Google. C'est ce qui aide le plus le resto :
            ton avis booste la visibilité Google Maps et permet à d'autres clients de nous découvrir.
          </p>

          <a href={`${SHOP.mapsLink}`} target="_blank" rel="noopener noreferrer"
             onClick={() => setTimeout(onClose, 400)}
             className="block w-full text-center py-4 rounded-2xl bg-[var(--vert)] text-[var(--bg)] font-bold uppercase tracking-wider text-sm hover:bg-[var(--vert-2)] transition-colors flex items-center justify-center gap-2">
            <svg viewBox="0 0 24 24" className="w-5 h-5" fill="currentColor">
              <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
              <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
              <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
              <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
            </svg>
            Écrire un avis sur Google
          </a>

          <div className="my-5 flex items-center gap-3">
            <div className="flex-1 h-px bg-[var(--line)]"/>
            <span className="text-[10px] uppercase tracking-wider text-[var(--muted)] font-bold">ou</span>
            <div className="flex-1 h-px bg-[var(--line)]"/>
          </div>

          <button onClick={onLocal}
                  className="block w-full text-center py-3 rounded-2xl border border-[var(--line)] text-[var(--cream-2)] hover:border-[var(--cream)]/30 text-sm">
            Poster un avis sur le site (visible ici seulement)
          </button>

          <p className="text-[10px] text-[var(--muted)] text-center mt-4 leading-relaxed">
            Les avis postés sur le site restent visibles ici mais ne comptent pas dans la note Google. Pour aider vraiment le resto, préfère Google 🙏
          </p>
        </div>
      </div>
    </div>
  );
}

function ReviewForm({ onSubmit, onClose }) {
  const [name, setName] = useState2('');
  const [rating, setRating] = useState2(5);
  const [hoverRating, setHoverRating] = useState2(0);
  const [text, setText] = useState2('');
  const [sent, setSent] = useState2(false);

  useEffect2(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  const submit = (e) => {
    e.preventDefault();
    if (!name.trim() || !text.trim()) return;
    setSent(true);
    setTimeout(() => {
      onSubmit({ name: name.trim(), rating, text: text.trim() });
    }, 1200);
  };

  return (
    <div className="fixed inset-0 voile-fonce backdrop-blur-sm z-[200] flex items-center justify-center p-4" onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()}
           className="w-full max-w-[480px] bg-[var(--bg-2)] rounded-3xl border border-[var(--line)] overflow-hidden">
        {sent ? (
          <div className="p-10 text-center">
            <div className="w-16 h-16 rounded-full bg-[var(--jade)]/15 border-2 border-[var(--jade)] mx-auto flex items-center justify-center mb-4">
              <Icon.Check className="w-8 h-8 text-[var(--jade)]"/>
            </div>
            <h3 className="font-display text-3xl">Merci !</h3>
            <p className="text-[var(--cream-2)] mt-2">Ton avis nous fait grave plaisir 🙏</p>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div className="px-6 py-5 border-b border-[var(--line)] flex items-center justify-between">
              <div>
                <div className="kicker">Avis</div>
                <h3 className="font-display text-3xl mt-1">Laisser un avis</h3>
              </div>
              <button type="button" onClick={onClose} className="w-10 h-10 rounded-full bg-[var(--bg)] flex items-center justify-center">
                <Icon.Close className="w-5 h-5"/>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="text-xs font-bold uppercase tracking-wider text-[var(--cream-2)] mb-2 block">Note</label>
                <div className="flex gap-1.5" onMouseLeave={() => setHoverRating(0)}>
                  {[1,2,3,4,5].map(n => (
                    <button key={n} type="button"
                            onMouseEnter={() => setHoverRating(n)}
                            onClick={() => setRating(n)}
                            className="text-3xl transition-transform hover:scale-110">
                      <Icon.Star className={`w-9 h-9 ${(hoverRating || rating) >= n ? 'text-[var(--vert)]' : 'text-[var(--line)]'}`}/>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="text-xs font-bold uppercase tracking-wider text-[var(--cream-2)] mb-1.5 block">Ton prénom *</label>
                <input value={name} onChange={(e) => setName(e.target.value)} required
                       placeholder="Sarah M."
                       className="w-full px-4 py-3 bg-[var(--bg)] border border-[var(--line)] rounded-xl focus:border-[var(--vert)] outline-none text-[var(--cream)]"/>
              </div>
              <div>
                <label className="text-xs font-bold uppercase tracking-wider text-[var(--cream-2)] mb-1.5 block">Ton avis *</label>
                <textarea value={text} onChange={(e) => setText(e.target.value)} required rows="4"
                          placeholder="Qu'est-ce que t'as kiffé ? Qu'est-ce qui pourrait être amélioré ?"
                          maxLength={400}
                          className="w-full px-4 py-3 bg-[var(--bg)] border border-[var(--line)] rounded-xl focus:border-[var(--vert)] outline-none text-[var(--cream)] resize-none"/>
                <div className="text-[10px] text-[var(--muted)] mt-1 text-right">{text.length}/400</div>
              </div>
            </div>
            <div className="px-6 py-4 border-t border-[var(--line)] flex items-center justify-between gap-3">
              <button type="button" onClick={onClose} className="btn btn-ghost !py-3 !px-5">Annuler</button>
              <button type="submit" disabled={!name.trim() || !text.trim()}
                      className="btn btn-primary !py-3 !px-6 disabled:opacity-40">
                Publier mon avis <Icon.ArrowRight className="w-4 h-4"/>
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

// ====== VISIT ======
function Visit() {
  return (
    /* Fond vert et blanc (28/11/2026) : la section devient une grande bande
       VERT LOGO, coupée au pinceau en haut et en bas ; les informations
       sont posées sur une carte blanche, le plan dans un cadre blanc. */
    <section id="visite" className="visite-verte feuillage py-24 md:py-32 relative overflow-hidden">
      <svg className="bord-pinceau haut" viewBox="0 0 1440 60" preserveAspectRatio="none" aria-hidden="true">
        <path fill="var(--bg)" d="M0 0H1440V20C1404 27 1372 17 1330 24C1282 33 1236 19 1180 27C1126 35 1084 22 1030 29C968 38 922 20 862 28C806 36 760 24 702 31C640 39 596 22 536 29C480 36 436 25 380 32C318 40 270 24 212 31C156 38 110 27 60 34C36 37 16 32 0 35Z"/>
        <path fill="var(--bg)" opacity=".55" d="M0 33C40 40 70 30 118 38C150 44 168 36 196 41L190 46C160 44 120 47 84 43C52 40 26 46 0 44Z"/>
        <path fill="var(--bg)" opacity=".55" d="M880 28C930 36 960 27 1010 33C1040 37 1064 31 1090 35L1084 40C1052 39 1012 42 978 38C944 34 910 40 884 38Z"/>
      </svg>
      <svg className="bord-pinceau bas" viewBox="0 0 1440 60" preserveAspectRatio="none" aria-hidden="true">
        <path fill="#0E0E0E" d="M0 0H1440V24C1398 31 1360 19 1316 27C1262 37 1220 21 1164 29C1110 37 1062 23 1006 30C946 38 904 21 846 29C790 37 744 25 686 32C628 39 580 23 522 30C466 37 420 26 362 33C304 40 258 25 198 32C142 39 96 28 48 35C28 38 12 34 0 36Z"/>
      </svg>
      <div className="max-w-[1400px] mx-auto px-5 md:px-8 grid lg:grid-cols-2 gap-6 lg:gap-8">
        <div className="visite-carte">
          <div className="kicker mb-4">Nous trouver</div>
          <h2 className="font-display text-5xl md:text-7xl text-[var(--cream)] leading-[0.9]">
            {/* Phrase demandée par Imad pour le patron (27/11/2026). Avant : « Poussez la porte. Ou commandez, on s'occupe du reste. » */}
            Goûtez<br/>et faites<br/><span className="text-[var(--vert)]">la différence.</span>
          </h2>

          <div className="mt-10 space-y-6">
            <InfoRow icon={Icon.MapPin} title="Adresse" lines={[SHOP.address]} link={SHOP.mapsLink}/>
            <div className="flex gap-4">
              <div className="info-icone w-10 h-10 rounded-full bg-[var(--vert)]/15 flex items-center justify-center shrink-0">
                <Icon.Clock className="w-4 h-4 text-[var(--vert)]"/>
              </div>
              <div className="flex-1">
                <div className="text-[10px] uppercase tracking-wider text-[var(--muted)] font-bold mb-1">Horaires</div>
                <HoursTable/>
              </div>
            </div>
            {SHOP.phone && <InfoRow icon={Icon.Phone} title="Téléphone" lines={[SHOP.phone]} link={`tel:${SHOP.phone.replace(/\s/g,'')}`}/>}
            {/* Réservations par téléphone seulement (Imad, 18/10/2026) : pas de réservation en ligne pour l'instant. */}
            {SHOP.phone && <InfoRow icon={Icon.Clock} title="Réservations" lines={[`Par téléphone : ${SHOP.phone}`]} link={`tel:${SHOP.phone.replace(/\s/g,'')}`}/>}
            <InfoRow icon={Icon.Insta} title="Instagram" lines={[SHOP.instagram]} link={`https://instagram.com/${SHOP.instagram.replace('@','')}`}/>
            {/* Les pseudos viennent de carte.js (avant : « @riva.denain » / « RIVA Denain » écrits en dur, restes de RIVA). */}
            {RESTO.tiktok && <InfoRow icon={Icon.TikTok} title="TikTok" lines={[RESTO.tiktokPseudo || 'TikTok']} link={RESTO.tiktok}/>}
            {RESTO.facebook && <InfoRow icon={Icon.Facebook} title="Facebook" lines={[RESTO.facebookNom || 'Facebook']} link={RESTO.facebook}/>}
          </div>

          <div className="mt-10 flex flex-wrap gap-3">
            <a href={`https://www.google.com/maps/dir/?api=1&destination=${SHOP.mapsQuery}`}
               target="_blank" rel="noopener noreferrer" className="btn btn-primary">
              <Icon.MapPin className="w-4 h-4"/> Itinéraire Google Maps
            </a>
            {SHOP.phone && (
              <a href={`tel:${SHOP.phone.replace(/\s/g,'')}`} className="btn btn-ghost">
                <Icon.Phone className="w-4 h-4"/> Appeler
              </a>
            )}
          </div>
        </div>

        <div className="visite-plan relative rounded-3xl overflow-hidden border border-[var(--line)] aspect-[4/5] lg:aspect-auto lg:min-h-[560px] bg-[var(--bg-3)]">
          {/* Le plan était retourné en négatif pour l'ancien fond noir. Sur fond
              clair on le laisse tel quel, juste un peu désaturé pour qu'il ne
              concurrence pas le vert de la maison. */}
          <iframe
            title="Localisation Bao Thaï Denain"
            src={`https://maps.google.com/maps?q=${SHOP.mapsQuery}&t=&z=16&ie=UTF8&iwloc=&output=embed`}
            className="absolute inset-0 w-full h-full"
            style={{ border: 0, colorScheme: 'light', filter: 'saturate(0.72) contrast(1.02)' }}
            loading="lazy"
            referrerPolicy="no-referrer-when-downgrade"
            allowFullScreen
          />
          <div className="absolute bottom-4 left-4 right-4 rounded-xl p-4 border border-[var(--line)] z-10 pointer-events-auto shadow-lg"
               style={{ background: '#FFFFFF' }}>
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="font-semibold text-sm text-[var(--cream)]">{SHOP.address}</div>
                <div className="text-xs text-[var(--muted)] mt-0.5">{SHOP.tagline}</div>
              </div>
              <a href={`https://www.google.com/maps/dir/?api=1&destination=${SHOP.mapsQuery}`}
                 target="_blank" rel="noopener noreferrer"
                 className="text-[var(--vert)] text-xs font-bold uppercase shrink-0">Itinéraire →</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HoursTable() {
  const today = (new Date().getDay() + 6) % 7;
  return (
    <ul className="space-y-0.5 text-sm">
      {SHOP.hours.map((h, i) => (
        <li key={i} className={`flex justify-between py-1 ${i === today ? 'text-[var(--vert)] font-semibold' : 'text-[var(--cream-2)]'}`}>
          <span className="flex items-center gap-2">
            {h.day}
            {i === today && <span className="text-[9px] uppercase tracking-wider bg-[var(--vert)] text-white px-1.5 py-0.5 rounded">Aujourd'hui</span>}
          </span>
          <span className={h.closed ? 'text-[var(--rouge-2)]' : ''}>{h.slots}</span>
        </li>
      ))}
    </ul>
  );
}

function InfoRow({ icon: I, title, lines, link }) {
  const inner = (
    <div className="flex gap-4">
      <div className="info-icone w-10 h-10 rounded-full bg-[var(--vert)]/15 flex items-center justify-center shrink-0">
        <I className="w-4 h-4 text-[var(--vert)]"/>
      </div>
      <div>
        <div className="text-[10px] uppercase tracking-wider text-[var(--muted)] font-bold">{title}</div>
        {lines.map((l, i) => <div key={i} className="text-[var(--cream)] text-base">{l}</div>)}
      </div>
    </div>
  );
  return link ? <a href={link} className="block hover:opacity-80 transition-opacity">{inner}</a> : inner;
}

// ====== COMMANDER ======
// Un seul bouton. Trois gros pavés qui menaient tous au même panier, ça
// oblige à choisir avant même d'avoir vu la carte — et « sur place » n'est
// pas un choix : on y arrive en scannant le QR de sa table, pas autrement.
// Le mode se choisit à la fin, au moment d'envoyer, quand il veut dire
// quelque chose.
function CommanderSection({ openCart, openPhone, openMenu, table, cartCount }) {
  const livraison = SHOP.delivery.active !== false;
  const plein = cartCount > 0;
  return (
    <section id="commander" className="feuillage feuillage-hg py-14 md:py-20 bg-[var(--bg)]">
      <div className="max-w-[1400px] mx-auto px-5 md:px-8">
        <div className="kicker mb-3">Commander</div>
        <h2 className="font-display text-4xl md:text-6xl text-[var(--cream)] max-w-3xl">
          {table ? `Vous êtes à la table ${table}.` : 'Composez, envoyez.'}{' '}
          <span className="text-[var(--vert)]">C’est tout.</span>
        </h2>
        <p className="text-[var(--muted)] mt-3 max-w-2xl">
          {table
            ? 'Votre commande part directement en cuisine avec votre numéro de table.'
            : `Vous choisissez à emporter${livraison ? ' ou en livraison' : ''} au moment d’envoyer. Sur place, il suffit de scanner le QR code posé sur la table.`}
        </p>

        <div className="mt-7 flex flex-wrap items-center gap-3">
          <button onClick={plein ? openCart : openMenu} className="btn btn-primary">
            {plein ? `Voir ma commande · ${cartCount} article${cartCount > 1 ? 's' : ''}` : 'Voir la carte'}
            <Icon.ArrowRight className="w-4 h-4"/>
          </button>
          {SHOP.phone && (
            <button onClick={openPhone} className="btn btn-ghost">
              <Icon.Phone className="w-3.5 h-3.5"/> Appeler le restaurant
            </button>
          )}
        </div>

        <div className="mt-7 flex flex-wrap gap-x-8 gap-y-2 text-sm text-[var(--muted)]">
          <span><Icon.Bag className="w-4 h-4 inline-block mr-1.5 -mt-0.5 text-[var(--vert)]"/>À emporter · prêt en {SHOP.pickup.time}</span>
          {livraison && (
            <span><Icon.Truck className="w-4 h-4 inline-block mr-1.5 -mt-0.5 text-[var(--vert)]"/>Livraison · {SHOP.delivery.time}, minimum de commande {SHOP.delivery.minOrder}€{SHOP.delivery.minOrderAutres ? ` ${SHOP.delivery.texteProche}, ${SHOP.delivery.minOrderAutres}€ au-delà` : ''}</span>
          )}
          <span><Icon.Store className="w-4 h-4 inline-block mr-1.5 -mt-0.5 text-[var(--vert)]"/>Sur place · en scannant le QR de votre table</span>
        </div>
      </div>
    </section>
  );
}

// ====== EN CE MOMENT ======
// Remplace « Commander », « La maison » et les avis (Imad, 24/10/2026) :
// un seul bloc court et utile — ouvert ou fermé à l'instant, d'après les
// horaires de carte.js, et les trois façons de commander.
function creneauxDuJour(i) {
  const h = RESTO.horaires[i];
  if (!h || h.ferme) return [];
  return (h.h.match(/\d{1,2}h\d{2}\s*–\s*\d{1,2}h\d{2}/g) || []).map(s => {
    const [a, b] = s.split('–').map(x => { const [hh, mm] = x.trim().split('h'); return +hh * 60 + +mm; });
    return { debut: a, fin: b };
  });
}
function heureTexte(m) { return Math.floor(m / 60) + 'h' + String(m % 60).padStart(2, '0'); }
function etatMaintenant() {
  const d = new Date();
  const jour = (d.getDay() + 6) % 7;
  const min = d.getHours() * 60 + d.getMinutes();
  const ouvert = creneauxDuJour(jour).find(c => min >= c.debut && min < c.fin);
  if (ouvert) return { ouvert: true, texte: `Ouvert jusqu’à ${heureTexte(ouvert.fin)}` };
  for (let k = 0; k < 8; k++) {
    const j = (jour + k) % 7;
    const c = creneauxDuJour(j).find(c => k > 0 || c.debut > min);
    if (c) {
      const quand = k === 0 ? 'aujourd’hui' : k === 1 ? 'demain' : RESTO.horaires[j].j.toLowerCase();
      return { ouvert: false, texte: `Fermé · ouvre ${quand} à ${heureTexte(c.debut)}` };
    }
  }
  return { ouvert: false, texte: 'Fermé' };
}

function EnCeMoment({ openCart, openMenu, table, cartCount }) {
  const [etat, setEtat] = useState2(etatMaintenant);
  React.useEffect(() => { const t = setInterval(() => setEtat(etatMaintenant()), 60000); return () => clearInterval(t); }, []);
  const liv = SHOP.delivery;
  const livraison = liv.active !== false;
  const plein = cartCount > 0;
  const euros = n => Number(n).toFixed(2).replace('.', ',').replace(',00', '') + ' €';
  const modes = [
    { icon: Icon.Bag, titre: 'À emporter', texte: `Prêt en ${SHOP.pickup.time}` },
    livraison && { icon: Icon.Truck, titre: 'Livraison', texte: `${liv.time} · dès ${euros(liv.minOrder)}${liv.minOrderAutres ? ` ${liv.texteProche} (${euros(liv.minOrderAutres)} au-delà)` : ''}${!Number(liv.fee) ? ' · livraison offerte' : liv.freeAbove ? ` · offerte dès ${euros(liv.freeAbove)}` : ''}` },
    { icon: Icon.Store, titre: 'Sur place', texte: 'Scannez le QR de votre table' },
  ].filter(Boolean);
  return (
    <section id="commander" className="py-12 md:py-16 bg-[var(--bg)]">
      <div className="max-w-[1100px] mx-auto px-5 md:px-8">
        <div className={`ce-moment-carte ${etat.ouvert ? "est-ouvert" : "est-ferme"} rounded-3xl bg-[var(--bg-2)] border border-[var(--line)] p-6 md:p-9`}>
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <span className="relative flex w-3 h-3">
                {etat.ouvert && <span className="absolute inset-0 rounded-full bg-[var(--logo-vert)] animate-ping opacity-60"/>}
                <span className={`relative w-3 h-3 rounded-full ${etat.ouvert ? 'bg-[var(--logo-vert)]' : 'bg-[#A61B1B]'}`}/>
              </span>
              <span className="font-display text-2xl md:text-3xl text-[var(--cream)]">{etat.texte}</span>
            </div>
            <button onClick={plein ? openCart : openMenu} className="btn btn-primary">
              {plein ? `Voir ma commande · ${cartCount}` : (table ? `Commander · table ${table}` : 'Voir la carte')}
              <Icon.ArrowRight className="w-4 h-4"/>
            </button>
          </div>
          <div className={`mt-6 grid gap-3 ${modes.length === 3 ? 'sm:grid-cols-3' : 'sm:grid-cols-2'}`}>
            {modes.map(m => (
              <div key={m.titre} className="ce-moment-mode flex items-center gap-3 rounded-2xl bg-[var(--bg)] border border-[var(--line)] px-4 py-3">
                <div className="ce-moment-icone w-10 h-10 rounded-full bg-[var(--vert)]/10 flex items-center justify-center shrink-0">
                  <m.icon className="w-4 h-4 text-[var(--vert)]"/>
                </div>
                <div>
                  <div className="font-semibold text-sm text-[var(--cream)]">{m.titre}</div>
                  <div className="text-xs text-[var(--muted)]">{m.texte}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ====== FOOTER ======
function Footer() {
  const [credits, setCredits] = useState2(false);
  const [legal, setLegal] = useState2(null);
  return (
    <footer className="pied-noir bg-[var(--bg-2)] text-[var(--cream)] border-t border-[var(--line)] pt-16 pb-8">
      <div className="max-w-[1400px] mx-auto px-5 md:px-8">
        <div className="grid md:grid-cols-12 gap-8">
          <div className="md:col-span-5">
            {/* Le logo est fait pour un fond blanc : sur le pied noir, on le pose dans un carré blanc (Imad, 24/10/2026). */}
            <div className="inline-block rounded-2xl p-4" style={{ background: '#FFFFFF' }}>
              <Logo size={150} empile/>
            </div>
            <p className="mt-4 text-[var(--cream-2)] max-w-xs leading-relaxed">
              {SHOP.tagline} — gua bao, sushis, plats thaï et poke bowls préparés à la commande, à Denain. 100 % frais.
            </p>
            <div className="mt-6 flex gap-2 flex-wrap">
              {SHOP.whatsappConfigured && (
                <a href={`https://wa.me/${SHOP.whatsapp}`} target="_blank" rel="noopener" className="btn btn-whatsapp !py-2 !px-4 !text-xs">
                  <Icon.WhatsApp className="w-4 h-4"/> WhatsApp
                </a>
              )}
              <a href={`https://instagram.com/${SHOP.instagram.replace('@','')}`} target="_blank" rel="noopener" className="btn btn-ghost !py-2 !px-4 !text-xs">
                <Icon.Insta className="w-4 h-4"/> Instagram
              </a>
              {RESTO.tiktok && (
                <a href={RESTO.tiktok} target="_blank" rel="noopener" className="btn btn-ghost !py-2 !px-4 !text-xs">
                  <Icon.TikTok className="w-4 h-4"/> TikTok
                </a>
              )}
              {RESTO.facebook && (
                <a href={RESTO.facebook} target="_blank" rel="noopener" className="btn btn-ghost !py-2 !px-4 !text-xs">
                  <Icon.Facebook className="w-4 h-4"/> Facebook
                </a>
              )}
            </div>
          </div>

          <div className="md:col-span-2">
            <div className="text-[10px] uppercase tracking-wider text-[var(--vert)] font-bold mb-3">Navigation</div>
            <ul className="space-y-2 text-sm">
              <li><a href="#menu" className="hover:text-[var(--vert)]">Menu</a></li>
              <li><a href="#commander" className="hover:text-[var(--vert)]">Commander</a></li>
              <li><a href="#visite" className="hover:text-[var(--vert)]">Nous trouver</a></li>
            </ul>
          </div>

          <div className="md:col-span-2">
            <div className="text-[10px] uppercase tracking-wider text-[var(--vert)] font-bold mb-3">Contact</div>
            <ul className="space-y-2 text-sm text-[var(--cream-2)]">
              <li>{SHOP.address}</li>
              {SHOP.phone && <li><a href={`tel:${SHOP.phone.replace(/\s/g,'')}`} className="hover:text-[var(--vert)]">{SHOP.phone}</a></li>}
              <li>{SHOP.instagram}</li>
            </ul>
          </div>

          <div className="md:col-span-3">
            <div className="text-[10px] uppercase tracking-wider text-[var(--vert)] font-bold mb-3">Newsletter</div>
            <p className="text-sm text-[var(--cream-2)]/80 mb-3">L’inscription à la newsletter n’est pas encore disponible.</p>
          </div>
        </div>

        <div className="mt-14 pt-6 border-t border-[var(--line)] flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
          <div className="text-xs text-[var(--muted)]">
            © {new Date().getFullYear()} {SHOP.name} — {SHOP.address}
          </div>
          <div className="flex flex-wrap gap-x-4 gap-y-2 text-xs text-[var(--muted)]">
            {typeof PAGES_LEGALES !== 'undefined' && PAGES_LEGALES.map(p => (
              <button key={p.cle} onClick={() => setLegal(p.cle)} className="hover:text-[var(--cream)]">{p.titre}</button>
            ))}
            {typeof CREDITS_PHOTOS !== 'undefined' && CREDITS_PHOTOS.length > 0 && (
              <button onClick={() => setCredits(true)} className="hover:text-[var(--cream)]">Crédits photos</button>
            )}
          </div>
        </div>
      </div>
      {credits && <CreditsPhotos onClose={() => setCredits(false)}/>}
      {legal && typeof PageLegale !== 'undefined' && <PageLegale page={legal} onChange={setLegal} onClose={() => setLegal(null)}/>}
    </footer>
  );
}

// ====== CRÉDITS PHOTOS ======
// Les licences Creative Commons des photos d'illustration obligent à citer
// l'auteur : la liste vit dans credits-photos.js.
function CreditsPhotos({ onClose }) {
  return (
    <div className="fixed inset-0 z-[200] voile-fonce backdrop-blur-sm flex items-center justify-center p-5" onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()}
           className="bg-[var(--bg-2)] border border-[var(--line)] rounded-3xl p-6 max-w-[640px] w-full max-h-[80vh] overflow-y-auto relative">
        <button onClick={onClose} aria-label="Fermer"
                className="absolute top-3 right-3 w-9 h-9 rounded-full bg-[var(--bg)] flex items-center justify-center hover:bg-[var(--bg-3)]">
          <Icon.Close className="w-4 h-4"/>
        </button>
        <h3 className="font-display text-2xl text-[var(--cream)]">Crédits photos</h3>
        <p className="mt-2 text-xs text-[var(--muted)]">Photos d'illustration, non contractuelles, publiées sous licence Creative Commons.</p>
        <ul className="mt-4 space-y-2 text-xs text-[var(--cream-2)]">
          {CREDITS_PHOTOS.map(c => (
            <li key={c.photo}>
              <a href={c.source} target="_blank" rel="noopener" className="underline hover:text-[var(--cream)]">{c.titre}</a>
              {' — '}{c.auteur}{' — '}
              <a href={c.licence_url} target="_blank" rel="noopener" className="underline hover:text-[var(--cream)]">{c.licence}</a>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Object.assign(window, { Story, Reviews, ReviewChoice, ReviewForm, Visit, HoursTable, InfoRow, CommanderSection, EnCeMoment, Footer });
