// Screen1Resumen.jsx — "Resumen": agregado mensual del 1 al fin de mes.
// - Hero: total pedidos del mes.
// - Gráfico: barras verticales día a día.
// - Click en día → abre detalle de ese día (DayDetail).
// - Flechas para navegar a meses anteriores.
// - Ranking por repartidor del mes.
//
// Sustituye a la antigua pestaña "Hoy" (Screen1Dashboard).

// Construye una "fila" agregada de un día (mismo shape que DAILY_HISTORY)
// leyendo de STATE_BY_DATE. Devuelve null si no hay actividad ese día.
function filaDeFecha(fecha) {
  const day = STATE_BY_DATE[fecha];
  if (!day) return null;
  let pedidos = 0, totalRec = 0, gasolina = 0, propina = 0, otros = 0;
  const ridersSet = new Set();
  RIDERS.forEach(r => {
    ['am','pm'].forEach(t => {
      const s = day.riders[r.id] && day.riders[r.id][t];
      if (!s || s.status !== 'done') return;
      const totZ1 = (s.z1 || 0) + (s.repZ1 || 0);
      const totZ2 = (s.z2 || 0) + (s.repZ2 || 0);
      const peds = totZ1 + totZ2;
      if (peds === 0 && (s.totalRecaudado || 0) === 0) return;
      pedidos += peds;
      totalRec += (s.totalRecaudado || 0);
      gasolina += (s.gasolina || 0);
      propina += (s.propinaTarjeta || 0);
      otros += (s.otrosGastos || 0);
      ridersSet.add(r.id);
    });
  });
  if (pedidos === 0 && totalRec === 0) return null;
  const [y, m, d] = fecha.split('-').map(Number);
  const dt = new Date(y, m - 1, d);
  return { fecha, weekday: dt.getDay(), pedidos, totalRec, gasolina, propina, otros, riders: ridersSet.size };
}

function Screen1Resumen({ tweaks, operador, onChangeOperator }) {
  const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
  const today = todayKey();
  const [y0, m0] = today.split('-').map(Number);

  // Mes actualmente visible. {y, m} con m 1-12.
  const [vista, setVista] = React.useState({ y: y0, m: m0 });
  const [diaSeleccionado, setDiaSeleccionado] = React.useState(null);

  // Sistema de carga desde backend
  const [loading, setLoading] = React.useState(false);
  const [progress, setProgress] = React.useState({ done: 0, total: 0 });
  const [, force] = React.useReducer(x => x + 1, 0);
  const cargaTokenRef = React.useRef(0);

  // ¿Estamos viendo el mes actual? Sólo entonces hay flecha "siguiente".
  const esMesActual = vista.y === y0 && vista.m === m0;

  const ultimoDia = new Date(vista.y, vista.m, 0).getDate();

  // Carga todos los días del mes visible desde el backend (con concurrencia 4).
  React.useEffect(() => {
    const miToken = ++cargaTokenRef.current;
    const fechas = [];
    for (let d = 1; d <= ultimoDia; d++) {
      const fecha = `${vista.y}-${String(vista.m).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
      if (fecha > today) continue; // sin sentido cargar el futuro
      fechas.push(fecha);
    }
    setLoading(true);
    setProgress({ done: 0, total: fechas.length });

    let idx = 0, done = 0;
    const CONC = 4;
    const trabajadores = Array.from({ length: Math.min(CONC, fechas.length) }, async () => {
      while (true) {
        if (cargaTokenRef.current !== miToken) return; // mes cambiado, abortar
        const i = idx++;
        if (i >= fechas.length) return;
        await cargarDia(fechas[i]);
        if (cargaTokenRef.current !== miToken) return;
        done++;
        setProgress({ done, total: fechas.length });
        force(); // refresca números mientras se va cargando
      }
    });
    Promise.all(trabajadores).then(() => {
      if (cargaTokenRef.current === miToken) setLoading(false);
    });
  }, [vista.y, vista.m, ultimoDia, today]);

  const dias = [];
  for (let d = 1; d <= ultimoDia; d++) {
    const fecha = `${vista.y}-${String(vista.m).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
    let row;
    if (fecha > today) row = null;
    else row = filaDeFecha(fecha); // lee de STATE_BY_DATE, da null si no hay datos
    dias.push({ fecha, row });
  }

  // Totales del mes
  const sum = dias.reduce((acc, d) => {
    if (!d.row) return acc;
    acc.pedidos += d.row.pedidos;
    acc.totalRec += d.row.totalRec;
    acc.gasolina += d.row.gasolina;
    acc.propina += d.row.propina;
    acc.otros += d.row.otros;
    acc.dias++;
    return acc;
  }, { pedidos: 0, totalRec: 0, gasolina: 0, propina: 0, otros: 0, dias: 0 });

  // Ranking por repartidor del mes
  const ranking = construirRanking(dias);

  const max = Math.max(1, ...dias.map(d => d.row ? d.row.pedidos : 0));

  // Navegación de meses
  const irMesAnterior = () => {
    setVista(v => v.m === 1 ? { y: v.y - 1, m: 12 } : { y: v.y, m: v.m - 1 });
  };
  const irMesSiguiente = () => {
    if (esMesActual) return;
    setVista(v => v.m === 12 ? { y: v.y + 1, m: 1 } : { y: v.y, m: v.m + 1 });
  };

  // Si hay día seleccionado, mostramos panel modal
  if (diaSeleccionado) {
    return (
      <DayDetail
        tweaks={tweaks}
        fecha={diaSeleccionado}
        onBack={() => setDiaSeleccionado(null)}
      />
    );
  }

  return (
    <div className={'app ' + (tweaks.dark ? 'dark' : '')}>
      <div className="appbar">
        <h1>Resumen</h1>
        <div className="date">
          Mes en curso · operador{' '}
          <span style={{ color: 'var(--ink-2)', fontWeight: 500, cursor: 'pointer', borderBottom: '0.5px dotted var(--ink-3)' }} onClick={onChangeOperator}>
            {operador || '—'}
          </span>
        </div>
      </div>

      <div className="scroll">
        {/* Selector de mes */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '14px 12px 6px',
        }}>
          <ArrowBtn dir="left" onClick={irMesAnterior} />
          <div style={{
            fontSize: 13, fontWeight: 600, letterSpacing: '0.04em',
            color: 'var(--ink)', textTransform: 'none',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
          }}>
            <span>{MONTH_NAMES[vista.m - 1]} {vista.y}</span>
            {loading && progress.total > 0 && (
              <span style={{
                fontSize: 10, fontWeight: 500, color: 'var(--ink-4)',
                fontVariantNumeric: 'tabular-nums', letterSpacing: '0.04em',
              }}>
                Sincronizando {progress.done}/{progress.total}…
              </span>
            )}
          </div>
          <ArrowBtn dir="right" onClick={irMesSiguiente} disabled={esMesActual} />
        </div>

        {/* HERO: pedidos del mes */}
        <div style={{ padding: '12px 20px 20px', borderBottom: '0.5px solid var(--hairline)' }}>
          <div style={{
            fontSize: 11, fontWeight: 600, letterSpacing: '0.1em',
            textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 6,
          }}>
            Pedidos del mes
          </div>
          <div className="num" style={{ fontSize: 44, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1.05 }}>
            {sum.pedidos}
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>
            {eur(sum.totalRec)} recaudado · {sum.dias}/{ultimoDia} días con cierre
          </div>
        </div>

        {/* GRÁFICO de barras día a día (pedidos) */}
        <div style={{ padding: '20px 16px 12px' }}>
          <div style={{
            fontSize: 11, fontWeight: 600, letterSpacing: '0.1em',
            textTransform: 'uppercase', color: 'var(--ink-3)',
            padding: '0 4px 12px',
          }}>
            Pedidos por día
          </div>
          <div style={{
            display: 'grid', gridTemplateColumns: `repeat(${ultimoDia}, 1fr)`, gap: 2,
            alignItems: 'end', height: 140,
          }}>
            {dias.map((d, i) => {
              const v = d.row ? d.row.pedidos : 0;
              const h = v > 0 ? Math.max(4, (v / max) * 100) : 2;
              const isToday = d.fecha === today;
              const isFuture = d.fecha > today;
              const tieneDatos = !!d.row && v > 0;
              return (
                <button
                  key={i}
                  onClick={() => tieneDatos && setDiaSeleccionado(d.fecha)}
                  disabled={!tieneDatos}
                  title={d.row ? `${Number(d.fecha.slice(-2))} · ${v} pedidos · ${eur(d.row.totalRec)}` : ''}
                  style={{
                    appearance: 'none', border: 0, padding: 0, margin: 0,
                    background: 'transparent',
                    height: '100%', display: 'flex', flexDirection: 'column',
                    justifyContent: 'flex-end', alignItems: 'stretch',
                    cursor: tieneDatos ? 'pointer' : 'default',
                  }}
                >
                  <div style={{
                    width: '100%', height: `${h}%`,
                    background: isFuture ? 'var(--bg-sunk)'
                      : isToday ? 'var(--ink)'
                      : v > 0 ? 'var(--ink-3)' : 'var(--bg-sunk)',
                    borderRadius: 2,
                    transition: 'height 200ms, background 120ms',
                  }}/>
                </button>
              );
            })}
          </div>
          {/* Eje numérico */}
          <div style={{
            display: 'grid', gridTemplateColumns: `repeat(${ultimoDia}, 1fr)`, gap: 2,
            marginTop: 8,
          }}>
            {dias.map((d, i) => {
              const dd = Number(d.fecha.slice(-2));
              const isToday = d.fecha === today;
              const mostrar = dd === 1 || dd === ultimoDia || dd % 5 === 0;
              return (
                <div key={i} style={{
                  fontSize: 9, textAlign: 'center',
                  color: isToday ? 'var(--ink)' : 'var(--ink-4)',
                  fontWeight: isToday ? 600 : 400,
                  fontVariantNumeric: 'tabular-nums',
                  letterSpacing: '0.02em',
                }}>
                  {mostrar ? dd : ''}
                </div>
              );
            })}
          </div>
          <div style={{
            padding: '10px 4px 0', fontSize: 11, color: 'var(--ink-4)',
            textAlign: 'center', lineHeight: 1.5,
          }}>
            Toca una barra para ver el detalle del día
          </div>
        </div>

        {/* RANKING por repartidor */}
        {ranking.length > 0 ? (
          <div style={{ borderTop: '0.5px solid var(--hairline)' }}>
            <div className="section-label">
              <span>Ranking repartidores</span>
              <span className="count">{ranking.length}</span>
            </div>
            {ranking.map((r, i) => (
              <RankingRow key={r.id} pos={i + 1} item={r} maxPedidos={ranking[0].pedidos} />
            ))}
          </div>
        ) : (
          <div style={{ padding: '24px 20px', textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>
            Sin actividad en {MONTH_NAMES[vista.m - 1].toLowerCase()}
          </div>
        )}

        <div style={{
          padding: '20px 20px 8px', fontSize: 12, color: 'var(--ink-4)',
          textAlign: 'center', lineHeight: 1.6,
        }}>
          Vista de solo lectura · para registrar cuentas usa{' '}
          <span style={{ color: 'var(--ink-3)', fontWeight: 500 }}>Cierre</span>
        </div>
        <div style={{ height: 16 }}/>
      </div>
    </div>
  );
}

// ─── Ranking por repartidor del mes ─────────────────────────────
function construirRanking(dias) {
  // Para cada día con datos, recorremos los riders del estado por fecha.
  const acc = {};
  RIDERS.forEach(r => { acc[r.id] = { id: r.id, name: r.name, initials: r.initials, pedidos: 0, ganancia: 0, totalRec: 0, dias: 0 }; });
  dias.forEach(d => {
    if (!d.row) return;
    const day = STATE_BY_DATE[d.fecha];
    if (!day) return;
    RIDERS.forEach(r => {
      let aporta = false;
      ['am','pm'].forEach(t => {
        const s = day.riders[r.id] && day.riders[r.id][t];
        if (!s || s.status !== 'done') return;
        const totZ1 = (s.z1 || 0) + (s.repZ1 || 0);
        const totZ2 = (s.z2 || 0) + (s.repZ2 || 0);
        const peds = totZ1 + totZ2;
        if (peds === 0 && (s.totalRecaudado || 0) === 0) return;
        acc[r.id].pedidos += peds;
        acc[r.id].ganancia += totZ1 * TARIFA_Z1 + totZ2 * TARIFA_Z2;
        acc[r.id].totalRec += s.totalRecaudado || 0;
        aporta = true;
      });
      if (aporta) acc[r.id].dias++;
    });
  });
  return Object.values(acc)
    .filter(r => r.pedidos > 0 || r.totalRec > 0)
    .sort((a, b) => b.pedidos - a.pedidos);
}

function RankingRow({ pos, item, maxPedidos }) {
  const pct = maxPedidos > 0 ? (item.pedidos / maxPedidos) * 100 : 0;
  return (
    <div style={{
      padding: '12px 20px',
      borderBottom: '0.5px solid var(--hairline)',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 22, fontSize: 11, fontWeight: 600,
        color: 'var(--ink-4)', fontVariantNumeric: 'tabular-nums',
        textAlign: 'right',
      }}>
        {pos}
      </div>
      <div className="avatar" style={{ flexShrink: 0 }}>{item.initials}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 14, fontWeight: 500, color: 'var(--ink)',
          marginBottom: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>
          {item.name}
        </div>
        <div style={{
          height: 4, background: 'var(--bg-sunk)', borderRadius: 2, overflow: 'hidden',
        }}>
          <div style={{
            width: `${pct}%`, height: '100%', background: 'var(--ink-2)',
            transition: 'width 200ms',
          }}/>
        </div>
        <div style={{
          fontSize: 11, color: 'var(--ink-4)', marginTop: 4,
          fontVariantNumeric: 'tabular-nums',
        }}>
          {item.dias} {item.dias === 1 ? 'día' : 'días'} · ganancia {eur(item.ganancia)}
        </div>
      </div>
      <div style={{
        textAlign: 'right', flexShrink: 0,
      }}>
        <div className="num" style={{
          fontSize: 16, fontWeight: 600, color: 'var(--ink)',
          fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em',
        }}>
          {item.pedidos}
        </div>
        <div style={{
          fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.06em',
          textTransform: 'uppercase', marginTop: 1,
        }}>
          pedidos
        </div>
      </div>
    </div>
  );
}

// ─── Detalle de un día ──────────────────────────────────────────
function DayDetail({ tweaks, fecha, onBack }) {
  const day = getDay(fecha);
  const today = todayKey();
  const [y, m, d] = fecha.split('-').map(Number);
  const dt = new Date(y, m - 1, d);
  const wd = WEEKDAY_SHORT[dt.getDay()];
  const titulo = fecha === today ? 'Hoy' : `${cap(wd)} ${d} ${MONTH_NAMES[m-1].toLowerCase().slice(0,3)}`;

  const aggTurno = (turno) => {
    const rows = [];
    let pedidos = 0, totalRec = 0, gan = 0;
    RIDERS.forEach(r => {
      const s = day.riders[r.id] && day.riders[r.id][turno];
      if (!s || s.status !== 'done') return;
      const totZ1 = (s.z1 || 0) + (s.repZ1 || 0);
      const totZ2 = (s.z2 || 0) + (s.repZ2 || 0);
      const peds = totZ1 + totZ2;
      if (peds === 0 && (s.totalRecaudado || 0) === 0) return;
      const ganR = totZ1 * TARIFA_Z1 + totZ2 * TARIFA_Z2;
      pedidos += peds;
      totalRec += s.totalRecaudado || 0;
      gan += ganR;
      rows.push({ rider: r, state: s, totZ1, totZ2, ganR });
    });
    rows.sort((a, b) => (b.totZ1 + b.totZ2) - (a.totZ1 + a.totZ2));
    return { rows, pedidos, totalRec, gan };
  };

  const am = aggTurno('am');
  const pm = aggTurno('pm');
  const totalPed = am.pedidos + pm.pedidos;
  const totalRec = am.totalRec + pm.totalRec;
  const totalGan = am.gan + pm.gan;

  function cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); }

  return (
    <div className={'app ' + (tweaks.dark ? 'dark' : '')}>
      <div className="appbar">
        <button onClick={onBack} style={{
          appearance: 'none', border: 0, background: 'transparent',
          padding: '8px 0', marginBottom: 4, cursor: 'pointer',
          fontFamily: 'inherit', fontSize: 13, color: 'var(--ink-3)',
          display: 'flex', alignItems: 'center', gap: 4,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="15 18 9 12 15 6"/>
          </svg>
          Resumen
        </button>
        <h1>{titulo}</h1>
        <div className="date">{formatDateLong(fecha)}</div>
      </div>

      <div className="scroll">
        {/* Hero */}
        <div style={{ padding: '20px 20px 18px', borderBottom: '0.5px solid var(--hairline)' }}>
          <div style={{
            fontSize: 11, fontWeight: 600, letterSpacing: '0.1em',
            textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 6,
          }}>
            Pedidos del día
          </div>
          <div className="num" style={{ fontSize: 38, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1.05 }}>
            {totalPed}
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>
            {eur(totalRec)} recaudado · ganancia {eur(totalGan)}
          </div>
        </div>

        {/* Por turno */}
        <DayShiftBlock label={TURNO_LABELS.am} data={am} />
        <DayShiftBlock label={TURNO_LABELS.pm} data={pm} />

        <div style={{ height: 24 }}/>
      </div>
    </div>
  );
}

function DayShiftBlock({ label, data }) {
  if (data.rows.length === 0) {
    return (
      <div style={{
        padding: '16px 20px', borderBottom: '0.5px solid var(--hairline)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      }}>
        <div style={{
          fontSize: 11, fontWeight: 600, letterSpacing: '0.1em',
          textTransform: 'uppercase', color: 'var(--ink-3)',
        }}>
          {label}
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-4)' }}>Sin actividad</div>
      </div>
    );
  }
  return (
    <div style={{ borderBottom: '0.5px solid var(--hairline)' }}>
      <div style={{
        padding: '16px 20px 8px',
        display: 'flex', alignItems: 'baseline', gap: 12,
      }}>
        <div style={{
          fontSize: 11, fontWeight: 600, letterSpacing: '0.1em',
          textTransform: 'uppercase', color: 'var(--ink-3)', flex: 1,
        }}>
          {label}
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', fontVariantNumeric: 'tabular-nums' }}>
          {data.pedidos} pedidos · {eur(data.totalRec)}
        </div>
      </div>
      {data.rows.map(({ rider, state, totZ1, totZ2, ganR }) => (
        <div key={rider.id} className="rider-row compact" style={{ cursor: 'default' }}>
          <div className="avatar">{rider.initials}</div>
          <div className="rider-meta">
            <div className="rider-name">{rider.name}</div>
            <div className="rider-sub">
              {totZ1 + totZ2} pedidos · Z1 {totZ1} · Z2 {totZ2}
            </div>
          </div>
          <div className="rider-amount">
            <div className="num">{eur(state.totalRecaudado || 0)}</div>
            <div className="small num">{eur(ganR)} gan.</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Botón flecha de navegación ─────────────────────────────────
function ArrowBtn({ dir, onClick, disabled }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      appearance: 'none', border: 0, background: 'transparent',
      width: 36, height: 36, borderRadius: 8,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      cursor: disabled ? 'default' : 'pointer',
      opacity: disabled ? 0.25 : 1,
      color: 'var(--ink-2)',
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        {dir === 'left'
          ? <polyline points="15 18 9 12 15 6"/>
          : <polyline points="9 18 15 12 9 6"/>}
      </svg>
    </button>
  );
}

Object.assign(window, { Screen1Resumen });
