/* global React, SFIcons */
const { Grid: AGrid, Package: APkg, CreditCard: ACC, Heart: AHrt, MapPin: AMap, User: AUsr, LogOut: AOut, Truck: ATruck, ChevronRight: AChev, Clock: AClock, Check: ACheck, Info: AInfo, FileText: ATkt, Plus: APlus, Trash: ATrash } = SFIcons;
const M = window.MADECIDesignSystem_419fb1;
const clpA = (n) => '$' + Number(n).toLocaleString('es-CL');

const NAV = [
  { id: 'resumen', label: 'Resumen', icon: AGrid },
  { id: 'pedidos', label: 'Mis pedidos', icon: APkg },
  { id: 'favoritos', label: 'Favoritos', icon: AHrt },
  { id: 'cambios', label: 'Cambios / reposición', icon: ATkt },
  { id: 'datos', label: 'Datos comerciales', icon: AUsr },
  { id: 'cobertura', label: 'Cobertura', icon: AMap },
];

// Motivos de un ticket de cambio (deben calzar con el backend).
const MOTIVOS = [
  { v: 'trizado', t: 'Trizado / roto' },
  { v: 'sin_gas', t: 'Sin gas' },
  { v: 'vencido', t: 'Vencido' },
  { v: 'falla_fabrica', t: 'Falla de fábrica' },
  { v: 'faltante', t: 'Faltó en la entrega' },
  { v: 'otro', t: 'Otro' },
];
const MOTIVO_LABEL = Object.fromEntries(MOTIVOS.map((m) => [m.v, m.t]));
// Estados del ticket + color del badge.
const EST_TICKET = {
  nueva: { t: 'Nueva', c: '#4f46e5', bg: '#eef2ff' },
  en_revision: { t: 'En revisión', c: '#b45309', bg: '#fef3c7' },
  aprobada: { t: 'Aprobada', c: '#1e7e46', bg: '#e7f6ee' },
  rechazada: { t: 'Rechazada', c: '#c8102e', bg: '#fdecef' },
  resuelta: { t: 'Resuelta', c: '#166534', bg: '#dcfce7' },
};

function Head({ eyebrow, title }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <span className="madeci-eyebrow">{eyebrow}</span>
      <h2 style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-.015em', margin: '3px 0 0' }}>{title}</h2>
    </div>
  );
}

// ── Cobertura de despacho ──────────────────────────────────────────────
// Política real de reparto MADECI: 6 comunas de la provincia de San Antonio,
// dos despachos diarios (mañana y tarde) de Lun a Sáb, uno el domingo (mañana),
// con horarios de corte y la excepción de Cartagena.
const COBERTURA_COMUNAS = [
  { name: 'San Antonio', nota: 'Mañana y tarde' },
  { name: 'Santo Domingo', nota: 'Mañana y tarde' },
  { name: 'Cartagena', nota: 'Mañana y tarde extendida', hub: true },
  { name: 'El Tabo', nota: 'Mañana y tarde' },
  { name: 'El Quisco', nota: 'Mañana y tarde' },
  { name: 'Algarrobo', nota: 'Mañana y tarde' },
];

function CobStat({ n, l }) {
  return (
    <div>
      <div style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 20, color: '#fff', lineHeight: 1 }}>{n}</div>
      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'rgba(255,255,255,.6)', marginTop: 3 }}>{l}</div>
    </div>
  );
}

// Tarjeta de un turno de despacho (mañana / tarde).
function TurnoCard({ titulo, sub, corte, llega, destacado }) {
  return (
    <div style={{ flex: 1, minWidth: 200, background: destacado ? 'var(--madeci-red-50)' : 'var(--surface-card)', border: `1px solid ${destacado ? 'var(--madeci-red)' : 'var(--border-subtle)'}`, borderRadius: 'var(--radius-md)', padding: '16px 18px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <AClock size={17} stroke={destacado ? 'var(--madeci-red)' : 'var(--text-muted)'} />
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--text-strong)' }}>{titulo}</div>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-muted)' }}>{sub}</div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 10.5, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>Pide antes de</div>
          <div style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 22, color: 'var(--text-strong)', lineHeight: 1.1 }}>{corte}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', color: 'var(--madeci-red)', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18 }}>→</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 10.5, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>Te llega</div>
          <div style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 22, color: 'var(--madeci-red-dark)', lineHeight: 1.1 }}>{llega}</div>
        </div>
      </div>
    </div>
  );
}

function CoberturaPanel() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {/* Banda con la zona y los indicadores */}
      <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
        <div style={{ position: 'relative', background: 'var(--madeci-ink)', padding: '26px 24px', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, opacity: 0.5, background: 'repeating-linear-gradient(115deg, transparent 0 38px, rgba(255,255,255,.04) 38px 40px)' }} />
          <div style={{ position: 'absolute', left: 0, right: 0, top: '52%', height: 2, background: 'repeating-linear-gradient(90deg, var(--madeci-red) 0 14px, transparent 14px 26px)', opacity: 0.85 }} />
          <div style={{ position: 'relative' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--madeci-red)' }}>Cobertura de reparto</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24, color: '#fff', letterSpacing: '-.01em', marginTop: 4 }}>Provincia de San Antonio y alrededores</div>
            <div style={{ display: 'flex', gap: 22, marginTop: 14, flexWrap: 'wrap' }}>
              <CobStat n="6" l="Comunas con reparto" />
              <CobStat n="2 al día" l="Despachos garantizados" />
              <CobStat n="Lun a Dom" l="Días de reparto" />
            </div>
          </div>
        </div>
        {/* Grilla de comunas */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }}>
          {COBERTURA_COMUNAS.map((z, i) => (
            <div key={z.name} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 20px', borderTop: '1px solid var(--border-subtle)', borderLeft: i % 2 ? '1px solid var(--border-subtle)' : 'none' }}>
              <AMap size={16} stroke="var(--madeci-red)" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: 'var(--text-strong)', display: 'flex', alignItems: 'center', gap: 7 }}>
                  {z.name}
                  {z.hub && <span style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, fontWeight: 700, letterSpacing: '.08em', color: 'var(--madeci-red)', background: 'var(--madeci-red-50)', padding: '2px 6px', borderRadius: 3 }}>SUCURSAL</span>}
                </div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>{z.nota}</div>
              </div>
              <span style={{ fontFamily: 'var(--font-display)', fontSize: 11.5, fontWeight: 600, color: 'var(--status-success)', display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--status-success)' }} /> Activa
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Horarios de corte */}
      <div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 600, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--madeci-red)', marginBottom: 10 }}>Horarios de despacho garantizado</div>
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
          <TurnoCard titulo="Despacho de la mañana" sub="Lun a Dom" corte="10:00" llega="antes de 13:00" />
          <TurnoCard titulo="Despacho de la tarde" sub="Lun a Sáb" corte="15:00" llega="antes de 18:00" />
        </div>
        {/* Excepción Cartagena */}
        <div style={{ marginTop: 14 }}>
          <TurnoCard titulo="Cartagena · tarde extendida" sub="Solo comuna de Cartagena" corte="17:00" llega="antes de 18:30" destacado />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)' }}>
          <AInfo size={15} stroke="var(--madeci-red)" /> El domingo hay reparto solo en la jornada de la mañana (corte 10:00).
        </div>
      </div>

      {/* Fuera de horario */}
      <div style={{ background: 'var(--neutral-25)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: '16px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--text-strong)', marginBottom: 6 }}>
          <AClock size={17} stroke="var(--text-muted)" /> ¿Pediste fuera del horario de corte?
        </div>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-body)', lineHeight: 1.5, margin: 0 }}>
          Tu pedido entra según la capacidad disponible del día. Si no alcanza, pasa automáticamente al <strong>siguiente despacho de tu comuna</strong>, a más tardar al día siguiente. Por ejemplo: si pides a las 11:00, tu pedido queda planificado para el despacho de la tarde de ese mismo día.
        </p>
      </div>

      {/* Despacho programado */}
      <div style={{ display: 'flex', gap: 12, background: 'var(--madeci-red-50)', border: '1px solid var(--madeci-red)', borderRadius: 'var(--radius-md)', padding: '16px 18px' }}>
        <ACheck size={20} stroke="var(--madeci-red)" style={{ flex: 'none', marginTop: 2 }} />
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--madeci-red-dark)', marginBottom: 4 }}>¿Prefieres recibirlo otro día?</div>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-body)', lineHeight: 1.5, margin: 0 }}>
            Puedes programar tu despacho para la fecha que más te acomode, hasta <strong>7 días</strong> desde que haces el pedido, y elegir la jornada (mañana o tarde).
          </p>
        </div>
      </div>

      {/* Contacto */}
      <div style={{ display: 'flex', gap: 9, fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', alignItems: 'center' }}>
        <ATruck size={16} stroke="var(--madeci-red)" /> ¿Tu comuna no aparece? Escríbenos al WhatsApp +56 9 9443 7835.
      </div>
    </div>
  );
}

function ActiveOrder({ order }) {
  return (
    <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 'var(--space-5)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12, marginBottom: 20 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 20, color: 'var(--text-strong)' }}>Pedido {order.number}</span>
            <M.DeliveryStatusBadge state={order.tracker} />
          </div>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-muted)', marginTop: 3 }}>{order.date} · {order.itemCount} productos · {clpA(order.total)}</div>
        </div>
      </div>
      <M.DeliveryTracker current={order.tracker} />
    </div>
  );
}

// Bloque simple cuando el cliente todavía no tiene pedidos / no hay nada que mostrar.
function Vacio({ texto }) {
  return (
    <div style={{ padding: '32px 24px', textAlign: 'center', fontFamily: 'var(--font-body)', color: 'var(--text-muted)', border: '1px dashed var(--border-default)', borderRadius: 'var(--radius-lg)' }}>{texto}</div>
  );
}

// Estado cuando NO hay ningún pedido en camino (todos entregados o aún no compró).
function SinEnCurso({ onShop }) {
  return (
    <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 'var(--space-5) var(--space-6)', display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
      <span style={{ width: 52, height: 52, flex: 'none', borderRadius: 999, background: 'var(--madeci-red-50)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <ATruck size={26} stroke="var(--madeci-red)" />
      </span>
      <div style={{ flex: 1, minWidth: 200 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, color: 'var(--text-strong)', lineHeight: 1.15 }}>No tienes pedidos en camino</div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-muted)', marginTop: 3 }}>Cuando hagas un pedido, podrás seguir aquí su preparación y despacho.</div>
      </div>
      <button onClick={onShop} style={{ flex: 'none', height: 44, padding: '0 20px', borderRadius: 'var(--radius-sm)', border: 'none', background: 'var(--madeci-red)', color: '#fff', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5 }}>Explorar catálogo</button>
    </div>
  );
}

// Ficha comercial editable (estilo checkout): muestra TODOS los datos y permite
// PEDIR la actualización de los editables. Los cambios quedan EN REVISIÓN (no tocan Random).
function DatosComerciales({ account: a }) {
  const raw = (a && a._raw) || {};
  const editables = [
    { k: 'giro', label: 'Giro / actividad' },
    { k: 'email', label: 'Email (comercial)' },
    { k: 'fono', label: 'Teléfono' },
    { k: 'contacto', label: 'Contacto' },
  ];
  const inicial = () => { const f = {}; [...editables, { k: 'direccion' }].forEach(({ k }) => (f[k] = raw[k] || '')); return f; };
  const [form, setForm] = React.useState(inicial);
  const [edit, setEdit] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [enviando, setEnviando] = React.useState(false);
  const [error, setError] = React.useState('');
  const [docs, setDocs] = React.useState([]);
  const fileRef = React.useRef(null);
  const set = (k) => (e) => setForm((s) => ({ ...s, [k]: e.target.value }));
  const cancelar = () => { setForm(inicial()); setEdit(false); setError(''); setDocs([]); };

  const cambioDireccion = edit && (form.direccion || '').trim() !== (raw.direccion || '').trim();

  const guardar = async () => {
    const cambios = {};
    [...editables, { k: 'direccion' }].forEach(({ k }) => {
      const antes = (raw[k] || '').trim(), despues = (form[k] || '').trim();
      if (despues !== antes) cambios[k] = { antes: antes || null, despues: despues || null };
    });
    if (Object.keys(cambios).length === 0) { setError('No cambiaste ningún dato.'); return; }
    // El documento de respaldo es OPCIONAL: si no lo adjunta, un ejecutivo se lo pedirá.
    setEnviando(true); setError('');
    try {
      const r = await window.MadeciAPI.crearSolicitud({ tipo: 'datos', cambios });
      for (const f of docs) { try { await window.MadeciAPI.subirDocumentoSolicitud(r.id, f); } catch (e) { /* sigue */ } }
      setEdit(false); setSaved(true); setDocs([]);
    }
    catch (e) { setError(e.message); }
    finally { setEnviando(false); }
  };
  return (
    <M.Card padding="lg">
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><AUsr size={18} stroke="var(--madeci-red)" /><h3 style={{ fontSize: 18, fontWeight: 700 }}>Ficha comercial</h3></div>
        {!edit && <button onClick={() => { setEdit(true); setSaved(false); }} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13.5, color: 'var(--madeci-red)' }}>Editar datos</button>}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <M.Input label="Razón social" value={a.name} disabled />
        <M.Input label="RUT" value={a.rut} disabled />
        <M.Input label="Lista de precio" value={a.priceList} disabled />
        <M.Input label="Condición de pago" value={a.paymentCondition} disabled />
        <M.Input label="Giro / actividad" value={form.giro} onChange={set('giro')} disabled={!edit} />
        <M.Input label="Email (comercial)" value={form.email} onChange={set('email')} disabled={!edit} />
        <M.Input label="Teléfono" value={form.fono} onChange={set('fono')} disabled={!edit} />
        <M.Input label="Contacto" value={form.contacto} onChange={set('contacto')} disabled={!edit} />
        <div style={{ gridColumn: '1 / -1' }}><M.Input label="Dirección de despacho" value={form.direccion} onChange={set('direccion')} disabled={!edit} /></div>
      </div>
      {cambioDireccion && (
        <div style={{ marginTop: 12, padding: 14, border: '1px dashed var(--border-strong)', borderRadius: 'var(--radius-sm)', background: 'var(--neutral-25)' }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13.5, marginBottom: 6 }}>Documento de respaldo <span style={{ fontWeight: 600, color: 'var(--text-subtle)' }}>(opcional)</span></div>
          <input ref={fileRef} type="file" accept="image/*,application/pdf" multiple style={{ display: 'none' }} onChange={(e) => setDocs(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)' }}>📎 Adjuntar documento</button>
          {docs.length > 0 && <div style={{ marginTop: 8, fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>{docs.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 ayuda a validar más rápido (ej.: cuenta de servicios, patente o contrato). Si no, un ejecutivo te lo solicitará.</div>
        </div>
      )}
      {error && <div style={{ marginTop: 12, color: 'var(--madeci-red)', fontFamily: 'var(--font-body)', fontSize: 13.5 }}>{error}</div>}
      {edit && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16 }}>
          <M.Button size="sm" onClick={guardar} disabled={enviando}>{enviando ? 'Enviando…' : 'Guardar cambios'}</M.Button>
          <button onClick={cancelar} 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' }}>Notificaremos a MADECI para validar los nuevos datos.</span>
        </div>
      )}
      {saved && !edit && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 16, 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)' }}>
          ✓ Solicitud enviada. Tus datos quedaron en revisión; te avisaremos cuando se apliquen.
        </div>
      )}
    </M.Card>
  );
}

// Modal con el detalle de un pedido (cabecera + ítems).
function PedidoDetalle({ pedido, onClose }) {
  const clp = (n) => '$' + Number(n || 0).toLocaleString('es-CL');
  const estados = { nuevo: 'Recibido', confirmado: 'Confirmado', en_despacho: 'En despacho', entregado: 'Entregado', anulado: 'Anulado' };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(20,15,16,.55)', zIndex: 100, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '48px 16px', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxWidth: 560, background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 'var(--space-6)' }}>
        {!pedido || pedido.loading ? (
          <div style={{ padding: 30, textAlign: 'center', fontFamily: 'var(--font-body)', color: 'var(--text-muted)' }}>Cargando…</div>
        ) : (
          <React.Fragment>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
              <div>
                <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 22, color: 'var(--text-strong)', margin: 0 }}>Pedido N° {pedido.id}</h2>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>{new Date(pedido.creado_en).toLocaleDateString('es-CL', { day: 'numeric', month: 'long', year: 'numeric' })} · {estados[pedido.estado] || pedido.estado}</div>
              </div>
              <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 24, color: 'var(--text-muted)', lineHeight: 1 }}>×</button>
            </div>
            <div style={{ border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', overflow: 'hidden' }}>
              {(pedido.items || []).map((it, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '11px 14px', borderBottom: i < pedido.items.length - 1 ? '1px solid var(--border-subtle)' : 'none', fontFamily: 'var(--font-body)', fontSize: 13.5 }}>
                  <div><div style={{ color: 'var(--text-strong)', fontWeight: 600 }}>{it.nombre}</div><div style={{ color: 'var(--text-muted)', fontSize: 12 }}>{it.cantidad} × {clp(it.precio_unitario)} · {it.unidad === 'CJ' ? 'Caja' : 'Unidad'}</div></div>
                  <div style={{ fontFamily: 'var(--font-data)', fontWeight: 700, color: 'var(--text-strong)', whiteSpace: 'nowrap' }}>{clp(it.subtotal)}</div>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 16 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>Total</span>
              <span style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 24, color: 'var(--madeci-red)' }}>{clp(pedido.total)}</span>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// Fila de pedido: la tarjeta del diseño + botón "Cancelar" si aún no fue confirmado.
function OrderRow({ o, onDetalle, onRepetir, onCancelar }) {
  return (
    <div>
      <M.OrderCard {...o} onReorder={onRepetir} onView={onDetalle} />
      {o.estadoRaw === 'ingresado' && (
        <div style={{ marginTop: 6, textAlign: 'right' }}>
          <button onClick={onCancelar} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 12.5, color: 'var(--madeci-red)' }}>Cancelar pedido</button>
        </div>
      )}
    </div>
  );
}

// Ventana de confirmación (reemplaza el popup gris del navegador).
function ConfirmModal({ titulo, texto, confirmarTexto, onConfirmar, onCerrar, cargando }) {
  return (
    <div onClick={onCerrar} style={{ position: 'fixed', inset: 0, background: 'rgba(20,15,16,.55)', zIndex: 110, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px 16px' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxWidth: 440, background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 'var(--space-6)' }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 20, color: 'var(--text-strong)', margin: '0 0 8px' }}>{titulo}</h2>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-body)', margin: '0 0 22px', lineHeight: 1.5 }}>{texto}</p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button onClick={onCerrar} disabled={cargando} style={{ height: 44, padding: '0 18px', borderRadius: 'var(--radius-sm)', border: '1px solid var(--border-default)', background: 'var(--surface-card)', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, color: 'var(--text-body)' }}>No, volver</button>
          <button onClick={onConfirmar} disabled={cargando} style={{ height: 44, padding: '0 20px', borderRadius: 'var(--radius-sm)', border: 'none', background: 'var(--madeci-red)', color: '#fff', cursor: cargando ? 'default' : 'pointer', opacity: cargando ? .7 : 1, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14 }}>{cargando ? 'Cancelando…' : confirmarTexto}</button>
        </div>
      </div>
    </div>
  );
}

// Estilos base para inputs de esta vista.
const inpBase = { width: '100%', padding: '11px 13px', fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-strong)', background: '#fff', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', boxSizing: 'border-box' };
const lblBase = { display: 'block', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 12.5, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 6 };

// Ticket ya creado (una tarjeta en la lista) — con sus productos.
function TicketRow({ t }) {
  const est = EST_TICKET[t.estado] || EST_TICKET.nueva;
  const fecha = new Date(t.creado_en).toLocaleDateString('es-CL', { day: 'numeric', month: 'short', year: 'numeric' });
  const items = Array.isArray(t.items) ? t.items : [];
  return (
    <div style={{ border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: '14px 16px', background: 'var(--surface-card)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--text-strong)' }}>Solicitud #{t.id} · {fecha}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3, marginTop: 7 }}>
            {items.map((it, i) => (
              <div key={i} style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-body)' }}>
                • {it.nombre} — <b>{it.cantidad} un</b> · {MOTIVO_LABEL[it.motivo] || it.motivo}
              </div>
            ))}
          </div>
          {t.descripcion && <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)', marginTop: 7 }}>{t.descripcion}</div>}
          {t.respuesta && (
            <div style={{ marginTop: 8, padding: '8px 11px', background: 'var(--neutral-50)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-body)' }}>
              <b>Respuesta:</b> {t.respuesta}
            </div>
          )}
        </div>
        <span style={{ flex: 'none', padding: '5px 11px', borderRadius: 999, background: est.bg, color: est.c, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12 }}>{est.t}</span>
      </div>
    </div>
  );
}

// Una línea de producto del formulario (combobox de producto + cantidad + motivo).
function LineaCambio({ value, products, onChange, onRemove, removable }) {
  const [open, setOpen] = React.useState(false);
  const sugerencias = (!value.sel && value.q.trim().length >= 2 && products)
    ? products.filter((p) => {
        const s = value.q.toLowerCase();
        return (p.name && p.name.toLowerCase().includes(s)) || (p.brand && p.brand.toLowerCase().includes(s)) || (p.sku && String(p.sku).toLowerCase().includes(s));
      }).slice(0, 8)
    : [];
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', flexWrap: 'wrap', paddingBottom: 12, marginBottom: 12, borderBottom: '1px dashed var(--border-subtle)' }}>
      <div style={{ position: 'relative', flex: 2, minWidth: 200 }}>
        <label style={lblBase}>Producto</label>
        <input style={inpBase} placeholder="Nombre del producto (o su código)"
          value={value.q}
          onChange={(e) => { onChange({ q: e.target.value, sel: null }); setOpen(true); }}
          onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 150)} />
        {open && sugerencias.length > 0 && (
          <div style={{ position: 'absolute', zIndex: 20, top: '100%', left: 0, right: 0, marginTop: 4, background: '#fff', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', boxShadow: 'var(--shadow-md)', maxHeight: 240, overflowY: 'auto' }}>
            {sugerencias.map((p) => (
              <button key={p.id} type="button" onMouseDown={() => { onChange({ q: p.name, sel: p }); setOpen(false); }}
                style={{ display: 'block', width: '100%', textAlign: 'left', padding: '9px 12px', border: 'none', borderBottom: '1px solid var(--border-subtle)', background: '#fff', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 14 }}>
                <span style={{ color: 'var(--text-strong)' }}>{p.name}</span>
                {p.sku && <span style={{ color: 'var(--text-subtle)', fontSize: 12.5 }}> · {p.sku}</span>}
              </button>
            ))}
          </div>
        )}
      </div>
      <div style={{ width: 92 }}>
        <label style={lblBase}>Cant.</label>
        <input type="number" min={1} style={inpBase} value={value.cantidad} onChange={(e) => onChange({ cantidad: e.target.value })} />
      </div>
      <div style={{ flex: 1, minWidth: 150 }}>
        <label style={lblBase}>Motivo</label>
        <select style={{ ...inpBase, cursor: 'pointer' }} value={value.motivo} onChange={(e) => onChange({ motivo: e.target.value })}>
          {MOTIVOS.map((m) => <option key={m.v} value={m.v}>{m.t}</option>)}
        </select>
      </div>
      {removable && (
        <button type="button" onClick={onRemove} title="Quitar producto"
          style={{ marginTop: 22, width: 40, height: 42, flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', background: '#fff', cursor: 'pointer' }}>
          <ATrash size={17} stroke="var(--madeci-red)" />
        </button>
      )}
    </div>
  );
}

// Panel de "Cambios / reposición": formulario (varios productos) + lista de tickets.
const LINEA_NUEVA = () => ({ q: '', sel: null, cantidad: 1, motivo: 'trizado' });
function CambiosPanel({ products }) {
  const [tickets, setTickets] = React.useState([]);
  const [cargando, setCargando] = React.useState(true);
  const [lineas, setLineas] = React.useState([LINEA_NUEVA()]);
  const [descripcion, setDescripcion] = React.useState('');
  const [enviando, setEnviando] = React.useState(false);
  const [msg, setMsg] = React.useState('');
  const [err, setErr] = React.useState('');

  const cargar = () => {
    setCargando(true);
    window.MadeciAPI.getMisCambios().then((r) => setTickets(r || [])).catch(() => setTickets([])).finally(() => setCargando(false));
  };
  React.useEffect(() => { cargar(); }, []);

  const setLinea = (i, patch) => setLineas((ls) => ls.map((l, idx) => idx === i ? { ...l, ...patch } : l));
  const addLinea = () => setLineas((ls) => [...ls, LINEA_NUEVA()]);
  const removeLinea = (i) => setLineas((ls) => ls.filter((_, idx) => idx !== i));

  const enviar = async () => {
    setErr(''); setMsg('');
    const items = lineas.map((l) => ({
      sku: l.sel ? l.sel.sku : undefined,
      nombre: (l.sel ? l.sel.name : l.q).trim(),
      cantidad: Number(l.cantidad),
      motivo: l.motivo,
    }));
    if (items.some((it) => it.nombre.length < 2)) { setErr('Completa el producto en cada línea.'); return; }
    if (items.some((it) => !it.cantidad || it.cantidad < 1)) { setErr('Indica una cantidad válida en cada línea.'); return; }
    setEnviando(true);
    try {
      await window.MadeciAPI.crearCambio({ items, descripcion: descripcion.trim() || undefined });
      setMsg('¡Listo! Tu solicitud de cambio quedó registrada. El equipo la revisará y te contactará.');
      setLineas([LINEA_NUEVA()]); setDescripcion('');
      cargar();
    } catch (e) {
      setErr(e.message || 'No se pudo enviar la solicitud.');
    } finally {
      setEnviando(false);
    }
  };

  return (
    <div>
      <Head eyebrow="Postventa" title="Cambios / reposición de producto" />
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-muted)', margin: '0 0 22px', lineHeight: 1.55, maxWidth: 560 }}>
        ¿Te llegó uno o varios productos con problema (botella trizada, sin gas, vencido, falla de fábrica)? Repórtalos acá y queda registrado como ticket. El equipo lo revisa y coordina el cambio.
      </p>

      {/* Formulario */}
      <div style={{ background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: '22px 22px 24px', maxWidth: 680 }}>
        {lineas.map((l, i) => (
          <LineaCambio key={i} value={l} products={products} removable={lineas.length > 1}
            onChange={(patch) => setLinea(i, patch)} onRemove={() => removeLinea(i)} />
        ))}

        <button type="button" onClick={addLinea}
          style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: '1px dashed var(--madeci-red)', color: 'var(--madeci-red)', borderRadius: 'var(--radius-sm)', padding: '9px 14px', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13.5, marginBottom: 18 }}>
          <APlus size={16} stroke="var(--madeci-red)" /> Agregar otro producto
        </button>

        <div style={{ marginBottom: 18 }}>
          <label style={lblBase}>Detalle (opcional)</label>
          <textarea style={{ ...inpBase, minHeight: 74, resize: 'vertical', fontFamily: 'var(--font-body)' }} placeholder="Cuéntanos qué pasó (ej. llegaron trizadas en la caja de ayer)."
            value={descripcion} onChange={(e) => setDescripcion(e.target.value)} maxLength={1000} />
        </div>

        {err && <div style={{ marginBottom: 14, padding: '10px 13px', background: 'var(--madeci-red-50)', border: '1px solid var(--madeci-red)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--madeci-red)' }}>{err}</div>}
        {msg && <div style={{ marginBottom: 14, padding: '10px 13px', background: 'var(--status-success-50)', border: '1px solid var(--status-success)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--status-success)' }}>{msg}</div>}

        <M.Button size="lg" onClick={enviar} disabled={enviando}>{enviando ? 'Enviando…' : 'Enviar solicitud de cambio'}</M.Button>
      </div>

      {/* Historial de tickets */}
      <div style={{ marginTop: 34 }}>
        <h3 style={{ fontSize: 17, fontWeight: 700, margin: '0 0 14px' }}>Tus solicitudes</h3>
        {cargando ? (
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-muted)' }}>Cargando…</p>
        ) : tickets.length === 0 ? (
          <Vacio texto="Todavía no has reportado ningún cambio. Cuando lo hagas, aparecerá acá con su estado." />
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {tickets.map((t) => <TicketRow key={t.id} t={t} />)}
          </div>
        )}
      </div>
    </div>
  );
}

function AccountView({ account: a, orders, invoices, frequent, favorites, products, onAdd, onRepeat, onCancel, onShop, onLogout }) {
  const [tab, setTab] = React.useState('resumen');
  const [detalle, setDetalle] = React.useState(null);
  const [aviso, setAviso] = React.useState('');
  const [cancelId, setCancelId] = React.useState(null); // pedido pendiente de confirmar cancelación
  const [cancelando, setCancelando] = React.useState(false);
  if (!a) return null; // aún cargando la cuenta
  // "Pedido en curso" = el más reciente que no esté entregado, cancelado ni con incidencia.
  const enCurso = orders.find((o) => o.status !== 'entregado' && o.status !== 'anulado');

  const verDetalle = async (id) => {
    setDetalle({ loading: true });
    try { const d = await window.MadeciAPI.getPedido(id); setDetalle(d || null); } catch (e) { setDetalle(null); }
  };
  const repetir = async (id) => {
    setAviso('');
    try {
      const r = await onRepeat(id);
      // Si al repetir no había ningún producto disponible, sí avisamos; si se cargó al menos uno,
      // no mostramos banner (el contador del carrito ya refleja el cambio).
      if (!r || !r.agregados) setAviso('Ninguno de los productos de ese pedido está disponible en este momento.');
    } catch (e) { setAviso('No se pudo repetir el pedido.'); }
  };
  // Abre la ventana de confirmación (no cancela todavía).
  const cancelar = (id) => { setAviso(''); setCancelId(id); };
  // Confirma la cancelación desde la ventana.
  const confirmarCancelacion = async () => {
    setCancelando(true);
    try {
      await onCancel(cancelId);
      const id = cancelId; setCancelId(null);
      setAviso(`Tu pedido N° ${id} fue cancelado. Queda registrado en tu historial.`);
    } catch (e) { setCancelId(null); setAviso(e.message); }
    finally { setCancelando(false); }
  };

  const body = () => {
    if (tab === 'resumen') return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 34 }}>
        <div>
          <Head eyebrow={enCurso ? 'En preparación' : 'Despacho'} title="Pedido en curso" />
          {enCurso ? <ActiveOrder order={enCurso} /> : <SinEnCurso onShop={onShop} />}
        </div>
        <div>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18 }}>
            <Head eyebrow="Historial" title="Pedidos recientes" />
            {orders.length > 0 && <a onClick={() => setTab('pedidos')} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14 }}>Ver todos <AChev size={16} /></a>}
          </div>
          {orders.length > 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {orders.slice(0, 3).map((o) => <OrderRow key={o.number} o={o} onDetalle={() => verDetalle(o.id)} onRepetir={() => repetir(o.id)} onCancelar={() => cancelar(o.id)} />)}
            </div>
          ) : <Vacio texto="Todavía no tienes pedidos. Cuando hagas uno, aparecerá acá." />}
        </div>
        {frequent.length > 0 && <M.ReorderList variant="frequent" products={frequent} onAdd={(p) => onAdd(p, 1)} />}
      </div>
    );
    if (tab === 'pedidos') return (
      <div>
        <Head eyebrow="Historial completo" title="Mis pedidos" />
        {orders.length > 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {orders.map((o) => <OrderRow key={o.number} o={o} onDetalle={() => verDetalle(o.id)} onRepetir={() => repetir(o.id)} onCancelar={() => cancelar(o.id)} />)}
          </div>
        ) : <Vacio texto="Todavía no tienes pedidos." />}
      </div>
    );
    if (tab === 'favoritos') return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 30 }}>
        {(favorites.length > 0 || frequent.length > 0) ? (
          <React.Fragment>
            {favorites.length > 0 && <M.ReorderList variant="favorites" products={favorites} onAdd={(p) => onAdd(p, 1)} />}
            {frequent.length > 0 && <M.ReorderList variant="frequent" products={frequent} onAdd={(p) => onAdd(p, 1)} />}
          </React.Fragment>
        ) : <Vacio texto="Marca productos como favoritos para tenerlos siempre a mano." />}
      </div>
    );
    if (tab === 'cambios') return <CambiosPanel products={products} />;
    if (tab === 'datos') return (
      <div>
        <Head eyebrow="Perfil" title="Datos comerciales" />
        <DatosComerciales account={a} />
      </div>
    );
    return (
      <div>
        <Head eyebrow="Reparto" title="Cobertura de despacho" />
        <CoberturaPanel />
      </div>
    );
  };

  return (
    <div className="sf-shell" style={{ maxWidth: 1280, margin: '0 auto', padding: '28px 24px 72px' }}>
      {detalle && <PedidoDetalle pedido={detalle} onClose={() => setDetalle(null)} />}
      {cancelId && <ConfirmModal titulo="Cancelar pedido" texto={`¿Seguro que quieres cancelar el pedido N° ${cancelId}? Quedará registrado como cancelado y no se puede deshacer.`} confirmarTexto="Sí, cancelar pedido" onConfirmar={confirmarCancelacion} onCerrar={() => setCancelId(null)} cargando={cancelando} />}
      <div style={{ marginBottom: 22 }}>
        <h1 style={{ fontSize: 34, fontWeight: 800, letterSpacing: '-.02em' }}>Mi cuenta</h1>
      </div>
      {aviso && (
        <div style={{ marginBottom: 18, padding: '12px 16px', borderRadius: 'var(--radius-md)', background: 'var(--madeci-red-50)', border: '1px solid var(--madeci-red)', color: 'var(--madeci-red-dark)', fontFamily: 'var(--font-body)', fontSize: 14, display: 'flex', justifyContent: 'space-between', gap: 12 }}>
          <span>{aviso}</span>
          <button onClick={() => setAviso('')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--madeci-red)', fontWeight: 700 }}>×</button>
        </div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 'var(--space-5) var(--space-6)', marginBottom: 26 }}>
        <div style={{ width: 52, height: 52, flex: 'none', borderRadius: 999, background: 'var(--madeci-red)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 20 }}>{a.name.slice(0, 2).toUpperCase()}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Bienvenido de vuelta</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24, color: 'var(--text-strong)', lineHeight: 1.1 }}>{a.name}</div>
          <div style={{ fontFamily: 'var(--font-data)', fontSize: 12.5, color: 'var(--text-muted)', marginTop: 2 }}>{a.code} · Ejecutivo: {a.salesRep}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 999, background: 'var(--madeci-red-50)', color: 'var(--madeci-red-dark)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13.5 }}>
          <ATruck size={17} stroke="var(--madeci-red)" /> Pago contra entrega
        </div>
      </div>

      <div className="sf-account-cols" style={{ display: 'grid', gridTemplateColumns: '224px 1fr', gap: 32, alignItems: 'start' }}>
        <nav className="sf-acct-nav" style={{ position: 'sticky', top: 96, display: 'flex', flexDirection: 'column', gap: 3 }}>
          {NAV.map(({ id, label, icon: Icon }) => {
            const on = tab === id;
            return (
              <button key={id} onClick={() => setTab(id)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 13px', textAlign: 'left', border: 'none', borderRadius: 'var(--radius-sm)', cursor: 'pointer', background: on ? 'var(--madeci-red-50)' : 'transparent', color: on ? 'var(--madeci-red-dark)' : 'var(--text-body)', fontFamily: 'var(--font-display)', fontWeight: on ? 700 : 600, fontSize: 14.5, whiteSpace: 'nowrap' }}>
                <Icon size={18} stroke={on ? 'var(--madeci-red)' : 'var(--text-muted)'} /> {label}
              </button>
            );
          })}
          <button onClick={onShop} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 13px', textAlign: 'left', border: 'none', borderRadius: 'var(--radius-sm)', cursor: 'pointer', background: 'transparent', color: 'var(--text-muted)', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14.5, marginTop: 8, borderTop: '1px solid var(--border-subtle)', paddingTop: 16 }}>
            <AChev size={18} stroke="var(--text-muted)" style={{ transform: 'rotate(180deg)' }} /> Volver a la tienda
          </button>
          <button onClick={onLogout} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 13px', textAlign: 'left', border: 'none', borderRadius: 'var(--radius-sm)', cursor: 'pointer', background: 'transparent', color: 'var(--madeci-red)', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14.5 }}>
            <AOut size={18} stroke="var(--madeci-red)" /> Cerrar sesión
          </button>
        </nav>
        <div style={{ minWidth: 0 }}>{body()}</div>
      </div>
    </div>
  );
}

Object.assign(window, { AccountView, CoberturaPanel });
