/* global React, SFIcons */
const { Truck: TruckK, Check: CheckK, MapPin: MapK, Clock: ClockK, Plus: PlusK, FileText: FileK } = SFIcons;
const { Button: BtnK, Input: InputK, Card: CardK } = window.MADECIDesignSystem_419fb1;
const clpK = (n) => '$' + Number(n).toLocaleString('es-CL');

// Locales de MADECI donde el cliente puede retirar. Agregar aquí si hay más sucursales.
const LOCALES = [
  { id: 'cartagena', nombre: 'Sucursal Cartagena', direccion: 'Av. Cartagena 498, Cartagena', horario: 'Lun a Sáb 9:00–13:00 y 15:00–18:30 · Dom y festivos 9:00–13:00' },
];

// Fecha de hoy y tope de 7 días, en formato YYYY-MM-DD (para el selector de fecha).
const _isoDia = (d) => {
  const z = new Date(d.getTime() - d.getTimezoneOffset() * 60000);
  return z.toISOString().slice(0, 10);
};
// Día de la semana (0 = domingo) de una fecha "YYYY-MM-DD", en hora local.
const _diaSemana = (iso) => { const [y, m, d] = iso.split('-').map(Number); return new Date(y, m - 1, d).getDay(); };
const _sinPunto = (s) => (s || '').replace('.', '');

function PayOption({ active, title, sub, onClick }) {
  return (
    <button onClick={onClick} style={{ textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', border: `1.5px solid ${active ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: active ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer', width: '100%' }}>
      <span style={{ width: 18, height: 18, borderRadius: 999, border: `5px solid ${active ? 'var(--madeci-red)' : 'var(--border-strong)'}`, flex: 'none', transition: 'border-color .15s' }} />
      <span><span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: 'var(--text-strong)' }}>{title}</span><span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)' }}>{sub}</span></span>
    </button>
  );
}

// Una dirección de despacho seleccionable (casa matriz o sucursal).
function DireccionOption({ dir, active, onClick }) {
  return (
    <button onClick={onClick} style={{ textAlign: 'left', display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', border: `1.5px solid ${active ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: active ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer', width: '100%' }}>
      <span style={{ width: 18, height: 18, borderRadius: 999, border: `5px solid ${active ? 'var(--madeci-red)' : 'var(--border-strong)'}`, flex: 'none', marginTop: 2 }} />
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 7, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: 'var(--text-strong)' }}>
          {dir.nombre || (dir.es_matriz ? 'Casa matriz' : 'Sucursal ' + dir.suen)}
          {dir.es_matriz && <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '.06em', color: 'var(--madeci-red)', background: 'var(--madeci-red-50)', padding: '2px 6px', borderRadius: 3 }}>CASA MATRIZ</span>}
        </span>
        <span style={{ display: 'block', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>
          {dir.direccion || 'Sin dirección registrada'}{dir.comuna ? ' · ' + dir.comuna : ''}
        </span>
      </span>
    </button>
  );
}

function CheckoutView({ items, onBack, onPlace, account }) {
  const [pay, setPay] = React.useState('entrega-efectivo');
  const [placing, setPlacing] = React.useState(false);
  const [placeErr, setPlaceErr] = React.useState('');

  const raw = (account && account._raw) || {};

  // ---- Direcciones de despacho ----
  const [direcciones, setDirecciones] = React.useState([]);
  const [selDir, setSelDir] = React.useState(0);
  React.useEffect(() => {
    window.MadeciAPI.getDirecciones().then((d) => setDirecciones(d || [])).catch(() => {});
  }, []);
  // Si Random no trae sucursales, armamos la casa matriz con los datos del cliente.
  const matrizSint = { suen: '', es_matriz: true, nombre: 'Casa matriz', direccion: raw.direccion || '', comuna: raw.comuna || '' };
  const addresses = direcciones.length ? direcciones : (raw.direccion ? [matrizSint] : []);
  const dirSel = addresses[selDir] || addresses[0] || null;

  // ---- Agregar otra dirección (queda como solicitud EN REVISIÓN) ----
  const [nuevaOpen, setNuevaOpen] = React.useState(false);
  const [nueva, setNueva] = React.useState({ nombre: '', direccion: '', comuna: '', fono: '' });
  const [nuevaDocs, setNuevaDocs] = React.useState([]);
  const [nuevaMsg, setNuevaMsg] = React.useState('');
  const [nuevaErr, setNuevaErr] = React.useState('');
  const [nuevaEnviando, setNuevaEnviando] = React.useState(false);
  const setN = (k) => (e) => setNueva((s) => ({ ...s, [k]: e.target.value }));
  const fileRef = React.useRef(null);

  const enviarNueva = async () => {
    setNuevaErr('');
    if (!nueva.direccion.trim() || !nueva.comuna.trim()) { setNuevaErr('Indica al menos dirección y comuna.'); return; }
    // El documento de respaldo es OPCIONAL: si no lo adjunta, un ejecutivo se lo pedirá.
    setNuevaEnviando(true);
    try {
      const cambios = { nombre: nueva.nombre.trim() || null, direccion: nueva.direccion.trim(), comuna: nueva.comuna.trim(), fono: nueva.fono.trim() || null };
      const r = await window.MadeciAPI.crearSolicitud({ tipo: 'sucursal', cambios });
      for (const f of nuevaDocs) { try { await window.MadeciAPI.subirDocumentoSolicitud(r.id, f); } catch (e) { /* sigue */ } }
      setNuevaOpen(false);
      setNueva({ nombre: '', direccion: '', comuna: '', fono: '' });
      setNuevaDocs([]);
      setNuevaMsg('Solicitamos tu nueva dirección de despacho. Queda en revisión; te avisaremos cuando esté habilitada.');
    } catch (e) { setNuevaErr(e.message || 'No se pudo enviar la solicitud.'); }
    finally { setNuevaEnviando(false); }
  };

  // ---- Despacho: próximo disponible o programado ----
  const hoy = new Date();
  // Próximos 8 días (hoy + 7) como opciones para elegir.
  const dias = Array.from({ length: 8 }, (_, i) => new Date(hoy.getFullYear(), hoy.getMonth(), hoy.getDate() + i));
  const [modoFecha, setModoFecha] = React.useState('pronto'); // 'pronto' | 'programar'
  const [fecha, setFecha] = React.useState('');
  const [jornada, setJornada] = React.useState('manana');
  const [obs, setObs] = React.useState(''); // instrucciones/observaciones para el despacho
  const [entrega, setEntrega] = React.useState('despacho'); // 'despacho' (a domicilio) | 'retiro' (en local)
  const [localSel, setLocalSel] = React.useState(0);        // índice del local elegido para retiro
  const esRetiro = entrega === 'retiro';
  const localElegido = LOCALES[localSel] || LOCALES[0];

  // Jornadas disponibles para una fecha: el domingo solo hay mañana, y si es HOY se
  // descartan las jornadas cuyo corte ya pasó (mañana 10:00, tarde 15:00 · Cartagena 17:00).
  const ahoraMin = hoy.getHours() * 60 + hoy.getMinutes();
  const comunaSel = ((dirSel && dirSel.comuna) || '').toLowerCase();
  const tardeCorteMin = comunaSel.includes('cartagena') ? 17 * 60 : 15 * 60;
  const jornadasDe = (iso) => {
    const esDomingo = _diaSemana(iso) === 0;
    const esHoy = iso === _isoDia(hoy);
    let manana = true, tarde = !esDomingo; // dom/festivos: solo mañana (retiro y despacho)
    if (esRetiro) {
      // Retiro en local: Lun-Sáb 09:00–13:00 y 15:00–18:30 · Dom/festivos 09:00–13:00.
      if (esHoy) {
        if (ahoraMin >= 13 * 60) manana = false;         // ya cerró la mañana del local
        if (ahoraMin >= 18 * 60 + 30) tarde = false;     // ya cerró el local
      }
    } else if (esHoy) {
      if (ahoraMin >= 10 * 60) manana = false;      // corte despacho mañana
      if (ahoraMin >= tardeCorteMin) tarde = false; // corte despacho tarde
    }
    return { manana, tarde, any: manana || tarde };
  };
  // Disponibilidad para la fecha elegida (en modo "próximo despacho" no hay restricción de hora).
  const disp = (modoFecha === 'programar' && fecha) ? jornadasDe(fecha) : { manana: true, tarde: true };
  const domingoProgramado = modoFecha === 'programar' && !!fecha && _diaSemana(fecha) === 0;
  const hoyMananaCerrada = modoFecha === 'programar' && !!fecha && fecha === _isoDia(hoy) && !disp.manana && disp.tarde;
  // Si la jornada elegida deja de estar disponible, la cambiamos a la que sí lo está.
  React.useEffect(() => {
    if (modoFecha === 'programar' && fecha) {
      if (jornada === 'manana' && !disp.manana && disp.tarde) setJornada('tarde');
      else if (jornada === 'tarde' && !disp.tarde && disp.manana) setJornada('manana');
    }
  }, [fecha, modoFecha, disp.manana, disp.tarde, jornada]);

  // Envía el pedido al backend con los datos de despacho elegidos.
  const confirmar = async () => {
    setPlaceErr('');
    if (modoFecha === 'programar' && !fecha) { setPlaceErr(esRetiro ? 'Elige la fecha para tu retiro programado.' : 'Elige la fecha para tu despacho programado.'); return; }
    setPlacing(true);
    try {
      await onPlace({
        tipo: esRetiro ? 'retiro' : 'domicilio',
        local: esRetiro ? `${localElegido.nombre} — ${localElegido.direccion}` : undefined,
        sucursal_suen: esRetiro ? '' : (dirSel ? (dirSel.suen || '') : ''),
        direccion: esRetiro ? '' : (dirSel ? dirSel.direccion : (raw.direccion || '')),
        comuna: esRetiro ? '' : (dirSel ? dirSel.comuna : (raw.comuna || '')),
        fecha: modoFecha === 'programar' && fecha ? fecha : undefined,
        jornada,
      }, obs.trim());
    } catch (e) {
      setPlaceErr(e.message || 'No se pudo enviar el pedido.');
    } finally {
      setPlacing(false);
    }
  };

  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const total = subtotal;
  const jornadaOps = (esRetiro
    ? [['manana', 'Mañana', 'Retiras entre 09:00 y 13:00'], ['tarde', 'Tarde', 'Retiras entre 15:00 y 18:30']]
    : [['manana', 'Mañana', 'Recibe entre 10:00 y 13:00'], ['tarde', 'Tarde', 'Recibe entre 15:00 y 18:00']]
  ).filter(([id]) => disp[id]);

  return (
    <div className="sf-shell" style={{ maxWidth: 1080, margin: '0 auto', padding: '32px 24px 80px' }}>
      <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, color: 'var(--text-muted)', padding: 0, marginBottom: 14 }}>← Volver al catálogo</button>
      <h1 style={{ fontSize: 38, fontWeight: 800, letterSpacing: '-.02em', marginBottom: 24 }}>Finalizar pedido</h1>
      <div className="sf-checkout-cols" style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 28, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

          {/* ---- ¿Despacho o retiro? ---- */}
          <CardK padding="lg">
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}><TruckK size={18} stroke="var(--madeci-red)" /><h3 style={{ fontSize: 18, fontWeight: 700 }}>¿Cómo lo recibes?</h3></div>
            <div style={{ display: 'flex', gap: 12 }}>
              {[['despacho', 'Despacho a domicilio', 'Te lo llevamos'], ['retiro', 'Retiro en local', 'Lo retiras tú']].map(([id, t, s]) => {
                const on = entrega === id;
                return (
                  <button key={id} onClick={() => setEntrega(id)} style={{ flex: 1, textAlign: 'left', padding: '14px 16px', border: `1.5px solid ${on ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: on ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer' }}>
                    <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: on ? 'var(--madeci-red-dark)' : 'var(--text-strong)' }}>{t}</span>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>{s}</span>
                  </button>
                );
              })}
            </div>
          </CardK>

          {/* ---- Retiro en local ---- */}
          {esRetiro && (
            <CardK padding="lg">
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}><MapK size={18} stroke="var(--madeci-red)" /><h3 style={{ fontSize: 18, fontWeight: 700 }}>Retiras en</h3></div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {LOCALES.map((l, i) => {
                  const on = i === localSel;
                  return (
                    <button key={l.id} onClick={() => setLocalSel(i)} style={{ textAlign: 'left', display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', border: `1.5px solid ${on ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: on ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer', width: '100%' }}>
                      <span style={{ width: 18, height: 18, borderRadius: 999, border: `5px solid ${on ? 'var(--madeci-red)' : 'var(--border-strong)'}`, flex: 'none', marginTop: 2 }} />
                      <span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: 'var(--text-strong)' }}>{l.nombre}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)' }}>{l.direccion}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-subtle)', marginTop: 2 }}>{l.horario}</span>
                      </span>
                    </button>
                  );
                })}
              </div>
              <div style={{ marginTop: 12, fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-subtle)' }}>Te avisamos cuando tu pedido esté listo para retirar.</div>
            </CardK>
          )}

          {/* ---- Dirección de despacho ---- */}
          {!esRetiro && (
          <CardK padding="lg">
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}><MapK size={18} stroke="var(--madeci-red)" /><h3 style={{ fontSize: 18, fontWeight: 700 }}>Dirección de despacho</h3></div>
            {addresses.length > 0 ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {addresses.map((d, i) => <DireccionOption key={(d.suen || 'matriz') + i} dir={d} active={i === selDir} onClick={() => setSelDir(i)} />)}
              </div>
            ) : (
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-muted)' }}>No tienes una dirección registrada. Agrega una para tu despacho.</div>
            )}

            {nuevaMsg && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, padding: '10px 14px', background: 'var(--status-success-50)', border: '1px solid var(--status-success)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-body)' }}>
                <CheckK size={16} stroke="var(--status-success)" /> {nuevaMsg}
              </div>
            )}

            {!nuevaOpen ? (
              <button onClick={() => { setNuevaOpen(true); setNuevaMsg(''); }} style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 14, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--madeci-red)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13.5, padding: 0 }}>
                <PlusK size={16} /> Despachar a otra dirección
              </button>
            ) : (
              <div style={{ marginTop: 16, padding: 16, border: '1px dashed var(--border-strong)', borderRadius: 'var(--radius-sm)', background: 'var(--neutral-25)' }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, marginBottom: 12 }}>Nueva dirección de despacho</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div style={{ gridColumn: '1 / -1' }}><InputK label="Nombre / referencia (opcional)" value={nueva.nombre} onChange={setN('nombre')} /></div>
                  <div style={{ gridColumn: '1 / -1' }}><InputK label="Dirección" value={nueva.direccion} onChange={setN('direccion')} /></div>
                  <InputK label="Comuna" value={nueva.comuna} onChange={setN('comuna')} />
                  <InputK label="Teléfono (opcional)" value={nueva.fono} onChange={setN('fono')} />
                </div>
                <div style={{ marginTop: 12 }}>
                  <input ref={fileRef} type="file" accept="image/*,application/pdf" multiple style={{ display: 'none' }} onChange={(e) => setNuevaDocs(Array.from(e.target.files || []))} />
                  <button onClick={() => fileRef.current && fileRef.current.click()} style={{ display: 'flex', alignItems: 'center', gap: 7, background: '#fff', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', padding: '9px 13px', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13.5, color: 'var(--text-body)' }}>
                    <FileK size={16} stroke="var(--madeci-red)" /> Adjuntar documento de respaldo (opcional)
                  </button>
                  {nuevaDocs.length > 0 && (
                    <div style={{ marginTop: 8, fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>
                      {nuevaDocs.map((f, i) => <div key={i}>📎 {f.name}</div>)}
                    </div>
                  )}
                  <div style={{ marginTop: 6, fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-subtle)' }}>Si lo tienes a mano (cuenta de servicios, patente o contrato) agiliza la validación. Si no, un ejecutivo te lo solicitará.</div>
                </div>
                {nuevaErr && <div style={{ marginTop: 10, color: 'var(--madeci-red)', fontFamily: 'var(--font-body)', fontSize: 13 }}>{nuevaErr}</div>}
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
                  <BtnK size="sm" onClick={enviarNueva} disabled={nuevaEnviando}>{nuevaEnviando ? 'Enviando…' : 'Enviar solicitud'}</BtnK>
                  <button onClick={() => { setNuevaOpen(false); setNuevaErr(''); }} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13.5, color: 'var(--text-muted)' }}>Cancelar</button>
                  <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-subtle)', marginLeft: 'auto' }}>Queda en revisión antes de habilitarse.</span>
                </div>
              </div>
            )}
          </CardK>
          )}

          {/* ---- Cuándo (despacho o retiro) ---- */}
          <CardK padding="lg">
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}><ClockK size={18} stroke="var(--madeci-red)" /><h3 style={{ fontSize: 18, fontWeight: 700 }}>{esRetiro ? '¿Cuándo lo retiras?' : '¿Cuándo lo despachamos?'}</h3></div>
            <div style={{ display: 'flex', gap: 12, marginTop: 12 }}>
              {(esRetiro
                ? [['pronto', 'Lo antes posible', 'Te avisamos cuando esté listo para retirar'], ['programar', 'Programar retiro', 'Elige la fecha (hasta 7 días)']]
                : [['pronto', 'Próximo despacho disponible', 'Según tu comuna y el horario de corte'], ['programar', 'Programar para otro día', 'Elige la fecha (hasta 7 días)']]
              ).map(([id, t, h]) => {
                const on = modoFecha === id;
                return (
                  <button key={id} onClick={() => setModoFecha(id)} style={{ flex: 1, textAlign: 'left', padding: '14px 16px', border: `1.5px solid ${on ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: on ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer' }}>
                    <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: on ? 'var(--madeci-red-dark)' : 'var(--text-strong)' }}>{t}</span>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>{h}</span>
                  </button>
                );
              })}
            </div>
            {modoFecha === 'programar' && (
              <div style={{ marginTop: 16 }}>
                <label style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 12.5, fontWeight: 600, color: 'var(--text-muted)', marginBottom: 8 }}>Elige el día de despacho</label>
                <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>
                  {dias.map((d, i) => {
                    const iso = _isoDia(d);
                    const on = fecha === iso;
                    const habil = jornadasDe(iso).any; // si es hoy y ya pasó todo, el día se bloquea
                    const dow = _sinPunto(d.toLocaleDateString('es-CL', { weekday: 'short' }));
                    const mes = _sinPunto(d.toLocaleDateString('es-CL', { month: 'short' }));
                    const etiqueta = i === 0 ? 'Hoy' : (i === 1 ? 'Mañ.' : dow);
                    return (
                      <button key={iso} onClick={() => habil && setFecha(iso)} disabled={!habil} title={habil ? '' : 'Ya cerró el despacho de hoy'}
                        style={{ flex: 'none', width: 62, padding: '10px 0', textAlign: 'center', border: `1.5px solid ${on ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: on ? 'var(--madeci-red)' : '#fff', cursor: habil ? 'pointer' : 'not-allowed', opacity: habil ? 1 : 0.4 }}>
                        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 11.5, fontWeight: 600, textTransform: 'capitalize', color: on ? 'rgba(255,255,255,.85)' : 'var(--text-muted)' }}>{etiqueta}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-data)', fontSize: 20, fontWeight: 700, lineHeight: 1.1, color: on ? '#fff' : 'var(--text-strong)' }}>{d.getDate()}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 10.5, textTransform: 'capitalize', color: on ? 'rgba(255,255,255,.85)' : 'var(--text-subtle)' }}>{mes}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
            <div style={{ marginTop: 18, marginBottom: 8, fontFamily: 'var(--font-display)', fontSize: 12.5, fontWeight: 600, color: 'var(--text-muted)' }}>Jornada</div>
            <div style={{ display: 'flex', gap: 12 }}>
              {jornadaOps.map(([id, t, h]) => {
                const on = jornada === id;
                return (
                  <button key={id} onClick={() => setJornada(id)} style={{ flex: 1, textAlign: 'left', padding: '12px 15px', border: `1.5px solid ${on ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: on ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer' }}>
                    <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: on ? 'var(--madeci-red-dark)' : 'var(--text-strong)' }}>{t}</span>
                    <span style={{ fontFamily: 'var(--font-data)', fontSize: 12.5, color: 'var(--text-muted)' }}>{h}</span>
                  </button>
                );
              })}
            </div>
            <div style={{ marginTop: 12, fontFamily: 'var(--font-body)', fontSize: 12, color: (domingoProgramado || hoyMananaCerrada) ? 'var(--madeci-red-dark)' : 'var(--text-subtle)' }}>
              {esRetiro
                ? (domingoProgramado
                    ? 'Elegiste un domingo: el local abre solo en la mañana (09:00–13:00).'
                    : hoyMananaCerrada
                      ? 'Para hoy la mañana del local ya cerró; puedes retirar en la tarde (hasta 18:30).'
                      : 'Retiro en local: Lun a Sáb 09:00–13:00 y 15:00–18:30. Domingos y festivos solo 09:00–13:00. Te avisamos cuando esté listo.')
                : (domingoProgramado
                    ? 'Elegiste un domingo: ese día despachamos solo en la jornada de la mañana.'
                    : hoyMananaCerrada
                      ? 'Para hoy ya cerró el corte de la mañana (10:00); puedes recibir en la tarde.'
                      : 'El domingo despachamos solo en la mañana. En Cartagena la tarde recibe hasta las 18:30 (pide antes de 17:00).')}
            </div>
          </CardK>

          {/* ---- Instrucciones para el despacho ---- */}
          <CardK padding="lg">
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}><FileK size={18} stroke="var(--madeci-red)" /><h3 style={{ fontSize: 18, fontWeight: 700 }}>{esRetiro ? 'Instrucciones para el retiro' : 'Instrucciones para el despacho'}</h3></div>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', marginBottom: 12 }}>{esRetiro ? '¿Algo que debamos saber para tu retiro? (opcional)' : '¿Algo que debamos saber para la entrega? (opcional)'}</p>
            <textarea value={obs} onChange={(e) => setObs(e.target.value)} maxLength={300} rows={3}
              placeholder={esRetiro ? 'Ej.: retira Juan Pérez, paso después de las 16 h. Necesito boleta.' : 'Ej.: local cerrado entre 14 y 16 h, llamar antes de llegar al 9 9426 4892.'}
              style={{ width: '100%', resize: 'vertical', padding: '11px 13px', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-strong)', lineHeight: 1.4 }} />
            <div style={{ marginTop: 6, textAlign: 'right', fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--text-subtle)' }}>{obs.length}/300</div>
          </CardK>

          {/* ---- Forma de pago ---- */}
          <CardK padding="lg">
            <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 6 }}>Forma de pago</h3>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', marginBottom: 16 }}>Pago contra entrega o pago electrónico anticipado.</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <PayOption active={pay === 'entrega-efectivo'} onClick={() => setPay('entrega-efectivo')} title="Efectivo contra entrega" sub="Paga en efectivo al recibir tu pedido" />
              <PayOption active={pay === 'entrega-tarjeta'} onClick={() => setPay('entrega-tarjeta')} title="Tarjeta contra entrega" sub="Débito o crédito con POS al recibir" />
              <PayOption active={pay === 'transfer'} onClick={() => setPay('transfer')} title="Transferencia electrónica" sub="Te enviamos los datos para transferir" />
              <PayOption active={pay === 'link'} onClick={() => setPay('link')} title="Pago electrónico (link de pago)" sub="Recibe un link para pagar con tarjeta en línea" />
            </div>
          </CardK>
        </div>

        <CardK padding="lg" style={{ position: 'sticky', top: 96 }}>
          <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 14 }}>Resumen</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 220, overflowY: 'auto', marginBottom: 14 }}>
            {items.map((i) => (
              <div key={i.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontFamily: 'var(--font-body)', fontSize: 13.5 }}>
                <span style={{ color: 'var(--text-body)' }}>{i.qty}× {i.name} <span style={{ color: 'var(--text-subtle)', fontSize: 12 }}>· {i.pack}</span></span>
                <span style={{ fontFamily: 'var(--font-data)', fontWeight: 600, color: 'var(--text-strong)', whiteSpace: 'nowrap' }}>{clpK(i.price * i.qty)}</span>
              </div>
            ))}
          </div>
          <div style={{ borderTop: '1px solid var(--border-subtle)', paddingTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <Row label="Subtotal" value={clpK(subtotal)} />
            <Row label={esRetiro ? 'Retiro en local' : 'Despacho'} value={<span style={{ color: 'var(--status-success)' }}>Gratis</span>} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 6 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>Total</span>
              <span style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 26, color: 'var(--madeci-red)' }}>{clpK(total)}</span>
            </div>
          </div>
          {placeErr && (
            <div style={{ marginTop: 14, padding: '10px 14px', background: 'var(--madeci-red-50)', border: '1px solid var(--madeci-red)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--madeci-red)' }}>{placeErr}</div>
          )}
          <BtnK block size="lg" style={{ marginTop: 18 }} onClick={confirmar} disabled={placing}>{placing ? 'Enviando…' : 'Confirmar pedido'}</BtnK>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, justifyContent: 'center', marginTop: 12, fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>
            <TruckK size={15} /> {esRetiro ? 'Retiro en Sucursal Cartagena' : 'Despacho express'}
          </div>
        </CardK>
      </div>
    </div>
  );
}

function Row({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-muted)' }}>
      <span>{label}</span><span style={{ fontFamily: 'var(--font-data)', fontWeight: 600, color: 'var(--text-strong)' }}>{value}</span>
    </div>
  );
}

function OrderConfirmed({ onHome, pedidoId }) {
  return (
    <div style={{ maxWidth: 560, margin: '0 auto', padding: '80px 24px', textAlign: 'center' }}>
      <div style={{ width: 76, height: 76, borderRadius: 999, background: 'var(--status-success-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 22px' }}>
        <CheckK size={40} stroke="var(--status-success)" strokeWidth={2.4} />
      </div>
      <h1 style={{ fontSize: 38, fontWeight: 800, letterSpacing: '-.02em' }}>¡Pedido confirmado!</h1>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 17, color: 'var(--text-muted)', marginTop: 12 }}>
        Pedido <strong style={{ color: 'var(--text-strong)' }}>#{pedidoId ?? '—'}</strong> recibido. Un ejecutivo de MADECI lo revisará y te confirmará por WhatsApp. Despacho express.
      </p>
      <BtnK size="lg" style={{ marginTop: 28 }} onClick={onHome}>Volver al inicio</BtnK>
    </div>
  );
}

Object.assign(window, { CheckoutView, OrderConfirmed });
