/* Módulo 1 — Importar pedidos de Mercado Libre (CSV). Upload -> loading -> análisis por zona ->
   asigna automáticamente por capacidad+ranking y salta a Asignación. window.CR.screens.Importar */
(function () {
  var React = window.React;
  var ui = window.CR.ui, store = window.CR.store, K = window.CR.const;
  var h = React.createElement;

  function Importar() {
    window.CR.useStore();
    var st = React.useState({ pedidos: [], zonas: [], fileName: '', loading: false, drag: false });
    var s = st[0], set = function (p) { st[1](Object.assign({}, st[0], p)); };

    function analizar(texto, fileName) {
      var pedidos = window.CR.csv.parse(texto);
      var zonas = window.CR.aggregate.porZona(pedidos);
      set({ pedidos: pedidos, zonas: zonas, fileName: fileName || s.fileName });
    }
    function onFile(file) {
      if (!file) return;
      var fr = new FileReader();
      fr.onload = function (e) { analizar(String(e.target.result), file.name); };
      fr.readAsText(file);
    }
    function cargarDemo() {
      fetch((window.CR_SEED && window.CR_SEED.csvDemo) || 'data/pedidos-mercadolibre-demo.csv')
        .then(function (r) { return r.text(); })
        .then(function (t) { analizar(t, 'pedidos-mercadolibre-demo.csv'); })
        .catch(function () { alert('No pude leer el CSV demo (¿estás sirviendo la carpeta con un server local?).'); });
    }
    function confirmar() { store.bulkSet('pedidos', s.pedidos); set({ loading: true }); }
    function trasLoading() {
      var ir = function () { set({ loading: false }); window.location.hash = '#/asignacion'; };
      // Si hay backend local conectado, la ingesta+optimización corre por la API (mismo contrato que la VPS).
      if (window.CR.backend && window.CR.backend.enabled) {
        var carga = parseInt(localStorage.getItem('cr.cargaObjetivo') || '75', 10);
        window.CR.backend.ingestarYOptimizar(s.pedidos, K.hoy(), carga)
          .then(function () { window.CR._leftovers = []; ir(); })
          .catch(function (e) { console.error('[backend] falló, caigo a local', e); local(); });
        return;
      }
      local();
      function local() {
        var zonas = window.CR.aggregate.porZona(s.pedidos);
        var carga = parseInt(localStorage.getItem('cr.cargaObjetivo') || '75', 10);
        var r = window.CR.engine.asignarPorCapacidad(zonas, store.list('vehiculos'), store.list('choferes'), { cargaObjetivo: carga });
        store.bulkSet('rutas', window.CR.engine.aplanar(r)); // incluye placeholders de leftovers
        store.bulkSet('eventos', []);
        window.CR._leftovers = [];
        ir();
      }
    }

    var tot = window.CR.aggregate.totales(s.pedidos);

    return h('div', null,
      h(ui.Page, { title: 'Importar pedidos', subtitle: 'Subí el archivo de pedidos a retirar que bajás de Mercado Libre (CSV).' }),
      h(ui.LoadingOverlay, {
        open: s.loading, title: 'Procesando información',
        steps: ['Leyendo pedidos del archivo…', 'Detectando zonas y localidades…', 'Calculando paquetes por zona…', 'Asignando camiones por capacidad y ranking…'],
        durationMs: 2600, onDone: trasLoading
      }),

      h(ui.Card, null,
        h('div', {
          className: 'dropzone' + (s.drag ? ' drag' : ''),
          onClick: function () { document.getElementById('cr-file').click(); },
          onDragOver: function (e) { e.preventDefault(); set({ drag: true }); },
          onDragLeave: function () { set({ drag: false }); },
          onDrop: function (e) { e.preventDefault(); set({ drag: false }); onFile(e.dataTransfer.files[0]); }
        },
          h('div', { style: { fontSize: 30, marginBottom: 6 } }, '📄'),
          h('b', null, s.fileName || 'Arrastrá el CSV acá o hacé click para elegirlo'),
          h('div', { className: 'muted', style: { marginTop: 4, fontSize: 12 } }, 'Columnas: id_pedido, seller, depósito, localidad, paquetes, franja horaria')),
        h('input', { id: 'cr-file', type: 'file', accept: '.csv,text/csv', style: { display: 'none' },
          onChange: function (e) { onFile(e.target.files[0]); } }),
        h('div', { className: 'toolbar', style: { marginTop: 14 } },
          h(ui.Button, { onClick: cargarDemo, icon: '⬇' }, 'Cargar archivo de ejemplo'),
          h('div', { className: 'spacer' }),
          s.pedidos.length ? h(ui.Button, { variant: 'primary', onClick: confirmar }, 'Confirmar e importar (' + tot.paquetes + ' paquetes)') : null)),

      s.pedidos.length ? h('div', null,
        h('div', { className: 'grid grid--stats', style: { marginBottom: 14 } },
          h(ui.StatCard, { label: 'Pedidos', value: tot.pedidos }),
          h(ui.StatCard, { label: 'Paquetes', value: tot.paquetes, tone: 'accent' }),
          h(ui.StatCard, { label: 'Zonas detectadas', value: tot.zonas }),
          h(ui.StatCard, { label: 'Sin zona', value: tot.sinZona, tone: tot.sinZona ? 'danger' : null })),

        h(ui.Card, { title: 'Paquetes por zona (análisis automático)' },
          s.zonas.map(function (z) {
            var max = Math.max.apply(null, s.zonas.map(function (x) { return x.total; }).concat([1]));
            return h('div', { key: z.zona, style: { marginBottom: 12 } },
              h('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 4 } },
                h('b', null, K.labelZona(z.zona)),
                h('span', { className: 'muted' }, z.total + ' paquetes · ' + z.localidades.length + ' localidades')),
              h('div', { className: 'bar' }, h('span', { style: { width: (z.total / max * 100) + '%' } })),
              h('div', { className: 'muted', style: { fontSize: 11, marginTop: 3 } },
                z.localidades.map(function (l) { return l.localidad + ' (' + l.paquetes + ')'; }).join(' · ')));
          })),

        h(ui.Card, { title: 'Detalle de pedidos' },
          h(ui.DataTable, {
            rowKey: 'id_pedido',
            columns: [
              { key: 'id_pedido', label: 'Pedido' },
              { key: 'seller', label: 'Seller' },
              { key: 'localidad', label: 'Localidad' },
              { key: 'zona', label: 'Zona', render: function (r) { return r.zona ? h(ui.Badge, { color: 'info' }, K.labelZona(r.zona)) : h(ui.Badge, { color: 'danger' }, 'sin zona'); } },
              { key: 'paquetes', label: 'Paquetes', align: 'right' },
              { key: 'franja', label: 'Franja' }
            ],
            rows: s.pedidos
          }))
      ) : h(ui.Card, null, h(ui.EmptyState, { title: 'Todavía no cargaste pedidos' }, 'Subí el CSV de Mercado Libre o usá el archivo de ejemplo para ver la demo.')),

      h('p', { className: 'muted', style: { fontSize: 12, marginTop: 10 } },
        'El formato del archivo es provisorio; se reajusta con un export real de Mercado Libre del cliente.'));
  }

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