// LOLA Consola Web — ANUNCIOS EN LA APP (publicidad in-app) + MODERACIÓN DE VIAJES DE RETORNO.
// Todo contra /admin/anuncios y /admin/retornos (Mongo). Métricas reales de impresiones/clics.

const aApi = () => window.LOLA.api;
const UBIC = { inicio_banner: 'Banner en Inicio (cliente)', marketplace_patrocinado: 'Tarjeta patrocinada (Marketplace)', ofertas_para_ti: 'Ofertas para ti (cupones)', tracking_espera: 'Mientras espera el viaje' };
const nf = (n) => Number(n || 0).toLocaleString('es-GT');

function AnunciosView() {
  const t = window.WC, I = window.WI;
  const q = window.useAsync(() => aApi().anuncios(), []);
  const [edit, setEdit] = React.useState(null);   // null | {} nuevo | anuncio
  const [met, setMet] = React.useState(null);
  const [filtro, setFiltro] = React.useState('todos');
  if (q.loading) return <window.Loading/>;
  if (q.error) return <window.ErrState error={q.error} onRetry={q.reload}/>;
  const items = (q.data.items || []).filter((a) => filtro === 'todos' || a.estado === filtro);
  const tot = (q.data.items || []).reduce((acc, a) => ({ imp: acc.imp + (a.metricas?.impresiones || 0), clics: acc.clics + (a.metricas?.clics || 0), act: acc.act + (a.estado === 'activo' ? 1 : 0) }), { imp: 0, clics: 0, act: 0 });
  const toggle = async (a) => { try { await aApi().actualizarAnuncio(a.id, { estado: a.estado === 'activo' ? 'pausado' : 'activo' }); q.reload(); } catch (e) { alert(e.message); } };
  const borrar = async (a) => { if (!window.confirm('¿Eliminar "' + a.titulo + '" y sus métricas?')) return; try { await aApi().borrarAnuncio(a.id); q.reload(); } catch (e) { alert(e.message); } };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 1100 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12 }}>
        {[['Activos', tot.act, t.brand], ['Impresiones', nf(tot.imp), t.text], ['Clics', nf(tot.clics), t.text], ['CTR', (tot.imp ? (tot.clics / tot.imp * 100).toFixed(2) : '0.00') + '%', '#1F8A5B']].map(([l, v, col]) => (
          <div key={l} style={{ background: '#fff', border: `1px solid ${t.border}`, borderRadius: 14, padding: '14px 18px' }}>
            <div style={{ fontSize: 11, color: t.ter, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700 }}>{l}</div>
            <div style={{ fontSize: 24, fontWeight: 800, color: col, marginTop: 4, letterSpacing: -.6 }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <div style={{ display: 'inline-flex', gap: 4, background: '#fff', border: `1px solid ${t.border}`, borderRadius: 12, padding: 4 }}>
          {[['todos', 'Todos'], ['activo', 'Activos'], ['pausado', 'Pausados'], ['borrador', 'Borradores'], ['finalizado', 'Finalizados']].map(([k, l]) => (
            <button key={k} onClick={() => setFiltro(k)} style={{ height: 34, padding: '0 14px', borderRadius: 9, border: 'none', cursor: 'pointer', fontFamily: t.font, fontSize: 13, fontWeight: 700, background: filtro === k ? t.brand + '12' : 'transparent', color: filtro === k ? t.brand : t.sec }}>{l}</button>
          ))}
        </div>
        <span style={{ flex: 1 }}/>
        <button onClick={() => setEdit({})} style={{ height: 40, padding: '0 16px', borderRadius: 10, border: 'none', ...window.GOLD, fontWeight: 750, cursor: 'pointer', fontFamily: t.font, fontSize: 13.5, display: 'flex', alignItems: 'center', gap: 8 }}><I.Plus size={16}/> Nuevo anuncio</button>
      </div>

      {items.length === 0 ? (
        <div style={{ background: '#fff', border: `1px dashed ${t.border}`, borderRadius: 16, padding: 48, textAlign: 'center', color: t.sec }}>
          <I.Image size={32}/><div style={{ fontSize: 16, fontWeight: 700, color: t.text, marginTop: 10 }}>Aún no hay anuncios{filtro !== 'todos' ? ' en este estado' : ''}</div>
          <div style={{ fontSize: 13.5, marginTop: 4 }}>Crea uno para que aparezca en el Inicio del cliente, en el Marketplace del transportista o como oferta.</div>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 14 }}>
          {items.map((a) => <AnuncioCard key={a.id} t={t} I={I} a={a} onEdit={() => setEdit(a)} onToggle={() => toggle(a)} onBorrar={() => borrar(a)} onMet={() => setMet(a)}/>)}
        </div>
      )}
      {edit && <AnuncioModal t={t} I={I} a={edit.id ? edit : null} onClose={() => setEdit(null)} onSaved={() => { setEdit(null); q.reload(); }}/>}
      {met && <MetricasModal t={t} I={I} a={met} onClose={() => setMet(null)}/>}
    </div>
  );
}

// Vista previa fiel a cómo se ve en la app (banner de Inicio).
function AnuncioPreview({ a, compact }) {
  const bg = a.colorFondo || '#1D57A9', fg = a.colorTexto || '#fff';
  return (
    <div style={{ borderRadius: 16, overflow: 'hidden', background: a.imagen ? `linear-gradient(90deg, ${bg} 45%, transparent 100%), url(${a.imagen}) right center / cover` : `radial-gradient(90% 120% at 100% 0%, rgba(255,255,255,.18) 0%, rgba(255,255,255,0) 60%), ${bg}`, color: fg, padding: compact ? '14px 16px' : '18px 18px', display: 'flex', alignItems: 'center', gap: 12, minHeight: compact ? 84 : 110, fontFamily: '"Geist", system-ui, sans-serif' }}>
      {a.logo ? <img src={a.logo} alt="" style={{ width: 40, height: 40, borderRadius: 11, objectFit: 'cover', background: '#fff', flexShrink: 0 }}/> : <span style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 15, flexShrink: 0 }}>{(a.anunciante || 'L')[0]}</span>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: .8, textTransform: 'uppercase', opacity: .8 }}>{a.anunciante || 'Anunciante'} · Patrocinado</div>
        <div style={{ fontSize: compact ? 15 : 17, fontWeight: 800, letterSpacing: -.3, lineHeight: 1.2, marginTop: 2 }}>{a.titulo || 'Título del anuncio'}</div>
        {a.texto && !compact && <div style={{ fontSize: 13, opacity: .9, marginTop: 3, lineHeight: 1.4 }}>{a.texto}</div>}
      </div>
      <span style={{ background: '#F4C71E', color: '#1A1400', fontWeight: 800, fontSize: 12.5, padding: '8px 12px', borderRadius: 999, whiteSpace: 'nowrap', flexShrink: 0 }}>{a.cta || 'Ver más'}</span>
    </div>
  );
}

function AnuncioCard({ t, I, a, onEdit, onToggle, onBorrar, onMet }) {
  const est = { activo: ['Activo', '#1F8A5B'], pausado: ['Pausado', '#D98A0B'], borrador: ['Borrador', t.ter], finalizado: ['Finalizado', t.ter] }[a.estado] || ['—', t.ter];
  const m = a.metricas || {};
  const ctr = m.impresiones ? (m.clics / m.impresiones * 100).toFixed(1) : '0.0';
  return (
    <div style={{ background: '#fff', border: `1px solid ${t.border}`, borderRadius: 16, padding: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <AnuncioPreview a={a} compact/>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
        <span style={{ fontSize: 11.5, fontWeight: 700, color: est[1], background: est[1] + '14', padding: '3px 9px', borderRadius: 999 }}>{est[0]}</span>
        {(a.ubicaciones || []).map((u) => <span key={u} style={{ fontSize: 11.5, color: t.sec, background: t.grid, padding: '3px 8px', borderRadius: 8 }}>{UBIC[u] || u}</span>)}
        <span style={{ fontSize: 11.5, color: t.sec, background: t.grid, padding: '3px 8px', borderRadius: 8 }}>{({ todos: 'Todos', cliente: 'Clientes', proveedor: 'Transportistas' })[a.audiencia]}</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, padding: '10px 12px', borderRadius: 10, background: '#F6F7F9' }}>
        {[['Impresiones', nf(m.impresiones)], ['Alcance', nf(m.alcance)], ['Clics', nf(m.clics)], ['CTR', ctr + '%']].map(([l, v]) => (
          <div key={l}><div style={{ fontSize: 10.5, color: t.ter, fontWeight: 700, textTransform: 'uppercase', letterSpacing: .5 }}>{l}</div><div style={{ fontSize: 15, fontWeight: 800, color: t.text }}>{v}</div></div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 6 }}>
        <button onClick={onEdit} style={aBtn(t)}>Editar</button>
        {(a.estado === 'activo' || a.estado === 'pausado' || a.estado === 'borrador') && <button onClick={onToggle} style={{ ...aBtn(t), color: a.estado === 'activo' ? '#D98A0B' : '#1F8A5B' }}>{a.estado === 'activo' ? 'Pausar' : 'Activar'}</button>}
        <button onClick={onMet} style={aBtn(t)}>Métricas</button>
        <span style={{ flex: 1 }}/>
        <button onClick={onBorrar} title="Eliminar" style={{ ...aBtn(t), color: t.danger, padding: '0 10px' }}><I.Trash size={15}/></button>
      </div>
    </div>
  );
}
const aBtn = (t) => ({ height: 34, padding: '0 12px', borderRadius: 9, border: `1px solid ${t.border}`, background: '#fff', color: t.text, fontWeight: 700, cursor: 'pointer', fontFamily: t.font, fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6 });

function leerImagen(file, max, cb) {
  const r = new FileReader();
  r.onload = () => {
    const img = new Image();
    img.onload = () => {
      const s = Math.min(1, max / Math.max(img.width, img.height));
      const cv = document.createElement('canvas'); cv.width = Math.round(img.width * s); cv.height = Math.round(img.height * s);
      cv.getContext('2d').drawImage(img, 0, 0, cv.width, cv.height);
      cb(cv.toDataURL('image/jpeg', 0.82));
    };
    img.src = r.result;
  };
  r.readAsDataURL(file);
}

function AnuncioModal({ t, I, a, onClose, onSaved }) {
  const [f, setF] = React.useState(a ? { ...a, destino: a.destino || { tipo: 'url', valor: '' }, cupon: a.cupon || {}, inicio: a.inicio ? a.inicio.slice(0, 10) : '', fin: a.fin ? a.fin.slice(0, 10) : '' }
    : { titulo: '', texto: '', anunciante: '', cta: 'Ver más', colorFondo: '#1D57A9', colorTexto: '#FFFFFF', destino: { tipo: 'url', valor: '' }, ubicaciones: ['inicio_banner'], audiencia: 'todos', deptos: [], cupon: {}, prioridad: 10, inicio: '', fin: '', estado: 'borrador', limiteImpresionesDia: 0 });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const inp = { width: '100%', height: 40, padding: '0 12px', borderRadius: 9, border: `1px solid ${t.border}`, fontFamily: t.font, fontSize: 13.5, color: t.text, background: '#fff', outline: 'none', boxSizing: 'border-box' };
  const lbl = { display: 'block', fontSize: 12.5, fontWeight: 700, color: t.text, marginBottom: 6 };
  const set = (k, v) => setF({ ...f, [k]: v });
  const guardar = async (estado) => {
    setBusy(true); setErr('');
    const body = { ...f, estado: estado || f.estado, inicio: f.inicio || null, fin: f.fin || null };
    try { if (a) await aApi().actualizarAnuncio(a.id, body); else await aApi().crearAnuncio(body); onSaved(); }
    catch (e) { setErr(e.message || 'No se pudo guardar'); }
    setBusy(false);
  };
  const paletas = ['#1D57A9', '#0A1626', '#15885A', '#7A5AF8', '#C0392B', '#D98A0B', '#0E9CA6', '#F4C71E'];
  return (
    <window.Modal title={a ? 'Editar anuncio' : 'Nuevo anuncio'} sub="Así se verá en la app. Los clics y las impresiones se miden en tiempo real." width={820} onClose={onClose}
      footer={<div style={{ display: 'flex', gap: 8, width: '100%' }}><span style={{ flex: 1 }}/><button onClick={onClose} style={aBtn(t)}>Cancelar</button>{f.estado !== 'activo' && <button disabled={busy} onClick={() => guardar('borrador')} style={aBtn(t)}>Guardar borrador</button>}<button disabled={busy} onClick={() => guardar('activo')} style={{ ...aBtn(t), ...window.GOLD }}>{busy ? 'Guardando…' : a && a.estado === 'activo' ? 'Guardar cambios' : 'Publicar ahora'}</button></div>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 22 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {err && <div style={{ padding: '10px 14px', borderRadius: 10, background: '#FDF0EF', border: '1px solid #F2C4C0', color: t.danger, fontSize: 13 }}>{err}</div>}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div><label style={lbl}>Anunciante</label><input style={inp} value={f.anunciante} placeholder="Ej. Llantas del Norte" onChange={(e) => set('anunciante', e.target.value)}/></div>
            <div><label style={lbl}>Botón (CTA)</label><input style={inp} value={f.cta} maxLength={24} onChange={(e) => set('cta', e.target.value)}/></div>
          </div>
          <div><label style={lbl}>Título <span style={{ color: t.ter, fontWeight: 500 }}>({(f.titulo || '').length}/60)</span></label><input style={inp} value={f.titulo} maxLength={60} placeholder="Ej. 20% en llantas para camión" onChange={(e) => set('titulo', e.target.value)}/></div>
          <div><label style={lbl}>Texto <span style={{ color: t.ter, fontWeight: 500 }}>({(f.texto || '').length}/140)</span></label><textarea style={{ ...inp, height: 64, padding: 10, resize: 'none' }} value={f.texto} maxLength={140} onChange={(e) => set('texto', e.target.value)}/></div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div><label style={lbl}>Al tocar, abre</label>
              <select style={inp} value={f.destino.tipo} onChange={(e) => set('destino', { ...f.destino, tipo: e.target.value })}>
                <option value="url">Sitio web</option><option value="whatsapp">WhatsApp</option><option value="telefono">Llamada</option><option value="pantalla">Pantalla de LOLA</option><option value="ninguno">Nada (solo imagen)</option>
              </select></div>
            <div><label style={lbl}>{({ url: 'URL', whatsapp: 'Número (+502…)', telefono: 'Número', pantalla: 'Pantalla (solicitar, retornos, marketplace…)', ninguno: '—' })[f.destino.tipo]}</label><input style={inp} disabled={f.destino.tipo === 'ninguno'} value={f.destino.valor} onChange={(e) => set('destino', { ...f.destino, valor: e.target.value })}/></div>
          </div>
          <div>
            <label style={lbl}>Dónde aparece</label>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {Object.entries(UBIC).map(([k, l]) => { const on = (f.ubicaciones || []).includes(k); return <button key={k} onClick={() => set('ubicaciones', on ? f.ubicaciones.filter((x) => x !== k) : [...(f.ubicaciones || []), k])} style={{ height: 34, padding: '0 12px', borderRadius: 999, border: `1px solid ${on ? t.brand : t.border}`, background: on ? t.brand + '12' : '#fff', color: on ? t.brand : t.sec, fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: t.font }}>{l}</button>; })}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
            <div><label style={lbl}>Audiencia</label><select style={inp} value={f.audiencia} onChange={(e) => set('audiencia', e.target.value)}><option value="todos">Todos</option><option value="cliente">Clientes</option><option value="proveedor">Transportistas</option></select></div>
            <div><label style={lbl}>Desde</label><input type="date" style={inp} value={f.inicio} onChange={(e) => set('inicio', e.target.value)}/></div>
            <div><label style={lbl}>Hasta</label><input type="date" style={inp} value={f.fin} onChange={(e) => set('fin', e.target.value)}/></div>
          </div>
          {(f.ubicaciones || []).includes('ofertas_para_ti') && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, padding: 12, borderRadius: 12, background: '#FFF8DC', border: '1px solid #F4C71E88' }}>
              <div><label style={lbl}>Código de cupón</label><input style={{ ...inp, fontFamily: t.mono }} value={f.cupon.codigo || ''} onChange={(e) => set('cupon', { ...f.cupon, codigo: e.target.value.toUpperCase() })}/></div>
              <div><label style={lbl}>Descuento</label><input style={inp} placeholder="20% / Q100" value={f.cupon.descuento || ''} onChange={(e) => set('cupon', { ...f.cupon, descuento: e.target.value })}/></div>
              <div><label style={lbl}>Vence</label><input type="date" style={inp} value={f.cupon.vence ? String(f.cupon.vence).slice(0, 10) : ''} onChange={(e) => set('cupon', { ...f.cupon, vence: e.target.value })}/></div>
            </div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div><label style={lbl}>Prioridad (1 = primero)</label><input type="number" min="1" max="99" style={inp} value={f.prioridad} onChange={(e) => set('prioridad', e.target.value)}/></div>
            <div><label style={lbl}>Límite de impresiones por día (0 = sin límite)</label><input type="number" min="0" style={inp} value={f.limiteImpresionesDia} onChange={(e) => set('limiteImpresionesDia', e.target.value)}/></div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ fontSize: 12, fontWeight: 800, color: t.ter, textTransform: 'uppercase', letterSpacing: .8 }}>Vista previa en la app</div>
          <div style={{ background: '#F2F5F9', borderRadius: 20, padding: 14 }}><AnuncioPreview a={f}/></div>
          <div>
            <label style={lbl}>Color de fondo</label>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{paletas.map((c) => <button key={c} onClick={() => set('colorFondo', c)} style={{ width: 28, height: 28, borderRadius: 8, background: c, border: f.colorFondo === c ? '3px solid #fff' : '1px solid rgba(0,0,0,.1)', boxShadow: f.colorFondo === c ? '0 0 0 2px ' + t.brand : 'none', cursor: 'pointer' }}/>)}
              <input type="color" value={f.colorFondo} onChange={(e) => set('colorFondo', e.target.value)} style={{ width: 28, height: 28, border: 'none', padding: 0, background: 'none', cursor: 'pointer' }}/></div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <label style={{ ...aBtn(t), justifyContent: 'center', cursor: 'pointer' }}><I.Image size={15}/> Logo<input type="file" accept="image/*" hidden onChange={(e) => e.target.files[0] && leerImagen(e.target.files[0], 160, (d) => set('logo', d))}/></label>
            <label style={{ ...aBtn(t), justifyContent: 'center', cursor: 'pointer' }}><I.Image size={15}/> Imagen<input type="file" accept="image/*" hidden onChange={(e) => e.target.files[0] && leerImagen(e.target.files[0], 900, (d) => set('imagen', d))}/></label>
          </div>
          {(f.logo || f.imagen) && <button onClick={() => setF({ ...f, logo: '', imagen: '' })} style={{ ...aBtn(t), justifyContent: 'center', color: t.sec }}>Quitar imágenes</button>}
          <div style={{ fontSize: 12, color: t.ter, lineHeight: 1.5 }}>Texto de color claro sobre fondo oscuro. Las imágenes se reducen automáticamente (máx. 900 px).</div>
        </div>
      </div>
    </window.Modal>
  );
}

function MetricasModal({ t, I, a, onClose }) {
  const q = window.useAsync(() => aApi().metricasAnuncio(a.id), [a.id]);
  return (
    <window.Modal title={'Métricas · ' + a.titulo} sub="Últimos 30 días, medidos en la app en tiempo real" width={720} onClose={onClose} footer={<button onClick={onClose} style={aBtn(t)}>Cerrar</button>}>
      {q.loading ? <window.Loading/> : q.error ? <window.ErrState error={q.error} onRetry={q.reload}/> : (() => {
        const d = q.data; const m = d.anuncio.metricas || {};
        const dias = {}; (d.porDia || []).forEach((r) => { dias[r._id.dia] = dias[r._id.dia] || { impresion: 0, clic: 0 }; dias[r._id.dia][r._id.tipo] = r.n; });
        const keys = Object.keys(dias).sort(); const max = Math.max(1, ...keys.map((k) => dias[k].impresion));
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
              {[['Impresiones', nf(m.impresiones)], ['Alcance único', nf(m.alcance)], ['Clics', nf(m.clics)], ['CTR', d.ctr + '%']].map(([l, v]) => <div key={l} style={{ padding: '12px 14px', borderRadius: 12, background: '#F6F7F9' }}><div style={{ fontSize: 11, color: t.ter, fontWeight: 700, textTransform: 'uppercase' }}>{l}</div><div style={{ fontSize: 22, fontWeight: 800, color: t.text }}>{v}</div></div>)}
            </div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 800, color: t.ter, textTransform: 'uppercase', letterSpacing: .8, marginBottom: 8 }}>Impresiones y clics por día</div>
              {keys.length === 0 ? <div style={{ color: t.sec, fontSize: 13.5 }}>Sin eventos todavía.</div> : (
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 120, padding: '0 4px' }}>
                  {keys.map((k) => <div key={k} title={k + ': ' + dias[k].impresion + ' imp · ' + dias[k].clic + ' clics'} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: 2, height: '100%' }}>
                    <div style={{ height: (dias[k].clic / max * 100) + '%', background: '#F4C71E', borderRadius: 3, minHeight: dias[k].clic ? 3 : 0 }}/>
                    <div style={{ height: (dias[k].impresion / max * 100) + '%', background: t.brand, borderRadius: 3, minHeight: 2 }}/>
                  </div>)}
                </div>
              )}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div><div style={{ fontSize: 12, fontWeight: 800, color: t.ter, textTransform: 'uppercase', marginBottom: 6 }}>Por ubicación</div>{(d.porUbicacion || []).map((r, i) => <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '5px 0', borderBottom: `1px solid ${t.grid}` }}><span>{UBIC[r._id.u] || r._id.u || '—'} · {r._id.tipo}</span><b>{nf(r.n)}</b></div>)}</div>
              <div><div style={{ fontSize: 12, fontWeight: 800, color: t.ter, textTransform: 'uppercase', marginBottom: 6 }}>Por tipo de usuario</div>{(d.porRol || []).map((r, i) => <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '5px 0', borderBottom: `1px solid ${t.grid}` }}><span>{({ cliente: 'Clientes', proveedor: 'Transportistas' })[r._id.rol] || r._id.rol || '—'} · {r._id.tipo}</span><b>{nf(r.n)}</b></div>)}</div>
            </div>
          </div>
        );
      })()}
    </window.Modal>
  );
}

// ── Moderación de viajes de retorno ──
function RetornosAdminView() {
  const t = window.WC, I = window.WI;
  const [estado, setEstado] = React.useState('');
  const [q, setQ] = React.useState('');
  const data = window.useAsync(() => aApi().retornosAdmin({ estado, q }), [estado, q]);
  const [sel, setSel] = React.useState(null);
  const [busy, setBusy] = React.useState('');
  const moderar = async (r, accion) => {
    const motivo = accion === 'cancelar' ? window.prompt('Motivo (se le avisa al transportista y a los clientes con solicitud):') : '';
    if (accion === 'cancelar' && motivo === null) return;
    setBusy(r.id);
    try { await aApi().moderarRetorno(r.id, accion, motivo || ''); data.reload(); setSel(null); } catch (e) { alert(e.message); }
    setBusy('');
  };
  const est = { publicado: ['Publicado', t.brand], reservado: ['Reservado', '#1F8A5B'], completado: ['Completado', t.ter], cancelado: ['Cancelado', t.danger] };
  const fecha = (d) => new Date(d).toLocaleDateString('es-GT', { weekday: 'short', day: 'numeric', month: 'short' });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 1100 }}>
      {data.data && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12 }}>
          {[['Publicados', data.data.resumen.publicados, t.brand], ['Reservados', data.data.resumen.reservados, '#1F8A5B'], ['Hoy', data.data.resumen.hoy, t.text], ['Total', data.data.resumen.total, t.text]].map(([l, v, c]) => (
            <div key={l} style={{ background: '#fff', border: `1px solid ${t.border}`, borderRadius: 14, padding: '14px 18px' }}><div style={{ fontSize: 11, color: t.ter, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700 }}>{l}</div><div style={{ fontSize: 24, fontWeight: 800, color: c, marginTop: 4 }}>{v}</div></div>
          ))}
        </div>
      )}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, border: `1px solid ${t.border}`, borderRadius: 10, background: '#fff', padding: '0 12px', height: 40, flex: 1, minWidth: 220 }}><I.Search size={16}/><input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar ciudad, transportista o vehículo…" style={{ border: 'none', outline: 'none', flex: 1, fontFamily: t.font, fontSize: 13.5 }}/></div>
        <div style={{ display: 'inline-flex', gap: 4, background: '#fff', border: `1px solid ${t.border}`, borderRadius: 12, padding: 4 }}>
          {[['', 'Todos'], ['publicado', 'Publicados'], ['reservado', 'Reservados'], ['completado', 'Completados'], ['cancelado', 'Cancelados']].map(([k, l]) => <button key={k} onClick={() => setEstado(k)} style={{ height: 32, padding: '0 12px', borderRadius: 9, border: 'none', cursor: 'pointer', fontFamily: t.font, fontSize: 13, fontWeight: 700, background: estado === k ? t.brand + '12' : 'transparent', color: estado === k ? t.brand : t.sec }}>{l}</button>)}
        </div>
      </div>
      {data.loading ? <window.Loading/> : data.error ? <window.ErrState error={data.error} onRetry={data.reload}/> : data.data.items.length === 0 ? (
        <div style={{ background: '#fff', border: `1px dashed ${t.border}`, borderRadius: 16, padding: 48, textAlign: 'center', color: t.sec }}><I.Repeat size={30}/><div style={{ fontSize: 16, fontWeight: 700, color: t.text, marginTop: 10 }}>Sin viajes de retorno</div></div>
      ) : (
        <div style={{ background: '#fff', border: `1px solid ${t.border}`, borderRadius: 16, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '110px 1.6fr 1.2fr 1fr 90px 110px 120px', gap: 10, padding: '11px 16px', background: '#FAFBFC', borderBottom: `1px solid ${t.border}`, fontSize: 10.5, fontWeight: 700, color: t.ter, textTransform: 'uppercase', letterSpacing: .8, fontFamily: t.mono }}>
            <span>Salida</span><span>Ruta</span><span>Transportista</span><span>Vehículo</span><span>Precio</span><span>Solicitudes</span><span>Estado</span>
          </div>
          {data.data.items.map((r) => { const e = est[r.estado] || est.publicado; const sols = r.solicitudes || []; return (
            <button key={r.id} onClick={() => setSel(r)} style={{ width: '100%', display: 'grid', gridTemplateColumns: '110px 1.6fr 1.2fr 1fr 90px 110px 120px', gap: 10, padding: '13px 16px', borderTop: `1px solid ${t.grid}`, border: 'none', borderBottom: 'none', background: '#fff', cursor: 'pointer', textAlign: 'left', fontFamily: t.font, fontSize: 13.5, color: t.text, alignItems: 'center' }}>
              <span style={{ fontWeight: 600 }}>{fecha(r.fechaSalida)}</span>
              <span style={{ minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}><b>{r.origen && r.origen.texto}</b> → {r.destino && r.destino.texto}</span>
              <span style={{ minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.transportistaNombre}</span>
              <span style={{ color: t.sec, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.tipoTransporte}</span>
              <span style={{ fontWeight: 800 }}>Q{nf(r.precio)}</span>
              <span>{sols.filter((s) => s.estado === 'pendiente').length} pend. · {sols.filter((s) => s.estado === 'aceptada').length} acep.</span>
              <span><span style={{ fontSize: 11.5, fontWeight: 700, color: e[1], background: e[1] + '14', padding: '3px 9px', borderRadius: 999 }}>{e[0]}</span></span>
            </button>
          ); })}
        </div>
      )}
      {sel && (
        <window.Modal title={(sel.origen && sel.origen.texto) + ' → ' + (sel.destino && sel.destino.texto)} sub={fecha(sel.fechaSalida) + ' · ' + sel.tipoTransporte + ' · Q' + nf(sel.precio) + (sel.precioReferencia ? ' (flete normal Q' + nf(sel.precioReferencia) + ')' : '')} width={680} onClose={() => setSel(null)}
          footer={<div style={{ display: 'flex', gap: 8, width: '100%' }}>
            {sel.estado === 'cancelado' && <button disabled={!!busy} onClick={() => moderar(sel, 'republicar')} style={aBtn(t)}>Republicar</button>}
            {sel.estado === 'reservado' && <button disabled={!!busy} onClick={() => moderar(sel, 'completar')} style={aBtn(t)}>Marcar completado</button>}
            <span style={{ flex: 1 }}/>
            {(sel.estado === 'publicado' || sel.estado === 'reservado') && <button disabled={!!busy} onClick={() => moderar(sel, 'cancelar')} style={{ ...aBtn(t), color: t.danger, borderColor: '#F2C4C0' }}>Retirar publicación</button>}
            <button onClick={() => setSel(null)} style={aBtn(t)}>Cerrar</button></div>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ padding: 14, borderRadius: 12, background: '#F6F7F9', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 13.5 }}>
              <div><div style={{ fontSize: 11, color: t.ter, fontWeight: 700, textTransform: 'uppercase' }}>Transportista</div><b>{sel.transportistaNombre}</b>{sel.transportista && sel.transportista.telefono && <div style={{ color: t.sec }}>{sel.transportista.telefono}</div>}</div>
              <div><div style={{ fontSize: 11, color: t.ter, fontWeight: 700, textTransform: 'uppercase' }}>Capacidad libre</div><b>{sel.capacidadKg ? nf(sel.capacidadKg) + ' kg' : '—'}</b></div>
              {sel.notas && <div style={{ gridColumn: '1 / -1' }}><div style={{ fontSize: 11, color: t.ter, fontWeight: 700, textTransform: 'uppercase' }}>Notas</div>{sel.notas}</div>}
            </div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 800, color: t.ter, textTransform: 'uppercase', letterSpacing: .8, marginBottom: 8 }}>Solicitudes ({(sel.solicitudes || []).length})</div>
              {(sel.solicitudes || []).length === 0 ? <div style={{ color: t.sec, fontSize: 13.5 }}>Nadie ha solicitado espacio todavía.</div> : (sel.solicitudes || []).map((s) => (
                <div key={s.id} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '10px 0', borderBottom: `1px solid ${t.grid}`, fontSize: 13.5 }}>
                  <div style={{ flex: 1 }}><b>{s.clienteNombre}</b>{s.pesoKg ? <span style={{ color: t.sec }}> · {nf(s.pesoKg)} kg</span> : null}<div style={{ color: t.sec, marginTop: 2 }}>{s.descripcion}</div></div>
                  <span style={{ fontSize: 11.5, fontWeight: 700, padding: '3px 9px', borderRadius: 999, background: t.grid, color: t.sec, whiteSpace: 'nowrap' }}>{({ pendiente: 'Pendiente', aceptada: 'Aceptada', rechazada: 'Rechazada', cancelada: 'Cancelada' })[s.estado]}</span>
                </div>
              ))}
            </div>
          </div>
        </window.Modal>
      )}
    </div>
  );
}

window.AnunciosView = AnunciosView;
window.RetornosAdminView = RetornosAdminView;
window.AnuncioPreview = AnuncioPreview;
