// Screens: Dashboard + Live Operations

const { useState, useEffect, useRef } = window.React;
const h = window.React.createElement;

// ── Dashboard ─────────────────────────────────────────────────────
function ScreenDashboard({ onNavigate, trips: tripsLive }) {
  const { weeklyStats, drivers } = ROUTING_DATA;
  const trips = tripsLive || ROUTING_DATA.trips;
  const active = trips.filter(t => t.status === 'en_ruta');
  const delayed = trips.filter(t => t.delay > 0 && t.status === 'en_ruta');

  return (
    <PageShell title="Dashboard" sub={`Semana del 21 al 27 de abril, 2026`}
      actions={<Btn small variant="ghost">↓ Exportar semana</Btn>}
    >
      {/* Alerts */}
      {delayed.length > 0 && (
        <div style={{ background: '#fef9c3', border: '1px solid #fde68a', borderRadius: 10, padding: '10px 16px', marginBottom: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 16 }}>⚠</span>
          <span style={{ fontSize: 13, color: '#92400e', fontWeight: 500 }}>
            {delayed.length} viaje{delayed.length > 1 ? 's' : ''} con retraso activo —
            {delayed.map(t => ` ${t.id} (+${t.delay} min)`).join(',')}
          </span>
        </div>
      )}

      {/* KPI row */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        <StatCard label="Viajes esta semana" value={weeklyStats.totalTrips} sub={`${weeklyStats.completed} completados`} accent="#10B981" trend={+8} />
        <StatCard label="En ruta ahora" value={active.length} sub="Actualizado en tiempo real" accent="#3B82F6" />
        <StatCard label="A tiempo" value={`${weeklyStats.onTimeRate}%`} sub={`${weeklyStats.onTime} de ${weeklyStats.totalTrips} viajes`} accent="#10B981" trend={-5} />
        <StatCard label="Con retraso" value={weeklyStats.delayed} sub={`Demora promedio: ${weeklyStats.avgDelay} min`} accent="#F59E0B" />
      </div>

      {/* Two cols */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 20 }}>
        {/* Recent trips */}
        <div>
          <SectionHeader title="Viajes recientes" action={
            <Btn small variant="ghost" onClick={() => onNavigate('trips')}>Ver todos →</Btn>
          } />
          <Table
            headers={['ID', 'Ruta', 'Conductor', 'Estado', 'ETA']}
            onRowClick={i => onNavigate('trip-detail', trips[i])}
            rows={trips.slice(0, 5).map(t => {
              const drv = ROUTING_DATA.drivers.find(d => d.id === t.driver);
              return [
                <span style={{ fontFamily: 'monospace', fontSize: 12, color: '#5a7366' }}>{t.id}</span>,
                <RouteArrow origin={t.origin} destination={t.destination} />,
                drv?.name || '—',
                <Chip status={t.status} small />,
                t.delay > 0
                  ? <span style={{ color: '#d97706', fontWeight: 600, fontSize: 12 }}>+{t.delay} min</span>
                  : <span style={{ color: '#15803d', fontSize: 12 }}>A tiempo</span>,
              ];
            })}
          />
        </div>

        {/* Right panel */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Weekly trend bars */}
          <div style={{ background: '#fff', borderRadius: 12, padding: '18px 20px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
            <SectionHeader title="Tendencia semanal" />
            <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end', height: 72 }}>
              {ROUTING_DATA.dailyTrends.map((d, i) => (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
                  <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 2, alignItems: 'center', justifyContent: 'flex-end', flex: 1 }}>
                    {d.delayed > 0 && <div style={{ width: '70%', height: d.delayed * 12, background: '#F59E0B', borderRadius: 3, minHeight: d.delayed > 0 ? 10 : 0 }} />}
                    {d.onTime > 0 && <div style={{ width: '70%', height: d.onTime * 12, background: '#10B981', borderRadius: 3, minHeight: d.onTime > 0 ? 10 : 0 }} />}
                    {d.trips === 0 && <div style={{ width: '70%', height: 4, background: '#e8f0ec', borderRadius: 3 }} />}
                  </div>
                  <span style={{ fontSize: 10, color: '#5a7366', fontWeight: 600 }}>{d.day}</span>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 12, marginTop: 10 }}>
              <span style={{ fontSize: 11, color: '#5a7366', display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, background: '#10B981', borderRadius: 2, display: 'inline-block' }}/>A tiempo</span>
              <span style={{ fontSize: 11, color: '#5a7366', display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, background: '#F59E0B', borderRadius: 2, display: 'inline-block' }}/>Retrasado</span>
            </div>
          </div>

          {/* Active drivers */}
          <div style={{ background: '#fff', borderRadius: 12, padding: '18px 20px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
            <SectionHeader title="Conductores activos" />
            {drivers.filter(d => d.status === 'en_ruta').map(d => (
              <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid #f0f4f2' }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, color: '#15803d', flexShrink: 0 }}>
                  {d.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#1a2e25', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</div>
                  <div style={{ fontSize: 11, color: '#5a7366' }}>Score: {d.score}%</div>
                </div>
                <Chip status="en_ruta" small />
              </div>
            ))}
          </div>
        </div>
      </div>
    </PageShell>
  );
}

// ── Live Operations ───────────────────────────────────────────────
function ScreenLiveOps({ onNavigate, trips: tripsLive }) {
  const { drivers, trucks } = ROUTING_DATA;
  const trips = tripsLive || ROUTING_DATA.trips;
  const [selected, setSelected] = useState(trips[0]);
  const [tick, setTick] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 4000);
    return () => clearInterval(id);
  }, []);

  const active = trips.filter(t => t.status === 'en_ruta');

  // Mocked route paths as SVG coordinates
  const routePaths = {
    'VJ-2026-041': { path: 'M 120 80 C 200 160 280 300 380 440', progress: 62 },
    'VJ-2026-040': { path: 'M 120 80 C 140 60 200 50 340 60', progress: 78 },
  };

  return (
    <PageShell title="Operaciones en vivo" sub="Estado actual de la flota">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20, height: 'calc(100vh - 180px)' }}>
        {/* Map panel */}
        <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 4px rgba(0,0,0,.06)', overflow: 'hidden', position: 'relative' }}>
          {/* Map BG */}
          <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0 }} viewBox="0 0 500 500" preserveAspectRatio="xMidYMid slice">
            {/* Grid lines */}
            {[0,50,100,150,200,250,300,350,400,450,500].map(x => (
              <line key={`v${x}`} x1={x} y1={0} x2={x} y2={500} stroke="#e8f0ec" strokeWidth="1"/>
            ))}
            {[0,50,100,150,200,250,300,350,400,450,500].map(y => (
              <line key={`h${y}`} x1={0} y1={y} x2={500} y2={y} stroke="#e8f0ec" strokeWidth="1"/>
            ))}
            {/* Coast shape (abstract) */}
            <path d="M 80 20 Q 100 40 90 80 Q 95 120 85 160 Q 90 200 80 240 Q 85 280 75 320 Q 80 360 70 400 Q 75 440 65 480" stroke="#c8e0d4" strokeWidth="3" fill="none" strokeDasharray="6 4"/>
            {/* Routes */}
            {/* Lima → Arequipa */}
            <path d="M 120 80 C 200 160 280 300 380 440" stroke="#10B981" strokeWidth="2.5" fill="none" strokeDasharray="8 4" opacity="0.6"/>
            {/* Lima → Trujillo */}
            <path d="M 120 80 C 140 60 200 50 340 60" stroke="#3B82F6" strokeWidth="2.5" fill="none" strokeDasharray="8 4" opacity="0.6"/>
            {/* City dots */}
            <circle cx="120" cy="80" r="7" fill="#10B981"/>
            <text x="130" y="84" fontSize="11" fill="#1a2e25" fontWeight="600">Lima</text>
            <circle cx="380" cy="440" r="6" fill="#e8f0ec" stroke="#10B981" strokeWidth="2"/>
            <text x="390" y="444" fontSize="11" fill="#5a7366">Arequipa</text>
            <circle cx="340" cy="60" r="6" fill="#e8f0ec" stroke="#3B82F6" strokeWidth="2"/>
            <text x="350" y="64" fontSize="11" fill="#5a7366">Trujillo</text>

            {/* Truck 1 on Lima→Arequipa route at 62% */}
            <circle cx={120 + (380-120)*.62} cy={80 + (440-80)*.62 + Math.sin(tick*.8)*6} r="10" fill={selected?.id === 'VJ-2026-041' ? '#10B981' : '#3B82F6'} stroke="#fff" strokeWidth="2.5"/>
            <text x={120 + (380-120)*.62 - 4} y={80 + (440-80)*.62 + Math.sin(tick*.8)*6 + 4} fontSize="10" fill="white" fontWeight="700">T1</text>

            {/* Truck 2 on Lima→Trujillo route at 78% */}
            <circle cx={120 + (340-120)*.78} cy={80 + (60-80)*.78 + Math.sin(tick*.8+1)*5} r="10" fill={selected?.id === 'VJ-2026-040' ? '#10B981' : '#3B82F6'} stroke="#fff" strokeWidth="2.5"/>
            <text x={120 + (340-120)*.78 - 4} y={80 + (60-80)*.78 + Math.sin(tick*.8+1)*5 + 4} fontSize="10" fill="white" fontWeight="700">T2</text>

            {/* Delay marker */}
            <circle cx={120 + (380-120)*.45} cy={80 + (440-80)*.45} r="8" fill="#fef9c3" stroke="#F59E0B" strokeWidth="2"/>
            <text x={120 + (380-120)*.45 - 4} y={80 + (440-80)*.45 + 4} fontSize="10" fill="#92400e" fontWeight="700">!</text>
          </svg>

          {/* Map legend */}
          <div style={{ position: 'absolute', bottom: 16, left: 16, background: 'rgba(255,255,255,.92)', backdropFilter: 'blur(4px)', borderRadius: 8, padding: '8px 12px', boxShadow: '0 2px 8px rgba(0,0,0,.1)', fontSize: 11, color: '#5a7366' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
              <div style={{ width: 20, height: 3, background: '#10B981', borderRadius: 2 }}/>Lima → Arequipa
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 20, height: 3, background: '#3B82F6', borderRadius: 2 }}/>Lima → Trujillo
            </div>
          </div>

          <div style={{ position: 'absolute', top: 16, left: 16, background: 'rgba(255,255,255,.92)', backdropFilter: 'blur(4px)', borderRadius: 8, padding: '6px 12px', fontSize: 11, color: '#5a7366', fontWeight: 600 }}>
            Vista de rutas — Perú
          </div>
        </div>

        {/* Right panel */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, overflowY: 'auto' }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.06em' }}>
            {active.length} viajes activos
          </div>
          {active.map(trip => {
            const drv = drivers.find(d => d.id === trip.driver);
            const trk = trucks.find(t => t.id === trip.truck);
            const isSel = selected?.id === trip.id;
            return (
              <div key={trip.id}
                onClick={() => setSelected(trip)}
                style={{
                  background: '#fff', borderRadius: 12, padding: '14px 16px',
                  boxShadow: isSel ? '0 0 0 2px #10B981, 0 2px 8px rgba(16,185,129,.15)' : '0 1px 4px rgba(0,0,0,.06)',
                  cursor: 'pointer', transition: 'box-shadow .2s',
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                  <span style={{ fontFamily: 'monospace', fontSize: 11, color: '#5a7366' }}>{trip.id}</span>
                  {trip.delay > 0 ? <Chip status="retrasado" small /> : <Chip status="en_ruta" small />}
                </div>
                <RouteArrow origin={trip.origin} destination={trip.destination} />
                <div style={{ marginTop: 10 }}>
                  <ProgressBar value={trip.progress} color={trip.delay > 0 ? '#F59E0B' : '#10B981'} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
                    <span style={{ fontSize: 11, color: '#5a7366' }}>{trip.progress}% completado</span>
                    <DelayBadge minutes={trip.delay} />
                  </div>
                </div>
                <div style={{ marginTop: 10, display: 'flex', gap: 12 }}>
                  <div>
                    <div style={{ fontSize: 10, color: '#5a7366', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.04em' }}>Conductor</div>
                    <div style={{ fontSize: 12, color: '#1a2e25', fontWeight: 600 }}>{drv?.name}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, color: '#5a7366', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.04em' }}>Camión</div>
                    <div style={{ fontSize: 12, color: '#1a2e25', fontWeight: 600 }}>{trk?.plate}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, color: '#5a7366', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.04em' }}>ETA</div>
                    <div style={{ fontSize: 12, color: '#1a2e25', fontWeight: 600 }}>{trip.etaReal ? trip.etaReal.split('T')[1] : trip.etaPlanned?.split('T')[1]}</div>
                  </div>
                </div>
              </div>
            );
          })}

          {/* Selected trip events mini */}
          {selected && selected.events.length > 0 && (
            <div style={{ background: '#fff', borderRadius: 12, padding: '14px 16px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#5a7366', marginBottom: 10, textTransform: 'uppercase', letterSpacing: '.04em' }}>Últimos eventos</div>
              {selected.events.slice(-3).map((ev, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, marginBottom: 8, alignItems: 'flex-start' }}>
                  <div style={{ width: 6, height: 6, borderRadius: '50%', marginTop: 4, background: ev.type === 'demora' ? '#F59E0B' : ev.type === 'llegada' ? '#10B981' : '#94a3b8', flexShrink: 0 }}/>
                  <div>
                    <div style={{ fontSize: 12, color: '#1a2e25', fontWeight: 500 }}>{ev.label}</div>
                    <div style={{ fontSize: 11, color: '#5a7366' }}>{ev.time} — {ev.detail.slice(0, 40)}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </PageShell>
  );
}

Object.assign(window, { ScreenDashboard, ScreenLiveOps });
