// js/components/widgets/SkuSurpriseModal.jsx
// [Wave 14 v223.39 20260520] Extraído de ReceberFrete.jsx L641-681 + state surpriseForm L73
// Modal SKU surpresa — form completo (product/qty/reason/evidence) + handler interno
//
// Props:
//   show, products, selectedNote, actionInFlight,
//   onSubmit (form) => Promise,
//   onClose () => void
(function(){
  'use strict';
  const {useState, useEffect} = React;

  function Field(p) {
    return (
      <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: '#374151' }}>{p.label}</span>
        {p.children}
      </label>
    );
  }

  function SkuSurpriseModal(props){
    const show = props.show;
    const products = props.products || [];
    const actionInFlight = props.actionInFlight;
    const onSubmit = props.onSubmit;
    const onClose = props.onClose;
    const Modal = window.Modal;
    const [form, setForm] = useState({ product_id: '', qty: 1, reason: '', evidence: '' });

    useEffect(() => {
      if (show) setForm({ product_id: '', qty: 1, reason: '', evidence: '' });
    }, [show]);

    if (!Modal) {
      console.error('[ZNX v224.71] Modal ausente');
      if(window.Sentry) window.Sentry.captureMessage('[v224.71] Modal undefined em widget', 'warning');
      if(typeof window.ZNX_toast === 'function') window.ZNX_toast('⚠ Modal indisponível · pressione Ctrl+Shift+R', 'warning');
      return null;
    }
    if (!show) return null;

    function handleSubmit() {
      onSubmit(form);
    }

    return (
      <Modal title="🆕 SKU Surpresa" onClose={onClose}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ padding: 12, background: '#EFF6FF', borderRadius: 8, fontSize: 12, color: '#1E40AF' }}>
            Use quando chegar um SKU que não estava na lista da nota.
            Admin recebe pendência e decide aceitar (cria item retroativo) ou bloquear.
          </div>
          <Field label="Produto*">
            <select value={form.product_id} onChange={e => setForm(f => Object.assign({}, f, { product_id: e.target.value }))}>
              <option value="">Selecione...</option>
              {products.map(p =>
                <option key={p.id} value={p.id}>{p.name}{p.volume ? ' · ' + p.volume : ''}</option>
              )}
            </select>
          </Field>
          <Field label="Quantidade*">
            <input type="number" min="1" value={form.qty}
                   onChange={e => setForm(f => Object.assign({}, f, { qty: e.target.value }))} />
          </Field>
          <Field label="Motivo / observação">
            <textarea rows={2} value={form.reason}
                      onChange={e => setForm(f => Object.assign({}, f, { reason: e.target.value }))}
                      placeholder="Ex: chegou caixa extra do mesmo perfume sem aviso" />
          </Field>
          <Field label="Evidência (URLs / descrição*)">
            <textarea rows={2} value={form.evidence}
                      onChange={e => setForm(f => Object.assign({}, f, { evidence: e.target.value }))}
                      placeholder="Cole URL(s) das fotos ou descrição. Pelo menos 1 obrigatório." />
            <span style={{ fontSize: 11, color: '#9CA3AF', marginTop: 2 }}>
              Separe múltiplas por vírgula ou nova linha. Upload via Storage virá em onda futura.
            </span>
          </Field>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <button className="btn-outline" onClick={onClose} disabled={actionInFlight}>Cancelar</button>
            <button className="btn-gold" onClick={handleSubmit} disabled={actionInFlight}>
              {actionInFlight ? '⏳ Enviando...' : 'Enviar pra admin'}
            </button>
          </div>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.SkuSurpriseModal = SkuSurpriseModal;
  window.SkuSurpriseModal = SkuSurpriseModal;
})();
