// LOLA Consola Web — Módulo de PUBLICIDAD
// Campañas multicanal (Facebook, Instagram, TikTok, WhatsApp y la app LOLA) al estilo
// Meta Ads Manager / TikTok Ads: overview con métricas, rendimiento por canal, lista de
// campañas y un asistente de creación con VISTA PREVIA EN VIVO por red social.
// Exporta window.PublicidadView.

const api = () => window.LOLA.api;

// ── Compacto no-monetario (1.2K, 3.4M) ──
const nc = (n) => {
  n = n || 0;
  if (Math.abs(n) >= 1e6) return (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + 'M';
  if (Math.abs(n) >= 1e3) return (n / 1e3).toFixed(n >= 1e5 ? 0 : 1) + 'K';
  return '' + n;
};

// ── Íconos de red social (marcas simplificadas) ──
function ChIcon({ ch, size = 16 }) {
  const s = size;
  if (ch === 'whatsapp') return <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.15-1.77-.87-2.04-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.94 1.17-.17.2-.35.22-.65.07-.3-.15-1.26-.46-2.4-1.48-.89-.79-1.49-1.77-1.66-2.07-.17-.3-.02-.46.13-.61.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.07-.15-.67-1.62-.92-2.22-.24-.58-.49-.5-.67-.51h-.57c-.2 0-.52.07-.8.37-.27.3-1.04 1.02-1.04 2.49 0 1.47 1.07 2.89 1.22 3.09.15.2 2.1 3.2 5.08 4.49.71.31 1.26.49 1.69.62.71.23 1.36.2 1.87.12.57-.08 1.77-.72 2.02-1.42.25-.7.25-1.3.17-1.42-.07-.13-.27-.2-.57-.35zM12 2a10 10 0 0 0-8.6 15.06L2 22l5.07-1.33A10 10 0 1 0 12 2z"/></svg>;
  if (ch === 'facebook') return <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor"><path d="M22 12a10 10 0 1 0-11.56 9.88v-6.99H7.9V12h2.54V9.8c0-2.5 1.49-3.89 3.77-3.89 1.1 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56V12h2.78l-.44 2.89h-2.34v6.99A10 10 0 0 0 22 12z"/></svg>;
  if (ch === 'instagram') return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2.5" y="2.5" width="19" height="19" rx="5.5"/><circle cx="12" cy="12" r="4.2"/><circle cx="17.6" cy="6.4" r="1.3" fill="currentColor" stroke="none"/></svg>;
  if (ch === 'tiktok') return <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor"><path d="M16.5 2c.35 2.5 1.9 4.2 4.3 4.4v3c-1.5.05-2.9-.35-4.3-1.1v6.1c0 4-2.9 6.3-6 6.3-3.2 0-5.5-2.3-5.5-5.3 0-3.1 2.4-5.3 5.4-5.3.4 0 .8.05 1.2.13v3.2a2.4 2.4 0 0 0-1.2-.3c-1.3 0-2.3 1-2.3 2.2 0 1.3 1 2.2 2.3 2.2 1.4 0 2.4-1 2.4-2.6V2h3.7z"/></svg>;
  return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 17h4V5H2v12h3"/><path d="M15 17h6v-5l-3-3h-3v8z"/><circle cx="7.5" cy="17.5" r="1.5"/><circle cx="17.5" cy="17.5" r="1.5"/></svg>;
}

const CH = {
  facebook: { label: 'Facebook', color: '#1877F2' },
  instagram: { label: 'Instagram', color: '#E1306C' },
  tiktok: { label: 'TikTok', color: '#111418' },
  whatsapp: { label: 'WhatsApp', color: '#25D366' },
  app: { label: 'App LOLA', color: '#1D57A9' },
};
const CH_ORDER = ['facebook', 'instagram', 'tiktok', 'whatsapp', 'app'];

const OBJETIVOS = [
  { id: 'reconocimiento', label: 'Reconocimiento', desc: 'Que más gente conozca la marca', icon: 'Globe' },
  { id: 'video', label: 'Reproducciones de video', desc: 'Que vean tu video primero', icon: 'Play' },
  { id: 'trafico', label: 'Tráfico', desc: 'Llevar visitas a la app o web', icon: 'Cursor' },
  { id: 'mensajes', label: 'Mensajes', desc: 'Conversaciones por WhatsApp', icon: 'Chat' },
  { id: 'leads', label: 'Clientes potenciales', desc: 'Registrar interesados', icon: 'Users' },
  { id: 'ventas', label: 'Ventas / solicitudes', desc: 'Generar solicitudes de carga', icon: 'Trend' },
];
const objMeta = (id) => OBJETIVOS.find((o) => o.id === id) || OBJETIVOS[0];

const ESTADOS = {
  activa: { label: 'Activa', color: '#1F8A5B' },
  pausada: { label: 'Pausada', color: '#D98A0B' },
  borrador: { label: 'Borrador', color: '#8A929E' },
  finalizada: { label: 'Finalizada', color: '#5B6470' },
};

const CTA_OPCIONES = ['Cotizar ahora', 'Enviar WhatsApp', 'Descargar app', 'Solicitar transporte', 'Más información', 'Registrarme'];
const DEPTOS = ['Todo el país', 'Guatemala', 'Escuintla', 'Quetzaltenango', 'Petén', 'Izabal', 'Sacatepéquez'];
const INTERESES = ['Carga seca', 'Refrigerada', 'Maquinaria', 'Materiales', 'Mudanzas', 'Paquetería'];

const PlayGlyph = ({ size = 34, color = '#fff' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color}><path d="M8 5v14l11-7z"/></svg>
);

// Placeholder de creativo (rayado, con explicación monoespaciada) ─────────────
function CreativeSlot({ tipo, ratio, dark }) {
  const t = window.WC;
  const vertical = ratio === '9:16';
  return (
    <div style={{ position: 'relative', width: '100%', aspectRatio: vertical ? '9 / 16' : '1 / 1',
      background: 'linear-gradient(160deg, #16305a, #0e1f38)',
      backgroundColor: '#12233b', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10,
      color: 'rgba(255,255,255,.9)', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'repeating-linear-gradient(135deg, rgba(255,255,255,.05), rgba(255,255,255,.05) 10px, transparent 10px, transparent 20px)' }}/>
      <div style={{ position: 'relative', width: 52, height: 52, borderRadius: '50%', background: 'rgba(255,255,255,.14)', border: '1px solid rgba(255,255,255,.3)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {tipo === 'video' ? <PlayGlyph size={26}/> : <window.WI.Scan size={24}/>}
      </div>
      <div style={{ position: 'relative', fontFamily: t.mono, fontSize: 11, letterSpacing: 1, color: 'rgba(255,255,255,.75)' }}>
        {tipo === 'video' ? 'TU VIDEO' : 'TU IMAGEN'} · {ratio}
      </div>
    </div>
  );
}

// ── VISTA PREVIA en la red seleccionada ──────────────────────────────────────
function AdPreview({ ch, tipo, titular, texto, cta, anunciante }) {
  const t = window.WC;
  const meta = CH[ch] || CH.facebook;
  const avatar = (
    <div style={{ width: 34, height: 34, borderRadius: '50%', background: `linear-gradient(158deg, ${t.brandHi}, ${t.brand})`, color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><window.WI.Truck size={18} sw={2}/></div>
  );
  const nombre = anunciante || 'LOLA Logística';
  const ctaBtn = (full) => (
    <div style={{ background: meta.color, color: ch === 'tiktok' ? '#fff' : '#fff', fontWeight: 700, fontSize: 13,
      padding: full ? '11px 0' : '9px 16px', borderRadius: 9, textAlign: 'center', width: full ? '100%' : 'auto',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
      {ch === 'whatsapp' && <ChIcon ch="whatsapp" size={15}/>}{cta}
    </div>
  );

  // Chat (WhatsApp) ─────────────────────
  if (ch === 'whatsapp') {
    return (
      <div style={{ background: '#E5DDD3', borderRadius: 16, overflow: 'hidden', border: `1px solid ${t.border}` }}>
        <div style={{ background: '#075E54', color: '#fff', padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
          {avatar}<div><div style={{ fontSize: 14, fontWeight: 700 }}>{nombre}</div><div style={{ fontSize: 11, opacity: .8 }}>Cuenta de empresa</div></div>
        </div>
        <div style={{ padding: 14 }}>
          <div style={{ background: '#fff', borderRadius: 12, borderTopLeftRadius: 3, overflow: 'hidden', boxShadow: '0 1px 1px rgba(0,0,0,.12)', maxWidth: 260 }}>
            <div style={{ width: '100%' }}><CreativeSlot tipo={tipo} ratio="1:1"/></div>
            <div style={{ padding: '10px 12px' }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: '#111' }}>{titular}</div>
              <div style={{ fontSize: 12.5, color: '#333', marginTop: 3, lineHeight: 1.4 }}>{texto}</div>
              <div style={{ marginTop: 10 }}>{ctaBtn(true)}</div>
            </div>
          </div>
          <div style={{ fontSize: 10.5, color: '#667', textAlign: 'right', marginTop: 4, fontFamily: t.mono }}>11:24 ✓✓</div>
        </div>
      </div>
    );
  }

  // Vertical (TikTok / App LOLA) ─────────
  if (ch === 'tiktok' || ch === 'app') {
    return (
      <div style={{ position: 'relative', borderRadius: 20, overflow: 'hidden', border: `1px solid ${t.border}`, background: '#000', maxWidth: 250, margin: '0 auto' }}>
        <CreativeSlot tipo={tipo} ratio="9:16"/>
        {ch === 'app' && (
          <div style={{ position: 'absolute', top: 12, right: 12, background: 'rgba(0,0,0,.55)', color: '#fff', fontSize: 11, fontFamily: t.mono,
            padding: '5px 10px', borderRadius: 999, backdropFilter: 'blur(4px)' }}>Publicidad · Saltar 5s</div>
        )}
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: 14,
          background: 'linear-gradient(transparent, rgba(0,0,0,.82))', color: '#fff' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 8 }}>
            {avatar}<div style={{ fontSize: 13.5, fontWeight: 700 }}>{nombre}</div>
            <span style={{ marginLeft: 'auto', fontSize: 10.5, fontFamily: t.mono, background: 'rgba(255,255,255,.2)', padding: '2px 8px', borderRadius: 999 }}>Ad</span>
          </div>
          <div style={{ fontSize: 13.5, fontWeight: 700 }}>{titular}</div>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,.85)', margin: '3px 0 10px', lineHeight: 1.4 }}>{texto}</div>
          {ctaBtn(true)}
        </div>
      </div>
    );
  }

  // Feed (Facebook / Instagram) ─────────
  const ig = ch === 'instagram';
  return (
    <div style={{ background: '#fff', borderRadius: 14, overflow: 'hidden', border: `1px solid ${t.border}`, maxWidth: 300, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 13px' }}>
        {avatar}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: '#111' }}>{nombre}</div>
          <div style={{ fontSize: 11, color: '#8A929E', fontFamily: t.mono }}>Patrocinado · {ig ? 'Instagram' : 'Facebook'}</div>
        </div>
        <span style={{ color: '#8A929E', fontWeight: 800, letterSpacing: 1 }}>···</span>
      </div>
      {!ig && <div style={{ padding: '0 13px 10px', fontSize: 13, color: '#222', lineHeight: 1.45 }}>{texto}</div>}
      <CreativeSlot tipo={tipo} ratio="1:1"/>
      <div style={{ padding: '12px 13px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: '#111', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{titular}</div>
          {ig && <div style={{ fontSize: 12, color: '#555', marginTop: 2 }}>{texto}</div>}
        </div>
        {ctaBtn(false)}
      </div>
    </div>
  );
}

// ── Chips de canales ──
function ChannelChips({ canales, size = 22 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      {canales.map((c, i) => {
        const m = CH[c] || {};
        return (
          <span key={c} title={m.label} style={{ width: size, height: size, borderRadius: '50%', background: m.color, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2px solid #fff', marginLeft: i ? -7 : 0, flexShrink: 0 }}>
            <ChIcon ch={c} size={size * 0.58}/>
          </span>
        );
      })}
    </div>
  );
}

// ── Botón principal ──
function PubBtn({ t, children, onClick, kind, disabled, style }) {
  const [h, setH] = React.useState(false);
  const bg = kind === 'ghost' ? '#fff' : t.brand;
  return (
    <button onClick={onClick} disabled={disabled} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: disabled ? 'default' : 'pointer',
        padding: '11px 18px', borderRadius: 11, fontFamily: t.font, fontSize: 14, fontWeight: 700,
        border: kind === 'ghost' ? `1px solid ${t.border}` : 'none', background: kind === 'ghost' ? '#fff' : (h && !disabled ? t.brandHi : t.brand),
        color: kind === 'ghost' ? t.text : '#fff', opacity: disabled ? .5 : 1, boxShadow: kind === 'ghost' ? 'none' : '0 10px 22px -12px rgba(29,87,169,.8)', ...style }}>{children}</button>
  );
}

// ═══════════════════════ VISTA PRINCIPAL ═══════════════════════
function PublicidadView() {
  const t = window.WC, I = window.WI;
  const isMobile = window.useIsMobile();
  const { data, loading, error, reload } = window.useAsync(() => api().campanias(), []);
  const [filtro, setFiltro] = React.useState('Todas');
  const [crear, setCrear] = React.useState(false);
  const [busyId, setBusyId] = React.useState(null);

  if (loading) return <window.Loading label="Cargando campañas…"/>;
  if (error) return <window.ErrState error={error} onRetry={reload}/>;

  const items = (data && data.items) || [];
  const activas = items.filter((c) => c.estado === 'activa');
  const agg = items.reduce((a, c) => {
    const m = c.metricas || {};
    a.impresiones += m.impresiones || 0; a.alcance += m.alcance || 0; a.repro += m.reproducciones || 0;
    a.clics += m.clics || 0; a.gasto += c.gastado || 0; return a;
  }, { impresiones: 0, alcance: 0, repro: 0, clics: 0, gasto: 0 });
  const ctr = agg.impresiones ? (agg.clics / agg.impresiones * 100) : 0;

  // rendimiento por canal
  const porCanal = {};
  items.forEach((c) => (c.canales || []).forEach((ch) => {
    const m = c.metricas || {}; const share = (c.canales.length || 1);
    porCanal[ch] = (porCanal[ch] || 0) + (m.impresiones || 0) / share;
  }));
  const canalMax = Math.max(1, ...Object.values(porCanal));

  const rows = items.filter((c) => filtro === 'Todas' ? true
    : filtro === 'Activas' ? c.estado === 'activa'
    : filtro === 'Pausadas' ? c.estado === 'pausada' : c.estado === 'borrador');

  const toggle = async (c) => {
    setBusyId(c.id);
    try { await api().toggleCampania(c.id); reload(); } catch (e) { alert(e.message || 'No se pudo actualizar'); }
    setBusyId(null);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Encabezado con CTA */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: t.sec }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: t.success + '16', color: t.success, fontWeight: 700, fontFamily: t.mono, padding: '4px 10px', borderRadius: 999, fontSize: 12 }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: t.success }}/>{activas.length} activa(s)
          </span>
          <span style={{ fontFamily: t.mono, fontSize: 12, color: t.ter }}>en Facebook · Instagram · TikTok · WhatsApp · App</span>
        </div>
        <PubBtn t={t} onClick={() => setCrear(true)}><I.Plus size={17}/> Crear campaña</PubBtn>
      </div>

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4,1fr)', gap: isMobile ? 12 : 16 }}>
        <window.KpiCard label="Alcance total" value={nc(agg.alcance)} icon={<I.Users/>} accent={t.brand}/>
        <window.KpiCard label="Reproducciones de video" value={nc(agg.repro)} icon={<I.Play/>} accent={t.purple}/>
        <window.KpiCard label="Clics · CTR" value={nc(agg.clics)} delta={ctr.toFixed(2) + '% CTR'} deltaUp icon={<I.Cursor/>} accent={t.accentDk}/>
        <window.KpiCard label="Inversión" value={window.fmtK(agg.gasto)} icon={<I.Wallet/>} accent={t.success}/>
      </div>

      {/* Rendimiento por canal + reparto de objetivos */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.5fr 1fr', gap: 18 }}>
        <window.Panel title="Rendimiento por canal" sub="Impresiones distribuidas por red social">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 4 }}>
            {CH_ORDER.map((ch) => {
              const v = porCanal[ch] || 0; const m = CH[ch];
              return (
                <div key={ch} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, background: m.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><ChIcon ch={ch} size={17}/></span>
                  <span style={{ width: 74, fontSize: 13, fontWeight: 600, color: t.text }}>{m.label}</span>
                  <div style={{ flex: 1, height: 9, borderRadius: 6, background: t.grid, overflow: 'hidden' }}>
                    <div style={{ width: (v / canalMax * 100) + '%', height: '100%', background: m.color, borderRadius: 6, transition: 'width .4s' }}/>
                  </div>
                  <span style={{ width: 52, textAlign: 'right', fontFamily: t.mono, fontSize: 12.5, fontWeight: 700, color: t.text }}>{nc(Math.round(v))}</span>
                </div>
              );
            })}
          </div>
        </window.Panel>
        <window.Panel title="Impresiones" sub="Total de la cuenta publicitaria">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', padding: '10px 0' }}>
            <div style={{ fontFamily: t.mono, fontSize: 40, fontWeight: 800, color: t.brand, letterSpacing: -1 }}>{nc(agg.impresiones)}</div>
            <div style={{ fontSize: 12.5, color: t.ter, marginTop: 4 }}>impresiones acumuladas</div>
            <div style={{ display: 'flex', gap: 18, marginTop: 18 }}>
              <div style={{ textAlign: 'center' }}><div style={{ fontFamily: t.mono, fontWeight: 800, fontSize: 18, color: t.text }}>{ctr.toFixed(2)}%</div><div style={{ fontSize: 11, color: t.ter, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8 }}>CTR</div></div>
              <div style={{ textAlign: 'center' }}><div style={{ fontFamily: t.mono, fontWeight: 800, fontSize: 18, color: t.text }}>{items.length}</div><div style={{ fontSize: 11, color: t.ter, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8 }}>campañas</div></div>
            </div>
          </div>
        </window.Panel>
      </div>

      {/* Lista de campañas */}
      <window.Panel title="Campañas" sub={`${items.length} en total`} pad={0}
        action={<window.Segmented options={['Todas', 'Activas', 'Pausadas', 'Borrador']} value={filtro} onChange={setFiltro}/>}>
        {rows.length ? (
          <div>
            {rows.map((c, i) => {
              const es = ESTADOS[c.estado] || ESTADOS.borrador; const om = objMeta(c.objetivo);
              const m = c.metricas || {}; const OIcn = I[om.icon] || I.Trend;
              return (
                <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: isMobile ? '14px 16px' : '15px 22px',
                  borderBottom: i < rows.length - 1 ? `1px solid ${t.grid}` : 'none', flexWrap: 'wrap' }}>
                  <div style={{ width: 46, height: 46, borderRadius: 11, background: '#12233b', flexShrink: 0, overflow: 'hidden', position: 'relative',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(255,255,255,.85)' }}>
                    <div style={{ position: 'absolute', inset: 0, background: 'repeating-linear-gradient(135deg, rgba(255,255,255,.06), rgba(255,255,255,.06) 5px, transparent 5px, transparent 10px)' }}/>
                    {c.creativo && c.creativo.tipo === 'video' ? <PlayGlyph size={18}/> : <window.WI.Scan size={18}/>}
                  </div>
                  <div style={{ flex: 1, minWidth: 160 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text }}>{c.nombre}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 3, flexWrap: 'wrap' }}>
                      <span style={{ fontSize: 11.5, color: c.anunciante && c.anunciante.tipo === 'empresa' ? t.purple : t.brand, fontFamily: t.mono, fontWeight: 700 }}>
                        {c.anunciante ? c.anunciante.nombre : 'LOLA'}</span>
                      <span style={{ fontSize: 11.5, color: t.ter, display: 'inline-flex', alignItems: 'center', gap: 4 }}><OIcn size={12}/> {om.label}</span>
                    </div>
                  </div>
                  <ChannelChips canales={c.canales || []}/>
                  {!isMobile && (
                    <div style={{ display: 'flex', gap: 20, minWidth: 210 }}>
                      <Metric t={t} k="Alcance" v={nc(m.alcance)}/>
                      <Metric t={t} k="CTR" v={(m.ctr || 0) + '%'}/>
                      <Metric t={t} k="Gasto" v={window.fmtK(c.gastado || 0)}/>
                    </div>
                  )}
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700, color: es.color,
                    background: es.color + '16', padding: '4px 11px', borderRadius: 999, fontFamily: t.mono }}>
                    <span style={{ width: 7, height: 7, borderRadius: '50%', background: es.color }}/>{es.label}</span>
                  {c.estado !== 'borrador' && (
                    <button disabled={busyId === c.id} onClick={() => toggle(c)} title={c.estado === 'activa' ? 'Pausar' : 'Activar'}
                      style={{ width: 38, height: 38, borderRadius: 10, border: `1px solid ${t.border}`, background: '#fff', cursor: 'pointer',
                        color: c.estado === 'activa' ? t.warn : t.success, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: busyId === c.id ? .5 : 1, flexShrink: 0 }}>
                      {c.estado === 'activa'
                        ? <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
                        : <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>}
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        ) : <window.EmptyState icon="Megaphone" title="Sin campañas en este filtro" sub="Crea tu primera campaña para llegar a miles de personas en redes sociales."/>}
      </window.Panel>

      {crear && <CrearCampania t={t} onClose={() => setCrear(false)} onCreated={() => { setCrear(false); reload(); }}/>}
    </div>
  );
}

function Metric({ t, k, v }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, color: t.ter, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8 }}>{k}</div>
      <div style={{ fontSize: 14, fontWeight: 700, color: t.text, fontFamily: t.mono, marginTop: 2 }}>{v}</div>
    </div>
  );
}

// ═══════════════════════ ASISTENTE DE CREACIÓN ═══════════════════════
function CrearCampania({ t, onClose, onCreated }) {
  const isMobile = window.useIsMobile(900);
  const [nombre, setNombre] = React.useState('');
  const [obj, setObj] = React.useState('reconocimiento');
  const [anunTipo, setAnunTipo] = React.useState('lola');
  const [anunEmpresa, setAnunEmpresa] = React.useState('Constructora Maya, S.A.');
  const [canales, setCanales] = React.useState(['facebook', 'instagram', 'tiktok']);
  const [publico, setPublico] = React.useState('todos');
  const [deptos, setDeptos] = React.useState(['Todo el país']);
  const [edad, setEdad] = React.useState('25-44');
  const [intereses, setIntereses] = React.useState(['Carga seca']);
  const [tipo, setTipo] = React.useState('video');
  const [titular, setTitular] = React.useState('A donde vayas, yo voy');
  const [texto, setTexto] = React.useState('Cotiza, asigna y rastrea tu carga en minutos con LOLA.');
  const [cta, setCta] = React.useState('Descargar app');
  const [presTipo, setPresTipo] = React.useState('diario');
  const [pres, setPres] = React.useState(300);
  const [dias, setDias] = React.useState(14);
  const [prevCh, setPrevCh] = React.useState('facebook');
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => { if (!canales.includes(prevCh) && canales.length) setPrevCh(canales[0]); }, [canales]);

  const toggleArr = (arr, set, v) => set(arr.includes(v) ? arr.filter((x) => x !== v) : arr.concat(v));
  const totalPres = presTipo === 'diario' ? pres * dias : pres;
  const factor = Math.max(1, canales.length);
  const reachLow = Math.round(totalPres * 26 * Math.sqrt(factor));
  const reachHigh = Math.round(totalPres * 68 * Math.sqrt(factor));
  const anunNombre = anunTipo === 'empresa' ? anunEmpresa : 'LOLA';

  const publicar = async (estado) => {
    if (!canales.length) { alert('Elige al menos un canal.'); return; }
    setBusy(true);
    const payload = {
      nombre: nombre.trim() || (objMeta(obj).label + ' — ' + anunNombre),
      anunciante: { tipo: anunTipo, nombre: anunNombre },
      objetivo: obj, canales,
      publico: { tipo: publico, deptos, edad, intereses },
      creativo: { tipo, titular, texto, cta },
      presupuesto: { tipo: presTipo, monto: pres, dias },
      estado,
    };
    try { await api().crearCampania(payload); onCreated(); }
    catch (e) { alert(e.message || 'No se pudo crear la campaña'); setBusy(false); }
  };

  const Section = ({ n, title, sub, children }) => (
    <div style={{ marginBottom: 26 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 13 }}>
        <span style={{ width: 24, height: 24, borderRadius: 7, background: t.brand + '15', color: t.brand, fontFamily: t.mono, fontWeight: 800, fontSize: 12.5, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{n}</span>
        <div><div style={{ fontSize: 15.5, fontWeight: 800, color: t.text, letterSpacing: -.3 }}>{title}</div>
          {sub && <div style={{ fontSize: 12.5, color: t.ter, marginTop: 1 }}>{sub}</div>}</div>
      </div>
      {children}
    </div>
  );

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 90, background: 'rgba(10,20,32,.62)', backdropFilter: 'blur(3px)',
      display: 'flex', alignItems: isMobile ? 'stretch' : 'center', justifyContent: 'center', padding: isMobile ? 0 : 26 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: '#fff', borderRadius: isMobile ? 0 : 20, width: '100%', maxWidth: 1000,
        height: isMobile ? '100%' : 'min(90vh, 860px)', overflow: 'hidden', display: 'flex', flexDirection: 'column',
        boxShadow: '0 40px 100px -30px rgba(0,0,0,.6)' }}>

        {/* header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '17px 22px', borderBottom: `1px solid ${t.border}`, flexShrink: 0 }}>
          <span style={{ width: 38, height: 38, borderRadius: 10, background: t.brand + '14', color: t.brand, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.WI.Megaphone size={20}/></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 800, color: t.text, letterSpacing: -.4 }}>Nueva campaña</div>
            <div style={{ fontSize: 12.5, color: t.ter }}>Publica en redes sociales y en la app LOLA</div>
          </div>
          <button onClick={onClose} style={{ width: 38, height: 38, borderRadius: 10, border: `1px solid ${t.border}`, background: '#fff', cursor: 'pointer', color: t.sec, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.WI.X size={18}/></button>
        </div>

        {/* cuerpo: formulario + preview */}
        <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: isMobile ? 'column' : 'row' }}>
          {/* formulario */}
          <div style={{ flex: 1, minWidth: 0, overflowY: 'auto', overflowX: 'hidden', padding: isMobile ? '22px 18px' : '26px 28px' }}>
            <Section n="1" title="Objetivo" sub="¿Qué quieres lograr?">
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 10 }}>
                {OBJETIVOS.map((o) => {
                  const on = obj === o.id; const Icn = window.WI[o.icon] || window.WI.Trend;
                  return (
                    <button key={o.id} onClick={() => setObj(o.id)} style={{ textAlign: 'left', cursor: 'pointer', padding: '13px 14px', borderRadius: 12,
                      border: `1.5px solid ${on ? t.brand : t.border}`, background: on ? '#F4F8FF' : '#fff', display: 'flex', gap: 11, alignItems: 'flex-start', fontFamily: t.font }}>
                      <span style={{ width: 32, height: 32, borderRadius: 9, background: on ? t.brand : t.grid, color: on ? '#fff' : t.sec, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icn size={17}/></span>
                      <span><span style={{ display: 'block', fontSize: 13.5, fontWeight: 700, color: t.text }}>{o.label}</span>
                        <span style={{ display: 'block', fontSize: 11.5, color: t.ter, marginTop: 2, lineHeight: 1.3 }}>{o.desc}</span></span>
                    </button>
                  );
                })}
              </div>
            </Section>

            <Section n="2" title="Anunciante" sub="¿Quién paga esta publicidad?">
              <Seg t={t} options={[{ v: 'lola', l: 'LOLA (marca propia)' }, { v: 'empresa', l: 'Una empresa' }]} value={anunTipo} onChange={setAnunTipo}/>
              {anunTipo === 'empresa' && (
                <select value={anunEmpresa} onChange={(e) => setAnunEmpresa(e.target.value)} style={{ marginTop: 10, width: '100%', padding: '11px 13px', borderRadius: 10, border: `1.5px solid ${t.border}`, fontFamily: t.font, fontSize: 14, color: t.text, background: '#fff' }}>
                  {['Constructora Maya, S.A.', 'Agrícola del Norte', 'Distribuidora Sur', 'Transportes Del Valle, S.A.'].map((e) => <option key={e}>{e}</option>)}
                </select>
              )}
            </Section>

            <Section n="3" title="Canales" sub="Dónde se mostrará (videos sociales para que la vean primero)">
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
                {CH_ORDER.map((ch) => {
                  const on = canales.includes(ch); const m = CH[ch];
                  return (
                    <button key={ch} onClick={() => toggleArr(canales, setCanales, ch)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
                      padding: '9px 14px', borderRadius: 999, fontFamily: t.font, fontSize: 13.5, fontWeight: 600,
                      border: `1.5px solid ${on ? m.color : t.border}`, background: on ? m.color + '12' : '#fff', color: on ? m.color : t.sec }}>
                      <ChIcon ch={ch} size={16}/> {m.label}{on && <window.WI.Check size={14}/>}
                    </button>
                  );
                })}
              </div>
            </Section>

            <Section n="4" title="Público" sub="A quién llega tu anuncio">
              <Seg t={t} options={[{ v: 'todos', l: 'Público general' }, { v: 'empresas', l: 'Empresas' }, { v: 'transportistas', l: 'Transportistas' }]} value={publico} onChange={setPublico}/>
              <div style={{ fontSize: 11.5, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700, margin: '16px 0 8px' }}>Ubicación</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
                {DEPTOS.map((d) => <Chip key={d} t={t} on={deptos.includes(d)} onClick={() => toggleArr(deptos, setDeptos, d)}>{d}</Chip>)}
              </div>
              <div style={{ fontSize: 11.5, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700, margin: '16px 0 8px' }}>Edad</div>
              <Seg t={t} options={[{ v: '18-24', l: '18-24' }, { v: '25-44', l: '25-44' }, { v: '45-65', l: '45-65' }, { v: 'todas', l: 'Todas' }]} value={edad} onChange={setEdad}/>
              <div style={{ fontSize: 11.5, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700, margin: '16px 0 8px' }}>Intereses</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
                {INTERESES.map((d) => <Chip key={d} t={t} on={intereses.includes(d)} onClick={() => toggleArr(intereses, setIntereses, d)}>{d}</Chip>)}
              </div>
            </Section>

            <Section n="5" title="Creativo" sub="El video o imagen que verá la gente">
              <Seg t={t} options={[{ v: 'video', l: 'Video' }, { v: 'imagen', l: 'Imagen' }]} value={tipo} onChange={setTipo}/>
              <div style={{ marginTop: 12 }}>
                <PubField t={t} label="Titular" value={titular} onChange={setTitular} placeholder="A donde vayas, yo voy"/>
                <PubField t={t} label="Texto principal" value={texto} onChange={setTexto} placeholder="Describe tu oferta…" area/>
                <div style={{ fontSize: 11, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700, margin: '4px 0 7px' }}>Botón (CTA)</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
                  {CTA_OPCIONES.map((o) => <Chip key={o} t={t} on={cta === o} onClick={() => setCta(o)}>{o}</Chip>)}
                </div>
              </div>
            </Section>

            <Section n="6" title="Presupuesto y calendario" sub="Cuánto inviertes y por cuánto tiempo">
              <Seg t={t} options={[{ v: 'diario', l: 'Diario' }, { v: 'total', l: 'Total' }]} value={presTipo} onChange={setPresTipo}/>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 14, flexWrap: 'wrap' }}>
                <span style={{ fontFamily: t.mono, fontWeight: 800, fontSize: 30, color: t.brand, minWidth: 120 }}>{window.fmtK(pres)}</span>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <input type="range" min="50" max="2000" step="50" value={pres} onChange={(e) => setPres(+e.target.value)} style={{ width: '100%', accentColor: t.brand }}/>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: t.ter, fontFamily: t.mono, marginTop: 3 }}><span>Q50</span><span>Q2,000{presTipo === 'diario' ? '/día' : ''}</span></div>
                </div>
              </div>
              {presTipo === 'diario' && (
                <div style={{ marginTop: 14 }}>
                  <div style={{ fontSize: 11.5, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700, marginBottom: 8 }}>Duración</div>
                  <Seg t={t} options={[{ v: 7, l: '7 días' }, { v: 14, l: '14 días' }, { v: 30, l: '30 días' }]} value={dias} onChange={setDias}/>
                </div>
              )}
            </Section>
          </div>

          {/* preview + resumen */}
          <div style={{ width: isMobile ? '100%' : 380, flexShrink: 0, background: '#F6F7F9', borderLeft: isMobile ? 'none' : `1px solid ${t.border}`,
            borderTop: isMobile ? `1px solid ${t.border}` : 'none', display: 'flex', flexDirection: 'column' }}>
            <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '20px 22px' }}>
              <div style={{ fontSize: 11.5, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: 1, fontWeight: 700, marginBottom: 12 }}>Vista previa</div>
              {canales.length ? (
                <React.Fragment>
                  <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
                    {canales.map((ch) => (
                      <button key={ch} onClick={() => setPrevCh(ch)} title={CH[ch].label} style={{ width: 34, height: 34, borderRadius: 9, cursor: 'pointer',
                        border: `1.5px solid ${prevCh === ch ? CH[ch].color : t.border}`, background: prevCh === ch ? CH[ch].color : '#fff', color: prevCh === ch ? '#fff' : CH[ch].color,
                        display: 'flex', alignItems: 'center', justifyContent: 'center' }}><ChIcon ch={ch} size={17}/></button>
                    ))}
                  </div>
                  <AdPreview ch={prevCh} tipo={tipo} titular={titular} texto={texto} cta={cta} anunciante={anunNombre === 'LOLA' ? 'LOLA Logística' : anunNombre}/>
                </React.Fragment>
              ) : <div style={{ fontSize: 13, color: t.ter, padding: '20px 0' }}>Elige al menos un canal para ver la vista previa.</div>}

              <div style={{ marginTop: 18, background: '#fff', border: `1px solid ${t.border}`, borderRadius: 12, padding: '14px 16px' }}>
                <div style={{ fontSize: 11.5, color: t.ter, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700 }}>Alcance estimado</div>
                <div style={{ fontSize: 20, fontWeight: 800, color: t.text, fontFamily: t.mono, marginTop: 4 }}>{nc(reachLow)} – {nc(reachHigh)}</div>
                <div style={{ fontSize: 12, color: t.ter, marginTop: 2 }}>personas · {window.fmtK(totalPres)} en {presTipo === 'diario' ? dias + ' días' : 'total'}</div>
              </div>
            </div>

            <div style={{ padding: '14px 20px', borderTop: `1px solid ${t.border}`, display: 'flex', gap: 10, flexShrink: 0 }}>
              <PubBtn t={t} kind="ghost" onClick={() => publicar('borrador')} disabled={busy} style={{ flex: 1 }}>Borrador</PubBtn>
              <PubBtn t={t} onClick={() => publicar('activa')} disabled={busy} style={{ flex: 1.4 }}>{busy ? 'Publicando…' : 'Publicar campaña'}</PubBtn>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Controles compartidos del asistente ──
function Seg({ t, options, value, onChange }) {
  return (
    <div style={{ display: 'inline-flex', gap: 3, background: t.grid, borderRadius: 10, padding: 3, flexWrap: 'wrap' }}>
      {options.map((o) => {
        const on = value === o.v;
        return (
          <button key={String(o.v)} onClick={() => onChange(o.v)} style={{ cursor: 'pointer', padding: '8px 14px', borderRadius: 8, border: 'none',
            background: on ? '#fff' : 'transparent', color: on ? t.brand : t.sec, fontFamily: t.font, fontSize: 13, fontWeight: on ? 700 : 600,
            boxShadow: on ? '0 1px 3px rgba(0,0,0,.12)' : 'none' }}>{o.l}</button>
        );
      })}
    </div>
  );
}
function Chip({ t, on, onClick, children }) {
  return (
    <button onClick={onClick} style={{ cursor: 'pointer', padding: '8px 13px', borderRadius: 999, fontFamily: t.font, fontSize: 12.5, fontWeight: 600,
      border: `1.5px solid ${on ? t.brand : t.border}`, background: on ? t.brand + '12' : '#fff', color: on ? t.brand : t.sec }}>{children}</button>
  );
}
function PubField({ t, label, value, onChange, placeholder, area }) {
  return (
    <label style={{ display: 'block', marginBottom: 14 }}>
      <span style={{ display: 'block', fontSize: 11, color: t.sec, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8, fontWeight: 700, marginBottom: 6 }}>{label}</span>
      {area
        ? <textarea value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} rows={2} style={{ width: '100%', boxSizing: 'border-box', padding: '11px 13px', borderRadius: 10, border: `1.5px solid ${t.border}`, fontFamily: t.font, fontSize: 14, color: t.text, resize: 'vertical', outline: 'none' }}/>
        : <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} style={{ width: '100%', boxSizing: 'border-box', padding: '11px 13px', borderRadius: 10, border: `1.5px solid ${t.border}`, fontFamily: t.font, fontSize: 14, color: t.text, outline: 'none' }}/>}
    </label>
  );
}

window.PublicidadView = PublicidadView;
