// js/components/common/DiscountReasonModal.jsx
// Modal pra vendedora justificar pedido de desconto — V6 (sistema 4).
// Motivo é OBRIGATÓRIO. Admin vê motivo antes de aprovar.
// Criado em 2026-05-06.
//
// Props:
//   totalDesconto: valor total de desconto solicitado (mostra no header)
//   totalLiquido: total da venda após desconto
//   client: cliente (mostra nome)
//   onConfirm: async (reason) => {} — callback que recebe motivo escolhido
//   onClose: fecha modal
//
// Deps runtime: fmt
(function() {
  'use strict';
  const {useState} = React;

  const MOTIVOS = [
    { id:'cliente_fiel', label:'⭐ Cliente fiel — fidelizar', emoji:'⭐' },
    { id:'volume_alto', label:'📦 Volume alto — atacado / valor médio acima', emoji:'📦' },
    { id:'cliente_novo', label:'🌱 Cliente novo — primeiro pedido', emoji:'🌱' },
    { id:'concorrencia', label:'🥊 Concorrência — comparou preço', emoji:'🥊' },
    { id:'fechar_meta', label:'🎯 Fechar venda — bater minha meta', emoji:'🎯' },
    { id:'outro', label:'📝 Outro motivo (descrever)', emoji:'📝' },
  ];

  function DiscountReasonModal({ totalDesconto, totalLiquido, 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 >= 5);

    async function handleConfirm() {
      if (!canConfirm || submitting) return;
      setSubmitting(true);
      try {
        await onConfirm(reasonText);
      } catch (e) {
        console.error('[ZNX] DiscountReasonModal onConfirm error:', e);
        setSubmitting(false);
      }
    }

    return (
      <div className="modal-overlay" onClick={e => { if (e.target === e.currentTarget && !submitting) onClose(); }}>
        <div className="modal" style={{ maxWidth: 540 }}>
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: '#EA580C', marginBottom: 4 }}>
              💰 Pedido de Desconto
            </div>
            <div style={{ fontSize: 13, color: '#6B7280' }}>
              {client?.name && <span><strong style={{ color: '#1B2A4A' }}>{client.name}</strong> · </span>}
              Líquido <strong style={{ color: '#16A34A' }}>{fmtMoney(totalLiquido)}</strong>
              {totalDesconto > 0 && <span> · Desconto <strong style={{ color: '#DC2626' }}>−{fmtMoney(totalDesconto)}</strong></span>}
            </div>
          </div>

          <div style={{ background: '#FEF3C7', border: '1px solid #FCD34D', borderRadius: 8, padding: '10px 14px', marginBottom: 14, fontSize: 12, color: '#92400E' }}>
            ⚠️ <strong>Motivo obrigatório.</strong> Admin vai ver pra decidir aprovar ou recusar.
          </div>

          <div style={{ fontSize: 11, color: '#9CA3AF', textTransform: 'uppercase', letterSpacing: 1, fontWeight: 700, marginBottom: 8 }}>
            Por que precisa do desconto?
          </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 #EA580C' : '1.5px solid #E4E7EC',
                  background: selected === m.id ? '#FFEDD5' : '#FFFFFF',
                  color: selected === m.id ? '#9A3412' : '#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. 5 caracteres)
              </label>
              <textarea
                value={otherText}
                onChange={e => setOtherText(e.target.value)}
                disabled={submitting}
                placeholder="Ex: cliente já comprou 3 vezes este mês e indicou 2 amigos..."
                maxLength={500}
                style={{
                  width: '100%',
                  minHeight: 75,
                  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-gold"
              onClick={handleConfirm}
              disabled={!canConfirm || submitting}
              style={{ opacity: canConfirm && !submitting ? 1 : 0.5 }}
            >
              {submitting ? '⏳ Enviando...' : '📤 Pedir aprovação'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.DiscountReasonModal = DiscountReasonModal;
  window.DiscountReasonModal = DiscountReasonModal;
  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.DiscountReasonModal = true;
})();
