/* Horarios por día + los ítems que faltaban · Pieza 3a
   El horario NO es un rango único para toda la semana. Un sábado corto (9 a 15)
   o un mediodía cerrado (9-12 y 15-20) son lo normal, no la excepción, y con
   un solo par abre/cierra no se pueden expresar: Mia termina ofreciendo turnos
   a las 13:30 de un sábado que está cerrado.
   Cada día tiene su lista de franjas. Cero, una o dos.                     */

const DIAS_L = [
  { k:'L', n:'Lunes' }, { k:'M', n:'Martes' }, { k:'X', n:'Miércoles' },
  { k:'J', n:'Jueves' }, { k:'V', n:'Viernes' }, { k:'S', n:'Sábado' }, { k:'D', n:'Domingo' },
];
/* Un rango por día de arranque. El que corta al mediodía agrega el segundo;
   el que trabaja corrido no toca nada. Antes venía con dos franjas puestas y
   un botón que decía "Corte al mediodía", que nombra UN caso —el almuerzo—
   cuando lo que hace es agregar un rango cualquiera. */
const HORARIO_INIT = {
  L:[['09:00','18:00']], M:[['09:00','18:00']], X:[['09:00','18:00']],
  J:[['09:00','18:00']], V:[['09:00','18:00']],
  S:[['09:00','13:00']],
  D:[],
};
const franjaTxt = f => f.map(([a,b]) => `${a}–${b}`).join(' y ');
const diasAbiertos = h => DIAS_L.filter(d => (h[d.k] || []).length);
/* Resumen corto: agrupa días consecutivos con el mismo horario.
   "Lun a Vie 9–12 y 15–20 · Sáb 9–15"                                     */
function horarioResumen(h) {
  const ab = diasAbiertos(h);
  if (!ab.length) return 'Cerrado';
  const grupos = [];
  ab.forEach(d => {
    const t = franjaTxt(h[d.k]), u = grupos[grupos.length - 1];
    if (u && u.t === t && DIAS_L.indexOf(d) === DIAS_L.indexOf(u.fin) + 1) u.fin = d;
    else grupos.push({ ini:d, fin:d, t });
  });
  return grupos.map(g => `${g.ini === g.fin ? g.ini.n.slice(0,3) : g.ini.n.slice(0,3) + ' a ' + g.fin.n.slice(0,3)} ${g.t}`).join(' · ');
}
/* Primera apertura y último cierre del día — los usa el recorrido. */
const bordesDia = (h, k) => { const f = h[k] || []; return f.length ? [f[0][0], f[f.length-1][1]] : null; };

function HorarioEditor({ cfg, set }) {
  const h = cfg.horario;
  const upd = (k, f) => set(c => ({ ...c, horario:{ ...c.horario, [k]:f } }));
  const hora = (k, i, j, v) => upd(k, h[k].map((f,n) => n === i ? (j ? [f[0], v] : [v, f[1]]) : f));
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <Card pad={0} gap={0} style={{ overflow:'hidden' }}>
        {DIAS_L.map((d,i) => { const f = h[d.k] || [], abierto = f.length > 0;
          return (
            <div key={d.k} style={{ borderTop:i?`1px solid ${T.g800}`:'none', padding:'11px 14px', display:'flex', flexDirection:'column', gap:9 }}>
              <div style={{ display:'flex', alignItems:'center', gap:11 }}>
                <button onClick={() => upd(d.k, abierto ? [] : [['09:00','18:00']])} aria-label={(abierto?'Cerrar ':'Abrir ') + d.n}
                  style={{ width:40, height:24, flex:'none', borderRadius:99, background:abierto?T.v600:T.g800, border:`1px solid ${abierto?T.v600:T.g700}`, position:'relative', cursor:'pointer', padding:0 }}>
                  <i style={{ position:'absolute', top:2, left:abierto?18:2, width:18, height:18, borderRadius:99, background:'#fff', display:'block', transition:'left 180ms cubic-bezier(.4,0,.2,1)' }} />
                </button>
                <span style={{ flex:1, minWidth:0, fontFamily:T.sans, fontSize:14.5, fontWeight:abierto?600:400, color:abierto?T.c100:T.c500 }}>{d.n}</span>
                {abierto
                  ? f.length < 3 && <button onClick={() => upd(d.k, [...f, ['15:00','20:00']])} style={{ flex:'none', minHeight:36, padding:'0 11px', borderRadius:8, background:T.vSoft, border:`1px solid ${T.vBorder}`, color:T.v600, fontFamily:T.sans, fontSize:11.5, fontWeight:600, cursor:'pointer' }}>+ Rango</button>
                  : <span style={{ fontFamily:T.mono, fontSize:9.5, letterSpacing:'.09em', color:T.c500 }}>CERRADO</span>}
              </div>
              {f.map((fr,n) => (
                <div key={n} style={{ display:'flex', alignItems:'center', gap:7, paddingLeft:51 }}>
                  <input value={fr[0]} onChange={e => hora(d.k, n, 0, e.target.value)} aria-label={`${d.n} franja ${n+1} desde`}
                    style={{ width:70, flex:'none', height:40, boxSizing:'border-box', padding:'0 9px', textAlign:'center', background:T.g950, border:`1px solid ${T.g700}`, borderRadius:9, color:T.c100, fontFamily:T.mono, fontSize:13, outline:'none' }} />
                  <span style={{ fontFamily:T.mono, fontSize:12, color:T.c500 }}>a</span>
                  <input value={fr[1]} onChange={e => hora(d.k, n, 1, e.target.value)} aria-label={`${d.n} franja ${n+1} hasta`}
                    style={{ width:70, flex:'none', height:40, boxSizing:'border-box', padding:'0 9px', textAlign:'center', background:T.g950, border:`1px solid ${T.g700}`, borderRadius:9, color:T.c100, fontFamily:T.mono, fontSize:13, outline:'none' }} />
                  {f.length > 1 && <button onClick={() => upd(d.k, f.filter((_,m) => m !== n))} aria-label="Borrar franja" style={{ width:34, height:40, flex:'none', background:'transparent', border:'none', color:T.c500, fontSize:13, cursor:'pointer', padding:0 }}>✕</button>}
                </div>
              ))}
            </div>
          );
        })}
      </Card>
      <button onClick={() => { const base = h.L && h.L.length ? h.L : [['09:00','18:00']]; set(c => ({ ...c, horario:{ ...c.horario, M:base.map(x=>[...x]), X:base.map(x=>[...x]), J:base.map(x=>[...x]), V:base.map(x=>[...x]) } })); }}
        style={{ minHeight:46, borderRadius:11, background:'transparent', border:`1px solid ${T.g800}`, color:T.c500, fontFamily:T.sans, fontSize:13, fontWeight:600, cursor:'pointer' }}>Copiar el lunes a toda la semana</button>
      <div style={{ fontFamily:T.sans, fontSize:12.5, lineHeight:1.55, color:T.c500, padding:'0 4px' }}>Un rango por día alcanza si trabajás corrido. <b style={{ color:T.c300 }}>+ Rango</b> agrega otro: para el corte del mediodía, o para un turno noche. Mia no ofrece turnos fuera de estas franjas.</div>
    </div>
  );
}

/* ── lo que faltaba para setear bien a Mia ────────────────────
   Auditoría contra lo que el bot necesita responder sin preguntarte:      */
function DuracionNota() {
  return <div style={{ display:'flex', gap:10, alignItems:'flex-start', padding:'11px 13px', background:T.aSoft, border:`1px solid ${T.aBorder}`, borderRadius:12 }}>
    <span style={{ fontFamily:T.mono, fontSize:12, color:T.amber, flex:'none', lineHeight:1.3 }}>!</span>
    <span style={{ flex:1, fontFamily:T.sans, fontSize:12.5, lineHeight:1.5, color:T.c300 }}>Sin duración, la agenda asume una hora para todo. Con esto Mia sabe cuánto bloquear y no te encima dos trabajos.</span>
  </div>;
}

function PagosEditor({ cfg, set }) {
  const p = cfg.pagos;
  const medios = ['Efectivo','Transferencia','Débito','Crédito','QR'];
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <Card gap={12}>
        <Lbl>QUÉ ACEPTÁS</Lbl>
        <div style={{ display:'flex', flexWrap:'wrap', gap:7 }}>
          {medios.map(m => { const on = p.medios.includes(m);
            return <Chip key={m} on={on} onClick={() => set(c => ({ ...c, pagos:{ ...c.pagos, medios:on ? c.pagos.medios.filter(x=>x!==m) : [...c.pagos.medios, m] } }))}>{m}</Chip>;
          })}
        </div>
        <div style={{ fontFamily:T.sans, fontSize:12, lineHeight:1.5, color:T.c500 }}>Mia se lo dice al cliente cuando pregunta cómo pagar, sin consultarte.</div>
      </Card>
      <Card gap={10}>
        <Toggle on={p.sena} label="Pido seña para reservar" onChange={v => set(c => ({ ...c, pagos:{ ...c.pagos, sena:v } }))} />
        {p.sena && <div style={{ paddingTop:10, borderTop:`1px solid ${T.g800}` }}>
          <Lbl mb={10}>CUÁNTO, SOBRE EL TOTAL</Lbl>
          <Stepper v={p.pct} min={5} max={100} sufijo="%" set={v => set(c => ({ ...c, pagos:{ ...c.pagos, pct:v } }))} />
          <div style={{ fontFamily:T.sans, fontSize:12, lineHeight:1.5, color:T.c500, marginTop:9 }}>Mia le pide la seña al confirmar y no reserva el turno hasta que la pague.</div>
        </div>}
      </Card>
    </div>
  );
}

function AusenciasEditor({ cfg, set }) {
  const a = cfg.ausencias;
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <Card pad={0} gap={0} style={{ overflow:'hidden' }}>
        <div style={{ padding:'14px 14px 10px' }}><Lbl>DÍAS QUE NO TRABAJÁS</Lbl></div>
        {a.length ? a.map((x,i) => (
          <div key={i} style={{ display:'flex', alignItems:'center', gap:10, minHeight:52, padding:'0 14px', borderTop:`1px solid ${T.g800}` }}>
            <span style={{ flex:1, minWidth:0, fontFamily:T.sans, fontSize:14, color:T.c100 }}>{x.n}</span>
            <span style={{ fontFamily:T.mono, fontSize:11, color:T.c500, flex:'none' }}>{x.d}</span>
            <button onClick={() => set(c => ({ ...c, ausencias:c.ausencias.filter((_,m) => m !== i) }))} aria-label={'Borrar ' + x.n} style={{ width:30, height:40, flex:'none', background:'transparent', border:'none', color:T.c500, fontSize:13, cursor:'pointer', padding:0 }}>✕</button>
          </div>
        )) : <div style={{ padding:'0 14px 16px', fontFamily:T.sans, fontSize:13, color:T.c500 }}>Ninguno cargado.</div>}
        <button onClick={() => set(c => ({ ...c, ausencias:[...c.ausencias, { n:'Feriado', d:'—' }] }))} style={{ minHeight:46, width:'100%', borderTop:`1px solid ${T.g800}`, background:'transparent', border:'none', color:T.v600, fontFamily:T.sans, fontSize:13, fontWeight:600, cursor:'pointer' }}>+ Agregar un día</button>
      </Card>
      <div style={{ fontFamily:T.sans, fontSize:12.5, lineHeight:1.55, color:T.c500, padding:'0 4px' }}>Feriados, vacaciones o el día que cerrás por algo puntual. Sin esto Mia sigue ofreciendo turnos el 25 de diciembre.</div>
    </div>
  );
}

function AvisosEditor({ cfg, set }) {
  const r = cfg.avisos;
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <Card gap={10}>
        <Toggle on={r.on} label="Recordarle al cliente" onChange={v => set(c => ({ ...c, avisos:{ ...c.avisos, on:v } }))} />
        {r.on && <div style={{ paddingTop:10, borderTop:`1px solid ${T.g800}` }}>
          <Lbl mb={10}>CUÁNTO ANTES</Lbl>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:6 }}>
            {[2,24,48].map(hh => <Chip key={hh} on={r.hs === hh} onClick={() => set(c => ({ ...c, avisos:{ ...c.avisos, hs:hh } }))}>{hh === 2 ? '2 horas' : hh + ' horas'}</Chip>)}
          </div>
        </div>}
      </Card>
      <Card gap={10}>
        <Toggle on={r.resena} label="Pedir reseña al terminar" onChange={v => set(c => ({ ...c, avisos:{ ...c.avisos, resena:v } }))} />
        <div style={{ fontFamily:T.sans, fontSize:12, lineHeight:1.5, color:T.c500 }}>{r.resena ? 'Mia le pide la reseña cuando cobrás el trabajo. Es lo que alimenta el 4,8 de Negocio.' : 'Mia no pide reseñas.'}</div>
      </Card>
      <Card gap={10}>
        <Toggle on={r.seguimiento} label="Insistir con presupuestos sin respuesta" onChange={v => set(c => ({ ...c, avisos:{ ...c.avisos, seguimiento:v } }))} />
        <div style={{ fontFamily:T.sans, fontSize:12, lineHeight:1.5, color:T.c500 }}>{r.seguimiento ? 'A los 3 días Mia le vuelve a escribir una vez. Si no contesta, te lo pone en Atención requerida.' : 'Mia no insiste: los presupuestos sin respuesta te quedan a vos.'}</div>
      </Card>
    </div>
  );
}

Object.assign(window, { DIAS_L, HORARIO_INIT, franjaTxt, diasAbiertos, horarioResumen, bordesDia, HorarioEditor, PagosEditor, AusenciasEditor, AvisosEditor, DuracionNota });
