/* seguimiento.jsx — Módulo 5 (v3): Seguimiento de camiones EN VIVO.
   NUEVO: panel "App Móvil de los choferes" — cada chofer (= 1 usuario de app, vinculado a su camión)
   marca desde el celular si arrancó / terminó la ruta, y el tablero web se actualiza on-live.
   Incluye autoplay "Simular jornada" para grabar la demo. Tablero por estado + historial.
   Registra window.CR.screens.Seguimiento. Patrón IIFE, JSX/Babel. */
(function () {
  window.CR = window.CR || {};
  window.CR.screens = window.CR.screens || {};
  var React = window.React;
  var ui = window.CR.ui, store = window.CR.store, K = window.CR.const;
  var h = React.createElement;

  var COLUMNAS = ['asignada', 'confirmada', 'en_curso', 'cerrada'];
  var SIGUIENTE = { asignada: 'confirmada', confirmada: 'en_curso', en_curso: 'cerrada' };
  var LABEL_AVANCE = { confirmada: 'Confirmar', en_curso: 'Arrancó', cerrada: 'Cerrar' };

  function avanzar(ruta, nuevo) {
    store.upsert('rutas', Object.assign({}, ruta, { estado: nuevo }));
    store.upsert('eventos', { rutaId: ruta.id, estado: nuevo, ts: Date.now() });
  }

  // tarjeta de un camión dentro de una columna del tablero
  function TarjetaCamion(props) {
    var r = props.ruta, chofer = props.chofer, sig = SIGUIENTE[r.estado];
    return h('div', { className: 'card', style: { padding: '12px', marginBottom: '10px' } },
      h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '8px', marginBottom: '6px' } },
        h('b', { style: { fontSize: '15px' } }, 'Camión ' + r.numero),
        h(ui.Badge, { color: 'neutral' }, K.labelZona(r.zona))),
      h('div', { className: 'muted', style: { fontSize: '13px', marginBottom: '4px' } }, chofer ? chofer.nombre : 'Sin chofer'),
      h('div', { style: { fontSize: '13px', marginBottom: '10px' } }, h('b', { className: 'tnum' }, r.paquetes || 0), ' paquetes'),
      sig
        ? h(ui.Button, { variant: sig === 'cerrada' ? 'danger' : 'primary', size: 'sm', onClick: function () { avanzar(r, sig); } }, LABEL_AVANCE[sig])
        : h('span', { className: 'muted', style: { fontSize: '12px' } }, 'Finalizada'));
  }

  function Columna(props) {
    var estado = props.estado, lista = props.rutas, choferById = props.choferById;
    return h('div', { style: { minWidth: 0 } },
      h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '10px' } },
        h(ui.Badge, { color: K.ESTADO_RUTA_COLOR[estado] || 'neutral', dot: true }, K.ESTADO_RUTA_LABEL[estado]),
        h('span', { className: 'muted tnum', style: { fontSize: '12px' } }, lista.length)),
      lista.length === 0
        ? h('div', { className: 'muted', style: { fontSize: '12px', padding: '8px 0' } }, 'Sin camiones')
        : lista.map(function (r) { return h(TarjetaCamion, { key: r.id, ruta: r, chofer: choferById[r.choferId] }); }));
  }

  // estado visual de la app del chofer según el estado de la ruta
  function appEstado(estado) {
    if (estado === 'en_curso') return { dot: 'live-dot live-dot--go', txt: 'En ruta — repartiendo', accion: 'cerrada', btn: 'Marcar: terminé', variant: 'danger' };
    if (estado === 'cerrada') return { dot: 'live-dot live-dot--on', txt: 'Jornada cerrada ✓', accion: null };
    if (estado === 'confirmada') return { dot: 'live-dot', txt: 'Avisado — esperando arranque', accion: 'en_curso', btn: 'Marcar: arranqué', variant: 'primary' };
    return { dot: 'live-dot', txt: 'Falta confirmar la programación', accion: null };
  }

  function Seguimiento() {
    window.CR.useStore();
    var playState = React.useState(false); var playing = playState[0], setPlaying = playState[1];
    var playRef = React.useRef(null);

    var rutas = store.list('rutas') || [];
    var choferes = store.list('choferes') || [];
    var vehiculos = store.list('vehiculos') || [];
    var eventos = store.list('eventos') || [];

    function stop() { if (playRef.current) { clearInterval(playRef.current); playRef.current = null; } setPlaying(false); }
    function tick() {
      var rs = store.list('rutas');
      var cand = rs.filter(function (r) { return r.choferId && (r.estado === 'confirmada' || r.estado === 'en_curso'); });
      if (!cand.length) { stop(); return; }
      // bias: si hay en_curso, a veces cerrar uno; si no, arrancar el primer confirmada
      var enCurso = cand.filter(function (r) { return r.estado === 'en_curso'; });
      var conf = cand.filter(function (r) { return r.estado === 'confirmada'; });
      var r = (enCurso.length && (!conf.length || Math.random() < 0.45)) ? enCurso[0] : (conf[0] || enCurso[0]);
      avanzar(r, SIGUIENTE[r.estado]);
    }
    function play() { if (playRef.current) return; playRef.current = setInterval(tick, 1200); setPlaying(true); }
    React.useEffect(function () { return function () { if (playRef.current) clearInterval(playRef.current); }; }, []);

    if (rutas.length === 0) {
      return h(ui.Page, { title: 'Seguimiento', subtitle: 'Estado de cada camión a lo largo del día' },
        h(ui.EmptyState, { title: 'Nada para seguir todavía',
          action: h(ui.Button, { variant: 'primary', onClick: function () { window.location.hash = '#/asignacion'; } }, 'Ir a Asignación') },
          'Cuando asignes camiones a las zonas van a aparecer acá para que los muevas por el día.'));
    }

    var choferById = {}; choferes.forEach(function (c) { choferById[c.id] = c; });
    var vById = {}; vehiculos.forEach(function (v) { vById[v.id] = v; });
    var rutaById = {}; rutas.forEach(function (r) { rutaById[r.id] = r; });

    // filas de la "app móvil": rutas con chofer asignado (1 chofer = 1 usuario de app, vinculado al camión)
    var appRows = rutas.filter(function (r) { return r.choferId; });
    var enRuta = appRows.filter(function (r) { return r.estado === 'en_curso'; }).length;
    var cerradas = appRows.filter(function (r) { return r.estado === 'cerrada'; }).length;
    var hayAvanzables = appRows.some(function (r) { return r.estado === 'confirmada' || r.estado === 'en_curso'; });

    var historial = eventos.slice().sort(function (a, b) { return b.ts - a.ts; });

    return h(ui.Page, { title: 'Seguimiento', subtitle: 'Estado de cada camión EN VIVO — los choferes actualizan desde su App Móvil' },

      // ---- App Móvil de los choferes (estado live) ----
      h(ui.Card, { title: 'App Móvil de los choferes (en vivo)',
        actions: h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
          h('span', { className: 'badge badge--info', dot: true }, 'En ruta: ' + enRuta),
          h('span', { className: 'badge badge--ok', dot: true }, 'Cerradas: ' + cerradas),
          playing
            ? h(ui.Button, { variant: 'danger', size: 'sm', onClick: stop }, '■ Parar simulación')
            : h(ui.Button, { variant: 'primary', size: 'sm', onClick: play, disabled: !hayAvanzables, title: hayAvanzables ? '' : 'Confirmá la programación primero' }, '▶ Simular jornada')) },
        h('p', { className: 'muted', style: { fontSize: 12, marginTop: 0 } },
          'Cada chofer entra con su usuario y ve sólo su camión. Lo que marca en el celular cambia el estado acá al instante.'),
        h('div', { className: 'appsim' },
          appRows.length === 0
            ? h('div', { className: 'muted', style: { fontSize: 13 } }, 'Todavía no hay camiones con chofer. Asigná y confirmá la programación.')
            : appRows.sort(function (a, b) { return (a.numero || '').localeCompare(b.numero || ''); }).map(function (r) {
                var ch = choferById[r.choferId];
                var veh = vById[r.vehiculoId];
                var au = window.CR.whatsapp.appUser(ch);
                var st = appEstado(r.estado);
                return h('div', { key: r.id, className: 'appsim-row' },
                  h('span', { className: st.dot }),
                  h('div', { className: 'who' },
                    h('b', null, ch ? ch.nombre : '—'),
                    h('span', { className: 'muted' }, (au ? au.handle + ' · ' : '') + 'Camión ' + r.numero + (veh ? ' · ' + veh.patente : ''))),
                  h('div', { style: { display: 'flex', flexDirection: 'column', minWidth: 150 } },
                    h('span', { style: { fontSize: 13 } }, st.txt),
                    h('span', { className: 'muted', style: { fontSize: 11 } }, K.labelZona(r.zona) + ' · ' + (r.paquetes || 0) + ' paquetes')),
                  h('div', { className: 'acts' },
                    st.accion
                      ? h(ui.Button, { variant: st.variant, size: 'sm', onClick: function () { avanzar(r, st.accion); } }, st.btn)
                      : h('span', { className: 'muted', style: { fontSize: 12 } }, '—')));
              }))),

      // ---- Tablero por estado ----
      h(ui.Card, { title: 'Tablero' },
        h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' } },
          COLUMNAS.map(function (estado) {
            var enEstado = rutas.filter(function (r) { return r.estado === estado; });
            return h(Columna, { key: estado, estado: estado, rutas: enEstado, choferById: choferById });
          }))),

      // ---- Historial ----
      h(ui.Card, { title: 'Historial' },
        historial.length === 0
          ? h('div', { className: 'muted', style: { fontSize: '13px' } }, 'Todavía no hay movimientos registrados.')
          : h('div', { className: 'timeline' },
              historial.map(function (ev, i) {
                var r = rutaById[ev.rutaId];
                var numero = r ? r.numero : ev.rutaId;
                return h('div', { className: 'ev', key: ev.id || i },
                  'Camión ' + numero + ' → ' + (K.ESTADO_RUTA_LABEL[ev.estado] || ev.estado) + ' · ' + new Date(ev.ts).toLocaleTimeString());
              }))));
  }

  window.CR.screens.Seguimiento = Seguimiento;
})();
