// Cranodato — Integraciones screen
const IntegracionesScreen = () => {
  const [conectando, setConectando] = React.useState(null);
  const [conectadas, setConectadas] = React.useState({ drive: true, n8n: true });
  const [apiKey, setApiKey] = React.useState('AIzaSy••••••••••••••••••••••');
  const [showKey, setShowKey] = React.useState(false);
  const [webhookCopied, setWebhookCopied] = React.useState(false);

  const webhookUrl = 'https://n8n.cranodato.com/webhook/facturas-entrada';

  const conectar = (id) => {
    setConectando(id);
    setTimeout(() => {
      setConectadas(prev => ({ ...prev, [id]: true }));
      setConectando(null);
    }, 1800);
  };

  const copyWebhook = () => {
    setWebhookCopied(true);
    setTimeout(() => setWebhookCopied(false), 2000);
  };

  const IntCard = ({ id, icon, title, desc, badge, connected, onConnect, children }) => (
    <div style={{
      background: 'white', border: `1.5px solid ${connected ? '#A7F3D0' : '#E2E8F0'}`,
      borderRadius: 10, padding: '22px 24px',
      transition: 'border-color 200ms, box-shadow 200ms',
      boxShadow: connected ? '0 0 0 3px rgba(5,150,105,0.06)' : 'none',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 40, height: 40, borderRadius: 9, background: '#F8FAFC', border: '1px solid #E2E8F0', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20 }}>
            {icon}
          </div>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A', marginBottom: 2 }}>{title}</div>
            {badge && <span style={{ fontSize: 11, background: '#EFF6FF', color: '#1D4ED8', padding: '1px 7px', borderRadius: 9999, fontWeight: 500 }}>{badge}</span>}
          </div>
        </div>
        {connected
          ? <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 500, color: '#047857', background: '#ECFDF5', padding: '4px 10px', borderRadius: 9999 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#059669', display: 'inline-block' }}></span>
              Conectado
            </span>
          : <Btn size="sm" variant="secondary" onClick={() => onConnect && onConnect(id)}
              style={{ opacity: conectando === id ? 0.7 : 1 }}>
              {conectando === id ? 'Conectando…' : 'Conectar'}
            </Btn>
        }
      </div>
      <p style={{ fontSize: 13, color: '#64748B', lineHeight: 1.6, marginBottom: children ? 16 : 0 }}>{desc}</p>
      {children}
    </div>
  );

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <Topbar title="Integraciones" subtitle="Conectá tus fuentes de entrada y destinos de datos" />
      <div style={{ flex: 1, overflowY: 'auto', padding: 28 }}>

        {/* Fuentes de entrada */}
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 14 }}>
            Fuentes de entrada
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <IntCard id="drive" icon="📁" title="Google Drive" badge="Recomendado"
              desc="Cranodato monitorea una carpeta de Drive y procesa automáticamente cada PDF o imagen nueva que aparezca."
              connected={conectadas.drive}>
              {conectadas.drive && (
                <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 7, padding: '10px 14px', fontSize: 13 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ color: '#64748B' }}>Carpeta monitoreada</span>
                    <span style={{ fontFamily: "'DM Mono',monospace", fontSize: 12, color: '#0F172A' }}>/Facturas/Entrada</span>
                  </div>
                </div>
              )}
            </IntCard>

            <IntCard id="email" icon="📧" title="Email / IMAP"
              desc="Conectá una casilla de correo. Cranodato lee los adjuntos de los emails recibidos y los procesa automáticamente."
              connected={conectadas.email} onConnect={conectar}>
              {conectadas.email && (
                <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 7, padding: '10px 14px', fontSize: 13 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#64748B' }}>Casilla configurada</span>
                    <span style={{ fontFamily: "'DM Mono',monospace", fontSize: 12, color: '#0F172A' }}>facturas@empresa.com</span>
                  </div>
                </div>
              )}
            </IntCard>

            <IntCard id="webhook" icon="⚡" title="Webhook de entrada"
              desc="Enviá facturas desde tu propio sistema via HTTP POST. Aceptamos PDF en base64 o URL pública del archivo."
              connected={true}>
              <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 7, padding: '10px 14px' }}>
                <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 6 }}>URL del webhook</div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <code style={{ flex: 1, fontSize: 11, fontFamily: "'DM Mono',monospace", color: '#475569', background: 'white', border: '1px solid #E2E8F0', borderRadius: 5, padding: '6px 10px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {webhookUrl}
                  </code>
                  <Btn size="sm" variant="secondary" onClick={copyWebhook}>
                    {webhookCopied ? '✓ Copiado' : 'Copiar'}
                  </Btn>
                </div>
              </div>
            </IntCard>

            <IntCard id="manual" icon="☁️" title="Subida manual"
              desc="Subís facturas directamente desde el panel, una por una o en lote."
              connected={true}>
            </IntCard>
          </div>
        </div>

        {/* Motor de IA */}
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 14 }}>
            Motor de inteligencia artificial
          </div>
          <div style={{ background: 'white', border: '1.5px solid #A7F3D0', borderRadius: 10, padding: '22px 24px', boxShadow: '0 0 0 3px rgba(5,150,105,0.06)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 40, height: 40, borderRadius: 9, background: '#F8FAFC', border: '1px solid #E2E8F0', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20 }}>🤖</div>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A', marginBottom: 2 }}>Gemini 1.5 Flash</div>
                  <span style={{ fontSize: 11, background: '#ECFDF5', color: '#047857', padding: '1px 7px', borderRadius: 9999, fontWeight: 500 }}>Activo</span>
                </div>
              </div>
              <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 500, color: '#047857', background: '#ECFDF5', padding: '4px 10px', borderRadius: 9999 }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#059669', display: 'inline-block' }}></span>
                Conectado
              </span>
            </div>
            <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 7, padding: '14px 16px' }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 8 }}>API Key de Google AI</div>
              <div style={{ display: 'flex', gap: 8 }}>
                <input
                  type={showKey ? 'text' : 'password'}
                  value={apiKey}
                  onChange={e => setApiKey(e.target.value)}
                  style={{ flex: 1, fontFamily: "'DM Mono',monospace", fontSize: 13, padding: '8px 12px', border: '1px solid #E2E8F0', borderRadius: 6, background: 'white', color: '#0F172A', outline: 'none' }}
                />
                <Btn size="sm" variant="secondary" onClick={() => setShowKey(s => !s)}>
                  {showKey ? 'Ocultar' : 'Ver'}
                </Btn>
                <Btn size="sm">Guardar</Btn>
              </div>
              <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 6 }}>Modelo activo: <code style={{ fontFamily: "'DM Mono',monospace" }}>gemini-1.5-flash-latest</code></div>
            </div>
          </div>
        </div>

        {/* Destinos */}
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#94A3B8', marginBottom: 14 }}>
            Destinos de datos
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <IntCard id="postgres" icon="🗄️" title="PostgreSQL"
              desc="Los datos extraídos se guardan automáticamente en tu base de datos. Soporte para múltiples schemas."
              connected={conectadas.postgres} onConnect={conectar}>
              {conectadas.postgres && (
                <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 7, padding: '10px 14px', fontSize: 12 }}>
                  {[['Host', 'db.servidor.com'], ['Puerto', '5432'], ['Base de datos', 'cranodato_prod']].map(([k,v]) => (
                    <div key={k} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span style={{ color: '#94A3B8' }}>{k}</span>
                      <span style={{ fontFamily: "'DM Mono',monospace", color: '#475569' }}>{v}</span>
                    </div>
                  ))}
                </div>
              )}
            </IntCard>

            <IntCard id="sheets" icon="📊" title="Google Sheets"
              desc="Cada factura procesada agrega una fila en tu hoja de cálculo en tiempo real."
              connected={conectadas.sheets} onConnect={conectar}>
            </IntCard>

            <IntCard id="afip" icon="🏛️" title="AFIP / ARCA" badge="Plan Empresa"
              desc="Validación de CUIT contra el padrón de AFIP y envío de datos al sistema fiscal argentino."
              connected={false}>
              <div style={{ fontSize: 12, color: '#94A3B8', background: '#F8FAFC', borderRadius: 6, padding: '8px 12px' }}>
                Disponible en el plan Empresa. <span style={{ color: '#059669', fontWeight: 500, cursor: 'pointer' }}>Contactar ventas →</span>
              </div>
            </IntCard>

            <IntCard id="n8n" icon="🔄" title="n8n (flujos personalizados)"
              desc="Motor de automatización interno. Podés editar los flujos, agregar pasos de aprobación, notificaciones y más."
              connected={conectadas.n8n}>
              {conectadas.n8n && (
                <div style={{ display: 'flex', gap: 8 }}>
                  <Btn size="sm" variant="secondary">
                    <i data-lucide="external-link" style={{width:13,height:13}}></i>
                    Abrir editor n8n
                  </Btn>
                  <Btn size="sm" variant="ghost">Ver flujos activos</Btn>
                </div>
              )}
            </IntCard>
          </div>
        </div>

      </div>
    </div>
  );
};

Object.assign(window, { IntegracionesScreen });
