/** Crumbs — build-your-own-box flavour picker sheet */
const { useState: useBState, useEffect: useBEffect } = React;

const BoxBuilderSheet = ({ open, ctx, onClose, onAdd }) => {
  const [counts, setCounts] = useBState({});
  useBEffect(() => { if (open) setCounts({}); }, [open, ctx?.item?.id, ctx?.vi]);

  if (!ctx) return <Sheet open={open} onClose={onClose}><div/></Sheet>;
  const { item, vi } = ctx;
  const v = item.variants[vi];
  const size = v.count || 0;
  const flavors = item.boxFlavors || [];

  const picked = Object.values(counts).reduce((s, n) => s + n, 0);
  const remaining = size - picked;
  const total = flavors.reduce((s, f) => s + (counts[f.id] || 0) * f.price, 0);
  const canAdd = picked === size && size > 0;

  const bump = (id, delta) => setCounts(c => {
    if (delta > 0 && remaining <= 0) return c;
    return { ...c, [id]: Math.max(0, (c[id] || 0) + delta) };
  });

  return (
    <Sheet open={open} onClose={onClose}>
      <div style={{ padding: '4px 22px 22px' }}>
        <div className="serif-italic" style={{ fontSize: 13, color: 'var(--ink-3)' }}>build your box</div>
        <div className="serif" style={{ fontSize: 28, letterSpacing: '-0.02em', marginBottom: 4 }}>
          {item.name} — {v.label}
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', marginBottom: 18 }}>
          pick {size} cookies, any mix of flavours. {remaining > 0 ? `${remaining} left to pick` : 'all picked!'}
        </div>

        <div style={{ display: 'grid', gap: 8 }}>
          {flavors.map(f => {
            const n = counts[f.id] || 0;
            return (
              <div key={f.id} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '12px 14px', borderRadius: 'var(--radius-md)',
                border: '1.5px solid ' + (n > 0 ? 'var(--red)' : 'var(--line)'),
                background: n > 0 ? 'rgba(255,48,48,0.08)' : 'transparent',
                transition: 'all 0.15s',
              }}>
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: n > 0 ? 600 : 500 }}>{f.label}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{fmt(f.price)} each</div>
                </div>
                <div style={{
                  display: 'flex', alignItems: 'center',
                  background: 'rgba(26,15,11,0.06)', borderRadius: 6, overflow: 'hidden',
                }}>
                  <button onClick={() => bump(f.id, -1)} disabled={n === 0} style={{ padding: '7px 11px', opacity: n === 0 ? 0.35 : 1 }}>
                    <Icon name="minus" size={13}/>
                  </button>
                  <span style={{ minWidth: 20, textAlign: 'center', fontWeight: 600, fontSize: 13 }}>{n}</span>
                  <button onClick={() => bump(f.id, 1)} disabled={remaining <= 0} style={{ padding: '7px 11px', opacity: remaining <= 0 ? 0.35 : 1 }}>
                    <Icon name="plus" size={13}/>
                  </button>
                </div>
              </div>
            );
          })}
        </div>

        <div style={{
          marginTop: 18, padding: '14px 0', borderTop: '1px dashed var(--line)',
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{picked} / {size} picked</div>
            <div className="serif" style={{ fontSize: 26, color: 'var(--ink)' }}>{fmt(total)}</div>
          </div>
          <button
            onClick={() => canAdd && onAdd(flavors.filter(f => counts[f.id] > 0).map(f => ({ id: f.id, qty: counts[f.id] })))}
            disabled={!canAdd}
            style={{
              padding: '13px 22px',
              background: canAdd ? 'var(--red)' : 'rgba(26,15,11,0.15)',
              color: canAdd ? 'var(--cream)' : 'var(--ink-3)',
              borderRadius: 'var(--radius-md)', fontSize: 14, fontWeight: 600,
              display: 'flex', alignItems: 'center', gap: 8,
              cursor: canAdd ? 'pointer' : 'not-allowed',
            }}>
            add to box <Icon name="arrow-right" size={14}/>
          </button>
        </div>
      </div>
    </Sheet>
  );
};

window.BoxBuilderSheet = BoxBuilderSheet;
