/* ============================================================
   EXTRAS — visor de PDF, banner de sugeridos, promo del día,
            y cross-sell (relacionados) para no perder la venta
   ============================================================ */
const { MENU_PDF: EX_PDF, WEEKLY_PROMOS: EX_PROMOS, FEATURE: EX_FEATURE } = window;

/* ---- Visor de menú en PDF (anclado a la página, overlay) ---- */
function PdfModal({ onClose }) {
  useEffect(() => {
    document.body.style.overflow = "hidden";
    const esc = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", esc);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", esc); };
  }, []);
  return (
    <div className="overlay pdf-overlay" onClick={onClose}>
      <div className="pdf-shell" onClick={(e) => e.stopPropagation()}>
        <div className="pdf-bar">
          <span className="pdf-title"><Icon d={I.cal} size={16} /> Menú digital · Dos Océanos</span>
          <div className="pdf-bar-actions">
            <a className="pdf-open" href={EX_PDF} target="_blank" rel="noopener">Abrir en pestaña ↗</a>
            <button className="modal-x" onClick={onClose} aria-label="Cerrar"><Icon d={I.close} size={22} /></button>
          </div>
        </div>
        <div className="pdf-frame">
          <iframe title="Menú digital Dos Océanos" src={EX_PDF}></iframe>
          <div className="pdf-hint">Cargando el menú digital…</div>
        </div>
      </div>
    </div>
  );
}

/* ---- Promo del día (miércoles de mariscos, etc.) ---- */
function getWeeklyPromo() {
  const p = EX_PROMOS[new Date().getDay()];
  return p || null;
}
function WeeklyPromo({ promo, onCta }) {
  if (!promo) return null;
  return (
    <div className={"promo promo-" + (promo.color || "sea")}>
      <div className="promo-inner">
        <span className="promo-tag"><Icon d={I.spark} size={14} fill="currentColor" stroke="none" /> {promo.kicker}</span>
        <div className="promo-main">
          <h3 className="promo-title">{promo.title}</h3>
          <p className="promo-msg">{promo.msg}</p>
        </div>
        <button className="promo-btn" onClick={() => onCta(promo)}>{promo.cta} <Icon d={I.arrow} size={18} /></button>
      </div>
    </div>
  );
}

/* ---- Banner de platos sugeridos: solo Premium y Favorito ----
   (la especialidad ya se destaca arriba, en el hero principal) */
function SuggestedBanner({ onOpen, store }) {
  const items = [];
  window.CATS.forEach(c => c.items.forEach(it => {
    if ((it.tag === "Favorito" || it.tag === "Premium") && itemAvailable(store, it.n)) items.push({ item: it, cat: c });
  }));
  if (!items.length) return null;
  return (
    <section className="sugg" id="sugeridos">
      <div className="sugg-head">
        <span className="kicker">El chef sugiere</span>
        <h2 className="sugg-title">Lo que no te puedes perder</h2>
      </div>
      <div className="sugg-track">
        {items.map(({ item, cat }, i) => (
          <button key={i} className="sugg-card" onClick={() => onOpen(item, cat)}>
            <div className="sugg-ph"><Placeholder label={item.n} kind="foto" img={window.PHOTOS[item.n]} />
              {item.tag && <span className={"badge " + tagClass(item.tag)}>{item.tag}</span>}</div>
            <div className="sugg-info">
              <span className="sugg-cat">{cat.name}</span>
              <h3>{item.n}</h3>
              <div className="sugg-foot"><span className="sugg-price">{priceLabel(item)}</span>
                <span className="sugg-add"><Icon d={I.plus} size={16} /></span></div>
            </div>
          </button>
        ))}
      </div>
    </section>
  );
}

/* ---- Cross-sell: relacionados dentro del modal ---- */
const PAIR_DRINKS = ["Limonada de Coco", "Borojó", "Limonada Cerezada"];
const PAIR_STARTERS = ["Ceviche de la casa", "Cóctel de camarón"];

function getRelated(item, cat, store) {
  const names = [];
  if (cat.id === "bebidas") {
    names.push("Pargo Rojo", "Arroz Marinero", "Ceviche de la casa");
  } else if (cat.id === "entradas") {
    names.push("Pargo Rojo", "Cazuela de Mariscos", "Limonada de Coco");
  } else {
    names.push(PAIR_STARTERS[0], PAIR_DRINKS[0], "Cazuela de Mariscos", EX_FEATURE.n);
  }
  const out = [];
  names.forEach(n => {
    if (n === item.n) return;
    if (!itemAvailable(store, n)) return;
    const f = findItem(n);
    if (f && !out.find(o => o.item.n === f.item.n)) out.push(f);
  });
  return out.slice(0, 3);
}

function RelatedItems({ item, cat, store, onQuickAdd, onTotalChange }) {
  const rel = getRelated(item, cat, store);
  const [count, setCount] = useState({}); // {nombre: cuántos agregados}
  if (!rel.length) return null;
  function add(f) {
    onQuickAdd(f.item, f.cat);
    setCount(c => {
      const next = { ...c, [f.item.n]: (c[f.item.n] || 0) + 1 };
      if (onTotalChange) {
        const sum = rel.reduce((s, r) => s + (next[r.item.n] || 0) * r.item.from, 0);
        onTotalChange(sum);
      }
      return next;
    });
  }
  return (
    <div className="block related">
      <span className="block-label">Acompáñalo con · y queda redondo</span>
      <div className="rel-row">
        {rel.map((f, i) => {
          const n = count[f.item.n] || 0;
          return (
            <div key={i} className={"rel-card " + (n ? "is-added" : "")}>
              <div className="rel-ph"><Placeholder label={f.item.n} kind="" img={window.PHOTOS[f.item.n]} /></div>
              <div className="rel-info">
                <span className="rel-name">{f.item.n}</span>
                <span className="rel-price">
                  {n
                    ? <span className="rel-added"><Icon d={I.check} size={12} /> Agregado{n > 1 ? " ×" + n : ""} · en tu pedido</span>
                    : priceLabel(f.item)}
                </span>
              </div>
              <button className={"rel-add " + (n ? "ok" : "")} onClick={() => add(f)} aria-label={"Agregar " + f.item.n}>
                <Icon d={I.plus} size={16} />
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { PdfModal, getWeeklyPromo, WeeklyPromo, SuggestedBanner, getRelated, RelatedItems });
