// Bom Pain — Sections components
// Depends on globals: React, Illus, BPData

const { useState, useEffect, useRef } = React;

// Hook: reveal-on-scroll for any element
function useReveal(threshold = 0.18) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            // also draw any pencil illustrations within
            e.target.querySelectorAll(".bp-illus").forEach((s) => s.classList.add("bp-drawn"));
          }
        });
      },
      { threshold: 0.05, rootMargin: "0px 0px -8% 0px" }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [threshold]);
  return ref;
}

// Reveal wrapper
function Reveal({ children, className = "", delay = 0, ...rest }) {
  const ref = useReveal();
  return (
    <div ref={ref} className={`reveal ${className}`} style={{ transitionDelay: `${delay}ms` }} {...rest}>
      {children}
    </div>
  );
}

// ─── Decorative SVG icons ─────────────────────────────────────────────────────
function DecoCookie({ style, className = "" }) {
  return (
    <svg viewBox="0 0 36 36" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" style={style} className={`deco ${className}`} aria-hidden="true">
      <circle cx="18" cy="18" r="13" />
      <circle cx="14" cy="13" r="2" fill="currentColor" stroke="none" />
      <circle cx="23" cy="16" r="2" fill="currentColor" stroke="none" />
      <circle cx="15" cy="23" r="2" fill="currentColor" stroke="none" />
      <path d="M22 23 Q24 21 22 19" strokeWidth="0.9" opacity="0.5" />
    </svg>
  );
}
function DecoLeaf({ style, className = "" }) {
  return (
    <svg viewBox="0 0 28 42" fill="none" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round" style={style} className={`deco ${className}`} aria-hidden="true">
      <path d="M14 40 Q1 25 5 10 Q9 1 14 1 Q19 1 23 10 Q27 25 14 40z" />
      <path d="M14 40 L14 8" strokeWidth="0.8" opacity="0.55" />
      <path d="M14 24 Q9 17 7 12" strokeWidth="0.7" opacity="0.45" />
      <path d="M14 24 Q19 17 21 12" strokeWidth="0.7" opacity="0.45" />
    </svg>
  );
}
function DecoCroissant({ style, className = "" }) {
  return (
    <svg viewBox="0 0 54 34" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" style={style} className={`deco ${className}`} aria-hidden="true">
      <path d="M8 28 Q1 14 10 6 Q26 0 44 6 Q53 14 46 28 Q36 34 27 31 Q18 34 8 28z" />
      <path d="M17 8 Q27 4 37 8" strokeWidth="0.9" opacity="0.5" />
      <path d="M11 21 Q22 27 34 23" strokeWidth="0.9" opacity="0.5" />
    </svg>
  );
}
function DecoStar({ style, className = "" }) {
  return (
    <svg viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round" style={style} className={`deco ${className}`} aria-hidden="true">
      <path d="M14 2 v8 M14 18 v8 M2 14 h8 M18 14 h8" />
      <path d="M5.5 5.5 l4.5 4.5 M17.5 17.5 l4.5 4.5 M22.5 5.5 l-4.5 4.5 M10.5 17.5 l-4.5 4.5" strokeWidth="0.9" opacity="0.7" />
    </svg>
  );
}
function DecoDots({ style, className = "" }) {
  return (
    <svg viewBox="0 0 52 16" fill="currentColor" style={style} className={`deco ${className}`} aria-hidden="true">
      <circle cx="6"  cy="8" r="3.5" opacity="0.45" />
      <circle cx="26" cy="8" r="3.5" opacity="0.65" />
      <circle cx="46" cy="8" r="3.5" opacity="0.45" />
    </svg>
  );
}
function DecoCup({ style, className = "" }) {
  return (
    <svg viewBox="0 0 42 46" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" style={style} className={`deco ${className}`} aria-hidden="true">
      <path d="M7 17 h28 l-3.5 19 H10.5z" />
      <path d="M31 23 h5 a4.5 4.5 0 0 1 0 9 h-5" />
      <path d="M4 36 h34" />
      <path d="M14 13 Q15.5 8 14 4" opacity="0.5" />
      <path d="M21 12 Q22.5 7 21 3" opacity="0.5" />
      <path d="M28 13 Q29.5 8 28 4" opacity="0.5" />
    </svg>
  );
}

// ============= NAV =============
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <a href="#" className="nav-brand">
        <Illus.Logo style={{ width: 50, height: 50 }} />
      </a>
      <div className="nav-links">
        <a href="#about">Historia</a>
        <a href="#menu">Menú</a>
        <a href="#gallery">Galería</a>
        <a href="#baby-shower">Eventos</a>
        <a href="#reserve">Reservas</a>
        <a href="#location">Visitanos</a>
      </div>
      <div className="nav-actions">
        <a href={BPData.contact.instagramUrl} target="_blank" rel="noopener noreferrer" className="nav-icon-btn" aria-label="Instagram">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" width="18" height="18">
            <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
            <circle cx="12" cy="12" r="4.5"/>
            <circle cx="17.5" cy="6.5" r="1.2" fill="currentColor" stroke="none"/>
          </svg>
        </a>
        <a href={BPData.contact.whatsappUrl} target="_blank" rel="noopener noreferrer" className="nav-icon-btn nav-wa-btn" aria-label="WhatsApp">
          <svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
          </svg>
        </a>
        <a href="#reserve" className="nav-cta">Reservar</a>
      </div>
    </nav>
  );
}

// ============= FLOATING WHATSAPP =============
function FloatingWhatsApp() {
  return (
    <a href={BPData.contact.whatsappUrl} target="_blank" rel="noopener noreferrer"
       className="floating-wa" aria-label="Escribinos por WhatsApp">
      <svg viewBox="0 0 24 24" fill="white" width="28" height="28">
        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
      </svg>
      <span className="floating-wa-label">WhatsApp</span>
    </a>
  );
}

// ============= HERO =============
function Hero({ variant = "a" }) {
  const ref = useReveal(0.05);
  useEffect(() => {
    if (ref.current) {
      ref.current.querySelectorAll(".bp-illus").forEach((s) => s.classList.add("bp-drawn"));
      ref.current.classList.add("in");
    }
  }, []);

  return (
    <section ref={ref} className="hero hero-photo-bg reveal">
      <div className="hero-bg-img">
        <img src="bompain-hero.jpg" alt="Bom Pain Café" className="hero-photo" loading="eager" />
      </div>
      <div className="hero-bg-overlay" />

      <div className="hero-content-wrap container">
        <div className="hero-eyebrow">
          <span className="line" style={{ background: "rgba(245,239,228,0.45)" }}></span>
          <span className="eyebrow" style={{ color: "var(--paper-edge)" }}>Boulangerie · Café · Ñemby</span>
        </div>
        <h1 style={{ color: "var(--cream)" }}>
          Bom Pain.
          <span className="script-line" style={{ color: "var(--paper-edge)" }}>El arte del café.</span>
        </h1>
        <p className="hero-lede" style={{ color: "rgba(245,239,228,0.85)" }}>
          Café artesanal, panadería fresca y los sabores de siempre.
        </p>
        <div className="hero-cta">
          <a href="#reserve" className="btn-primary">
            Reservar mesa <span className="btn-arrow">→</span>
          </a>
          <a href="#menu" className="btn-ghost btn-ghost-light">
            Ver el menú <span className="btn-arrow">→</span>
          </a>
        </div>
      </div>

      <div className="hero-marquee">
        <div className="hero-marquee-inner">
          {[...BPData.marquee, ...BPData.marquee].map((s, i) => (
            <span key={i}>
              {s}
              <span className="dot"></span>
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============= ABOUT =============
function About() {
  return (
    <section id="about" className="section section-paper">
      <DecoCookie style={{ width: 68, top: "8%", right: "5%", transform: "rotate(18deg)" }} className="deco-float deco-delay1" />
      <DecoLeaf  style={{ width: 50, bottom: "10%", left: "2.5%", transform: "rotate(-14deg)" }} className="deco-sway deco-delay2" />
      <DecoStar  style={{ width: 26, top: "52%", right: "9%" }} className="deco-pulse deco-delay3" />
      <div className="container">
        <div className="about-grid">
          <Reveal>
            <div className="about-image">
              <img
                src="about-cafe.jpg"
                alt="Café con croissants en Bom Pain"
                style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center", display: "block" }}
                loading="lazy"
              />
            </div>
          </Reveal>
          <Reveal delay={150}>
            <div className="about-text">
              <span className="eyebrow">Nuestra historia</span>
              <h2 style={{ marginTop: 18 }}>
                Donde el café
                <span className="script">— te espera cada mañana</span>
              </h2>
              <p>
                Abrimos en 2023 con una idea simple: un lugar donde el café sea de verdad,
                el almuerzo sepa a casa y siempre haya algo rico en la vitrina. Somos un café
                de barrio con alma — atendido por sus dueños, para los de siempre y para quien
                nos descubra.
              </p>
              <div className="about-stats">
                <div className="about-stat">
                  <span className="num">03</span>
                  <span className="label">Años con vos</span>
                </div>
                <div className="about-stat">
                  <span className="num">7am</span>
                  <span className="label">Abrimos cada día</span>
                </div>
                <div className="about-stat">
                  <span className="num">∞</span>
                  <span className="label">Razones para volver</span>
                </div>
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// ============= SUBCAT ICON =============
// k = icon key stored in Notion's Icono field (e.g. 'croissant', 'cafe', 'desayuno')
function SubcatIcon({ k = '', size = 20 }) {
  const key = (k || '').toLowerCase().trim();
  const p = { fill: "none", stroke: "currentColor", strokeWidth: "1.3", strokeLinecap: "round", strokeLinejoin: "round" };
  const box = "0 0 32 32";
  const s = { width: size, height: size, flexShrink: 0, display: "block" };

  if (key === 'croissant') return (
    <svg viewBox="0 0 48 28" style={{ ...s, width: size * 1.7 }} {...p}>
      <path d="M7 22 Q2 12 9 6 Q24 1 38 6 Q46 13 40 22 Q30 28 24 25 Q17 28 7 22z"/>
      <path d="M14 8 Q24 5 32 8" strokeWidth="1" opacity="0.5"/>
      <path d="M9 18 Q18 24 29 20" strokeWidth="1" opacity="0.5"/>
    </svg>
  );
  if (key === 'medialuna') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M20 6 a11 11 0 1 0 0 20 a8 8 0 1 1 0 -20z"/>
    </svg>
  );
  if (key === 'mbeju') return (
    <svg viewBox={box} style={s} {...p}>
      <ellipse cx="16" cy="16" rx="12" ry="8"/>
      <path d="M7 13 Q16 11 25 13" strokeWidth="1" opacity="0.5"/>
      <path d="M6 16 Q16 19 26 16" strokeWidth="1" opacity="0.5"/>
    </svg>
  );
  if (key === 'especial') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M5 23 L7 13 L13 19 L16 8 L19 19 L25 13 L27 23z"/>
      <line x1="5" y1="26" x2="27" y2="26"/>
      <circle cx="16" cy="8" r="1.8" fill="currentColor" stroke="none"/>
      <circle cx="7" cy="13" r="1.4" fill="currentColor" stroke="none"/>
      <circle cx="25" cy="13" r="1.4" fill="currentColor" stroke="none"/>
    </svg>
  );
  if (key === 'desayuno') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M8 21 Q5 15 9 10 Q12 7 16 8 Q20 7 23 10 Q27 15 24 21 Q21 25 16 25 Q11 25 8 21z"/>
      <circle cx="16" cy="17" r="4.5"/>
    </svg>
  );
  if (key === 'cafe') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M7 14 h18 l-2.5 12 H9.5z"/>
      <path d="M23 17.5 h4 a3.5 3.5 0 0 1 0 7 h-4"/>
      <line x1="5" y1="27" x2="27" y2="27"/>
      <path d="M12 10 Q13.5 7 12 4" opacity="0.55"/>
      <path d="M17 9 Q18.5 6 17 3" opacity="0.55"/>
      <path d="M22 10 Q23.5 7 22 4" opacity="0.55"/>
    </svg>
  );
  if (key === 'frappe') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M9 12 h14 l-2 14 H11z"/>
      <path d="M8 12 Q9 7 16 7 Q23 7 24 12"/>
      <line x1="16" y1="3" x2="16" y2="12"/>
      <line x1="6" y1="27" x2="26" y2="27"/>
    </svg>
  );
  if (key === 'milkshake') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M8 15 h16 l-2 11 H10z"/>
      <path d="M7 15 Q8 9 16 9 Q24 9 25 15"/>
      <line x1="16" y1="4" x2="16" y2="9"/>
      <line x1="13" y1="4" x2="19" y2="4"/>
      <line x1="6" y1="27" x2="26" y2="27"/>
    </svg>
  );
  if (key === 'sandwich') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M5 8 Q5 6 16 6 Q27 6 27 8 l-1 3 H6z"/>
      <rect x="5" y="13" width="22" height="3" rx="0.5"/>
      <rect x="5" y="18" width="22" height="2" rx="0.5" opacity="0.55"/>
      <path d="M5 23 h22 Q27 26 16 26 Q5 26 5 23z"/>
    </svg>
  );
  if (key === 'horno') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M7 22 Q16 6 25 22z"/>
      <line x1="5" y1="26" x2="27" y2="26"/>
      <circle cx="13" cy="18" r="1.2" fill="currentColor" stroke="none" opacity="0.7"/>
      <circle cx="19" cy="18" r="1.2" fill="currentColor" stroke="none" opacity="0.7"/>
    </svg>
  );
  if (key === 'empanada') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M6 20 Q6 8 16 8 Q26 8 26 20 Q16 27 6 20z"/>
      <path d="M8.5 18 Q16 11 23.5 18" strokeWidth="1" opacity="0.5"/>
    </svg>
  );
  if (key === 'minuta') return (
    <svg viewBox={box} style={s} {...p}>
      <circle cx="14" cy="17" r="10"/>
      <line x1="26" y1="6" x2="26" y2="28"/>
      <path d="M23 6 Q23 11 26 11"/>
      <path d="M29 6 Q29 11 26 11"/>
    </svg>
  );
  if (key === 'hamburguesa') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M6 13 Q6 8 16 8 Q26 8 26 13"/>
      <rect x="5" y="13" width="22" height="3.5" rx="0.5"/>
      <rect x="5" y="19" width="22" height="3.5" rx="0.5"/>
      <path d="M5 22.5 Q5 27 16 27 Q27 27 27 22.5"/>
      <line x1="9" y1="16.5" x2="23" y2="16.5" strokeWidth="0.9" opacity="0.5"/>
    </svg>
  );
  if (key === 'postre') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M7 26 L16 7 L25 26z"/>
      <line x1="5" y1="26" x2="27" y2="26"/>
      <line x1="11" y1="19" x2="21" y2="19" strokeWidth="1" opacity="0.5"/>
      <circle cx="16" cy="5" r="1.8"/>
    </svg>
  );
  if (key === 'helado') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M10 18 Q10 8 16 8 Q22 8 22 18z"/>
      <path d="M10 18 Q13 24 16 29 Q19 24 22 18"/>
      <path d="M12 13 Q16 11 20 13" strokeWidth="1" opacity="0.5"/>
    </svg>
  );
  if (key === 'jarra') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M9 8 h12 l-2 17 H11z"/>
      <path d="M21 12 Q27 12 27 17 Q27 20 21 20"/>
      <line x1="7" y1="26" x2="23" y2="26"/>
      <line x1="13" y1="5" x2="13" y2="8" opacity="0.6"/>
    </svg>
  );
  if (key === 'vaso') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M10 8 h12 l-1.5 18 H11.5z"/>
      <line x1="16" y1="4" x2="16" y2="11"/>
      <line x1="8" y1="26" x2="24" y2="26"/>
    </svg>
  );
  if (key === 'gaseosa') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M13 8 Q12 10 12 12 L11 23 Q11 26 16 26 Q21 26 21 23 L20 12 Q20 10 19 8z"/>
      <rect x="13" y="5" width="6" height="3" rx="1"/>
      <circle cx="14" cy="17" r="1" fill="currentColor" stroke="none" opacity="0.6"/>
      <circle cx="18" cy="20" r="1" fill="currentColor" stroke="none" opacity="0.6"/>
      <circle cx="14" cy="22" r="1" fill="currentColor" stroke="none" opacity="0.6"/>
    </svg>
  );
  if (key === 'bebida') return (
    <svg viewBox={box} style={s} {...p}>
      <rect x="10" y="9" width="12" height="17" rx="3"/>
      <line x1="10" y1="13" x2="22" y2="13" strokeWidth="1" opacity="0.6"/>
      <line x1="10" y1="22" x2="22" y2="22" strokeWidth="1" opacity="0.6"/>
      <path d="M14 7 Q15.5 5 16 7 Q16.5 5 18 7" strokeWidth="1.1"/>
    </svg>
  );
  if (key === 'almuerzo') return (
    <svg viewBox={box} style={s} {...p}>
      <circle cx="13" cy="18" r="9"/>
      <circle cx="13" cy="18" r="5" strokeWidth="0.9" opacity="0.4"/>
      <line x1="26" y1="7" x2="26" y2="27"/>
      <path d="M23 7 Q23 12 26 12"/>
      <path d="M29 7 Q29 12 26 12"/>
    </svg>
  );
  if (key === 'guarnicion') return (
    <svg viewBox={box} style={s} {...p}>
      <path d="M6 18 Q7 27 16 27 Q25 27 26 18z"/>
      <line x1="4" y1="18" x2="28" y2="18"/>
      <path d="M12 18 Q10 12 13 9 Q13 13 14 18" strokeWidth="1.1" opacity="0.65"/>
      <path d="M16 18 Q16 10 17 7 Q18 10 17 18" strokeWidth="1.1" opacity="0.65"/>
      <path d="M20 18 Q22 12 19 9 Q19 13 18 18" strokeWidth="1.1" opacity="0.65"/>
    </svg>
  );
  // fallback
  return (
    <svg viewBox={box} style={s} {...p}>
      <circle cx="16" cy="16" r="10"/>
      <circle cx="16" cy="16" r="5" strokeWidth="0.9" opacity="0.4"/>
    </svg>
  );
}

// ============= MENU =============
function MenuItem({ item, modoVista, delay }) {
  return (
    <div className="menu-item reveal in" style={{ transitionDelay: `${delay}ms` }}>
      {modoVista && item.imagenUrl ? (
        <div className="menu-item-img">
          <img src={item.imagenUrl} alt={item.name} loading="lazy" />
        </div>
      ) : (
        <div className="menu-item-icon">
          <SubcatIcon k={item.iconKey || ''} size={32} />
        </div>
      )}
      <div className="menu-item-body">
        <h4>{item.name}</h4>
        {item.tags && <div className="item-tags">{item.tags}</div>}
        {item.desc && <p>{item.desc}</p>}
      </div>
      <div className="menu-item-price">{item.price}</div>
    </div>
  );
}

function Menu() {
  const [menuData, setMenuData] = useState(null);
  const [tab, setTab]           = useState(null);
  const [subTab, setSubTab]     = useState(null);

  useEffect(() => {
    window.loadBPMenu()
      .then(menu => { setMenuData(menu); setTab(Object.keys(menu)[0] ?? null); })
      .catch(() => { setMenuData(BPData.menu); setTab(Object.keys(BPData.menu)[0] ?? null); });
  }, []);

  // Auto-select first subcategory whenever the category changes (never leave empty)
  useEffect(() => {
    if (!menuData || !tab) { setSubTab(null); return; }
    const subs = menuData[tab]?.subcategories ?? [];
    setSubTab(subs.length > 0 ? subs[0].id : null);
  }, [tab, menuData]);

  const tabs      = menuData ? Object.keys(menuData) : [];
  const active    = menuData && tab ? menuData[tab] ?? null : null;
  const subs      = active?.subcategories ?? [];
  const activeSub = subTab ? subs.find(s => s.id === subTab) ?? null : null;
  const modoVista = !!active?.modoVista;

  // For categories with no subcategories (legacy / daily special), show items directly
  const directItems = subs.length === 0 ? (active?.directItems ?? active?.items ?? []) : [];

  const itemsRef = useRef(null);
  useEffect(() => {
    if (!itemsRef.current) return;
    const svgs = itemsRef.current.querySelectorAll(".bp-illus");
    svgs.forEach(s => s.classList.remove("bp-drawn"));
    requestAnimationFrame(() => requestAnimationFrame(() => svgs.forEach(s => s.classList.add("bp-drawn"))));
  }, [subTab]);

  return (
    <section id="menu" className="section">
      <DecoCroissant style={{ width: 84, top: "5%", left: "2.5%", transform: "rotate(-10deg)" }} className="deco-float" />
      <DecoDots      style={{ width: 58, bottom: "6%", right: "4%" }} className="deco-pulse deco-delay2" />
      <DecoStar      style={{ width: 24, top: "20%", right: "6%" }} className="deco-sway deco-delay3" />
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">La carta</span>
          <h2>Para todo el día</h2>
        </div>

        {!menuData ? (
          <div style={{ textAlign:"center", padding:"48px 0", color:"var(--coffee-soft)", fontFamily:"var(--font-serif)", fontSize:"1.1em", opacity:0.7 }}>
            Cargando menú…
          </div>
        ) : (
          <>
            {/* ── Row 1: main category tabs ── */}
            <Reveal>
              <div className="menu-tabs">
                {tabs.map(k => (
                  <button key={k} className={`menu-tab ${tab === k ? "active" : ""}`} onClick={() => setTab(k)}>
                    {menuData[k].label}
                  </button>
                ))}
              </div>
            </Reveal>

            {/* ── Row 2: subcategory pills ── */}
            {subs.length > 0 && (
              <div className="menu-subtabs">
                {subs.map(sub => (
                  <button
                    key={sub.id}
                    className={`menu-subtab ${subTab === sub.id ? "active" : ""}`}
                    onClick={() => setSubTab(sub.id)}
                  >
                    <SubcatIcon k={sub.icono} size={16} />
                    {sub.nombre}
                  </button>
                ))}
              </div>
            )}

            {/* ── Row 3: items (only when a subcategory is selected) ── */}
            {activeSub && (
              <div ref={itemsRef} key={subTab} className="menu-items-panel">
                {activeSub.items.length > 0 ? (
                  <div className={`menu-grid ${modoVista ? "menu-grid-img" : ""}`}>
                    {activeSub.items.map((item, i) => (
                      <MenuItem key={item.id ?? item.name} item={item} modoVista={modoVista} delay={i * 35} />
                    ))}
                  </div>
                ) : (
                  <p className="menu-empty">Próximamente…</p>
                )}
              </div>
            )}

            {/* ── Direct items (no subcategories, e.g. daily special) ── */}
            {directItems.length > 0 && (
              <div className={`menu-grid ${modoVista ? "menu-grid-img" : ""}`} style={{ marginTop: 24 }}>
                {directItems.map((item, i) => (
                  <MenuItem key={item.id ?? item.name} item={item} modoVista={modoVista} delay={i * 35} />
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </section>
  );
}

// ============= GALLERY — Instagram Carousel =============
function extractIgId(url) {
  const m = (url || '').match(/\/p\/([^/?#]+)/);
  return m ? m[1] : null;
}

function Gallery() {
  const [igPosts, setIgPosts] = useState(null);
  const trackRef = useRef(null);
  const viewportRef = useRef(null);

  useEffect(() => {
    window.loadBPInstagram()
      .then(data => setIgPosts(data?.length ? data : window.IG_FALLBACK))
      .catch(() => setIgPosts(window.IG_FALLBACK));
  }, []);

  const posts = igPosts ?? window.IG_FALLBACK;
  const doubled = [...posts, ...posts];

  // Drag-to-scroll
  useEffect(() => {
    const viewport = viewportRef.current;
    const track = trackRef.current;
    if (!viewport || !track) return;

    const animDuration = posts.length * 9;
    let isDragging = false;
    let startX = 0;
    let startTranslateX = 0;

    const getTranslateX = (el) => new DOMMatrix(window.getComputedStyle(el).transform).m41;

    const onDown = (e) => {
      const clientX = e.touches ? e.touches[0].clientX : e.clientX;
      isDragging = true;
      startX = clientX;
      startTranslateX = getTranslateX(track);
      track.style.animation = 'none';
      track.style.transform = `translateX(${startTranslateX}px)`;
      viewport.style.cursor = 'grabbing';
    };

    const onMove = (e) => {
      if (!isDragging) return;
      const clientX = e.touches ? e.touches[0].clientX : e.clientX;
      const dx = clientX - startX;
      track.style.transform = `translateX(${startTranslateX + dx}px)`;
    };

    const onUp = () => {
      if (!isDragging) return;
      isDragging = false;
      viewport.style.cursor = 'grab';
      const finalX = getTranslateX(track);
      const halfWidth = track.scrollWidth / 2;
      let norm = (-finalX) % halfWidth;
      if (norm < 0) norm += halfWidth;
      const delay = -(norm / halfWidth) * animDuration;
      track.style.transform = '';
      track.style.animation = 'none';
      requestAnimationFrame(() => requestAnimationFrame(() => {
        track.style.animation = `ig-scroll ${animDuration}s linear ${delay}s infinite`;
      }));
    };

    viewport.addEventListener('mousedown', onDown);
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    viewport.addEventListener('touchstart', onDown, { passive: true });
    window.addEventListener('touchmove', onMove, { passive: true });
    window.addEventListener('touchend', onUp);

    return () => {
      viewport.removeEventListener('mousedown', onDown);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      viewport.removeEventListener('touchstart', onDown);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, [igPosts]);

  return (
    <section id="gallery" className="section section-paper">
      <DecoStar   style={{ width: 30, top: "6%", left: "5%" }} className="deco-pulse deco-delay1" />
      <DecoDots   style={{ width: 60, bottom: "5%", right: "5%" }} className="deco-float deco-delay2" />
      <DecoCookie style={{ width: 56, top: "8%", right: "4%", transform: "rotate(-15deg)" }} className="deco-sway deco-delay3" />
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Galería</span>
          <h2>Tras la vitrina</h2>
        </div>
      </div>

      <div className="ig-carousel-viewport" ref={viewportRef} style={{ cursor: 'grab' }}>
        <div className="ig-carousel-track" ref={trackRef} style={{ animationDuration: `${posts.length * 9}s` }}>
          {doubled.map((post, i) => {
            const id = extractIgId(post.urlPost);
            if (!id) return null;
            return (
              <div key={i} className="ig-carousel-item">
                <iframe
                  src={`https://www.instagram.com/p/${id}/embed/`}
                  width="326"
                  height="430"
                  frameBorder="0"
                  scrolling="no"
                  title={post.titulo || `Post ${i + 1}`}
                  loading="lazy"
                />
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ============= RESERVATIONS =============
function Reservations() {
  const today = new Date().toISOString().split("T")[0];
  const [form, setForm] = useState({
    name: "", phone: "", email: "",
    date: today, time: "12:30", party: 2,
    occasion: "Almuerzo", notes: "",
  });
  const [hoursData, setHoursData] = useState(null);

  useEffect(() => {
    window.loadBPHours()
      .then(data => { if (data) setHoursData(data); })
      .catch(() => {});
  }, []);

  useEffect(() => {
    const handler = (e) => setForm(f => ({ ...f, occasion: e.detail.occasion }));
    window.addEventListener('bpSelectOccasion', handler);
    return () => window.removeEventListener('bpSelectOccasion', handler);
  }, []);
  const [submitted, setSubmitted] = useState(false);
  const [confirmation, setConfirmation] = useState(null);
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState(null);

  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.phone) return;
    setSending(true);
    setSendError(null);
    try {
      const res = await fetch('https://app.indexte.com/api/bom-pain/reservas', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          nombre:   form.name,
          email:    form.email,
          telefono: form.phone,
          fecha:    form.date,
          hora:     form.time,
          notas:    [form.occasion, form.notes].filter(Boolean).join(' · '),
        }),
      });
      if (!res.ok) throw new Error('server');
      const data = await res.json();
      const code = 'BP-' + (data.id ?? '').replace(/-/g, '').slice(0, 6).toUpperCase();
      setConfirmation({ ...form, code });
      setSubmitted(true);
    } catch {
      setSendError('No se pudo enviar la reserva. Intentá de nuevo o escribinos por WhatsApp.');
    } finally {
      setSending(false);
    }
  };

  const reset = () => {
    setSubmitted(false);
    setForm({ name: "", phone: "", email: "", date: today, time: "12:30", party: 2, occasion: "Almuerzo", notes: "" });
  };

  const times = [];
  for (let h = 8; h <= 20; h++) {
    times.push(`${String(h).padStart(2, "0")}:00`);
    times.push(`${String(h).padStart(2, "0")}:30`);
  }

  return (
    <section id="reserve" className="section section-coffee">
      <DecoCup    style={{ width: 70, top: "8%", right: "5%" }} className="deco-float deco-delay1" />
      <DecoLeaf   style={{ width: 54, bottom: "10%", left: "3%", transform: "rotate(-8deg)" }} className="deco-sway deco-delay2" />
      <DecoDots   style={{ width: 52, top: "45%", left: "2%" }} className="deco-pulse deco-delay3" />
      <div className="container">
        <div className="reserve-grid">
          <Reveal className="reserve-info">
            <span className="eyebrow">Reservas</span>
            <h2 style={{ marginTop: 18 }}>
              Aparta tu mesa<span className="script" style={{ display: "block", color: "var(--paper-edge)" }}>— para una buena tarde</span>
            </h2>
            <p>
              Te esperamos con el horno encendido.
            </p>
            <Illus.Ornament style={{ width: 240, color: "var(--paper-edge)", margin: "30px 0" }} className="bp-drawn" />
            <div className="hours">
              <h4>Horarios de atención</h4>
              {(hoursData ?? BPData.hours).map((h) => (
                <div key={h.day} className={`hours-row${h.cerrado ? ' hours-row-closed' : ''}`}>
                  <span>{h.day}</span>
                  <span>{h.time}</span>
                </div>
              ))}
            </div>
          </Reveal>

          <Reveal delay={150}>
            <div className="reserve-form">
              {!submitted ? (
                <form onSubmit={submit}>
                  <div className="form-row">
                    <div className="field">
                      <label>Nombre completo *</label>
                      <input
                        type="text"
                        value={form.name}
                        onChange={(e) => update("name", e.target.value)}
                        placeholder="María González"
                        required
                      />
                    </div>
                    <div className="field">
                      <label>Teléfono *</label>
                      <input
                        type="tel"
                        value={form.phone}
                        onChange={(e) => update("phone", e.target.value)}
                        placeholder="+595 981 000 000"
                        required
                      />
                    </div>
                  </div>

                  <div className="form-row single">
                    <div className="field">
                      <label>Correo electrónico</label>
                      <input
                        type="email"
                        value={form.email}
                        onChange={(e) => update("email", e.target.value)}
                        placeholder="maria@correo.com"
                      />
                    </div>
                  </div>

                  <div className="form-row">
                    <div className="field">
                      <label>Fecha *</label>
                      <input
                        type="date"
                        value={form.date}
                        min={today}
                        onChange={(e) => update("date", e.target.value)}
                        required
                      />
                    </div>
                    <div className="field">
                      <label>Hora *</label>
                      <select value={form.time} onChange={(e) => update("time", e.target.value)}>
                        {times.map((t) => <option key={t} value={t}>{t}</option>)}
                      </select>
                    </div>
                  </div>

                  <div className="form-row">
                    <div className="field">
                      <label>Personas *</label>
                      <div className="party-counter">
                        <button type="button" onClick={() => update("party", Math.max(1, form.party - 1))}>−</button>
                        <span>{form.party}</span>
                        <button type="button" onClick={() => update("party", Math.min(20, form.party + 1))}>+</button>
                      </div>
                    </div>
                    <div className="field">
                      <label>Ocasión</label>
                      <select value={form.occasion} onChange={(e) => update("occasion", e.target.value)}>
                        <option>Desayuno</option>
                        <option>Almuerzo</option>
                        <option>Merienda</option>
                        <option>Reunión</option>
                        <option>Cumpleaños</option>
                        <option>Baby Shower</option>
                        <option>Otro</option>
                      </select>
                    </div>
                  </div>

                  <div className="form-row single">
                    <div className="field">
                      <label>Comentarios</label>
                      <textarea
                        value={form.notes}
                        onChange={(e) => update("notes", e.target.value)}
                        placeholder="Mesa junto a la ventana, alergias, celebración..."
                      />
                    </div>
                  </div>

                  {sendError && (
                    <p style={{ color: '#c0392b', fontSize: '0.9em', margin: '8px 0 0', textAlign: 'center' }}>
                      {sendError}
                    </p>
                  )}
                  <button type="submit" className="btn-submit" disabled={sending}>
                    {sending ? 'Enviando…' : <span>Confirmar reserva <span>→</span></span>}
                  </button>
                </form>
              ) : (
                <div className="reserve-success">
                  <Illus.Ornament style={{ width: 200, margin: "0 auto", color: "var(--coffee-soft)" }} className="bp-drawn" />
                  <h3>Reserva confirmada</h3>
                  <p>Hasta pronto, {confirmation.name.split(" ")[0]}.</p>
                  <dl className="ticket">
                    <dt>Código</dt><dd>{confirmation.code}</dd>
                    <dt>Fecha</dt><dd>{confirmation.date}</dd>
                    <dt>Hora</dt><dd>{confirmation.time}</dd>
                    <dt>Personas</dt><dd>{confirmation.party}</dd>
                    <dt>Ocasión</dt><dd>{confirmation.occasion}</dd>
                    <dt>Contacto</dt><dd>{confirmation.phone}</dd>
                  </dl>
                  <button className="btn-submit" onClick={reset} style={{ marginTop: 20 }}>
                    Hacer otra reserva
                  </button>
                </div>
              )}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// ============= TESTIMONIALS =============
function Testimonials() {
  const [testimonialsData, setTestimonialsData] = useState(null);

  useEffect(() => {
    window.loadBPTestimonials()
      .then(data => { setTestimonialsData(data ?? BPData.testimonials); })
      .catch(() => setTestimonialsData(BPData.testimonials));
  }, []);

  const items = testimonialsData ?? BPData.testimonials;

  return (
    <section id="testimonios" className="section">
      <DecoCookie  style={{ width: 62, top: "4%", right: "4%", transform: "rotate(-22deg)" }} className="deco-sway deco-delay1" />
      <DecoStar    style={{ width: 30, bottom: "8%", left: "5%" }} className="deco-float deco-delay2" />
      <DecoCroissant style={{ width: 72, bottom: "6%", right: "3%", transform: "rotate(8deg)" }} className="deco-pulse deco-delay3" />
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Lo dicen quienes nos visitan</span>
          <h2>Pequeñas cartas</h2>
        </div>

        <div className="testimonials">
          {items.map((t, i) => (
            <Reveal key={i} delay={i * 100}>
              <div className="testimonial">
                <span className="quote-mark">"</span>
                <div className="stars">★ ★ ★ ★ ★</div>
                <blockquote>{t.quote}</blockquote>
                <cite>
                  <span className="name">{t.name}</span>
                  {t.meta}
                </cite>
              </div>
            </Reveal>
          ))}
        </div>

        {/* Google Maps review CTA */}
        <Reveal>
          <div className="maps-review-cta">
            <p className="maps-review-eyebrow">¿Ya nos visitaste?</p>
            <p className="maps-review-lede">Tu opinión ayuda a más personas a encontrarnos.</p>
            <a
              href={BPData.contact.mapsUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="btn-maps-review"
            >
              <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true">
                <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
              </svg>
              Dejanos una reseña en Google
            </a>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ============= BABY SHOWER =============
function BabyShower() {
  const goToReserve = (e) => {
    e.preventDefault();
    window.dispatchEvent(new CustomEvent('bpSelectOccasion', { detail: { occasion: 'Baby Shower' } }));
    document.querySelector('#reserve')?.scrollIntoView({ behavior: 'smooth' });
  };

  return (
    <section id="baby-shower" className="section section-babyshower">
      <DecoLeaf  style={{ width: 54, top: "5%", right: "4%", transform: "rotate(12deg)" }} className="deco-sway" />
      <DecoDots  style={{ width: 54, bottom: "6%", left: "5%" }} className="deco-pulse deco-delay2" />
      <DecoStar  style={{ width: 26, top: "40%", left: "3%" }} className="deco-float deco-delay1" />
      <div className="container">
        <Reveal>
          <div className="baby-header">
            <span className="eyebrow">Eventos especiales</span>
            <h2 style={{ marginTop: 14 }}>
              Tu Baby Shower
              <span className="script" style={{ display: "block" }}>— en el lugar perfecto</span>
            </h2>
          </div>
        </Reveal>

        <div className="baby-two-col">
          <Reveal>
            <div className="baby-embed-col">
              <iframe
                src="https://www.instagram.com/p/DOTJso8gJ-8/embed/"
                frameBorder="0"
                scrolling="no"
                title="Baby Shower en Bom Pain"
                className="baby-embed-frame"
              />
            </div>
          </Reveal>

          <Reveal delay={120}>
            <div className="baby-info-col">
              <p style={{ fontFamily: "var(--font-serif)", fontSize: 18, fontStyle: "italic", color: "var(--coffee-soft)", marginBottom: 36 }}>
                Un espacio acogedor, café artesanal y una atención de casa — el escenario ideal para celebrar la llegada de quien más amás.
              </p>
              <div className="baby-features">
                <div className="baby-feature">
                  <span className="baby-feature-icon">🌸</span>
                  <div>
                    <strong>Mesa decorada</strong>
                    <p>Arreglo floral y ambientación especial para el festejo</p>
                  </div>
                </div>
                <div className="baby-feature">
                  <span className="baby-feature-icon">🎂</span>
                  <div>
                    <strong>Menú especial</strong>
                    <p>Selección de dulces, panadería artesanal y bebidas</p>
                  </div>
                </div>
                <div className="baby-feature">
                  <span className="baby-feature-icon">🤍</span>
                  <div>
                    <strong>Espacio reservado</strong>
                    <p>Salón exclusivo para tu grupo, sin interrupciones</p>
                  </div>
                </div>
                <div className="baby-feature">
                  <span className="baby-feature-icon">📸</span>
                  <div>
                    <strong>Ambiente único</strong>
                    <p>Rincones cálidos y perfectos para las fotos del día</p>
                  </div>
                </div>
              </div>
              <a href="#reserve" onClick={goToReserve} className="btn-primary baby-cta">
                Consultar disponibilidad <span className="btn-arrow">→</span>
              </a>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// ============= INSTAGRAM FEED =============
function InstagramFeed() {
  return (
    <section className="section section-ig-handle">
      <div className="container" style={{ textAlign: 'center' }}>
        <span className="eyebrow" style={{ color: 'var(--paper-edge, #c9a96e)' }}>Seguinos en Instagram</span>
        <a
          href={BPData.contact.instagramUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="ig-handle-link"
        >
          @{BPData.contact.instagram}
        </a>
      </div>
    </section>
  );
}

// ============= LOCATION =============
function Location() {
  return (
    <section id="location" className="section section-paper">
      <DecoStar    style={{ width: 28, top: "5%", right: "6%" }} className="deco-pulse" />
      <DecoCroissant style={{ width: 72, bottom: "7%", left: "3%", transform: "rotate(6deg)" }} className="deco-float deco-delay3" />
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Visítanos</span>
          <h2>Donde nos encuentras</h2>
        </div>

        <div className="location-grid">
          <Reveal>
            <div className="location-info">
              <h3>Bom Pain<br /><span style={{ fontSize: "0.65em", color: "var(--coffee-soft)" }}>Ñemby, Paraguay</span></h3>
              <p className="address">
                Abierto de lunes a domingo.
              </p>
              <a href={BPData.contact.whatsappUrl} target="_blank" rel="noopener noreferrer" className="contact-row contact-row-link">
                <span className="label">WhatsApp</span>
                <span className="value">{BPData.contact.whatsappDisplay}</span>
                <span className="contact-arrow">→</span>
              </a>
              <a href={BPData.contact.instagramUrl} target="_blank" rel="noopener noreferrer" className="contact-row contact-row-link">
                <span className="label">Instagram</span>
                <span className="value">@{BPData.contact.instagram}</span>
                <span className="contact-arrow">→</span>
              </a>
              <a href={BPData.contact.mapsUrl} target="_blank" rel="noopener noreferrer" className="contact-row contact-row-link">
                <span className="label">Ubicación</span>
                <span className="value">Ver en Google Maps</span>
                <span className="contact-arrow">→</span>
              </a>
              <div className="socials">
                <a href={BPData.contact.instagramUrl} target="_blank" rel="noopener noreferrer"
                   className="nav-icon-btn loc-social-icon" aria-label="Instagram" title={`@${BPData.contact.instagram}`}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" width="20" height="20">
                    <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
                    <circle cx="12" cy="12" r="4.5"/>
                    <circle cx="17.5" cy="6.5" r="1.2" fill="currentColor" stroke="none"/>
                  </svg>
                </a>
                <a href={BPData.contact.whatsappUrl} target="_blank" rel="noopener noreferrer"
                   className="nav-icon-btn nav-wa-btn loc-social-icon" aria-label="WhatsApp" title={BPData.contact.whatsappDisplay}>
                  <svg viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                  </svg>
                </a>
              </div>
            </div>
          </Reveal>

          <Reveal delay={150}>
            <div className="location-map location-map-real">
              <iframe
                src={BPData.contact.mapsEmbed}
                width="100%"
                height="100%"
                style={{ border: 0 }}
                allowFullScreen=""
                loading="lazy"
                referrerPolicy="no-referrer-when-downgrade"
                title="Ubicación Bom Pain"
              />
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// ============= FOOTER =============
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <div className="footer-brand">
            Bom Pain
            <span className="script">Boulangerie · Café — Ñemby, 2023</span>
          </div>
          <p className="footer-tagline">
            Panadería artesanal, café de origen. Atendido por sus dueños.
          </p>
        </div>
        <div className="footer-col">
          <h5>Visítanos</h5>
          <ul>
            <li><a href="#about">Historia</a></li>
            <li><a href="#menu">Menú</a></li>
            <li><a href="#gallery">Galería</a></li>
            <li><a href="#location">Ubicación</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>Servicios</h5>
          <ul>
            <li>Reservas</li>
            <li>Eventos privados</li>
            <li>Pedidos para llevar</li>
            <li>Pan por encargo</li>
          </ul>
        </div>
        <div className="footer-col">
          <h5>Síguenos</h5>
          <ul>
            <li><a href={BPData.contact.instagramUrl} target="_blank" rel="noopener noreferrer">@{BPData.contact.instagram}</a></li>
            <li><a href={BPData.contact.whatsappUrl} target="_blank" rel="noopener noreferrer">{BPData.contact.whatsappDisplay}</a></li>
            <li><a href={BPData.contact.mapsUrl} target="_blank" rel="noopener noreferrer">Google Maps</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Bom Pain — Hecho con manos pacientes</span>
        <span>Ñemby, Paraguay · <a href={BPData.contact.instagramUrl} target="_blank" rel="noopener noreferrer" style={{color:"inherit"}}>@{BPData.contact.instagram}</a></span>
        <span>Desarrollado por <a href="https://www.indexte.com" target="_blank" rel="noopener noreferrer" style={{color:"#fff", fontWeight:600, textDecoration:"none"}}>Indexte</a></span>
      </div>
    </footer>
  );
}

// ============= INTRO SCREEN =============
function IntroScreen() {
  const [phase, setPhase] = useState("visible");

  useEffect(() => {
    // Remove the plain-HTML pre-splash now that React intro is painted
    const pre = document.getElementById("pre-intro");
    if (pre) pre.style.display = "none";

    document.body.style.overflow = "hidden";
    const tOut = setTimeout(() => setPhase("exiting"), 1900);
    const tGone = setTimeout(() => {
      setPhase("gone");
      document.body.style.overflow = "";
    }, 2700);
    return () => {
      clearTimeout(tOut);
      clearTimeout(tGone);
      document.body.style.overflow = "";
    };
  }, []);

  if (phase === "gone") return null;

  return (
    <div className={`intro-screen intro-${phase}`} aria-hidden="true">
      <div className="intro-inner">
        <Illus.CoffeeCup className="bp-drawn steam-loop" style={{ width: 180, color: "var(--coffee)" }} />
      </div>
    </div>
  );
}

Object.assign(window, {
  Nav, Hero, About, Menu, Gallery, Reservations, Testimonials, BabyShower, InstagramFeed, Location, Footer, Reveal, useReveal, FloatingWhatsApp, IntroScreen,
});
