/* Snack Overflow — Configurable Product Builder */

function ConfigBuilder({ item, onAdd, accent }) {
  const { useState, useMemo } = React;

  const [selections, setSelections] = useState(() => {
    const init = {};
    item.steps.forEach(step => {
      init[step.id] = step.type === "pick-one" ? null : [];
    });
    return init;
  });
  const [qty, setQty] = useState(1);

  const handlePickOne = (stepId, optionId) => {
    setSelections(prev => ({ ...prev, [stepId]: prev[stepId] === optionId ? null : optionId }));
  };

  const handlePickMany = (stepId, optionId) => {
    setSelections(prev => {
      const cur = prev[stepId] || [];
      return { ...prev, [stepId]: cur.includes(optionId) ? cur.filter(id => id !== optionId) : [...cur, optionId] };
    });
  };

  /* Summary & pricing */
  const summaryLines = useMemo(() => {
    const lines = [];
    item.steps.forEach(step => {
      const sel = selections[step.id];
      if (step.type === "pick-one" && sel) {
        const opt = step.options.find(o => o.id === sel);
        if (opt) lines.push({ name: opt.name, price: opt.price });
      } else if (Array.isArray(sel)) {
        sel.forEach(optId => {
          const opt = step.options.find(o => o.id === optId);
          if (opt) lines.push({ name: opt.name, price: opt.price });
        });
      }
    });
    return lines;
  }, [selections, item.steps]);

  const unitPrice = summaryLines.reduce((s, l) => s + l.price, 0);

  const canAdd = item.steps.every(step => {
    if (!step.required) return true;
    const sel = selections[step.id];
    return step.type === "pick-one" ? sel !== null : (sel && sel.length > 0);
  });

  const handleAdd = () => {
    if (!canAdd) return;
    onAdd({ itemId: item.id, name: item.name, selections: { ...selections }, summaryLines, unitPrice, qty });
  };

  return (
    <div className="bldr">
      <div className="bldr-scroll">
        <div className="bldr-head">
          <h2 className="bldr-title">Build your {item.name}</h2>
          <p className="bldr-sub">Customise it just the way you like it</p>
        </div>

        {item.steps.map(step => (
          <div key={step.id} className="bldr-step">
            <div className="bldr-step-hdr">
              <h3 className="bldr-step-title">{step.title}</h3>
              {step.required
                ? <span className="bldr-req">Required</span>
                : <span className="bldr-opt">Optional</span>}
            </div>

            {step.type === "pick-one" ? (
              <div className="bldr-picks">
                {step.options.map(opt => {
                  const on = selections[step.id] === opt.id;
                  return (
                    <button key={opt.id}
                      className={`bldr-pick ${on ? "bldr-pick--on" : ""}`}
                      style={on ? { borderColor: accent, background: accent + "18" } : undefined}
                      onClick={() => handlePickOne(step.id, opt.id)}>
                      <span className="bldr-pick-name">{opt.name}</span>
                      <span className="bldr-pick-price">R{opt.price.toFixed(2)}</span>
                    </button>
                  );
                })}
              </div>
            ) : (
              <div className="bldr-toggles">
                {step.options.map(opt => {
                  const on = (selections[step.id] || []).includes(opt.id);
                  return (
                    <button key={opt.id}
                      className={`bldr-toggle ${on ? "bldr-toggle--on" : ""}`}
                      style={on ? { borderColor: accent, background: accent + "12" } : undefined}
                      onClick={() => handlePickMany(step.id, opt.id)}>
                      <span className="bldr-toggle-ck" style={on ? { background: accent, borderColor: accent } : undefined}>
                        {on && <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2.5 6l2.5 2.5 4.5-4.5" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                      </span>
                      <span className="bldr-toggle-name">{opt.name}</span>
                      <span className="bldr-toggle-price">{opt.price > 0 ? `+R${opt.price.toFixed(2)}` : "Free"}</span>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        ))}

        {summaryLines.length > 0 && (
          <div className="bldr-summary">
            <div className="bldr-summary-hd">Your order</div>
            {summaryLines.map((l, i) => (
              <div key={i} className="bldr-summary-row">
                <span>{l.name}</span><span>R{l.price.toFixed(2)}</span>
              </div>
            ))}
            <div className="bldr-summary-total">
              <span>Total per item</span><span>R{unitPrice.toFixed(2)}</span>
            </div>
          </div>
        )}
      </div>

      <div className="bldr-foot">
        <div className="bldr-qty">
          <button className="qty-btn qty-minus" onClick={() => setQty(q => Math.max(1, q - 1))}>−</button>
          <span className="qty-val">{qty}</span>
          <button className="qty-btn qty-plus" style={{ background: accent, color: textOnColor(accent) }}
            onClick={() => setQty(q => q + 1)}>+</button>
        </div>
        <button className="bldr-add" disabled={!canAdd}
          style={{ background: canAdd ? accent : "#e5e5e5", color: canAdd ? textOnColor(accent) : "#999" }}
          onClick={handleAdd}>
          {canAdd ? `Add to Cart · R${(unitPrice * qty).toFixed(2)}` : "Select required options"}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ConfigBuilder });
