// Cranodato — Upload modal con Claude AI real
const UploadModal = ({ onClose, onInvoiceAdded }) => {
  const [stage, setStage] = React.useState('idle'); // idle | processing | done | error
  const [texto, setTexto] = React.useState('');
  const [result, setResult] = React.useState(null);
  const [errorMsg, setErrorMsg] = React.useState('');

  const procesarConIA = async () => {
    if (!texto.trim()) return;
    setStage('processing');
    setErrorMsg('');

    const prompt = `Sos un sistema de extracción de datos de facturas argentinas. Analizá el siguiente texto de factura y devolvé ÚNICAMENTE un objeto JSON válido con estos campos exactos, sin ningún texto adicional, sin markdown, sin explicaciones:

{
  "proveedor": "nombre completo del proveedor o empresa emisora",
  "cuit": "CUIT en formato XX-XXXXXXXX-X, o null si no se encuentra",
  "tipo": "tipo de comprobante (Factura A, Factura B, Factura C, Nota de crédito A, etc.)",
  "neto": "importe neto gravado como string con formato argentino ej: $10.000,00, o null",
  "iva": "importe IVA como string con formato argentino, o null",
  "total": "importe total como string con formato argentino ej: $12.100,00, o null",
  "numero": "número de comprobante en formato XXXX-XXXXXXXX, o null",
  "confianza": "alta, media o baja según qué tan completos son los datos extraídos"
}

Texto de la factura:
${texto}`;

    try {
      const respuesta = await window.claude.complete(prompt);

      // Limpiar respuesta (quitar markdown si hay)
      let json = respuesta.trim();
      json = json.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim();

      const datos = JSON.parse(json);
      setResult(datos);
      setStage('done');
    } catch (e) {
      setStage('error');
      setErrorMsg('No se pudo interpretar la respuesta de la IA. Intentá con más texto de la factura.');
    }
  };

  const agregarFactura = () => {
    if (!result || !onInvoiceAdded) return;
    const nueva = {
      id: result.numero || `0001-${String(Date.now()).slice(-5)}`,
      proveedor: result.proveedor || 'Proveedor desconocido',
      cuit: result.cuit || '—',
      monto: result.total || '—',
      iva: result.iva || '—',
      neto: result.neto || '—',
      tipo: result.tipo || '—',
      estado: result.confianza === 'baja' ? 'revisar' : 'procesada',
      fecha: new Date().toLocaleDateString('es-AR').replace(/\//g, '/'),
      archivo: 'factura_manual.txt',
    };
    onInvoiceAdded(nueva);
    onClose();
  };

  const ejemplos = [
    "Factura A 0001-00123\nFecha: 30/04/2025\nEmisor: Distribuidora Norte S.A.\nCUIT: 30-71234567-0\nNeto gravado: $40.000,00\nIVA 21%: $8.400,00\nTotal: $48.400,00",
    "FERRETERÍA EL TORNILLO\nCUIT 20-33445566-7\nFactura B N° 0002-00456\nFecha 28/04/2025\nTotal a pagar: $15.200,00",
    "Nota de Crédito A\nEmisor: Logística del Sur\nCUIT: 27-38812341-5\nN° 0001-00089\nImporte: $5.000,00 + IVA $1.050,00 = $6.050,00",
  ];

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 20 }}>
      <div style={{ background: 'white', borderRadius: 12, width: '100%', maxWidth: 540, boxShadow: '0 20px 40px rgba(0,0,0,0.15)', overflow: 'hidden', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}>

        {/* Header */}
        <div style={{ padding: '18px 24px', borderBottom: '1px solid #F1F5F9', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600, color: '#0F172A' }}>Procesar factura con IA</div>
            <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>Pegá el texto de la factura y Claude extrae los datos</div>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#94A3B8', display: 'flex', padding: 4 }}>
            <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
          </button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>

          {/* IDLE — input */}
          {stage === 'idle' && (
            <>
              <div style={{ marginBottom: 14 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#64748B', marginBottom: 7 }}>
                  Texto de la factura
                </label>
                <textarea
                  value={texto}
                  onChange={e => setTexto(e.target.value)}
                  placeholder="Pegá acá el contenido de la factura: número, CUIT, proveedor, importes, tipo de comprobante..."
                  style={{
                    width: '100%', height: 160, fontFamily: "'DM Mono', monospace", fontSize: 12,
                    padding: '10px 12px', border: '1px solid #E2E8F0', borderRadius: 8,
                    background: '#F8FAFC', color: '#0F172A', outline: 'none', resize: 'vertical',
                    lineHeight: 1.6, transition: 'border-color 150ms',
                  }}
                  onFocus={e => e.target.style.borderColor = '#059669'}
                  onBlur={e => e.target.style.borderColor = '#E2E8F0'}
                />
              </div>

              {/* Ejemplos rápidos */}
              <div style={{ marginBottom: 4 }}>
                <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 8 }}>
                  Probá con un ejemplo
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {ejemplos.map((ej, i) => (
                    <button
                      key={i}
                      onClick={() => setTexto(ej)}
                      style={{
                        background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 7,
                        padding: '8px 12px', textAlign: 'left', cursor: 'pointer',
                        fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#64748B',
                        lineHeight: 1.4, transition: 'border-color 150ms, background 150ms',
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                      }}
                      onMouseEnter={e => { e.currentTarget.style.borderColor = '#059669'; e.currentTarget.style.background = '#F0FDF4'; }}
                      onMouseLeave={e => { e.currentTarget.style.borderColor = '#E2E8F0'; e.currentTarget.style.background = '#F8FAFC'; }}
                    >
                      {ej.split('\n')[0]}…
                    </button>
                  ))}
                </div>
              </div>
            </>
          )}

          {/* PROCESSING */}
          {stage === 'processing' && (
            <div style={{ textAlign: 'center', padding: '32px 0' }}>
              <div style={{ width: 52, height: 52, borderRadius: '50%', background: '#ECFDF5', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', animation: 'spin 1.5s linear infinite' }}>
                <i data-lucide="zap" style={{ width: 24, height: 24, color: '#059669' }}></i>
              </div>
              <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A', marginBottom: 6 }}>Claude está leyendo la factura…</div>
              <div style={{ fontSize: 13, color: '#94A3B8' }}>Extrayendo CUIT, proveedor, montos e impuestos</div>
              <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
            </div>
          )}

          {/* DONE */}
          {stage === 'done' && result && (
            <>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18, background: '#ECFDF5', border: '1px solid #A7F3D0', borderRadius: 8, padding: '12px 14px' }}>
                <i data-lucide="check-circle" style={{ width: 18, height: 18, color: '#059669', flexShrink: 0 }}></i>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#047857' }}>Datos extraídos correctamente</div>
                  <div style={{ fontSize: 11, color: '#059669' }}>Confianza: {result.confianza}</div>
                </div>
              </div>

              <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden' }}>
                {[
                  ['N° comprobante', result.numero || '—', true],
                  ['Tipo', result.tipo || '—', false],
                  ['Proveedor', result.proveedor || '—', false],
                  ['CUIT', result.cuit || '—', true],
                  ['Neto gravado', result.neto || '—', true],
                  ['IVA', result.iva || '—', true],
                  ['Total', result.total || '—', true],
                ].map(([k, v, mono], i, arr) => (
                  <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '11px 16px', borderBottom: i < arr.length - 1 ? '1px solid #F1F5F9' : 'none' }}>
                    <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#94A3B8' }}>{k}</span>
                    <span style={{ fontSize: 13, fontFamily: mono ? "'DM Mono', monospace" : 'inherit', color: k === 'Total' ? '#047857' : '#0F172A', fontWeight: k === 'Total' ? 700 : 400 }}>{v}</span>
                  </div>
                ))}
              </div>

              {result.confianza === 'baja' && (
                <div style={{ marginTop: 12, background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 8, padding: '10px 14px', fontSize: 12, color: '#B45309' }}>
                  Confianza baja — revisá los datos antes de guardar. El comprobante se marcará como "Revisar".
                </div>
              )}
            </>
          )}

          {/* ERROR */}
          {stage === 'error' && (
            <div style={{ textAlign: 'center', padding: '24px 0' }}>
              <div style={{ width: 52, height: 52, borderRadius: '50%', background: '#FEF2F2', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
                <i data-lucide="alert-triangle" style={{ width: 24, height: 24, color: '#DC2626' }}></i>
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A', marginBottom: 6 }}>No se pudo procesar</div>
              <div style={{ fontSize: 13, color: '#94A3B8', marginBottom: 0 }}>{errorMsg}</div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 24px', borderTop: '1px solid #F1F5F9', display: 'flex', justifyContent: 'flex-end', gap: 8, flexShrink: 0 }}>
          {stage === 'idle' && (
            <>
              <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
              <Btn onClick={procesarConIA} disabled={!texto.trim()}>
                <i data-lucide="zap" style={{ width: 15, height: 15 }}></i>
                Procesar con IA
              </Btn>
            </>
          )}
          {stage === 'processing' && <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>}
          {stage === 'done' && (
            <>
              <Btn variant="ghost" onClick={() => { setStage('idle'); setResult(null); }}>Procesar otra</Btn>
              <Btn onClick={agregarFactura}>
                <i data-lucide="check" style={{ width: 15, height: 15 }}></i>
                Guardar en panel
              </Btn>
            </>
          )}
          {stage === 'error' && (
            <>
              <Btn variant="secondary" onClick={onClose}>Cerrar</Btn>
              <Btn onClick={() => setStage('idle')}>Intentar de nuevo</Btn>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// Placeholder screen for unbuilt sections
const PlaceholderScreen = ({ title, icon }) => (
  <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
    <Topbar title={title} />
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, color: '#CBD5E1' }}>
      <i data-lucide={icon} style={{ width: 48, height: 48 }}></i>
      <div style={{ fontSize: 14, color: '#94A3B8' }}>Esta sección no está incluida en el kit de UI</div>
    </div>
  </div>
);

Object.assign(window, { UploadModal, PlaceholderScreen });
