/* ============================================================
   SECTIONS — hero, banner de fecha especial, info, reservas, QR, footer
   ============================================================ */
const { SPECIAL_DATES: _SD, PAYMENTS: _P2, HOURS: _H, WA: _WA2, MENU_URL: _MU, CATS: _CATS, SOCIAL: _SOCIAL, SlotPicker } = window;

/* fecha especial activa (la más cercana) */
function getActiveSpecial(override) {
  if (override && override !== "auto") return _SD.find(s => s.id === override) || _SD[0];
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  let best = null, bestDiff = Infinity;
  _SD.forEach(s => {
    const span = s.id === "semana" ? 8 : 1;
    let d = new Date(s.date + "T00:00:00");
    while (d.getTime() + span * 864e5 < today.getTime()) d.setFullYear(d.getFullYear() + 1);
    const diff = d - today;
    if (diff < bestDiff) { bestDiff = diff; best = s; }
  });
  return best;
}

/* ---- Hero: carrusel horizontal automático ---- */
function HeroSlide({ slotId, placeholder, children }) {
  return (
    <div className="hero-slide">
      <image-slot id={slotId} class="hero-bg photo-dark" shape="rect" fit="cover" placeholder={placeholder}></image-slot>
      <div className="hero-veil"></div>
      <div className="hero-inner">{children}</div>
    </div>
  );
}

function Hero({ onOrder, onScrollTo, onOpenItem, onPdf, isOpen }) {
  const [i, setI] = useState(0);
  const n = 4;
  const pause = useRef(false);
  useEffect(() => {
    const t = setInterval(() => { if (!pause.current) setI(p => (p + 1) % n); }, 6500);
    return () => clearInterval(t);
  }, []);
  const go = (d) => setI((d + n) % n);

  return (
    <header className="hero" id="top"
      onMouseEnter={() => { pause.current = true; }}
      onMouseLeave={() => { pause.current = false; }}>
      <div className="hero-track" style={{ transform: `translateX(-${i * 100}%)` }}>
        {/* Slide 1 — marca */}
        <HeroSlide slotId="do-hero-bg" placeholder="Plato característico o ambiente del restaurante">
          <span className="kicker light">Pescadería &amp; Restaurante · Cocina del Pacífico</span>
          <h1 className="hero-title">Del mar<br /><em>a tu mesa</em></h1>
          <p className="hero-sub">Pescado fresco, salsas marineras y leche de coco. Arma tu pedido, personalízalo y recíbelo en casa.</p>
          <div className="hero-cta">
            <button className="btn-primary big" onClick={onOrder}>Haz tu pedido <Icon d={I.arrow} size={20} /></button>
            <button className="btn-outline big light" onClick={() => onScrollTo("reservas")}>Reservar mesa</button>
          </div>
          <div className="hero-meta">
            <div><b>40+</b><span>Platos</span></div>
            <div><b>9</b><span>Pescados frescos</span></div>
            <div><b>100%</b><span>Del Pacífico</span></div>
          </div>
        </HeroSlide>

        {/* Slide 2 — especialidad: Langosta Marinera */}
        <HeroSlide slotId="do-hero-2" placeholder="Foto · Langosta Marinera">
          <span className="kicker light">La especialidad · Plato estrella</span>
          <h1 className="hero-title">Langosta<br /><em>Marinera</em></h1>
          <p className="hero-sub">Langosta con frutos del mar en salsa marinera cremosa. La joya de Dos Océanos.</p>
          <div className="hero-cta">
            <button className="btn-primary big" onClick={() => onOpenItem("Langosta Marinera")}>Pedir ahora <Icon d={I.arrow} size={20} /></button>
            <button className="btn-outline big light" onClick={onPdf}><Icon d={I.pdf} size={18} /> Ver menú digital</button>
          </div>
        </HeroSlide>

        {/* Slide 3 — especialidad: Salmón marinero */}
        <HeroSlide slotId="do-hero-3" placeholder="Foto · Salmón marinero">
          <span className="kicker light">La especialidad</span>
          <h1 className="hero-title">Salmón<br /><em>marinero</em></h1>
          <p className="hero-sub">Salmón fresco bajo una generosa salsa de frutos del mar.</p>
          <div className="hero-cta">
            <button className="btn-primary big" onClick={() => onOpenItem("Salmón marinero")}>Pedir ahora <Icon d={I.arrow} size={20} /></button>
            <button className="btn-outline big light" onClick={onPdf}><Icon d={I.pdf} size={18} /> Ver menú digital</button>
          </div>
        </HeroSlide>

        {/* Slide 4 — especialidad: Cazuela de Mariscos */}
        <HeroSlide slotId="do-hero-4" placeholder="Foto · Cazuela de Mariscos">
          <span className="kicker light">La especialidad</span>
          <h1 className="hero-title">Cazuela<br /><em>de Mariscos</em></h1>
          <p className="hero-sub">Frutos del mar en un caldo cremoso de leche de coco.</p>
          <div className="hero-cta">
            <button className="btn-primary big" onClick={() => onOpenItem("Cazuela de Mariscos")}>Pedir ahora <Icon d={I.arrow} size={20} /></button>
            <button className="btn-outline big light" onClick={onPdf}><Icon d={I.pdf} size={18} /> Ver menú digital</button>
          </div>
        </HeroSlide>
      </div>

      <button className="hero-arrow left" onClick={() => go(i - 1)} aria-label="Anterior"><Icon d={I.back} size={22} /></button>
      <button className="hero-arrow right" onClick={() => go(i + 1)} aria-label="Siguiente"><Icon d={I.arrow} size={22} /></button>
      <div className="hero-dots">
        {[0, 1, 2, 3].map(d => (
          <button key={d} className={"hero-dot " + (i === d ? "on" : "")} onClick={() => setI(d)} aria-label={"Ir al slide " + (d + 1)}></button>
        ))}
      </div>
    </header>
  );
}

/* ---- Banda de experiencia (persona probando un plato) ---- */
function Experience({ onOrder }) {
  return (
    <section className="exp">
      <image-slot id="do-exp" class="exp-bg photo-dark" shape="rect" fit="cover"
        placeholder="Persona disfrutando un plato — foto horizontal, ambiente"></image-slot>
      <div className="exp-veil"></div>
      <div className="exp-inner">
        <span className="kicker">La experiencia Dos Océanos</span>
        <h3>Se ve, se huele, se antoja</h3>
        <p>Pescado recién traído, salsas que se cocinan al momento y el sabor del Pacífico en cada bocado. Pide y vívelo en tu mesa.</p>
        <button className="btn-primary big" onClick={onOrder}>Quiero probarlo <Icon d={I.arrow} size={20} /></button>
      </div>
    </section>
  );
}

/* ---- Banner de fecha especial ---- */
function SpecialBanner({ special, onCta }) {
  if (!special) return null;
  return (
    <div className={"special special-" + special.theme}>
      <div className="special-inner">
        <div className="special-text">
          <span className="special-kicker"><Icon d={I.spark} size={15} fill="currentColor" stroke="none" /> {special.kicker} · {special.dateLabel}</span>
          <h3 className="special-title">{special.title}</h3>
          <p className="special-msg">{special.msg}</p>
        </div>
        <button className="special-btn" onClick={onCta}>{special.cta} <Icon d={I.arrow} size={18} /></button>
      </div>
    </div>
  );
}

/* ---- Nav de categorías ---- */
function CategoryNav({ cats, active, onJump }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current && ref.current.querySelector(".on");
    if (el && ref.current) {
      const r = el.getBoundingClientRect(), pr = ref.current.getBoundingClientRect();
      ref.current.scrollBy({ left: r.left - pr.left - pr.width / 2 + r.width / 2, behavior: "smooth" });
    }
  }, [active]);
  return (
    <nav className="catnav" ref={ref}>
      {cats.map(c => (
        <button key={c.id} className={active === c.id ? "on" : ""} onClick={() => onJump(c.id)}>{c.name}</button>
      ))}
    </nav>
  );
}

/* ---- Reservas ---- */
function Reservas() {
  const [f, setF] = useState({ name: "", date: "", time: "", people: 2, notes: "" });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const valid = isValidName(f.name) && f.date && f.time;
  function send() {
    window.addReservation({ name: f.name, date: f.date, time: f.time, people: f.people, notes: f.notes.trim() });
    const L = ["*RESERVA — Dos Océanos*", `Nombre: ${f.name}`, `Fecha: ${f.date}`, `Hora: ${f.time}`, `Personas: ${f.people}`];
    if (f.notes.trim()) L.push(`Notas: ${f.notes}`);
    window.open(`https://wa.me/${_WA2}?text=${encodeURIComponent(L.join("\n"))}`, "_blank");
  }
  return (
    <section className="sec" id="reservas">
      <div className="sec-grid">
        <div className="sec-head-col">
          <span className="kicker">Reservas</span>
          <h2 className="sec-title">Aparta tu mesa<br />frente al mar</h2>
          <p className="sec-lead">Para fechas especiales recomendamos reservar con anticipación. Te confirmamos por WhatsApp.</p>
          <div className="sec-facts">
            <div><Icon d={I.clock} size={18} stroke="var(--coral)" /> {_H.days}, {_H.label}</div>
            <div><Icon d={I.users} size={18} stroke="var(--coral)" /> Grupos y eventos disponibles</div>
          </div>
          <a className="quote-btn" target="_blank" rel="noopener"
            href={`https://wa.me/${_WA2}?text=${encodeURIComponent("¡Hola Dos Océanos! Quiero cotizar un evento. Estos son mis datos:\n\nTipo de evento: \nFecha: \nNº de personas: ")}`}>
            <Wa size={18} /> Cotizar evento por WhatsApp
          </a>
          <image-slot id="do-reservas" class="res-photo do-slot" shape="rounded" radius="18" fit="cover"
            placeholder="Ambiente del restaurante o mesa servida"
            style={{ marginTop: "1.4rem" }}></image-slot>
        </div>
        <div className="rcard">
          <div className="rrow">
            <label className="fld"><span>Nombre</span><input value={f.name} onChange={(e) => set("name", filterName(e.target.value))} placeholder="Tu nombre" autoComplete="name" maxLength={50} /></label>
            <label className="fld"><span>Personas</span>
              <div className="people"><Stepper value={f.people} onChange={(v) => set("people", v)} min={1} max={15} size="sm" /></div></label>
          </div>
          <div className="rrow">
            <label className="fld"><span>Fecha</span><input type="date" value={f.date} min={new Date().toISOString().slice(0, 10)}
              onChange={(e) => setF(s => ({ ...s, date: e.target.value, time: "" }))} /></label>
          </div>
          <label className="fld"><span>Hora</span>
            <SlotPicker date={f.date} time={f.time} onPick={(t) => set("time", t)} />
          </label>
          <label className="fld"><span>Notas (opcional)</span><input value={f.notes} onChange={(e) => set("notes", filterNotes(e.target.value))} placeholder="Cumpleaños, ubicación preferida…" maxLength={120} /></label>
          <p className="res-note">Máximo 15 personas por reserva. Si pasan 30 minutos de la hora reservada sin confirmación de llegada, la mesa no se garantiza.</p>
          <button className="btn-add wa" disabled={!valid} onClick={send}><Wa size={18} /> Solicitar reserva</button>
        </div>
      </div>
    </section>
  );
}

/* ---- Info: horarios, cobertura, pagos ---- */
function InfoSection({ store }) {
  const openNow = store ? isStoreOpen(store) : true;
  return (
    <section className="sec band" id="info">
      <div className="info-grid">
        <div className="icard">
          <span className="icard-ic"><Icon d={I.clock} size={22} stroke="var(--coral)" /></span>
          <h3>Horarios</h3>
          <p className={"openpill " + (openNow ? "open" : "closed")}>
            <i></i>{openNow ? "Abierto ahora" : "Cerrado ahora"}</p>
          <ul className="ilist">
            <li><span>{_H.days}</span><b>{_H.label}</b></li>
            <li className="muted"><span>Cocina hasta</span><b>{_H.kitchenLabel}</b></li>
          </ul>
        </div>
        <div className="icard">
          <span className="icard-ic"><Icon d={I.pin} size={22} stroke="var(--coral)" /></span>
          <h3>Domicilios</h3>
          <ul className="ilist">
            <li><span>Tarifa única</span><b>{fmt(5000)}</b></li>
          </ul>
        </div>
        <div className="icard">
          <span className="icard-ic"><Icon d={I.card} size={22} stroke="var(--coral)" /></span>
          <h3>Métodos de pago</h3>
          <div className="paychips">
            {_P2.map(p => <span key={p.id} className={"paychip " + (p.pse ? "hl" : "")}>{p.label}</span>)}
          </div>
          <p className="icard-note">Paga en línea con PSE de forma segura, o al recibir tu pedido.</p>
        </div>
      </div>
    </section>
  );
}

/* ---- QR ---- */
function QRSection() {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    ref.current.innerHTML = "";
    if (window.qrcode) {
      const qr = window.qrcode(0, "M");
      qr.addData(_MU); qr.make();
      ref.current.innerHTML = qr.createSvgTag({ cellSize: 6, margin: 0, scalable: true });
      const svg = ref.current.querySelector("svg");
      if (svg) { svg.style.width = "100%"; svg.style.height = "100%"; svg.removeAttribute("width"); svg.removeAttribute("height"); }
    } else {
      ref.current.innerHTML = '<div class="qr-fallback">QR</div>';
    }
  }, []);
  return (
    <section className="sec" id="qr">
      <div className="qr-card">
        <div className="qr-left">
          <span className="kicker light">Escanea &amp; pide</span>
          <h2 className="qr-title">Lleva la carta<br />en tu bolsillo</h2>
          <p className="qr-lead">Escanea este código para abrir la carta en tu celular, armar tu pedido y recibirlo a domicilio. Imprímelo para tu mesa o compártelo con tus clientes.</p>
          <div className="qr-actions">
            <button className="btn-outline light" onClick={() => window.print()}>Imprimir tarjeta</button>
          </div>
          <image-slot id="do-qr-dish" class="qr-dish photo-dark" shape="rounded" radius="16" fit="cover"
            placeholder="Plato listo para domicilio — antójalos"></image-slot>
        </div>
        <div className="qr-right">
          <div className="qr-frame">
            <div className="qr-canvas" ref={ref}></div>
          </div>
          <span className="qr-cap">Dos Océanos · Haz tu pedido</span>
        </div>
      </div>
    </section>
  );
}

/* ---- Footer ---- */
function Footer({ onAdmin }) {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div className="footer-brand">
          <span className="brand-mark"><Icon d={I.anchor} size={20} stroke="currentColor" /></span>
          <p className="brand-name">Dos <em>Océanos</em></p>
          <p className="brand-tag">Pescadería y restaurante de cocina del Pacífico. Del mar a tu mesa.</p>
          <a className="wa-btn" href={`https://wa.me/${_WA2}`} target="_blank" rel="noopener"><Wa size={18} /> Pedir por WhatsApp</a>
          <div className="socials">
            <a href={_SOCIAL.instagram} target="_blank" rel="noopener" aria-label="Instagram" className="social"><Icon d={I.ig} size={20} /></a>
            <a href={_SOCIAL.facebook} target="_blank" rel="noopener" aria-label="Facebook" className="social"><Icon d={I.fb} size={20} /></a>
            <a href={_SOCIAL.tiktok} target="_blank" rel="noopener" aria-label="TikTok" className="social"><Icon d={I.tt} size={20} /></a>
          </div>
        </div>
        <div className="footer-col">
          <h4>Visítanos</h4>
          <a href="https://maps.app.goo.gl/8vtKU1V3Q8TSkTKD8" target="_blank" rel="noopener">Ver en el mapa →</a>
          <span>{_H.days}</span>
          <span>{_H.label}</span>
        </div>
        <div className="footer-col">
          <h4>Pedidos &amp; reservas</h4>
          <a href={`https://wa.me/${_WA2}`} target="_blank" rel="noopener">WhatsApp 302 383 9789</a>
          <span>Domicilios 310 340 4613</span>
          <span>Fijo 445 5895</span>
          <span>Pago con PSE, Nequi y más</span>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Pescadería Dos Océanos</span>
        <div className="footer-bottom-r">
          <button className="admin-link" onClick={onAdmin}><Icon d={I.card} size={14} /> Panel del restaurante</button>
          <span>Del mar a tu mesa 🌊</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { getActiveSpecial, Hero, Experience, SpecialBanner, CategoryNav, Reservas, InfoSection, QRSection, Footer });
