﻿/* ComboConfig modal.
   Lets the user pick which items fill each slot (e.g. 15 recipientes, 15 filetes)
   and never allows more than the combo includes. */

function ItemPicker({ item, qty, canAdd, onInc, onDec }) {
  return (
    <div className={'cfg-item' + (qty > 0 ? ' on' : '')}>
      <div className="cfg-thumb" style={{ background: item.img ? 'var(--eo-white)' : `color-mix(in srgb, ${item.color} 18%, white)` }}>
        {item.img ? <img src={item.img} alt="" /> : <span className="cfg-dot" style={{ background: item.color }}></span>}
      </div>
      <div className="cfg-item-info">
        <div className="cfg-item-name">{item.name}</div>
        {item.unit && <div className="cfg-item-unit">{item.unit}</div>}
      </div>
      {qty > 0 ? (
        <div className="stepper sm">
          <button onClick={onDec} aria-label="Quitar"><Icon name={qty === 1 ? 'Trash' : 'Minus'} size={qty === 1 ? 13 : 14}/></button>
          <span>{qty}</span>
          <button onClick={onInc} disabled={!canAdd} aria-label="Agregar"><Icon name="Plus" size={14}/></button>
        </div>
      ) : (
        <button className="cfg-add" onClick={onInc} disabled={!canAdd} aria-label="Agregar"><Icon name="Plus" size={18}/></button>
      )}
    </div>
  );
}

function ComboSlot({ slot, sel, onInc, onDec, onFill }) {
  const pool = window.EO_DATA.comboPool(slot.pool);
  const total = Object.values(sel).reduce((s, n) => s + n, 0);
  const full = total >= slot.qty;
  const pct = Math.min(100, Math.round((total / slot.qty) * 100));

  // group pool items by their `group` label
  const groups = {};
  pool.forEach((it) => { (groups[it.group] = groups[it.group] || []).push(it); });
  const groupNames = Object.keys(groups);

  return (
    <section className="cfg-slot">
      <div className="cfg-slot-head">
        <div>
          <h4 className="cfg-slot-title">{slot.label}</h4>
          {slot.sub && <p className="cfg-slot-sub">{slot.sub}</p>}
        </div>
        <div className={'cfg-count' + (full ? ' full' : '')}>
          {full ? <Icon name="Check" size={16}/> : null}
          <span><b>{total}</b> / {slot.qty}</span>
        </div>
      </div>

      <div className="cfg-bar"><span className={'cfg-bar-fill' + (full ? ' full' : '')} style={{ width: pct + '%' }}></span></div>

      <div className="cfg-slot-tools">
        <span className="cfg-help">
          {full ? '¡Cupo completo!' : `Elige ${slot.qty - total} ${slot.unit} más`}
        </span>
        <button className="cfg-fill" onClick={() => onFill(slot)} disabled={full}>
          <Icon name="Sparkles" size={14}/> Autocompletar
        </button>
      </div>

      {groupNames.map((g) => (
        <React.Fragment key={g}>
          {groupNames.length > 1 && <div className="cfg-group-label">{g}</div>}
          <div className="cfg-grid">
            {groups[g].map((it) => (
              <ItemPicker
                key={it.id} item={it}
                qty={sel[it.id] || 0}
                canAdd={!full}
                onInc={() => onInc(slot, it.id)}
                onDec={() => onDec(slot, it.id)}
              />
            ))}
          </div>
        </React.Fragment>
      ))}
    </section>
  );
}

function ComboConfig({ combo, initial, onClose, onConfirm }) {
  const [sel, setSel] = React.useState(() => {
    const base = {};
    combo.slots.forEach((s) => { base[s.id] = (initial && initial[s.id]) ? { ...initial[s.id] } : {}; });
    return base;
  });

  const slotTotal = (id) => Object.values(sel[id] || {}).reduce((s, n) => s + n, 0);

  const inc = (slot, itemId) => setSel((prev) => {
    if (slotTotal(slot.id) >= slot.qty) return prev;
    const s = { ...prev, [slot.id]: { ...prev[slot.id], [itemId]: (prev[slot.id][itemId] || 0) + 1 } };
    return s;
  });
  const dec = (slot, itemId) => setSel((prev) => {
    const cur = (prev[slot.id][itemId] || 0) - 1;
    const slotSel = { ...prev[slot.id] };
    if (cur <= 0) delete slotSel[itemId]; else slotSel[itemId] = cur;
    return { ...prev, [slot.id]: slotSel };
  });
  const fill = (slot) => setSel((prev) => {
    const pool = window.EO_DATA.comboPool(slot.pool);
    const slotSel = { ...prev[slot.id] };
    let total = Object.values(slotSel).reduce((s, n) => s + n, 0);
    let i = 0;
    while (total < slot.qty && pool.length) {
      const it = pool[i % pool.length];
      slotSel[it.id] = (slotSel[it.id] || 0) + 1;
      total++; i++;
    }
    return { ...prev, [slot.id]: slotSel };
  });

  const remaining = combo.slots.reduce((acc, s) => {
    const left = s.qty - slotTotal(s.id);
    if (left > 0) acc.push(`${left} ${s.unit}`);
    return acc;
  }, []);
  const complete = remaining.length === 0;

  return (
    <React.Fragment>
      <div className="cfg-scrim" onClick={onClose}></div>
      <div className="cfg-modal" role="dialog" aria-label={'Personalizar ' + combo.name}>
        <header className="cfg-head" style={{ background: combo.color }}>
          <div className="cfg-head-row">
            <div>
              <div className="cfg-eyebrow">Personaliza tu combo</div>
              <h3 className="cfg-title">{combo.name}</h3>
            </div>
            <button className="cfg-close" onClick={onClose} aria-label="Cerrar"><Icon name="X" size={20}/></button>
          </div>
          <div className="cfg-head-meta">
            <span className="cfg-price">{window.eoMoney(combo.price)}</span>
            <span className="cfg-dot-sep">·</span>
            <span className="cfg-incl"><Icon name="Truck" size={14}/> Incluye domicilio</span>
          </div>
        </header>

        <div className="cfg-body">
          <p className="cfg-intro">
            Tú eliges qué llevas. Marca los productos hasta completar cada cupo —
            <b> no puedes pasarte de lo que incluye el combo.</b>
          </p>

          {combo.slots.map((slot) => (
            <ComboSlot key={slot.id} slot={slot} sel={sel[slot.id]} onInc={inc} onDec={dec} onFill={fill} />
          ))}

          {combo.includes.length > 0 && (
            <section className="cfg-includes">
              <div className="cfg-group-label">También incluye (ya va en tu combo)</div>
              <ul className="cfg-incl-list">
                {combo.includes.map((it, i) => (
                  <li key={i}><Icon name="Check" size={15}/> {it}</li>
                ))}
              </ul>
            </section>
          )}
        </div>

        <footer className="cfg-foot">
          <span className={'cfg-status' + (complete ? ' ok' : '')}>
            {complete
              ? <React.Fragment><Icon name="Check" size={17}/> ¡Todo listo para agregar!</React.Fragment>
              : <React.Fragment>Te falta elegir: <b>{remaining.join(' · ')}</b></React.Fragment>}
          </span>
          <div className="cfg-foot-btns">
            <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
            <button className="btn btn-primary" disabled={!complete} onClick={() => onConfirm(sel)}>
              <Icon name="Check" size={18}/> {initial ? 'Guardar cambios' : 'Agregar al pedido'}
            </button>
          </div>
        </footer>
      </div>
    </React.Fragment>
  );
}

window.ComboConfig = ComboConfig;
