/** Options open inline, in the list, right under the dish — no card, no overlay.
 *  The row unrolls; the menu keeps its place behind it. */
function ItemOptions({ item, onAdd, onClose }) {
  const [qty, setQty] = React.useState(1);
  const [open, setOpen] = React.useState(false);
  const [sel, setSel] = React.useState(() => {
    const s = {};
    (item.options || []).forEach((g, i) => { s[i] = g.multi ? [] : (g.required ? 0 : null); });
    return s;
  });

  React.useEffect(() => { const r = requestAnimationFrame(() => setOpen(true)); return () => cancelAnimationFrame(r); }, []);

  const groups = item.options || [];
  const extra = groups.reduce((sum, g, i) => {
    const v = sel[i];
    if (g.multi) return sum + (v || []).reduce((a, j) => a + g.choices[j].delta, 0);
    return sum + (v == null ? 0 : g.choices[v].delta);
  }, 0);
  const unit = parse(item.price) + extra;
  const missing = groups.some((g, i) => g.required && !g.multi && sel[i] == null);

  const pick = (gi, ci, multi) => setSel(s => {
    if (!multi) return { ...s, [gi]: ci };
    const cur = s[gi] || [];
    return { ...s, [gi]: cur.includes(ci) ? cur.filter(x => x !== ci) : [...cur, ci] };
  });

  const chosenNames = groups.flatMap((g, i) => {
    const v = sel[i];
    if (g.multi) return (v || []).map(j => g.choices[j].name);
    return v == null ? [] : [g.choices[v].name];
  });

  return (
    <div style={{
      display: "grid", gridTemplateRows: open ? "1fr" : "0fr",
      transition: "grid-template-rows var(--dur-slow) var(--ease-out)"
    }}>
      <div style={{ overflow: "hidden", minHeight: 0 }}>
        <div style={{
          borderLeft: "1px solid var(--ink-600)", paddingLeft: 12, margin: "2px 0 16px",
          opacity: open ? 1 : 0, transition: "opacity var(--dur-base) var(--ease-out) 90ms"
        }}>
          {groups.map((g, gi) => (
            <div key={g.title} style={{ marginBottom: 14 }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 7, marginBottom: 8 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 9.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-300)" }}>{g.title}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 8.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-500)" }}>
                  {g.required ? "obrigatório" : g.multi ? "opcional" : ""}
                </span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                {g.choices.map((c, ci) => {
                  const on = g.multi ? (sel[gi] || []).includes(ci) : sel[gi] === ci;
                  return (
                    <button key={c.name} type="button" onClick={() => pick(gi, ci, g.multi)}
                      style={{
                        display: "flex", alignItems: "center", gap: 9, width: "100%", textAlign: "left",
                        padding: "7px 0", cursor: "pointer", background: "none", border: "none", color: "var(--white)"
                      }}>
                      <span style={{
                        flex: "0 0 auto", width: 14, height: 14,
                        borderRadius: g.multi ? 3 : 999,
                        border: "1.5px solid " + (on ? "var(--white)" : "var(--ink-500)"),
                        background: on ? "var(--white)" : "transparent",
                        transition: "background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out)"
                      }} />
                      <span style={{ flex: 1, fontSize: 14, fontWeight: on ? 600 : 400, color: on ? "var(--white)" : "var(--ink-200)" }}>{c.name}</span>
                      {c.delta > 0 && (
                        <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 11, color: "var(--ink-300)" }}>+ {brl(c.delta)}</span>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}

          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <QuantityStepper value={qty} min={1} onChange={setQty} />
            <button type="button" disabled={missing}
              onClick={() => { onAdd({ ...item, price: brl(unit), options: chosenNames }, qty); onClose(); }}
              style={{
                flex: 1, height: 40, cursor: missing ? "not-allowed" : "pointer",
                background: missing ? "var(--ink-700)" : "var(--white)",
                color: missing ? "var(--ink-400)" : "var(--black)",
                border: "none", borderRadius: "var(--radius-md)",
                fontFamily: "var(--font-display)", fontWeight: 900, fontStretch: "125%", textTransform: "uppercase", fontSize: 12
              }}>Adicionar {brl(unit * qty)}</button>
            <button type="button" onClick={onClose} aria-label="Fechar opções"
              style={{ flex: "0 0 auto", width: 34, height: 40, background: "none", border: "none", color: "var(--ink-400)", cursor: "pointer" }}>
              <Icon d={P.x} size={16} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { ItemOptions });
