// Screen1Hoy.jsx — Resumen del TURNO actual.
//
// Vista de SOLO LECTURA enfocada en un único turno (AM o PM) de un día concreto.
// Por defecto muestra "ahora mismo": currentTurno() del todayKey().
// Flechas en la cabecera para retroceder / avanzar de turno en turno.
// Botón "Ir al turno actual" cuando estás viendo otro distinto del actual.

function Screen1Hoy({ tweaks, operador, onChangeOperator }) {
  const ahoraFecha = todayKey();
  const ahoraTurno = currentTurno();

  const [fecha, setFecha] = React.useState(ahoraFecha);
  const [turno, setTurno] = React.useState(ahoraTurno);

  const [refreshing, setRefreshing] = React.useState(false);
  const [lastSync, setLastSync] = React.useState(null);
  const [, force] = React.useReducer(x => x + 1, 0);

  const refresh = React.useCallback(async (silent) => {
    if (!silent) setRefreshing(true);
    const res = await cargarDia(fecha);
    if (res.ok) setLastSync(new Date());
    setRefreshing(false);
    force();
  }, [fecha]);

  // Refresca cuando cambia la fecha (no hace falta al cambiar turno: misma fecha).
  React.useEffect(() => { refresh(true); }, [fecha]);

  // ── Agregado del turno seleccionado ────────────────────────────
  const day = getDay(fecha);
  const turnoCerrado = day.turnos[turno].closed;
  const closedAt = day.turnos[turno].closedAt;

  let z1 = 0, z2 = 0, repZ1 = 0, repZ2 = 0;
  let totalRec = 0, propina = 0, gasolina = 0, otros = 0, entregado = 0;
  const ridersDone = [];
  const otrosDetalle = [];

  RIDERS.forEach(r => {
    const s = day.riders[r.id] && day.riders[r.id][turno];
    if (!s || s.status !== 'done') return;
    const peds = (s.z1 || 0) + (s.z2 || 0) + (s.repZ1 || 0) + (s.repZ2 || 0);
    const hayAlgo = peds > 0 || (s.totalRecaudado || 0) > 0
                  || (s.gasolina || 0) > 0 || (s.otrosGastos || 0) > 0;
    if (!hayAlgo) return;
    z1 += (s.z1 || 0);
    z2 += (s.z2 || 0);
    repZ1 += (s.repZ1 || 0);
    repZ2 += (s.repZ2 || 0);
    totalRec += s.totalRecaudado || 0;
    propina += s.propinaTarjeta || 0;
    gasolina += s.gasolina || 0;
    otros += s.otrosGastos || 0;
    entregado += s.entregadoEfectivo || 0;
    if ((s.otrosGastos || 0) > 0) {
      otrosDetalle.push({ rider: r, importe: s.otrosGastos, desc: s.otrosGastosDesc || '' });
    }
    ridersDone.push({ rider: r, state: s, peds });
  });

  const totZ1 = z1 + repZ1;
  const totZ2 = z2 + repZ2;
  const pedidos = totZ1 + totZ2;
  const totalRiders = totZ1 * TARIFA_Z1 + totZ2 * TARIFA_Z2;

  // ── Navegación entre turnos ────────────────────────────────────
  const goPrev = () => {
    const { fecha: f, turno: t } = shiftTurno(fecha, turno, -1);
    setFecha(f); setTurno(t);
  };
  const goNext = () => {
    const { fecha: f, turno: t } = shiftTurno(fecha, turno, +1);
    setFecha(f); setTurno(t);
  };
  const goAhora = () => { setFecha(ahoraFecha); setTurno(ahoraTurno); };

  const esAhora = (fecha === ahoraFecha) && (turno === ahoraTurno);
  const esFuturo = fecha > ahoraFecha || (fecha === ahoraFecha && turno === 'pm' && ahoraTurno === 'am');

  // Etiqueta principal del turno
  const turnoLabel = TURNO_LABELS[turno];
  const fechaLabel = formatDateLong(fecha);

  return (
    <div className={'app ' + (tweaks.dark ? 'dark' : '')}>
      <div className="appbar">
        <div className="eyebrow" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
          <span>Resumen de turno · {operador || '—'}</span>
          {!esAhora && (
            <button onClick={goAhora} style={{
              appearance: 'none', border: 0, background: 'transparent',
              fontFamily: 'inherit', fontSize: 11, color: 'var(--ink-2)',
              cursor: 'pointer', padding: 0, fontWeight: 500,
              borderBottom: '0.5px dotted var(--ink-3)',
              letterSpacing: 0,
            }}>
              Ir al turno actual
            </button>
          )}
        </div>
        <h1 style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <span>{turnoLabel}</span>
          <button onClick={() => refresh(false)} disabled={refreshing}
            aria-label="Refrescar desde Sheets"
            style={{
              width: 38, height: 38, border: 0, borderRadius: 10,
              background: 'var(--bg-sunk)', cursor: refreshing ? 'default' : 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--ink-2)', flexShrink: 0,
            }}>
            <svg width="16" height="16" viewBox="0 0 16 16"
              style={{ animation: refreshing ? 'spin 0.9s linear infinite' : 'none' }}>
              <path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2v3.5H10"
                stroke="currentColor" strokeWidth="1.5" fill="none"
                strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </h1>

        {/* Navegación de turno */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          marginTop: 8,
          background: 'var(--bg-sunk)', borderRadius: 12, padding: 4,
        }}>
          <button onClick={goPrev} aria-label="Turno anterior" style={{
            width: 36, height: 36, border: 0, background: 'transparent', cursor: 'pointer',
            borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--ink-2)',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M9 2l-5 5 5 5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <div style={{ flex: 1, textAlign: 'center', padding: '2px 0' }}>
            <div style={{
              fontSize: 13, fontWeight: 600, color: 'var(--ink)',
              letterSpacing: '-0.005em',
              display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8,
            }}>
              <span>{fechaLabel}</span>
              {esAhora && (
                <span style={{
                  fontSize: 9, fontWeight: 600, padding: '2px 6px',
                  borderRadius: 4, background: 'var(--good-bg)', color: 'var(--good)',
                  letterSpacing: 0.4, textTransform: 'uppercase',
                }}>Ahora</span>
              )}
              {turnoCerrado && (
                <span style={{
                  fontSize: 9, fontWeight: 600, padding: '2px 6px',
                  borderRadius: 4, background: 'var(--bg-elev)', color: 'var(--ink-3)',
                  border: '0.5px solid var(--hairline-2)',
                  letterSpacing: 0.4, textTransform: 'uppercase',
                }}>Cerrado</span>
              )}
            </div>
            <div style={{
              fontSize: 10, color: 'var(--ink-3)', marginTop: 2,
              fontFeatureSettings: '"tnum"', letterSpacing: '0.04em',
            }}>
              {formatDateShort(fecha)} · {turnoLabel}
              {turnoCerrado && closedAt && (
                <> · cerrado a las {new Date(closedAt).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })}</>
              )}
            </div>
          </div>
          <button onClick={goNext} aria-label="Turno siguiente" style={{
            width: 36, height: 36, border: 0, background: 'transparent', cursor: 'pointer',
            borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--ink-2)',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M5 2l5 5-5 5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>

        {lastSync && (
          <div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 6, fontFeatureSettings: '"tnum"', textAlign: 'right' }}>
            Sincronizado · {lastSync.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })}
          </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 turno
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
            <div className="num" style={{ fontSize: 48, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1 }}>
              {pedidos}
            </div>
            <div className="num" style={{
              fontSize: 14, color: 'var(--ink-3)', fontVariantNumeric: 'tabular-nums',
              letterSpacing: 0,
            }}>
              {totZ1} Z1 · {totZ2} Z2
              {(repZ1 + repZ2) > 0 && (
                <span style={{ marginLeft: 6, color: 'var(--ink-4)' }}>
                  ({repZ1 + repZ2} rep.)
                </span>
              )}
            </div>
          </div>
          <div style={{
            marginTop: 10, padding: '12px 14px',
            background: 'var(--bg-sunk)', borderRadius: 10,
            display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12,
          }}>
            <div>
              <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
                Total portes
              </div>
              <div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>
                {totZ1} × {eur(TARIFA_Z1)} + {totZ2} × {eur(TARIFA_Z2)}
              </div>
            </div>
            <div className="num" style={{
              fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em',
              fontVariantNumeric: 'tabular-nums', color: 'var(--ink)',
            }}>
              {eur(totalRiders)}
            </div>
          </div>
        </div>

        {esFuturo && pedidos === 0 && (
          <div style={{ padding: '24px 20px', textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>
            Turno futuro — sin cuentas aún
          </div>
        )}

        {!esFuturo && pedidos === 0 && totalRec === 0 && gasolina === 0 && otros === 0 && (
          <div style={{ padding: '24px 20px', textAlign: 'center', color: 'var(--ink-4)', fontSize: 13, lineHeight: 1.6 }}>
            No hay cuentas registradas en este turno todavía.
            {esAhora && <><br/>Cuando los repartidores hagan sus cuentas en <span style={{ color: 'var(--ink-3)', fontWeight: 500 }}>Cierre</span>, aparecerán aquí.</>}
          </div>
        )}

        {/* Gastos */}
        {(gasolina > 0 || otros > 0) && (
          <>
            <div className="section-label">
              <span>Gastos del turno</span>
            </div>
            {gasolina > 0 && <KPIRow label="Gasolina" value={eur(gasolina)} />}
            {otros > 0 && (
              <KPIRow label="Otros gastos" value={eur(otros)}
                extra={<OtrosLista items={otrosDetalle} />} />
            )}
          </>
        )}

        {/* Caja */}
        {(totalRec > 0 || propina > 0 || entregado > 0) && (
          <>
            <div className="section-label">
              <span>Caja</span>
            </div>
            <KPIRow label="Total recaudado" value={eur(totalRec)} />
            {propina > 0 && <KPIRow label="Propina tarjeta" value={eur(propina)} muted />}
            {entregado > 0 && <KPIRow label="Entregado efectivo" value={eur(entregado)} muted />}
          </>
        )}

        {/* Detalle por repartidor */}
        {ridersDone.length > 0 && (
          <>
            <div className="section-label">
              <span>Repartidores</span>
              <span className="count">{ridersDone.length}</span>
            </div>
            {ridersDone
              .sort((a, b) => b.peds - a.peds)
              .map(({ rider, state, peds }) => {
                const rZ1 = (state.z1 || 0) + (state.repZ1 || 0);
                const rZ2 = (state.z2 || 0) + (state.repZ2 || 0);
                const rGan = rZ1 * TARIFA_Z1 + rZ2 * TARIFA_Z2;
                return (
                  <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">
                        {peds} pedidos · Z1 {rZ1} · Z2 {rZ2}
                      </div>
                    </div>
                    <div className="rider-amount">
                      <div className="num">{eur(state.totalRecaudado || 0)}</div>
                      <div className="small num">{eur(rGan)} gan.</div>
                    </div>
                  </div>
                );
              })}
          </>
        )}

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

function KPIRow({ label, value, muted, extra }) {
  return (
    <div style={{
      padding: '14px 20px',
      borderBottom: '0.5px solid var(--hairline)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12,
      }}>
        <div style={{
          fontSize: 13, color: muted ? 'var(--ink-3)' : 'var(--ink-2)',
          fontWeight: muted ? 400 : 500,
        }}>
          {label}
        </div>
        <div className="num" style={{
          fontSize: muted ? 15 : 18, fontWeight: muted ? 500 : 600,
          letterSpacing: '-0.01em', fontVariantNumeric: 'tabular-nums',
          color: muted ? 'var(--ink-2)' : 'var(--ink)',
        }}>
          {value}
        </div>
      </div>
      {extra}
    </div>
  );
}

function OtrosLista({ items }) {
  return (
    <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 4 }}>
      {items.map((it, i) => (
        <div key={i} style={{
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12,
          fontSize: 11, color: 'var(--ink-4)',
        }}>
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {it.rider.name}
            {it.desc ? <span style={{ color: 'var(--ink-3)' }}> — {it.desc}</span> : null}
          </span>
          <span className="num" style={{ fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>
            {eur(it.importe)}
          </span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Screen1Hoy });
