// js/components/common/CancelQuoteModal.jsx
// Modal pra cancelar orçamento exigindo motivo (V2 — Análise de Cancelamento R$133k).
// Criado em 2026-05-06 (sistema 4 onda V2).
//
// Props:
//   quote: orçamento sendo cancelado (mostra number/cliente/total no header)
//   client: cliente do orçamento (opcional, pra mostrar nome)
//   onConfirm: async (reason) => {} — callback que recebe o motivo escolhido
//   onClose: fecha modal
//
// 6 motivos pré-definidos + Outro (text livre). Backend exige reason não vazio.
// Deps runtime: Modal, fmt
(function() {
  'use strict';
  const {useState} = React;

  const MOTIVOS = [
    { id:'preco_alto', label:'💰 Preço alto pro cliente', emoji:'💰' },
    { id:'sem_estoque', label:'📦 Sem estoque do produto desejado', emoji:'📦' },
    { id:'cliente_desistiu', label:'🚪 Cliente desistiu / não respondeu', emoji:'🚪' },
    { id:'erro_cadastro', label:'✏️ Erro de cadastro / vai refazer', emoji:'✏️' },
    { id:'comprou_concorrente', label:'😢 Cliente comprou de concorrente', emoji:'😢' },
    { id:'outro', label:'📝 Outro motivo (descrever)', emoji:'📝' },
  ];

  function CancelQuoteModal({ quote, client, onConfirm, onClose }) {
    const [selected, setSelected] = useState(null);
    const [otherText, setOtherText] = useState('');
    const [submitting, setSubmitting] = useState(false);

    const isOther = selected === 'outro';
    const reasonText = isOther
      ? otherText.trim()
      : (MOTIVOS.find(m => m.id === selected)?.label.replace(/^[^\s]+\s/, '') || '');

    const canConfirm = !!selected && (!isOther || otherText.trim().length >= 3);

    async function handleConfirm() {
      if (!canConfirm || submitting) return;
      setSubmitting(true);
      try {
        await onConfirm(reasonText);
        // onClose é responsabilidade do caller (ele chama após o sucesso)
      } catch (e) {
        console.error('[ZNX] CancelQuoteModal onConfirm error:', e);
        setSubmitting(false);
      }
    }

    return (
      <div className="modal-overlay" onClick={e => { if (e.target === e.currentTarget && !submitting) onClose(); }}>
        <div className="modal" style={{ maxWidth: 520 }}>
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: '#DC2626', marginBottom: 4 }}>
              ⚠️ Cancelar Orçamento
            </div>
            <div style={{ fontSize: 13, color: '#6B7280' }}>
              <strong style={{ color: '#1B2A4A' }}>{quote?.number || '—'}</strong>
              {client?.name && <span> · {client.name}</span>}
              {quote?.total && <span> · {typeof fmt === 'function' ? fmt(quote.total) : 'R$ ' + Number(quote.total).toFixed(2)}</span>}
            </div>
          </div>

          <div style={{ fontSize: 12, color: '#9CA3AF', textTransform: 'uppercase', letterSpacing: 1, fontWeight: 700, marginBottom: 10 }}>
            Por que está sendo cancelado?
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
            {MOTIVOS.map(m => (
              <button
                key={m.id}
                onClick={() => setSelected(m.id)}
                disabled={submitting}
                style={{
                  textAlign: 'left',
                  padding: '11px 14px',
                  borderRadius: 8,
                  border: selected === m.id ? '2px solid #DC2626' : '1.5px solid #E4E7EC',
                  background: selected === m.id ? '#FEE2E2' : '#FFFFFF',
                  color: selected === m.id ? '#991B1B' : '#374151',
                  cursor: submitting ? 'not-allowed' : 'pointer',
                  fontSize: 13.5,
                  fontWeight: selected === m.id ? 600 : 500,
                  fontFamily: 'inherit',
                  transition: 'all .15s',
                }}
              >
                {m.label}
              </button>
            ))}
          </div>

          {isOther && (
            <div style={{ marginBottom: 14 }}>
              <label style={{ fontSize: 11, color: '#6B7280', textTransform: 'uppercase', letterSpacing: 1, fontWeight: 700, marginBottom: 5, display: 'block' }}>
                Descreva o motivo (mín. 3 caracteres)
              </label>
              <textarea
                value={otherText}
                onChange={e => setOtherText(e.target.value)}
                disabled={submitting}
                placeholder="Ex: produto chegou danificado e cliente trocou por outro modelo..."
                maxLength={500}
                style={{
                  width: '100%',
                  minHeight: 70,
                  padding: '10px 12px',
                  border: '1.5px solid #E4E7EC',
                  borderRadius: 8,
                  fontSize: 13,
                  fontFamily: 'inherit',
                  resize: 'vertical',
                  boxSizing: 'border-box',
                  outline: 'none',
                }}
              />
              <div style={{ fontSize: 11, color: '#9CA3AF', textAlign: 'right', marginTop: 3 }}>
                {otherText.length}/500
              </div>
            </div>
          )}

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
            <button className="btn-outline" onClick={onClose} disabled={submitting}>
              ← Voltar
            </button>
            <button
              className="btn-danger"
              onClick={handleConfirm}
              disabled={!canConfirm || submitting}
              style={{ opacity: canConfirm && !submitting ? 1 : 0.5 }}
            >
              {submitting ? '⏳ Cancelando...' : '✕ Confirmar Cancelamento'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Namespace
  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.CancelQuoteModal = CancelQuoteModal;
  window.CancelQuoteModal = CancelQuoteModal;

  // Marca onda V2
  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.CancelQuoteModal = true;
})();
