/* notificar.jsx — pantalla "Notificar choferes" (v2).
   Un mensaje de WhatsApp por camión asignado, listo para enviar.
   Patrón IIFE. JSX/Babel. Registra window.CR.screens.Notificar. NO redefine globals. */
(function () {
  var React = window.React;
  var ui = window.CR.ui, store = window.CR.store, K = window.CR.const;

  var ACK_OPTS = ['pendiente', 'enviado', 'visto', 'confirmo', 'sin_respuesta'].map(function (k) {
    return { value: k, label: K.ACK_LABEL[k] };
  });

  function Notificar() {
    window.CR.useStore(); // re-render reactivo
    var copiadoState = React.useState(null);
    var copiado = copiadoState[0], setCopiado = copiadoState[1];
    var sendState = React.useState(false); var sending = sendState[0], setSending = sendState[1];
    var sentState = React.useState(false); var sent = sentState[0], setSent = sentState[1];

    var rutas = store.list('rutas');
    var choferes = store.list('choferes');
    var lote = window.CR.whatsapp.lote(rutas, choferes, store.list('vehiculos'));

    if (!lote || lote.length === 0) {
      return (
        <ui.Page title="Notificar choferes" subtitle="Un mensaje por camión asignado, listo para enviar">
          <ui.EmptyState
            title="Asigná los camiones primero"
            action={<ui.Button variant="primary" onClick={function () { window.location.hash = '#/asignacion'; }}>Ir a Asignación</ui.Button>}
          >
            Todavía no hay camiones asignados con chofer. Cuando asignes las unidades vas a ver acá un mensaje listo para cada camión.
          </ui.EmptyState>
        </ui.Page>
      );
    }

    // ack vive en el chofer asignado a cada ruta (fuente de verdad)
    function ackDe(item) {
      var ch = store.get('choferes', item.choferId);
      return ch ? (ch.ack || 'pendiente') : (item.ack || 'pendiente');
    }

    var total = lote.length;
    var confirmados = lote.filter(function (it) { return ackDe(it) === 'confirmo'; }).length;

    // Pantalla demo: el envío real vive en asignacion-real -> backend.notificar().
    function enviarTodo() { setSending(true); }
    function trasEnviar() {
      window.CR.whatsapp.dispararLote(lote).catch(function () {});
      lote.forEach(function (it) {
        var ch = store.get('choferes', it.choferId);
        if (ch && (!ch.ack || ch.ack === 'pendiente')) store.upsert('choferes', Object.assign({}, ch, { ack: 'enviado' }));
      });
      setSending(false); setSent(true);
    }

    function copiar(item) {
      var txt = item.mensaje || '';
      function ok() {
        setCopiado(item.rutaId);
        window.setTimeout(function () {
          setCopiado(function (cur) { return cur === item.rutaId ? null : cur; });
        }, 1800);
      }
      try {
        if (navigator.clipboard && navigator.clipboard.writeText) {
          navigator.clipboard.writeText(txt).then(ok, function () { fallbackCopy(txt); ok(); });
        } else { fallbackCopy(txt); ok(); }
      } catch (e) { fallbackCopy(txt); ok(); }
    }

    function fallbackCopy(txt) {
      try {
        var ta = document.createElement('textarea');
        ta.value = txt; ta.style.position = 'fixed'; ta.style.left = '-9999px';
        document.body.appendChild(ta); ta.select();
        document.execCommand('copy'); document.body.removeChild(ta);
      } catch (e) { /* sin clipboard disponible */ }
    }

    function setAck(item, nuevo) {
      var ch = store.get('choferes', item.choferId);
      if (!ch) return;
      var next = {}; for (var k in ch) next[k] = ch[k];
      next.ack = nuevo;
      store.upsert('choferes', next);
    }

    return (
      <ui.Page title="Notificar choferes" subtitle="Aviso automático por App Móvil + WhatsApp. Un mensaje por camión asignado.">
        <ui.LoadingOverlay open={sending} title="Simulando avisos"
          steps={['Preparando la vista previa…', 'Simulando la notificación…', 'Actualizando el estado local…']}
          durationMs={1900} onDone={trasEnviar} />
        <ui.SuccessOverlay open={sent} title="Simulación completada"
          subtitle={total + ' aviso(s) simulados. No se envió ningún WhatsApp desde esta pantalla.'}
          ctaLabel="Entendido" onClose={function () { setSent(false); }} />

        <ui.Toolbar>
          <ui.Button variant="primary" icon="📲" onClick={enviarTodo}>
            Simular avisos ({total})
          </ui.Button>
          <ui.Badge dot color={confirmados === total ? 'ok' : 'info'}>
            Confirmaron {confirmados} de {total}
          </ui.Badge>
          <span className="muted" style={{ fontSize: '13px' }}>
            {confirmados === total ? 'Todos los choferes confirmaron' : 'Esperando confirmaciones'}
          </span>
          <div className="spacer" />
          <ui.Badge color="neutral" dot>{'WhatsApp: ' + window.CR.whatsapp.modo()}</ui.Badge>
        </ui.Toolbar>

        <p className="muted" style={{ fontSize: '12px', margin: '0 0 12px' }}>
          Esta pantalla sólo previsualiza y simula avisos; <b>no envía WhatsApp</b>. El envío operativo se realiza al confirmar la jornada
          mediante el backend, que resuelve el destino y aplica las guardas de seguridad e idempotencia.
        </p>

        {lote.map(function (item) {
          var ackActual = ackDe(item);
          var actions = (
            <ui.Toolbar>
              <ui.Button onClick={function () { copiar(item); }}>
                {copiado === item.rutaId ? 'Copiado' : 'Copiar'}
              </ui.Button>
              <ui.Button variant="primary" onClick={function () { window.open(item.link, '_blank'); }}>
                Abrir WhatsApp
              </ui.Button>
            </ui.Toolbar>
          );
          var header = (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
              <span>{item.chofer ? item.chofer.nombre : '—'}</span>
              {item.esAgencia ? <ui.Badge color="info">Agencia</ui.Badge> : null}
              {item.chofer ? <span className="appphone">📱 {window.CR.whatsapp.appUser(item.chofer).handle}</span> : null}
              <span className="muted" style={{ fontWeight: 400 }}>
                Camión {item.numero} · {K.labelZona(item.zona)} · {item.paquetes} paquetes
              </span>
            </span>
          );
          return (
            <ui.Card key={item.rutaId} title={header} actions={actions}>
              <div
                style={{
                  whiteSpace: 'pre-wrap', fontFamily: 'inherit', margin: 0,
                  background: 'var(--surface-2, rgba(0,0,0,.04))', borderRadius: '10px',
                  padding: '12px 14px', fontSize: '13px', lineHeight: 1.5
                }}
              >
                {item.mensaje}
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: '12px', marginTop: '12px', flexWrap: 'wrap' }}>
                <ui.Field label="Estado de respuesta">
                  <ui.Select
                    value={ackActual}
                    options={ACK_OPTS}
                    onChange={function (v) { setAck(item, v); }}
                  />
                </ui.Field>
                <div style={{ paddingBottom: '6px' }}>
                  <ui.Badge dot color={K.ACK_COLOR[ackActual] || 'neutral'}>
                    {K.ACK_LABEL[ackActual] || ackActual}
                  </ui.Badge>
                </div>
              </div>
            </ui.Card>
          );
        })}
      </ui.Page>
    );
  }

  window.CR.screens = window.CR.screens || {};
  window.CR.screens.Notificar = Notificar;
})();
