/* ============================================================
   MENU — tarjeta de plato + modal de personalización (estilo Yanuba)
   ============================================================ */
const { RICE: _RICE, DRINKS: _DRINKS } = window;
const PHOTOS = window.PHOTOS;
// bebida incluida por defecto (no aparece como opción seleccionable)
const _DRINK_DEFAULT = (_DRINKS.find(d => d.included) || _DRINKS[0]).id;

/* ---- Tarjeta de plato ---- */
function MenuCard({ it, cat, onOpen, store }) {
  const av = !store || itemAvailable(store, it.n);
  return (
    <article className={"card " + (av ? "" : "is-off")} onClick={() => av && onOpen(it, cat)}>
      <div className="card-ph">
        <Placeholder label={it.n} kind="foto" img={PHOTOS[it.n] || null} fit={it.n === "Arroz Marinero" || it.n === "Arroz de Camarón" ? "fill" : (it.n === "Limonada Cerezada" || it.n === "Limonada Natural") ? "cover" : "contain"} />
        {av && it.tag && <span className={"badge " + tagClass(it.tag)}>{it.tag}</span>}
        {!av && <span className="soldout">Agotado</span>}
      </div>
      <div className="card-body">
        <h3 className="card-name">{it.n}</h3>
        {it.d && <p className="card-desc">{it.d}</p>}
        <div className="card-foot">
          <span className="card-price">{priceLabel(it)}</span>
          <span className={"card-add c-" + (cat.c || "deep")}>{av ? <Icon d={I.plus} size={18} /> : <Icon d={I.close} size={16} />}</span>
        </div>
      </div>
    </article>
  );
}

/* ---- Modal de personalización ---- */
function ProductModal({ item, cat, store, onAdd, onQuickAdd, onClose }) {
  const inc = (item.includes || cat.includes || {});
  const serves = item.serves || cat.serves;
  const [rice, setRice] = useState(_RICE[0].id);
  const [drink, setDrink] = useState(_DRINK_DEFAULT);
  const [qty, setQty] = useState(1);
  const [notes, setNotes] = useState("");
  const [added, setAdded] = useState(false);
  const [relatedTotal, setRelatedTotal] = useState(0);

  useEffect(() => {
    document.body.style.overflow = "hidden";
    const onEsc = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onEsc);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onEsc); };
  }, []);

  const drinkObj = inc.drink ? _DRINKS.find(d => d.id === drink) : null;
  const drinkExtra = drinkObj ? (drinkObj.extra || 0) : 0;
  const unit = item.from + drinkExtra;
  const total = unit * qty + relatedTotal;

  function add() {
    const riceObj = inc.rice ? _RICE.find(r => r.id === rice) : null;
    onAdd({
      uid: "L" + Date.now() + Math.random().toString(36).slice(2, 6),
      name: item.n, catName: cat.name,
      unitPrice: unit, ranged: !!(item.to && item.to !== item.from), from: item.from, to: item.to, drinkExtra,
      weights: item.weights || null,
      size: null,
      qty, rice: riceObj ? riceObj.label : null,
      drink: drinkObj ? drinkObj.label + (drinkExtra ? " (+" + fmt(drinkExtra) + ")" : "") : null,
      notes: notes.trim(),
    });
    setAdded(true);
    setTimeout(onClose, 650);
  }

  return (
    <div className="overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-x" onClick={onClose} aria-label="Cerrar"><Icon d={I.close} size={22} /></button>
        <div className="modal-media">
          <Placeholder label={item.n} kind="foto" className="modal-ph" img={PHOTOS[item.n] || null} fit={item.n === "Arroz Marinero" || item.n === "Arroz de Camarón" ? "fill" : (item.n === "Limonada Cerezada" || item.n === "Limonada Natural") ? "cover" : "contain"} />
          {item.tag && <span className={"badge " + tagClass(item.tag)}>{item.tag}</span>}
        </div>
        <div className="modal-info">
          <span className="kicker">{cat.kicker || cat.name}</span>
          <h2 className="modal-name">{item.n}</h2>
          <div className="modal-price">{priceLabel(item)}
            {item.to && item.to !== item.from && <small> · según tamaño</small>}
          </div>
          {item.d && <p className="modal-desc">{item.d}</p>}

          {item.ing && (
            <div className="block">
              <span className="block-label">Ingredientes</span>
              <div className="chips">{item.ing.map((g, i) => <span key={i} className="chip">{g}</span>)}</div>
            </div>
          )}

          {serves && (
            <div className="block">
              <span className="block-label">Incluye</span>
              <p className="serves"><Icon d={I.check} size={15} stroke="var(--coral)" /> {serves}</p>
            </div>
          )}

          <div className="modal-custom">
            {inc.rice && (
              <div className="block">
                <span className="block-label">Elige el arroz</span>
                <div className="opts">
                  {_RICE.map(r => (
                    <button key={r.id} className={"opt " + (rice === r.id ? "on" : "")}
                      onClick={() => setRice(r.id)}>{r.label}</button>
                  ))}
                </div>
              </div>
            )}
            {inc.drink && (
              <div className="block">
                <span className="block-label">Elige tu bebida incluida</span>
                <div className="opts">
                  {_DRINKS.map(d => (
                    <button key={d.id} className={"opt " + (drink === d.id ? "on" : "")}
                      onClick={() => setDrink(d.id)}>
                      {d.label}{d.extra ? <span className="opt-extra">+{fmt(d.extra)}</span> : null}
                    </button>
                  ))}
                </div>
              </div>
            )}
            <div className="block">
              <span className="block-label">Notas especiales</span>
              <input className="notes" value={notes} maxLength={80}
                onChange={(e) => setNotes(sanitizeBase(e.target.value, 80))}
                placeholder="Sin cebolla, extra patacón, bien dorado…" />
            </div>
          </div>

          {onQuickAdd && <RelatedItems item={item} cat={cat} store={store}
            onQuickAdd={onQuickAdd}
            onTotalChange={(sum) => setRelatedTotal(sum)} />}

          <div className="modal-foot">
            <Stepper value={qty} onChange={setQty} />
            <button className={"btn-add " + (added ? "ok" : "")} onClick={add} disabled={added}>
              {added
                ? <><Icon d={I.check} size={18} /> ¡Agregado!</>
                : <>Agregar · {fmt(total)}{item.to && item.to !== item.from ? "+" : ""}</>}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MenuCard, ProductModal });
