/* Recorrido del día + Agenda · Pieza 3a
   La corrección de fondo: "Trabajos" mezclaba dos cosas que no se parecen.
     · TURNOS       → tienen hora. Se ordenan en el tiempo, tienen huecos y
                      recorrido. Es lo que el tipo mira 20 veces por día.
     · PRESUPUESTOS → no tienen hora. Esperan respuesta. Es pipeline.
   Filtrar una sola lista por estado (Todos/Confirmados/Esperando) escondía esa
   diferencia. Ahora la pestaña es AGENDA y adentro hay dos segmentos.        */

const min = h => { const [a,b] = h.split(':').map(Number); return a * 60 + b; };
const hm = m => m < 60 ? `${m}\u2032` : `${Math.floor(m/60)} h${m%60 ? ' ' + (m%60) + '\u2032' : ''}`;
const conHora = j => j.hora && j.hora !== '\u2014';

/* ── recorrido del día: rail de tiempo con huecos ─────────── */
function Recorrido({ jobs, cfg, open, dia = 'HOY' }) {
  const dom = atiendeDomicilio(cfg);
  const dia_ = jobs.filter(j => j.dia === dia && conHora(j)).sort((a,b) => min(a.hora) - min(b.hora));
  /* Los bordes salen del horario de ESE día. Si el día tiene corte al mediodía
     el hueco del almuerzo no es un hueco libre: está cerrado. */
  const clave = dia === 'HOY' ? 'J' : dia === 'MAÑANA' ? 'V' : 'S';
  const b = bordesDia(cfg.horario, clave) || ['09:00','19:00'];
  const abre = b[0], cierra = b[1];
  const enCurso = dia_.find(j => !esCierre(j.tsm) && j.tsm !== 'RELEVADO');

  if (!dia_.length) return (
    <Card pad={16} gap={6}>
      <Lbl>RECORRIDO DE {dia}</Lbl>
      <div style={{ fontFamily:T.sans, fontSize:14, color:T.c300 }}>Sin turnos agendados.</div>
      <div style={{ fontFamily:T.mono, fontSize:10, color:T.c500 }}>ABIERTO {abre} A {cierra}</div>
    </Card>
  );

  const filas = [];
  const franjas = (cfg.horario[clave] || [[abre, cierra]]).map(([x,y]) => [min(x), min(y)]);
  /* El hueco libre se mide DENTRO de las franjas abiertas: el mediodía cerrado
     no es tiempo disponible, y decir "3 h libre" ahí sería mentira. */
  const libreEntre = (d, h) => franjas.reduce((s,[a,b]) => s + Math.max(0, Math.min(h,b) - Math.max(d,a)), 0);
  const cerrado = (d, h) => (h - d) - libreEntre(d, h);
  filas.push({ t:'borde', hora:abre, txt:'ABRÍS' });
  dia_.forEach((j, i) => {
    const prev = i ? dia_[i-1] : null;
    const desde = prev ? min(prev.hora) + 60 : min(abre);
    const hasta = min(j.hora);
    const libre = libreEntre(desde, hasta), cerr = cerrado(desde, hasta);
    if (cerr >= 30) filas.push({ t:'cerrado', m:cerr });
    if (libre >= 30) filas.push({ t:'hueco', m:libre });
    filas.push({ t:'job', j });
  });
  const ultimo = min(dia_[dia_.length-1].hora) + 60;
  const libreFin = libreEntre(ultimo, min(cierra)), cerrFin = cerrado(ultimo, min(cierra));
  if (cerrFin >= 30) filas.push({ t:'cerrado', m:cerrFin });
  if (libreFin >= 30) filas.push({ t:'hueco', m:libreFin });
  filas.push({ t:'borde', hora:cierra, txt:'CERRÁS' });

  return (
    <Card pad={0} gap={0} style={{ overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'baseline', gap:10, padding:'15px 16px 12px' }}>
        <Lbl>RECORRIDO DE {dia}</Lbl>
        <span style={{ marginLeft:'auto', fontFamily:T.mono, fontSize:9.5, color:T.c500 }}>{dia_.length} {dia_.length === 1 ? 'PARADA' : 'PARADAS'}</span>
      </div>
      <div style={{ padding:'0 16px 14px' }}>
        {filas.map((f, k) => {
          if (f.t === 'borde') return (
            <div key={k} style={{ display:'flex', alignItems:'center', gap:12, minHeight:30 }}>
              <span style={{ width:44, flex:'none', fontFamily:T.mono, fontSize:10, color:T.c500, textAlign:'right' }}>{f.hora}</span>
              <span style={{ width:9, flex:'none', height:1, background:T.g700, display:'block' }} />
              <span style={{ fontFamily:T.mono, fontSize:9, letterSpacing:'.12em', color:T.c500 }}>{f.txt}</span>
            </div>
          );
          if (f.t === 'cerrado') return (
            <div key={k} style={{ display:'flex', alignItems:'center', gap:12, minHeight:30 }}>
              <span style={{ width:44, flex:'none' }} />
              <span style={{ width:9, flex:'none', display:'flex', justifyContent:'center' }}><i style={{ width:1, height:30, background:T.g800, display:'block' }} /></span>
              <span style={{ fontFamily:T.mono, fontSize:9, letterSpacing:'.11em', color:T.c500 }}>CERRADO · {hm(f.m)}</span>
            </div>
          );
          if (f.t === 'hueco') return (
            <div key={k} style={{ display:'flex', alignItems:'center', gap:12, minHeight:34 }}>
              <span style={{ width:44, flex:'none' }} />
              <span style={{ width:9, flex:'none', display:'flex', justifyContent:'center' }}><i style={{ width:1, height:34, background:`repeating-linear-gradient(${T.g700} 0 3px, transparent 3px 7px)`, display:'block' }} /></span>
              <span style={{ fontFamily:T.mono, fontSize:9.5, color:T.c300, letterSpacing:'.06em' }}>{hm(f.m)} libre</span>
            </div>
          );
          const j = f.j, ahora = enCurso && j.id === enCurso.id, hecho = esCobrado(j.tsm);
          const c = hecho ? T.green : ahora ? T.v600 : T.c500;
          return (
            <button key={k} onClick={() => open(j)} style={{ display:'flex', alignItems:'flex-start', gap:12, minHeight:64, width:'100%', background:'transparent', border:'none', padding:'7px 0', cursor:'pointer', textAlign:'left' }}>
              <span style={{ width:44, flex:'none', fontFamily:T.mono, fontSize:12.5, color:ahora?T.c100:T.c300, textAlign:'right', paddingTop:2 }}>{j.hora}</span>
              <span style={{ width:9, flex:'none', display:'flex', justifyContent:'center', paddingTop:5 }}>
                <i style={{ width:9, height:9, borderRadius:9, background:hecho||ahora?c:'transparent', border:`1.5px solid ${c}`, display:'block', boxShadow:ahora?`0 0 0 4px ${T.vSoft}`:'none' }} />
              </span>
              <span style={{ flex:1, minWidth:0 }}>
                <span style={{ display:'flex', alignItems:'baseline', gap:8 }}>
                  <span style={{ fontFamily:T.sans, fontSize:14.5, fontWeight:600, color:hecho?T.c500:T.c100, textDecoration:hecho?'line-through':'none', minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{j.svc}</span>
                  <span style={{ marginLeft:'auto', fontFamily:T.mono, fontSize:12, color:hecho?T.green:T.c300, flex:'none' }}>{money(j.monto)}</span>
                </span>
                <span style={{ display:'block', fontFamily:T.sans, fontSize:12.5, color:T.c500, marginTop:2 }}>{j.cli}</span>
                <span style={{ display:'flex', alignItems:'center', gap:7, marginTop:5 }}>
                  {ahora && <span style={{ fontFamily:T.mono, fontSize:8.5, letterSpacing:'.11em', color:T.c100, background:T.vSoft, border:`1px solid ${T.vBorder}`, borderRadius:4, padding:'3px 6px' }}>SIGUE</span>}
                  <span style={{ fontFamily:T.mono, fontSize:9.5, color:T.c500, letterSpacing:'.04em', minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{dom ? (j.donde || 'En el local') : 'En tu local'}</span>
                </span>
              </span>
            </button>
          );
        })}
      </div>
    </Card>
  );
}

/* ── pestaña Agenda: turnos (tiempo) vs presupuestos (pipeline) ── */
const RANGOS = ['Hoy','Semana','Mes'];

function Agenda({ jobs, cfg, open, seg, setSeg, rango, setRango, off, setOff, conPresupuesto = true }) {
  const turnos = jobs.filter(j => conHora(j));
  const pres = conPresupuesto ? jobs.filter(j => !conHora(j) && !esCierre(j.tsm)) : [];

  if (conPresupuesto && seg === 'Presupuestos') return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <Segmento seg={seg} setSeg={setSeg} nTurnos={turnos.filter(j=>!esCierre(j.tsm)).length} nPres={pres.length} />
      {pres.length ? (
        <div style={{ display:'flex', flexDirection:'column', gap:9 }}>
          {pres.map(j => (
            <button key={j.id} onClick={() => open(j)} style={{ background:T.g900, border:`1px solid ${T.g800}`, borderRadius:14, padding:14, display:'flex', flexDirection:'column', gap:11, cursor:'pointer', textAlign:'left' }}>
              <span style={{ display:'flex', alignItems:'flex-start', gap:12 }}>
                <span style={{ flex:1, minWidth:0 }}>
                  <span style={{ display:'block', fontFamily:T.sans, fontSize:15.5, fontWeight:700, color:T.c100, letterSpacing:'-.2px' }}>{j.svc}</span>
                  <span style={{ display:'block', fontFamily:T.sans, fontSize:12.5, color:T.c500, marginTop:2 }}>{j.cli}</span>
                </span>
                <span style={{ fontFamily:T.mono, fontSize:14, color:T.c100, letterSpacing:'-.2px', whiteSpace:'nowrap' }}>{money(j.monto)}</span>
              </span>
              <span style={{ display:'flex', alignItems:'center', gap:8, paddingTop:11, borderTop:`1px solid ${T.g800}` }}>
                <span style={{ fontFamily:T.mono, fontSize:9.5, letterSpacing:'.09em', color:T.c500, marginRight:'auto' }}>{j.enviado ? j.extra.toUpperCase() : 'SIN ENVIAR'}</span>
                <Badge tsm={j.tsm} />
              </span>
            </button>
          ))}
        </div>
      ) : (
        <Card pad={20} gap={6}><div style={{ fontFamily:T.sans, fontSize:14, color:T.c300 }}>No tenés presupuestos abiertos.</div><div style={{ fontFamily:T.sans, fontSize:12.5, color:T.c500 }}>Cuando cargues uno aparece acá hasta que el cliente responda.</div></Card>
      )}
    </div>
  );

  const p = periodo(rango === 'Hoy' ? 'Semana' : rango, off);
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      {conPresupuesto && <Segmento seg={seg} setSeg={setSeg} nTurnos={turnos.filter(j=>!esCierre(j.tsm)).length} nPres={pres.length} />}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:7 }}>
        {RANGOS.map(r => <Chip key={r} on={rango===r} onClick={() => { setRango(r); setOff(0); }}>{r}</Chip>)}
      </div>
      {/* Navegar en el tiempo: mismo eje que Reportes, así "la semana que
          viene" quiere decir lo mismo en las dos pantallas. */}
      {rango !== 'Hoy' && (
        <div style={{ display:'flex', alignItems:'center', gap:9 }}>
          <button onClick={() => setOff(off - 1)} aria-label="Anterior" style={{ width:38, height:38, flex:'none', borderRadius:10, background:'transparent', border:`1px solid ${T.g700}`, color:T.c300, cursor:'pointer', fontSize:15 }}>‹</button>
          <span style={{ flex:1, textAlign:'center', fontFamily:T.mono, fontSize:11, letterSpacing:'.07em', color:T.c100 }}>{p.lbl}</span>
          <button onClick={() => setOff(off + 1)} aria-label="Siguiente" style={{ width:38, height:38, flex:'none', borderRadius:10, background:'transparent', border:`1px solid ${T.g700}`, color:T.c300, cursor:'pointer', fontSize:15 }}>›</button>
          {off !== 0 && <button onClick={() => setOff(0)} style={{ flex:'none', minHeight:38, padding:'0 12px', borderRadius:10, background:'transparent', border:`1px solid ${T.g700}`, color:T.c500, fontFamily:T.sans, fontSize:12.5, fontWeight:600, cursor:'pointer' }}>Hoy</button>}
        </div>
      )}
      {rango === 'Hoy' ? <Recorrido jobs={jobs} cfg={cfg} open={open} dia="HOY" />
        : rango === 'Semana' ? <Semana jobs={jobs} cfg={cfg} open={open} off={off} />
        : <Mes jobs={jobs} cfg={cfg} open={open} off={off} />}
    </div>
  );
}

function Segmento({ seg, setSeg, nTurnos, nPres }) {
  return (
    <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:4, background:T.g900, border:`1px solid ${T.g800}`, borderRadius:12, padding:4 }}>
      {[['Turnos', nTurnos], ['Presupuestos', nPres]].map(([t,n]) => { const on = seg === t;
        return <button key={t} onClick={() => setSeg(t)} style={{ minHeight:42, display:'flex', alignItems:'center', justifyContent:'center', gap:6, borderRadius:9, border:'none', background:on?T.vSoft:'transparent', boxShadow:on?`inset 0 0 0 1px ${T.vBorder}`:'none', color:on ? T.c100:T.c500, fontFamily:T.sans, fontSize:13.5, fontWeight:on?700:500, cursor:'pointer' }}>
          {t}<span style={{ fontFamily:T.mono, fontSize:11, opacity:.7 }}>{n}</span>
        </button>;
      })}
    </div>
  );
}

/* Semana y Mes reales, con navegación: mismo eje de tiempo que Reportes.
   Antes eran tres días fijos (HOY/MAÑANA/SAB) sin forma de moverse. */
function Semana({ jobs, cfg, open, off }) {
  const p = periodo('Semana', off);
  const clave = ['L','M','X','J','V','S','D'];
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
      {p.baldes.map(b => {
        const del = jobs.filter(j => { const f = fechaJob(j); return f && f >= b.desde && f < b.hasta; })
          .sort((x,y) => x.hora.localeCompare(y.hora));
        const total = del.reduce((s,j) => s + j.monto, 0);
        const k = clave[(b.desde.getDay() + 6) % 7];
        const fr = cfg.horario[k] || [];
        const libre = cfg.capacidad - del.length;
        return (
          <Card key={b.k} pad={0} gap={0} style={{ overflow:'hidden' }}>
            <div style={{ display:'flex', alignItems:'baseline', gap:10, padding:'13px 16px', borderBottom:del.length?`1px solid ${T.g800}`:'none' }}>
              <span style={{ fontFamily:T.mono, fontSize:10.5, letterSpacing:'.11em', color:T.c100 }}>{b.k.toUpperCase()} · {fmtD(b.desde).toUpperCase()}</span>
              <span style={{ marginLeft:'auto', fontFamily:T.mono, fontSize:10, color:T.c500 }}>{del.length ? money(total) : ''}</span>
              <span style={{ fontFamily:T.mono, fontSize:9, letterSpacing:'.1em', color:!fr.length ? T.c500 : libre > 0 ? T.green : T.amber, background:!fr.length ? T.g800 : libre > 0 ? T.gSoft : T.aSoft, border:`1px solid ${!fr.length ? T.g700 : libre > 0 ? T.gBorder : T.aBorder}`, borderRadius:4, padding:'3px 6px' }}>{!fr.length ? 'CERRADO' : libre > 0 ? `${libre} LUGAR${libre === 1 ? '' : 'ES'}` : 'COMPLETO'}</span>
            </div>
            {del.map((j,n) => (
              <button key={j.id} onClick={() => open(j)} style={{ display:'flex', alignItems:'center', gap:12, minHeight:52, width:'100%', padding:'0 16px', background:'transparent', border:'none', borderTop:n?`1px solid ${T.g800}`:'none', cursor:'pointer', textAlign:'left' }}>
                <span style={{ width:42, flex:'none', fontFamily:T.mono, fontSize:11.5, color:T.c300 }}>{j.hora}</span>
                <span style={{ flex:1, minWidth:0, fontFamily:T.sans, fontSize:14, color:T.c100, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{j.svc} <span style={{ color:T.c500 }}>· {j.cli.split(' ')[0]}</span></span>
                <Badge tsm={j.tsm} />
              </button>
            ))}
          </Card>
        );
      })}
    </div>
  );
}

/* Mes: la grilla del calendario. En el teléfono no cabe una agenda mensual
   con detalle, pero sí el mapa de carga: qué días están llenos y cuáles no. */
function Mes({ jobs, cfg, open, off }) {
  const p = periodo('Mes', off);
  const ini = p.desde, primerDia = (ini.getDay() + 6) % 7;
  const dias = new Date(ini.getFullYear(), ini.getMonth() + 1, 0).getDate();
  const celdas = [...Array(primerDia).fill(null), ...Array.from({ length:dias }, (_, i) => new Date(ini.getFullYear(), ini.getMonth(), i + 1))];
  const clave = ['L','M','X','J','V','S','D'];
  return (
    <Card gap={12}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:4 }}>
        {clave.map(d => <div key={d} style={{ textAlign:'center', fontFamily:T.mono, fontSize:9, letterSpacing:'.1em', color:T.c500 }}>{d}</div>)}
        {celdas.map((d,i) => {
          if (!d) return <div key={'e'+i} />;
          const del = jobs.filter(j => { const f = fechaJob(j); return f && mismoDia(f, d); });
          const abierto = (cfg.horario[clave[(d.getDay()+6)%7]] || []).length > 0;
          const hoy = mismoDia(d, HOY_D);
          return (
            <button key={i} onClick={() => del.length && open(del[0])} style={{ aspectRatio:'1', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:3, borderRadius:9, cursor:del.length?'pointer':'default',
              background:hoy?T.vSoft:'transparent', border:`1px solid ${hoy?T.vBorder:abierto?T.g800:'transparent'}`, padding:0 }}>
              <span style={{ fontFamily:T.mono, fontSize:11, color:abierto?(hoy?T.c100:T.c300):T.c500 }}>{d.getDate()}</span>
              <span style={{ display:'flex', gap:2, height:5 }}>
                {del.slice(0,3).map(j => <i key={j.id} style={{ width:4, height:4, borderRadius:9, background:esCobrado(j.tsm)?T.green:j.tsm==='CANCELADO'?T.coral:T.v600, display:'block' }} />)}
              </span>
            </button>
          );
        })}
      </div>
      <div style={{ display:'flex', gap:14, paddingTop:11, borderTop:`1px solid ${T.g800}`, fontFamily:T.mono, fontSize:9, letterSpacing:'.08em', color:T.c500 }}>
        {[['AGENDADO',T.v600],['COBRADO',T.green],['CANCELADO',T.coral]].map(([l,c]) => (
          <span key={l} style={{ display:'flex', alignItems:'center', gap:5 }}><i style={{ width:5, height:5, borderRadius:9, background:c, display:'block' }} />{l}</span>
        ))}
      </div>
    </Card>
  );
}

Object.assign(window, { Recorrido, Agenda, Semana, Segmento, RANGOS, conHora });
