// Modal para registrar un pago nuevo.
function RegistrarPagoModal({ factura, vendedora, onClose, onSaved }) {
  const T = window.T;
  const { Icon } = window;
  // Fallback si Icon no existe, usamos SVG inline
  const CameraIcon = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
      <circle cx="12" cy="13" r="4"/>
    </svg>
  );

  const billing = window.useBilling
    ? window.useBilling(factura?.vendedoraId)
    : { state: window.loadBilling(), loading: false };
  const state = billing.state;
  const pagos = state.pagos.filter(p => p.facturaId === factura.id);
  const saldo = window.facturaSaldo(factura, pagos);

  const [metodo, setMetodo] = React.useState('Pago Móvil');
  const [monto, setMonto] = React.useState(saldo.toFixed(2));
  const [banco, setBanco] = React.useState('Banesco');
  const [referencia, setReferencia] = React.useState('');
  const [fecha, setFecha] = React.useState(new Date().toISOString().slice(0, 10));
  const [nota, setNota] = React.useState('');
  const [captura, setCaptura] = React.useState(null);
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);

  const metodos = ['Pago Móvil', 'Transferencia', 'Efectivo'];
  const bancos = ['Banesco', 'Mercantil', 'Venezuela', 'Provincial', 'BNC', 'Bicentenario', 'Otro'];

  const onFile = (e) => {
    const f = e.target.files[0]; if (!f) return;
    const reader = new FileReader();
    reader.onload = (ev) => setCaptura(ev.target.result);
    reader.readAsDataURL(f);
  };

  const submit = async () => {
    setError('');
    const m = parseFloat(monto);
    if (!m || m <= 0) { setError('Ingresa un monto válido'); return; }
    if (metodo !== 'Efectivo' && !referencia) { setError('Ingresa la referencia'); return; }
    if (metodo !== 'Efectivo' && !captura) { setError('Sube la captura del pago'); return; }
    if (!fecha) { setError('Ingresa la fecha del pago'); return; }

    setSubmitting(true);
    try {
      const payload = {
        facturaId: factura.id, vendedoraId: vendedora.id,
        monto: m, metodo, banco: metodo === 'Efectivo' ? '' : banco,
        referencia, fecha, capturaDataUrl: captura, nota,
      };
      if (window.pedidosApi && window.pedidosApi.registrarPago) {
        const res = await window.pedidosApi.registrarPago(payload);
        if (!res.ok) {
          setError(res.error || 'No se pudo registrar el pago');
          setSubmitting(false);
          return;
        }
      } else {
        window.registrarPago(payload);
      }
      onSaved();
    } catch (e) {
      console.error(e);
      setError('Error inesperado: ' + (e.message || e));
      setSubmitting(false);
    }
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 40,
      display: 'flex', alignItems: 'flex-end',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', background: T.paper, borderRadius: '28px 28px 0 0',
        maxHeight: '92%', display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ width: 40, height: 4, background: T.hairlineStrong, borderRadius: 999, margin: '8px auto 12px' }} />
        <div style={{ padding: '0 24px 10px' }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute }}>
            Registrar pago
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 26, color: T.ink, letterSpacing: -0.5, marginTop: 2 }}>
            Saldo {window.fmtMoney(saldo)}
          </div>
        </div>

        <div style={{ overflow: 'auto', padding: '0 24px 12px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Método */}
          <div>
            <Lbl>Método</Lbl>
            <div style={{ display: 'flex', gap: 6 }}>
              {metodos.map(m => (
                <button key={m} onClick={() => setMetodo(m)} style={{
                  flex: 1, padding: '10px', borderRadius: 10,
                  background: metodo === m ? T.ink : T.paperAlt,
                  color: metodo === m ? T.paper : T.ink,
                  border: `1px solid ${metodo === m ? T.ink : T.hairline}`,
                  cursor: 'pointer', fontFamily: T.sans, fontSize: 12,
                }}>{m}</button>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{ flex: 1 }}>
              <Lbl>Monto</Lbl>
              <Input value={monto} onChange={setMonto} type="number" placeholder="0.00" />
            </div>
            <div style={{ flex: 1 }}>
              <Lbl>Fecha</Lbl>
              <Input value={fecha} onChange={setFecha} type="date" />
            </div>
          </div>

          {metodo !== 'Efectivo' && (
            <>
              <div>
                <Lbl>Banco</Lbl>
                <select value={banco} onChange={(e) => setBanco(e.target.value)} style={selStyle(T)}>
                  {bancos.map(b => <option key={b}>{b}</option>)}
                </select>
              </div>
              <div>
                <Lbl>Referencia</Lbl>
                <Input value={referencia} onChange={setReferencia} placeholder="Nº de referencia o confirmación" />
              </div>
              <div>
                <Lbl>Captura del pago</Lbl>
                <label style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: 14, borderRadius: 12, cursor: 'pointer',
                  background: captura ? 'oklch(0.94 0.06 155)' : T.paperAlt,
                  border: `1px dashed ${captura ? 'oklch(0.55 0.14 155)' : T.hairlineStrong}`,
                }}>
                  <input type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
                  {captura ? (
                    <>
                      <img src={captura} style={{ width: 48, height: 48, borderRadius: 8, objectFit: 'cover' }} />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontFamily: T.sans, fontSize: 13, color: 'oklch(0.4 0.14 155)', fontWeight: 500 }}>
                          Captura cargada ✓
                        </div>
                        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.inkSoft, marginTop: 2 }}>
                          Tocar para cambiar
                        </div>
                      </div>
                    </>
                  ) : (
                    <>
                      <div style={{
                        width: 44, height: 44, borderRadius: 10, background: T.paper,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        border: `1px solid ${T.hairline}`,
                      }}>
                        <CameraIcon />
                      </div>
                      <div>
                        <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink, fontWeight: 500 }}>
                          Subir captura del pago
                        </div>
                        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.inkSoft, marginTop: 2 }}>
                          Foto del comprobante
                        </div>
                      </div>
                    </>
                  )}
                </label>
              </div>
            </>
          )}

          <div>
            <Lbl>Nota (opcional)</Lbl>
            <Input value={nota} onChange={setNota} placeholder="Ej: abono parcial" />
          </div>

          {error && (
            <div style={{
              padding: '10px 12px', borderRadius: 10,
              background: 'oklch(0.94 0.04 25)', color: 'oklch(0.4 0.14 25)',
              fontFamily: T.sans, fontSize: 12,
            }}>{error}</div>
          )}
        </div>

        <div style={{ padding: '10px 24px 24px', display: 'flex', gap: 8 }}>
          <button onClick={onClose} style={{
            flex: 1, padding: 14, borderRadius: 999,
            background: T.paperAlt, border: `1px solid ${T.hairline}`,
            color: T.ink, cursor: 'pointer', fontFamily: T.sans, fontSize: 13,
          }}>Cancelar</button>
          <button onClick={submit} disabled={submitting} style={{
            flex: 2, padding: 14, borderRadius: 999,
            background: T.ink, color: T.paper, border: 'none',
            cursor: submitting ? 'wait' : 'pointer',
            opacity: submitting ? 0.6 : 1,
            fontFamily: T.sans, fontSize: 13, fontWeight: 500,
          }}>{submitting ? 'Subiendo…' : 'Registrar pago'}</button>
        </div>
      </div>
    </div>
  );
}

function Lbl({ children }) {
  const T = window.T;
  return <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.3, textTransform: 'uppercase', color: T.inkMute, marginBottom: 6 }}>{children}</div>;
}
function Input({ value, onChange, placeholder, type = 'text' }) {
  const T = window.T;
  return (
    <input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
      style={{
        width: '100%', padding: '12px 14px', borderRadius: 12,
        background: T.paperAlt, border: `1px solid ${T.hairline}`,
        fontFamily: T.sans, fontSize: 14, color: T.ink, outline: 'none', boxSizing: 'border-box',
      }} />
  );
}
function selStyle(T) {
  return {
    width: '100%', padding: '12px 14px', borderRadius: 12,
    background: T.paperAlt, border: `1px solid ${T.hairline}`,
    fontFamily: T.sans, fontSize: 14, color: T.ink, outline: 'none', boxSizing: 'border-box',
  };
}

window.RegistrarPagoModal = RegistrarPagoModal;
