// Screens: Drivers, Weekly Performance, Chat MCP

const { useState: useState3, useRef: useRef3, useEffect: useEffect3 } = window.React;

// ── Drivers ───────────────────────────────────────────────────────
function ScreenDrivers() {
  const { drivers, trucks, trips } = ROUTING_DATA;
  const [selected, setSelected] = useState3(null);

  return (
    <PageShell title="Conductores" sub={`${drivers.length} conductores registrados`}
      actions={<Btn small>+ Registrar conductor</Btn>}
    >
      <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 320px' : '1fr', gap: 20 }}>
        <Table
          headers={['Conductor', 'Licencia', 'Estado', 'Viajes', 'A tiempo', 'Score', '']}
          onRowClick={i => setSelected(selected?.id === drivers[i].id ? null : drivers[i])}
          rows={drivers.map(d => {
            const trk = trucks.find(t => t.driver === d.id);
            const activeTrip = trips.find(t => t.driver === d.id && t.status === 'en_ruta');
            return [
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 34, height: 34, borderRadius: '50%', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, color: '#15803d' }}>
                  {d.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#1a2e25' }}>{d.name}</div>
                  <div style={{ fontSize: 11, color: '#5a7366' }}>{d.phone}</div>
                </div>
              </div>,
              <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{d.license}</span>,
              <Chip status={d.status} small />,
              <span style={{ fontWeight: 600 }}>{d.trips}</span>,
              <div style={{ width: 80 }}>
                <ProgressBar value={d.onTime} />
                <span style={{ fontSize: 11, color: '#5a7366' }}>{d.onTime}%</span>
              </div>,
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 14, fontWeight: 700, color: d.score >= 90 ? '#15803d' : d.score >= 80 ? '#d97706' : '#dc2626' }}>{d.score}</span>
                <span style={{ fontSize: 11, color: '#5a7366' }}>/ 100</span>
              </div>,
              <span style={{ fontSize: 12, color: '#10B981', fontWeight: 600 }}>Ver →</span>,
            ];
          })}
        />

        {/* Detail panel */}
        {selected && (() => {
          const trk = trucks.find(t => t.driver === selected.id);
          const driverTrips = trips.filter(t => t.driver === selected.id);
          return (
            <div style={{ background: '#fff', borderRadius: 12, padding: '22px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
                  <div style={{ width: 52, height: 52, borderRadius: '50%', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 700, color: '#15803d' }}>
                    {selected.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                  </div>
                  <div>
                    <div style={{ fontSize: 16, fontWeight: 700, color: '#1a2e25' }}>{selected.name}</div>
                    <Chip status={selected.status} small />
                  </div>
                </div>
                <button onClick={() => setSelected(null)} style={{ border: 'none', background: 'none', cursor: 'pointer', color: '#5a7366', fontSize: 18 }}>✕</button>
              </div>

              {[
                ['Licencia', selected.license],
                ['Teléfono', selected.phone],
                ['Viajes totales', selected.trips],
                ['% A tiempo', `${selected.onTime}%`],
                ['Camión asignado', trk?.plate || <span style={{ color: '#94a3b8' }}>Sin camión</span>],
              ].map(([k, v], i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #f0f4f2' }}>
                  <span style={{ fontSize: 12, color: '#5a7366' }}>{k}</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: '#1a2e25' }}>{v}</span>
                </div>
              ))}

              <div style={{ marginTop: 16 }}>
                <div style={{ fontSize: 12, color: '#5a7366', marginBottom: 6 }}>Score de rendimiento</div>
                <ProgressBar value={selected.score} height={10} color={selected.score >= 90 ? '#10B981' : selected.score >= 80 ? '#F59E0B' : '#EF4444'} />
                <div style={{ fontSize: 20, fontWeight: 800, color: '#1a2e25', marginTop: 6 }}>{selected.score}<span style={{ fontSize: 12, fontWeight: 400, color: '#5a7366' }}> / 100</span></div>
              </div>

              {driverTrips.length > 0 && (
                <div style={{ marginTop: 20 }}>
                  <div style={{ fontSize: 12, color: '#5a7366', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 10 }}>Viajes recientes</div>
                  {driverTrips.slice(0, 3).map(t => (
                    <div key={t.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: '1px solid #f0f4f2' }}>
                      <div>
                        <div style={{ fontSize: 12, fontFamily: 'monospace', color: '#5a7366' }}>{t.id}</div>
                        <div style={{ fontSize: 11, color: '#1a2e25' }}>{t.route}</div>
                      </div>
                      <Chip status={t.status} small />
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })()}
      </div>
    </PageShell>
  );
}

// ── Weekly Performance ────────────────────────────────────────────
function ScreenPerformance() {
  const { routePerformance, weeklyStats, drivers, dailyTrends } = ROUTING_DATA;
  const [tab, setTab] = useState3('rutas');

  const tabs = [
    { id: 'rutas', label: 'Por ruta' },
    { id: 'conductores', label: 'Por conductor' },
    { id: 'camiones', label: 'Por camión' },
  ];

  const maxTrips = Math.max(...routePerformance.map(r => r.trips));

  return (
    <PageShell title="Rendimiento semanal" sub="Semana 17 · 21–27 abril 2026">
      {/* KPI summary */}
      <div style={{ display: 'flex', gap: 14, marginBottom: 24, flexWrap: 'wrap' }}>
        <StatCard label="Viajes completados" value={weeklyStats.completed} sub={`de ${weeklyStats.totalTrips} totales`} accent="#10B981" trend={+8} />
        <StatCard label="Tasa puntualidad" value={`${weeklyStats.onTimeRate}%`} sub={`${weeklyStats.onTime} viajes a tiempo`} accent="#3B82F6" trend={-5} />
        <StatCard label="Demora promedio" value={`${weeklyStats.avgDelay} min`} sub="Por viaje con retraso" accent="#F59E0B" />
      </div>

      {/* Daily bar chart */}
      <div style={{ background: '#fff', borderRadius: 12, padding: '20px 24px', boxShadow: '0 1px 4px rgba(0,0,0,.06)', marginBottom: 20 }}>
        <SectionHeader title="Tendencia diaria" sub="Viajes por día esta semana" />
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-end', height: 120, paddingBottom: 4 }}>
          {dailyTrends.map((d, i) => (
            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
              <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 2, alignItems: 'center', justifyContent: 'flex-end', flex: 1 }}>
                {d.delayed > 0 && <div style={{ width: '60%', height: d.delayed * 28, background: '#fde68a', border: '1px solid #F59E0B', borderRadius: '3px 3px 0 0' }}/>}
                {d.onTime > 0 && <div style={{ width: '60%', height: d.onTime * 28, background: '#10B981', borderRadius: d.delayed ? '0' : '3px 3px 0 0' }}/>}
                {d.trips === 0 && <div style={{ width: '60%', height: 4, background: '#e8f0ec', borderRadius: 3 }}/>}
              </div>
              <span style={{ fontSize: 11, color: '#5a7366', fontWeight: 700 }}>{d.day}</span>
              {d.trips > 0 && <span style={{ fontSize: 10, color: '#94a3b8' }}>{d.trips}</span>}
            </div>
          ))}
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 16, borderBottom: '2px solid #e8f0ec' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            border: 'none', background: 'none', padding: '8px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer',
            color: tab === t.id ? '#10B981' : '#5a7366',
            borderBottom: tab === t.id ? '2px solid #10B981' : '2px solid transparent',
            marginBottom: -2, transition: 'color .15s',
          }}>{t.label}</button>
        ))}
      </div>

      {tab === 'rutas' && (
        <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 4px rgba(0,0,0,.06)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: '#f7faf8', borderBottom: '1px solid #e4ede8' }}>
                {['Ruta', 'Viajes', 'A tiempo', 'Demora prom.', 'Distancia', 'Rendimiento'].map((h, i) => (
                  <th key={i} style={{ padding: '11px 16px', textAlign: 'left', fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.05em' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {routePerformance.map((r, i) => (
                <tr key={i} style={{ borderBottom: '1px solid #f0f4f2' }}>
                  <td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 600, color: '#1a2e25' }}>{r.route}</td>
                  <td style={{ padding: '12px 16px', fontSize: 13, color: '#1a2e25' }}>{r.trips}</td>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ width: 60 }}><ProgressBar value={Math.round(r.onTime / r.trips * 100)} /></div>
                      <span style={{ fontSize: 12, color: '#5a7366' }}>{r.onTime}/{r.trips}</span>
                    </div>
                  </td>
                  <td style={{ padding: '12px 16px' }}>
                    {r.avgDelay > 0
                      ? <span style={{ color: '#d97706', fontWeight: 600, fontSize: 13 }}>+{r.avgDelay} min</span>
                      : <span style={{ color: '#15803d', fontWeight: 600, fontSize: 13 }}>Sin demora</span>}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: 13, color: '#5a7366' }}>{r.avgKm.toLocaleString()} km</td>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ width: 100 }}>
                      <ProgressBar value={Math.round(r.onTime / r.trips * 100)} color={r.onTime/r.trips >= .9 ? '#10B981' : r.onTime/r.trips >= .7 ? '#F59E0B' : '#EF4444'} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'conductores' && (
        <Table
          headers={['Conductor', 'Viajes', '% A tiempo', 'Score', 'Estado']}
          rows={ROUTING_DATA.drivers.map(d => [
            d.name,
            d.trips,
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 80 }}><ProgressBar value={d.onTime} color={d.onTime >= 90 ? '#10B981' : d.onTime >= 80 ? '#F59E0B' : '#EF4444'} /></div>
              <span style={{ fontSize: 12 }}>{d.onTime}%</span>
            </div>,
            <span style={{ fontWeight: 700, color: d.score >= 90 ? '#15803d' : d.score >= 80 ? '#d97706' : '#dc2626' }}>{d.score}</span>,
            <Chip status={d.status} small />,
          ])}
        />
      )}

      {tab === 'camiones' && (
        <Table
          headers={['Placa', 'Modelo', 'Kilometraje', 'Estado', 'Viajes semana']}
          rows={ROUTING_DATA.trucks.map(t => [
            <span style={{ fontFamily: 'monospace', fontWeight: 700 }}>{t.plate}</span>,
            t.model,
            `${t.km.toLocaleString()} km`,
            <Chip status={t.status} small />,
            ROUTING_DATA.trips.filter(tr => tr.truck === t.id).length,
          ])}
        />
      )}
    </PageShell>
  );
}

const GROQ_API_KEY = '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';

// ── Chat MCP ──────────────────────────────────────────────────────
function ScreenChat({ trips }) {
  const liveTrips = trips || ROUTING_DATA.trips;
  const initMessages = (() => {
    const delayed = liveTrips.filter(t => t.status === 'en_ruta' && t.delay > 60);
    const base = [...ROUTING_DATA.chatHistory];
    if (delayed.length > 0) {
      base.push({
        role: 'assistant',
        text: `⚠️ Alerta automática: ${delayed.length} viaje${delayed.length > 1 ? 's' : ''} con retraso crítico detectado${delayed.length > 1 ? 's' : ''}:\n${delayed.map(t => `• ${t.id} — ${t.route} (+${t.delay} min)`).join('\n')}\n\n¿Deseas que analice las causas o sugiera acciones?`,
        isAlert: true,
      });
    }
    return base;
  })();
  const [messages, setMessages] = useState3(initMessages);
  const [input, setInput] = useState3('');
  const [loading, setLoading] = useState3(false);
  const bottomRef = useRef3(null);

  useEffect3(() => {
    if (bottomRef.current) bottomRef.current.scrollTop = bottomRef.current.scrollHeight;
  }, [messages]);

  const quickPrompts = [
    '¿Qué viajes están retrasados ahora?',
    'Resumen de rendimiento semanal',
    '¿Qué camiones están disponibles?',
    'Estado del conductor Carlos Mendoza',
  ];

  const send = async (text) => {
    const userText = text || input.trim();
    if (!userText) return;
    setInput('');
    setMessages(m => [...m, { role: 'user', text: userText }]);
    setLoading(true);

    // Build context about the fleet
    const { trips, drivers, trucks, weeklyStats } = ROUTING_DATA;
    const activeTrips = trips.filter(t => t.status === 'en_ruta');
    const delayed = activeTrips.filter(t => t.delay > 0);
    const available = trucks.filter(t => t.status === 'disponible');

    const context = `Eres el asistente operativo del sistema Routing (control de flota de camiones).
Datos actuales:
- Viajes en ruta: ${activeTrips.map(t => `${t.id} (${t.route}, ${t.delay > 0 ? 'retrasado +' + t.delay + ' min' : 'a tiempo'})`).join('; ')}
- Viajes retrasados: ${delayed.length} (${delayed.map(t => t.id).join(', ') || 'ninguno'})
- Camiones disponibles: ${available.map(t => t.plate).join(', ') || 'ninguno'}
- Estadísticas semana: ${weeklyStats.totalTrips} viajes, ${weeklyStats.onTimeRate}% puntualidad, demora promedio ${weeklyStats.avgDelay} min
- Conductores activos: ${drivers.filter(d => d.status === 'en_ruta').map(d => d.name).join(', ')}
Responde en español, de forma concisa y operativa. Usa datos reales del contexto.`;

    try {
      const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${GROQ_API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: 'llama-3.3-70b-versatile',
          messages: [{ role: 'user', content: context + '\n\nPregunta del despachador: ' + userText }],
          max_tokens: 400,
          temperature: 0.4
        })
      });
      const data = await res.json();
      console.log('[Groq]', res.status, JSON.stringify(data));
      if (!res.ok) throw new Error(data.error?.message || `HTTP ${res.status}`);
      const reply = data.choices?.[0]?.message?.content || 'Sin respuesta del asistente.';
      setMessages(m => [...m, { role: 'assistant', text: reply }]);
    } catch(e) {
      console.error('[Groq error]', e);
      setMessages(m => [...m, { role: 'assistant', text: `Error: ${e.message}` }]);
    }
    setLoading(false);
  };

  return (
    <PageShell title="Asistente MCP" sub="Consulta operativa con inteligencia artificial">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 260px', gap: 20, height: 'calc(100vh - 180px)' }}>
        {/* Chat window */}
        <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 4px rgba(0,0,0,.06)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {/* Messages */}
          <div ref={bottomRef} style={{ flex: 1, overflowY: 'auto', padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {messages.map((msg, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start' }}>
                {msg.role === 'assistant' && (
                  <div style={{ width: 30, height: 30, borderRadius: '50%', background: '#111c17', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, color: '#10B981', fontWeight: 700, flexShrink: 0, marginRight: 10, alignSelf: 'flex-end' }}>R</div>
                )}
                <div style={{
                  maxWidth: '72%', padding: '10px 14px', borderRadius: msg.role === 'user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                  background: msg.role === 'user' ? '#10B981' : '#f7faf8',
                  color: msg.role === 'user' ? '#fff' : '#1a2e25',
                  fontSize: 13, lineHeight: 1.55, whiteSpace: 'pre-wrap',
                }}>
                  {msg.text}
                </div>
              </div>
            ))}
            {loading && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 30, height: 30, borderRadius: '50%', background: '#111c17', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, color: '#10B981', fontWeight: 700 }}>R</div>
                <div style={{ background: '#f7faf8', borderRadius: '14px 14px 14px 4px', padding: '10px 16px' }}>
                  <div style={{ display: 'flex', gap: 4 }}>
                    {[0,1,2].map(i => <div key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: '#10B981', animation: `pulse 1.2s ease-in-out ${i*.2}s infinite` }}/>)}
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Input */}
          <div style={{ padding: '14px 20px', borderTop: '1px solid #f0f4f2', display: 'flex', gap: 10 }}>
            <input
              value={input} onChange={e => setInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && !e.shiftKey && send()}
              placeholder="Escribe tu consulta operativa…"
              style={{ flex: 1, border: '1px solid #dde8e2', borderRadius: 10, padding: '9px 14px', fontSize: 13, color: '#1a2e25', outline: 'none', background: '#f7faf8' }}
            />
            <Btn onClick={() => send()} disabled={loading}>Enviar</Btn>
          </div>
        </div>

        {/* Quick prompts */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 4 }}>Consultas rápidas</div>
          {quickPrompts.map((p, i) => (
            <button key={i} onClick={() => send(p)}
              style={{ textAlign: 'left', background: '#fff', border: '1px solid #dde8e2', borderRadius: 10, padding: '10px 14px', fontSize: 13, color: '#1a2e25', cursor: 'pointer', lineHeight: 1.4, boxShadow: '0 1px 4px rgba(0,0,0,.04)', transition: 'border-color .15s' }}
              onMouseEnter={e => e.currentTarget.style.borderColor = '#10B981'}
              onMouseLeave={e => e.currentTarget.style.borderColor = '#dde8e2'}
            >
              {p}
            </button>
          ))}

          <div style={{ background: '#f7faf8', borderRadius: 10, padding: '14px', marginTop: 8, border: '1px solid #e8f0ec' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 8 }}>Estado flota</div>
            {[
              ['En ruta', ROUTING_DATA.trips.filter(t => t.status === 'en_ruta').length, '#10B981'],
              ['Retrasados', ROUTING_DATA.trips.filter(t => t.delay > 0 && t.status === 'en_ruta').length, '#F59E0B'],
              ['Disponibles', ROUTING_DATA.trucks.filter(t => t.status === 'disponible').length, '#3B82F6'],
            ].map(([label, count, color], i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                <span style={{ fontSize: 12, color: '#5a7366' }}>{label}</span>
                <span style={{ fontSize: 14, fontWeight: 700, color }}>{count}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <style>{`@keyframes pulse { 0%,100%{opacity:.3;transform:scale(.85)} 50%{opacity:1;transform:scale(1)} }`}</style>
    </PageShell>
  );
}

// ── Integraciones & Automatizaciones ──────────────────────────────
function ScreenIntegrations({ onNavigate }) {
  const [activeChannel, setActiveChannel] = useState3(null);

  const channels = [
    {
      id: 'telegram',
      name: 'Telegram',
      icon: '✈',
      color: '#229ED9',
      status: 'disponible',
      desc: 'Alertas automáticas al grupo de despacho',
      features: ['Alertas de retraso', 'Confirmación de llegada', 'Notificación de incidentes'],
    },
    {
      id: 'whatsapp',
      name: 'WhatsApp',
      icon: '◎',
      color: '#25D366',
      status: 'disponible',
      desc: 'Mensajes directos a conductores y supervisores',
      features: ['Estado del viaje', 'Cambios de ruta', 'Emergencias'],
    },
    {
      id: 'sms',
      name: 'SMS',
      icon: '▤',
      color: '#6366F1',
      status: 'proximo',
      desc: 'Respaldo sin internet para zonas sin cobertura',
      features: ['Alertas críticas', 'Sin app requerida'],
    },
  ];

  const automations = [
    { trigger: 'Retraso > 60 min', action: 'Notificar despachador vía Telegram', channel: 'telegram', active: true, freq: '3 veces hoy' },
    { trigger: 'Viaje completado', action: 'Enviar resumen al supervisor', channel: 'whatsapp', active: true, freq: '5 veces hoy' },
    { trigger: 'Camión detenido > 30 min', action: 'Alerta de incidente potencial', channel: 'telegram', active: false, freq: '—' },
    { trigger: 'Inicio de viaje', action: 'Confirmar salida al cliente', channel: 'whatsapp', active: true, freq: '2 veces hoy' },
    { trigger: 'Retraso > 120 min', action: 'Escalar a gerencia', channel: 'sms', active: false, freq: '—' },
  ];

  const routeOps = [
    { label: 'Optimización de rutas IA', desc: 'Reasignación automática ante cierres viales', tag: 'Próximamente' },
    { label: 'Planificación predictiva', desc: 'Sugiere horarios según historial de tráfico', tag: 'Próximamente' },
    { label: 'Asignación automática', desc: 'Conductor + camión óptimo por ruta y carga', tag: 'Próximamente' },
  ];

  const miniChatMsgs = [
    { role: 'bot', text: 'VJ-2026-041 reporta retraso +150 min en Ruta PE-1S. ¿Notificar al cliente ahora?' },
    { role: 'user', text: 'Sí, enviar WhatsApp al contacto del pedido.' },
    { role: 'bot', text: '✓ Mensaje enviado a +51 987 654 321. ¿Reasigno el camión disponible T-003 para el siguiente turno?' },
    { role: 'user', text: 'Confirmar.' },
    { role: 'bot', text: '✓ T-003 asignado. Conductor Luis Torres notificado vía Telegram.' },
  ];

  const chColor = { telegram: '#229ED9', whatsapp: '#25D366', sms: '#6366F1' };

  return (
    <PageShell title="Integraciones" sub="Automatizaciones, alertas y canales de comunicación">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 20 }}>

        {/* Left column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

          {/* Channel cards */}
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 12 }}>Canales de notificación</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
              {channels.map(ch => (
                <div key={ch.id}
                  onClick={() => ch.status !== 'proximo' && setActiveChannel(activeChannel === ch.id ? null : ch.id)}
                  style={{
                    background: '#fff', border: `1.5px solid ${activeChannel === ch.id ? ch.color : '#e8f0ec'}`,
                    borderRadius: 12, padding: '16px', cursor: ch.status === 'proximo' ? 'default' : 'pointer',
                    transition: 'border-color .15s', opacity: ch.status === 'proximo' ? .6 : 1,
                  }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                    <div style={{ width: 36, height: 36, borderRadius: 10, background: ch.color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, color: ch.color }}>
                      {ch.icon}
                    </div>
                    {ch.status === 'proximo'
                      ? <span style={{ fontSize: 9, fontWeight: 700, background: '#f1f5f9', color: '#94a3b8', borderRadius: 6, padding: '2px 7px', textTransform: 'uppercase' }}>Próximo</span>
                      : <button style={{ fontSize: 11, fontWeight: 700, background: activeChannel === ch.id ? ch.color : 'transparent', color: activeChannel === ch.id ? '#fff' : ch.color, border: `1.5px solid ${ch.color}`, borderRadius: 7, padding: '3px 10px', cursor: 'pointer' }}>
                          {activeChannel === ch.id ? 'Configurado' : 'Conectar'}
                        </button>
                    }
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#1a2e25', marginBottom: 4 }}>{ch.name}</div>
                  <div style={{ fontSize: 11, color: '#5a7366', lineHeight: 1.4 }}>{ch.desc}</div>
                  {activeChannel === ch.id && (
                    <div style={{ marginTop: 10, borderTop: '1px solid #e8f0ec', paddingTop: 10 }}>
                      {ch.features.map((f, i) => (
                        <div key={i} style={{ fontSize: 11, color: '#5a7366', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                          <span style={{ color: ch.color, fontSize: 10 }}>✓</span> {f}
                        </div>
                      ))}
                      <input placeholder="Token del bot / número..." style={{ marginTop: 8, width: '100%', fontSize: 11, border: '1px solid #e8f0ec', borderRadius: 6, padding: '6px 8px', outline: 'none', color: '#1a2e25' }} />
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Automation rules */}
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.06em' }}>Reglas de automatización</div>
              <button style={{ fontSize: 11, fontWeight: 600, color: '#10B981', border: '1px solid #10B981', background: 'transparent', borderRadius: 7, padding: '3px 10px', cursor: 'pointer' }}>+ Nueva regla</button>
            </div>
            <div style={{ background: '#fff', border: '1px solid #e8f0ec', borderRadius: 12, overflow: 'hidden' }}>
              {automations.map((a, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 80px 80px 36px', alignItems: 'center', gap: 12, padding: '12px 16px', borderBottom: i < automations.length - 1 ? '1px solid #f0f6f3' : 'none' }}>
                  <div>
                    <div style={{ fontSize: 11, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 2 }}>Si</div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: '#1a2e25' }}>{a.trigger}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 11, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 2 }}>Entonces</div>
                    <div style={{ fontSize: 12, color: '#2d4a3a' }}>{a.action}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                    <div style={{ width: 8, height: 8, borderRadius: '50%', background: chColor[a.channel] }} />
                    <span style={{ fontSize: 11, color: '#5a7366', textTransform: 'capitalize' }}>{a.channel}</span>
                  </div>
                  <div style={{ fontSize: 11, color: '#94a3b8', fontFamily: 'monospace' }}>{a.freq}</div>
                  <div style={{
                    width: 32, height: 18, borderRadius: 9,
                    background: a.active ? '#10B981' : '#e8f0ec',
                    position: 'relative', cursor: 'pointer', flexShrink: 0,
                    transition: 'background .2s',
                  }}>
                    <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#fff', position: 'absolute', top: 3, left: a.active ? 17 : 3, transition: 'left .2s' }} />
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Route ops */}
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 12 }}>Operaciones de ruta</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
              {routeOps.map((r, i) => (
                <div key={i} style={{ background: '#fff', border: '1px solid #e8f0ec', borderRadius: 12, padding: 16, opacity: .7 }}>
                  <div style={{ fontSize: 9, fontWeight: 700, background: '#f1f5f9', color: '#94a3b8', borderRadius: 6, padding: '2px 7px', textTransform: 'uppercase', display: 'inline-block', marginBottom: 10 }}>{r.tag}</div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#1a2e25', marginBottom: 6 }}>{r.label}</div>
                  <div style={{ fontSize: 11, color: '#5a7366', lineHeight: 1.5 }}>{r.desc}</div>
                </div>
              ))}
            </div>
          </div>

        </div>

        {/* Right column — mini chat */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ background: '#fff', border: '1px solid #e8f0ec', borderRadius: 14, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid #f0f6f3', display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#10B981' }} />
              <div style={{ fontSize: 13, fontWeight: 700, color: '#1a2e25' }}>Chat coordinación</div>
              <span style={{ marginLeft: 'auto', fontSize: 9, fontWeight: 700, background: '#dcfce7', color: '#15803d', borderRadius: 6, padding: '2px 7px', textTransform: 'uppercase' }}>Demo</span>
            </div>
            <div style={{ padding: '14px 12px', display: 'flex', flexDirection: 'column', gap: 10, minHeight: 320 }}>
              {miniChatMsgs.map((m, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
                  <div style={{
                    maxWidth: '85%', fontSize: 12, lineHeight: 1.5, padding: '8px 12px', borderRadius: 10,
                    background: m.role === 'user' ? '#10B981' : '#f7faf8',
                    color: m.role === 'user' ? '#fff' : '#2d4a3a',
                    borderBottomRightRadius: m.role === 'user' ? 2 : 10,
                    borderBottomLeftRadius: m.role === 'bot' ? 2 : 10,
                  }}>{m.text}</div>
                </div>
              ))}
            </div>
            <div style={{ padding: '10px 12px', borderTop: '1px solid #f0f6f3', display: 'flex', gap: 8 }}>
              <input disabled placeholder="Disponible con integración activa..." style={{ flex: 1, fontSize: 12, border: '1px solid #e8f0ec', borderRadius: 8, padding: '7px 10px', background: '#f7faf8', color: '#94a3b8', outline: 'none' }} />
              <button disabled style={{ background: '#e8f0ec', border: 'none', borderRadius: 8, padding: '7px 12px', cursor: 'not-allowed', color: '#94a3b8', fontSize: 12 }}>→</button>
            </div>
          </div>

          <div style={{ background: '#fff', border: '1px solid #e8f0ec', borderRadius: 14, padding: '16px' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 12 }}>Actividad hoy</div>
            {[
              { time: '09:14', msg: 'Alerta enviada: VJ-2026-041 retrasado', ch: 'telegram' },
              { time: '09:01', msg: 'Viaje completado: VJ-2026-039 a Ica', ch: 'whatsapp' },
              { time: '08:45', msg: 'Inicio confirmado: VJ-2026-041', ch: 'whatsapp' },
              { time: '07:30', msg: 'Turno iniciado — 3 viajes programados', ch: 'telegram' },
            ].map((e, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 10 }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: chColor[e.ch], marginTop: 4, flexShrink: 0 }} />
                <div>
                  <div style={{ fontSize: 11, color: '#1a2e25' }}>{e.msg}</div>
                  <div style={{ fontSize: 10, color: '#94a3b8', fontFamily: 'monospace' }}>{e.time} · {e.ch}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

      </div>
    </PageShell>
  );
}

Object.assign(window, { ScreenDrivers, ScreenPerformance, ScreenChat, ScreenIntegrations });
