// Shared interactive widgets used by both landing-a and landing-b.
// Exposes globals: MenuExplorer, GalleryLightbox, applyPalette, usePalette, smoothScrollTo

// --- Palette plumbing: parent canvas can postMessage palette swatches in ---
// Each palette is { accent, sun, fiesta, deep, ink }
window.SDM_PALETTES = {
  original: { name: "Logo Original", sun: "#F5B81C", fiesta: "#E63A1A", accent: "#1FA9B5", deep: "#1B2C5B", ink: "#1a1208" },
  mercado:  { name: "Mercado",       sun: "#E8A317", fiesta: "#C8311A", accent: "#7A2E2A", deep: "#3A1A12", ink: "#2a1208" },
  costa:    { name: "Costa",         sun: "#F2C13B", fiesta: "#E96A2B", accent: "#178A8E", deep: "#0D3B40", ink: "#0d2326" },
  nocturno: { name: "Nocturno",      sun: "#E5B23A", fiesta: "#D44A2A", accent: "#2BB0A8", deep: "#0E1735", ink: "#070b1a" },
  jardin:   { name: "Jardín",        sun: "#D89D2B", fiesta: "#C24A2A", accent: "#3B7A4F", deep: "#1F3326", ink: "#0e1c12" },
};

window.applyPalette = function (paletteKey) {
  const p = window.SDM_PALETTES[paletteKey] || window.SDM_PALETTES.original;
  const r = document.documentElement;
  r.style.setProperty("--sun", p.sun);
  r.style.setProperty("--fiesta", p.fiesta);
  r.style.setProperty("--accent", p.accent);
  r.style.setProperty("--deep", p.deep);
  r.style.setProperty("--ink", p.ink);
  r.setAttribute("data-palette", paletteKey);
};

// Listen for parent postMessage palette changes
window.addEventListener("message", (e) => {
  if (e.data && e.data.type === "sdm-palette" && e.data.palette) {
    window.applyPalette(e.data.palette);
  }
});

// Smooth scroll helper for in-page nav
window.smoothScrollTo = function (id) {
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 12;
  window.scrollTo({ top, behavior: "smooth" });
};

// ============ MenuExplorer ============
function MenuExplorer({ accentClass = "accent-default", pillStyle = "pill", layout = "cards" }) {
  const cats = window.SDM_MENU.categories;
  const items = window.SDM_MENU.items;
  const [active, setActive] = React.useState(cats[0].id);

  const filtered = items.filter((i) => i.cat === active);

  return (
    <div className={"menu-explorer " + accentClass}>
      <div className={"menu-pills " + (pillStyle === "tabs" ? "is-tabs" : "is-pill")}>
        {cats.map((c) => (
          <button
            key={c.id}
            className={"menu-pill " + (active === c.id ? "is-active" : "")}
            onClick={() => setActive(c.id)}
          >
            {c.label}
            <span className="menu-pill-count">{items.filter((i) => i.cat === c.id).length}</span>
          </button>
        ))}
      </div>
      <div className={"menu-items " + (layout === "list" ? "is-list" : "is-cards")}>
        {filtered.map((it) => (
          <article key={it.name} className="menu-item">
            <div className="menu-item-head">
              <h4 className="menu-item-name">{it.name}</h4>
              <span className="menu-item-dot" aria-hidden="true"></span>
              <span className="menu-item-price">${it.price}</span>
            </div>
            <p className="menu-item-desc">{it.desc}</p>
          </article>
        ))}
      </div>
    </div>
  );
}

// ============ GalleryLightbox ============
function GalleryLightbox({ photos, layout = "mosaic" }) {
  const [open, setOpen] = React.useState(null); // index or null

  React.useEffect(() => {
    if (open === null) return;
    const onKey = (e) => {
      if (e.key === "Escape") setOpen(null);
      if (e.key === "ArrowRight") setOpen((i) => (i + 1) % photos.length);
      if (e.key === "ArrowLeft") setOpen((i) => (i - 1 + photos.length) % photos.length);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, photos.length]);

  return (
    <React.Fragment>
      <div className={"gallery gallery-" + layout}>
        {photos.map((p, i) => (
          <button
            key={p.src}
            className="gallery-tile"
            onClick={() => setOpen(i)}
            aria-label={"Open photo: " + p.alt}
          >
            <img src={p.src} alt={p.alt} loading="lazy" />
          </button>
        ))}
      </div>

      {open !== null && (
        <div className="lightbox" onClick={() => setOpen(null)}>
          <button
            className="lightbox-close"
            onClick={(e) => { e.stopPropagation(); setOpen(null); }}
            aria-label="Close"
          >×</button>
          <button
            className="lightbox-nav lightbox-prev"
            onClick={(e) => { e.stopPropagation(); setOpen((i) => (i - 1 + photos.length) % photos.length); }}
            aria-label="Previous"
          >‹</button>
          <figure className="lightbox-figure" onClick={(e) => e.stopPropagation()}>
            <img src={photos[open].src} alt={photos[open].alt} />
            <figcaption>{photos[open].alt}</figcaption>
          </figure>
          <button
            className="lightbox-nav lightbox-next"
            onClick={(e) => { e.stopPropagation(); setOpen((i) => (i + 1) % photos.length); }}
            aria-label="Next"
          >›</button>
        </div>
      )}
    </React.Fragment>
  );
}

// ============ HoursBlock ============
function HoursBlock({ highlightToday = true }) {
  const todayIdx = new Date().getDay(); // 0 = Sunday
  return (
    <ul className="hours-list">
      {window.SDM_INFO.hours.map((h, i) => (
        <li key={h.day} className={"hours-row " + (highlightToday && i === todayIdx ? "is-today" : "")}>
          <span className="hours-day">{h.day}</span>
          <span className="hours-dots" aria-hidden="true"></span>
          <span className="hours-time">{h.hours}</span>
          {highlightToday && i === todayIdx && <span className="hours-pip">Today</span>}
        </li>
      ))}
    </ul>
  );
}

// Expose to global scope so each landing page's app.jsx can use these
Object.assign(window, { MenuExplorer, GalleryLightbox, HoursBlock });
