// shared.jsx — Header, Footer, Reveal, icon util
const { useState, useEffect, useRef } = React;

// ───────────────────────────────────────────────
// WhatsApp — config dinámica desde Supabase
// Los placeholders aquí se usan SOLO si la tabla "config" no responde.
// Para cambiar números reales, editarlos en /admin → Configuración.
// ───────────────────────────────────────────────
const WA_DEFAULTS = {
  servicios:   '56900000000',
  arriendo:    '56900000000',
  general:     '56900000000',
  corporativo: '56900000000',
  fab:         '56900000000',
};
const WA_FAB_MESSAGE_DEFAULT = 'Hola, me gustaría consultar sobre los servicios de PERTEC.';
const EMAIL_DEFAULTS = {
  to:      'comercial@pertec.cl',
  subject: 'Consulta desde el sitio web PERTEC',
  body:    'Hola, me gustaría consultar sobre los servicios de PERTEC.',
};

let _waConfigPromise = null;
function loadWaConfig() {
  if (_waConfigPromise) return _waConfigPromise;
  const supa = window.supabaseClient;
  const fallback = { numbers: WA_DEFAULTS, message: WA_FAB_MESSAGE_DEFAULT, email: EMAIL_DEFAULTS };
  if (!supa) return Promise.resolve(fallback);
  _waConfigPromise = supa.from('config').select('key, value').then(({ data }) => {
    const m = {};
    (data || []).forEach(r => { m[r.key] = r.value; });
    return {
      numbers: {
        servicios:   m.wa_servicios   || WA_DEFAULTS.servicios,
        arriendo:    m.wa_arriendo    || WA_DEFAULTS.arriendo,
        general:     m.wa_general     || WA_DEFAULTS.general,
        corporativo: m.wa_corporativo || WA_DEFAULTS.corporativo,
        fab:         m.wa_fab         || WA_DEFAULTS.fab,
      },
      message: m.wa_fab_message || WA_FAB_MESSAGE_DEFAULT,
      email: {
        to:      m.email_to      || EMAIL_DEFAULTS.to,
        subject: m.email_subject || EMAIL_DEFAULTS.subject,
        body:    m.email_body    || EMAIL_DEFAULTS.body,
      },
    };
  }).catch(() => fallback);
  return _waConfigPromise;
}
function invalidateWaConfig() { _waConfigPromise = null; }

function useWaConfig() {
  const [cfg, setCfg] = useState({ numbers: WA_DEFAULTS, message: WA_FAB_MESSAGE_DEFAULT, email: EMAIL_DEFAULTS });
  useEffect(() => { loadWaConfig().then(setCfg); }, []);
  return cfg;
}

// ───────────────────────────────────────────────
// Generador de catálogo PDF dinámico desde Supabase
// ───────────────────────────────────────────────
async function fetchAsDataURL(url) {
  if (!url) return null;
  try {
    const r = await fetch(url, { mode: 'cors' });
    if (!r.ok) return null;
    const blob = await r.blob();
    return await new Promise((resolve, reject) => {
      const fr = new FileReader();
      fr.onload = () => resolve(fr.result);
      fr.onerror = reject;
      fr.readAsDataURL(blob);
    });
  } catch (_) { return null; }
}

function detectImgFmt(dataURL) {
  if (!dataURL) return null;
  if (dataURL.startsWith('data:image/png')) return 'PNG';
  if (dataURL.startsWith('data:image/webp')) return 'WEBP';
  return 'JPEG';
}

async function generateCatalogPDF(equipos, opts) {
  const options = opts || {};
  const wantBase64 = options.output === 'base64';
  if (!window.jspdf || !window.jspdf.jsPDF) {
    if (!wantBase64) {
      alert('No se pudo cargar el generador de PDF. Recarga la página e intenta de nuevo.');
    }
    throw new Error('jsPDF no disponible');
  }
  const list = (equipos || []).slice();
  const { jsPDF } = window.jspdf;
  const doc = new jsPDF({ unit: 'mm', format: 'a4', compress: true });
  const PW = 210, PH = 297, M = 18;

  const drawPageFooter = (pageIdx, total) => {
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(8);
    doc.setTextColor(140, 140, 140);
    doc.text('contacto@pertec.cl · pertec.cl', M, PH - 10);
    doc.text(`${pageIdx} / ${total}`, PW - M, PH - 10, { align: 'right' });
  };

  // ---- Cover ----
  doc.setFillColor(23, 20, 17);
  doc.rect(0, 0, PW, PH, 'F');
  doc.setFillColor(0, 168, 120);
  doc.rect(0, 0, 4, PH, 'F');
  doc.setFillColor(200, 82, 23);
  doc.rect(PW - 4, 0, 4, PH, 'F');
  doc.setTextColor(168, 162, 158);
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(11);
  doc.text('PERTEC · PERFORMANCE TECHNOLOGIES', M, 30);
  doc.setTextColor(255, 255, 255);
  doc.setFontSize(46);
  doc.text('Catálogo de', M, 130);
  doc.text('arriendo', M, 148);
  doc.setTextColor(0, 168, 120);
  doc.setFontSize(46);
  doc.text('.', M + 60, 148);
  doc.setTextColor(168, 162, 158);
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(13);
  const subtitle = doc.splitTextToSize(
    'Equipos vulcanizadores certificados, complementarios y servicios técnicos para mantenimiento de correas transportadoras en la gran minería.',
    PW - M * 2,
  );
  doc.text(subtitle, M, 170);
  const today = new Date().toLocaleDateString('es-CL', { day: '2-digit', month: 'long', year: 'numeric' });
  doc.setTextColor(255, 255, 255);
  doc.setFontSize(10);
  doc.text(`Catálogo generado el ${today}`, M, PH - 30);
  doc.setTextColor(168, 162, 158);
  doc.text(`${list.length} equipos / servicios disponibles`, M, PH - 22);

  // ---- Páginas por equipo ----
  for (let i = 0; i < list.length; i++) {
    const e = list[i];
    doc.addPage();

    // header de página
    doc.setTextColor(168, 162, 158);
    doc.setFontSize(9);
    doc.setFont('helvetica', 'bold');
    doc.text('PERTEC', M, 14);
    doc.setFont('helvetica', 'normal');
    doc.text('Catálogo de arriendo', M + 22, 14);
    doc.setDrawColor(220, 220, 220);
    doc.setLineWidth(0.2);
    doc.line(M, 18, PW - M, 18);

    // imagen
    const imgY = 30, imgW = 80, imgH = 60;
    const dataURL = await fetchAsDataURL(e.imagen_url);
    if (dataURL) {
      try { doc.addImage(dataURL, detectImgFmt(dataURL), M, imgY, imgW, imgH, undefined, 'FAST'); }
      catch (_) {}
    } else {
      doc.setFillColor(245, 245, 240);
      doc.rect(M, imgY, imgW, imgH, 'F');
      doc.setTextColor(180, 175, 168);
      doc.setFontSize(9);
      doc.text('Imagen no disponible', M + imgW / 2, imgY + imgH / 2, { align: 'center' });
    }

    // bloque de texto a la derecha
    const tx = M + imgW + 12;
    const txMax = PW - M - tx;
    let cy = imgY + 4;

    doc.setTextColor(0, 168, 120);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(9);
    doc.text((e.tipo || 'Equipo').toUpperCase(), tx, cy);
    cy += 8;

    doc.setTextColor(23, 20, 17);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(18);
    const titleLines = doc.splitTextToSize(e.nombre || 'Equipo', txMax);
    doc.text(titleLines, tx, cy);
    cy += titleLines.length * 7;

    if (e.descripcion_corta) {
      doc.setFont('helvetica', 'normal');
      doc.setFontSize(10.5);
      doc.setTextColor(80, 75, 70);
      const descLines = doc.splitTextToSize(e.descripcion_corta, txMax);
      doc.text(descLines, tx, cy + 4);
    }

    // ficha de specs
    let sy = imgY + imgH + 16;
    doc.setDrawColor(230, 228, 224);
    doc.setLineWidth(0.3);
    doc.line(M, sy - 6, PW - M, sy - 6);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(9);
    doc.setTextColor(140, 130, 120);
    doc.text('FICHA TÉCNICA', M, sy);
    sy += 8;

    const specs = [
      ['Tipo', e.tipo || '—'],
      ['Categoría', e.categoria || '—'],
      ['Ancho máximo de correa', e.ancho_correa_max || '—'],
      ['Disponibilidad', e.disponible ? 'Disponible para faena' : 'Consultar'],
      ['Destacado', e.destacado ? 'Sí' : 'No'],
    ];
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(10.5);
    specs.forEach(([k, v]) => {
      doc.setTextColor(140, 130, 120);
      doc.text(k, M, sy);
      doc.setTextColor(23, 20, 17);
      doc.text(String(v), M + 70, sy);
      sy += 6.5;
    });

    if (e.descripcion_larga) {
      sy += 6;
      doc.setFont('helvetica', 'bold');
      doc.setFontSize(9);
      doc.setTextColor(140, 130, 120);
      doc.text('DESCRIPCIÓN', M, sy);
      sy += 6;
      doc.setFont('helvetica', 'normal');
      doc.setFontSize(10.5);
      doc.setTextColor(50, 45, 40);
      const longLines = doc.splitTextToSize(String(e.descripcion_larga), PW - M * 2);
      doc.text(longLines, M, sy);
    }

    drawPageFooter(i + 1, list.length);
  }

  // ---- Última página: contacto ----
  doc.addPage();
  doc.setFillColor(23, 20, 17);
  doc.rect(0, 0, PW, PH, 'F');
  doc.setTextColor(255, 255, 255);
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(28);
  doc.text('¿Listo para cotizar?', M, 100);
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(13);
  doc.setTextColor(168, 162, 158);
  const cta = doc.splitTextToSize(
    'Conversemos sobre tu requerimiento. El equipo PERTEC responde en menos de 24 horas hábiles.',
    PW - M * 2,
  );
  doc.text(cta, M, 115);
  doc.setTextColor(0, 168, 120);
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(14);
  doc.text('contacto@pertec.cl', M, 145);
  doc.text('www.pertec.cl', M, 155);

  if (wantBase64) {
    const dataUri = doc.output('datauristring');
    const idx = dataUri.indexOf(',');
    return idx >= 0 ? dataUri.slice(idx + 1) : dataUri;
  }
  doc.save(`catalogo-pertec-${new Date().toISOString().slice(0, 10)}.pdf`);
  return null;
}

window.generateCatalogPDF = generateCatalogPDF;

function DownloadCatalogButton({ className = '', variant = 'primary', equipos: equiposProp }) {
  const [busy, setBusy] = useState(false);
  useLucide(busy);

  const onClick = async () => {
    if (busy) return;
    setBusy(true);
    try {
      let equipos = equiposProp;
      if (!equipos) {
        const supa = window.supabaseClient;
        if (supa) {
          const { data } = await supa.from('equipos')
            .select('*')
            .eq('disponible', true)
            .order('orden', { ascending: true })
            .order('created_at', { ascending: true });
          equipos = data || [];
        } else {
          equipos = [];
        }
      }
      if (!equipos.length) {
        alert('Aún no hay equipos disponibles para incluir en el catálogo.');
        return;
      }
      await generateCatalogPDF(equipos);
    } catch (err) {
      console.error('catalog pdf error', err);
      alert('No se pudo generar el catálogo. Intenta de nuevo en un momento.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <button
      type="button"
      className={`btn ${variant} ${className}`}
      onClick={onClick}
      disabled={busy}
    >
      <i data-lucide={busy ? 'loader-2' : 'download'} className={`arrow ${busy ? 'is-spinning' : ''}`}></i>
      {busy ? 'Generando…' : 'Descargar catálogo PDF'}
    </button>
  );
}

function buildMailtoUrl(to, subject, body) {
  const params = [];
  if (subject) params.push(`subject=${encodeURIComponent(subject)}`);
  if (body)    params.push(`body=${encodeURIComponent(body)}`);
  return `mailto:${to || ''}${params.length ? '?' + params.join('&') : ''}`;
}

function buildWhatsAppUrl(phone, message) {
  const clean = String(phone || '').replace(/\D/g, '');
  return `https://wa.me/${clean}?text=${encodeURIComponent(message || '')}`;
}

// Lucide re-render hook
function useLucide(dep) {
  useEffect(() => {
    const tick = () => window.lucide && window.lucide.createIcons();
    tick();
    const id = setTimeout(tick, 80);
    return () => clearTimeout(id);
  }, [dep]);
}

// Reveal on scroll
function Reveal({ children, className = '', delay = 0, as: As = 'div', style }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { el.classList.add('is-in'); io.unobserve(el); } });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const d = delay ? ` d${delay}` : '';
  return <As ref={ref} className={`reveal${d} ${className}`} style={style}>{children}</As>;
}

const NAV = [
  { id: 'home', label: 'Inicio' },
  { id: 'empresa', label: 'Empresa' },
  { id: 'servicios', label: 'Servicios' },
  { id: 'arriendo', label: 'Arriendo' },
  // { id: 'casos', label: 'Casos' },
  { id: 'recursos', label: 'Recursos' },
  { id: 'noticias', label: 'Noticias' },
  { id: 'hse', label: 'HSE' },
  { id: 'contacto', label: 'Contacto' },
];

function Header({ page, go, transparent }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 40);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  useEffect(() => {
    if (!mobileOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setMobileOpen(false); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [mobileOpen]);
  useLucide(`${scrolled}_${mobileOpen}`);
  const isLight = transparent && !scrolled;
  const goAndClose = (id) => { setMobileOpen(false); go(id); };
  return (
    <header className={`hdr ${scrolled ? 'scrolled' : ''} ${isLight ? 'light' : ''} ${mobileOpen ? 'mobile-open' : ''}`}>
      <div className="hdr-inner">
        <a className="hdr-brand" onClick={() => goAndClose('home')} style={{cursor:'pointer'}}>
          <img className="hdr-logo" src="assets/logo-white.png" alt="PERTEC" />
        </a>
        <nav className="hdr-nav">
          {NAV.slice(1, 8).map(n => (
            <a
              key={n.id}
              className={`hdr-link ${page === n.id ? 'active' : ''} ${n.id === 'arriendo' ? 'featured' : ''}`}
              onClick={() => go(n.id)}
            >
              {n.id === 'arriendo' && <i data-lucide="zap" className="hdr-link-icon"></i>}
              {n.label}
            </a>
          ))}
        </nav>
        <div className="hdr-actions">
          <a className="btn ghost sm" onClick={() => go('contacto')}>
            <i data-lucide="phone"></i> Hablar con un especialista
          </a>
          <a className="btn primary sm" onClick={() => go('contacto')}>
            Cotizar <i data-lucide="arrow-right" className="arrow"></i>
          </a>
        </div>
        <button
          type="button"
          className="hdr-burger"
          aria-label={mobileOpen ? 'Cerrar menú' : 'Abrir menú'}
          aria-expanded={mobileOpen}
          onClick={() => setMobileOpen(v => !v)}
        >
          <span></span><span></span><span></span>
        </button>
      </div>
      <div className={`hdr-mobile ${mobileOpen ? 'is-open' : ''}`} aria-hidden={!mobileOpen}>
        <nav className="hdr-mobile-nav">
          {NAV.slice(1, 8).map(n => (
            <a
              key={n.id}
              className={`hdr-mobile-link ${page === n.id ? 'active' : ''} ${n.id === 'arriendo' ? 'featured' : ''}`}
              onClick={() => goAndClose(n.id)}
            >
              {n.id === 'arriendo' && <i data-lucide="zap"></i>}
              <span>{n.label}</span>
              <i data-lucide="arrow-right" className="hdr-mobile-arrow"></i>
            </a>
          ))}
        </nav>
        <div className="hdr-mobile-actions">
          <a className="btn ghost lg" onClick={() => goAndClose('contacto')}>
            <i data-lucide="phone"></i> Hablar con un especialista
          </a>
          <a className="btn primary lg" onClick={() => goAndClose('contacto')}>
            Cotizar <i data-lucide="arrow-right" className="arrow"></i>
          </a>
        </div>
      </div>
      {mobileOpen && (
        <div
          className="hdr-mobile-backdrop"
          onClick={() => setMobileOpen(false)}
          aria-hidden="true"
        />
      )}
    </header>
  );
}

function Footer({ go }) {
  useLucide();
  return (
    <footer className="ftr">
      <div className="ftr-inner">
        <div className="ftr-brand">
          <img src="assets/logo-white.png" alt="PERTEC" />
          <p className="ftr-tag">Aseguramos la continuidad operativa de la gran minería. Mantenimiento de correas transportadoras, arriendo de equipos vulcanizadores y servicios técnicos especializados.</p>
          <div className="ftr-social">
            <a href="https://www.linkedin.com/company/pertec-cl" target="_blank" rel="noopener noreferrer" aria-label="LinkedIn">
              <svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.268 2.37 4.268 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.063 2.063 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/>
              </svg>
            </a>
            <a href="https://www.instagram.com/pertec.cl/" target="_blank" rel="noopener noreferrer" aria-label="Instagram">
              <svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2.163c3.204 0 3.584.012 4.849.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.849.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
              </svg>
            </a>
          </div>
        </div>
        <div className="ftr-col">
          <div className="ftr-h">Servicios</div>
          <a onClick={() => go('mantenimiento')}>Mantenimiento de correas</a>
          <a onClick={() => go('tecnicos')}>Servicios técnicos especializados</a>
          <a onClick={() => go('servicio-detalle')}>Inspección radiográfica</a>
          <a onClick={() => go('servicio-detalle')}>Ultrasonido aplicado</a>
          <a onClick={() => go('servicio-detalle')}>Inspección termográfica</a>
        </div>
        <div className="ftr-col">
          <div className="ftr-h">Compañía</div>
          <a onClick={() => go('empresa')}>Empresa</a>
          <a onClick={() => go('recursos')}>Recursos técnicos</a>
          <a onClick={() => go('hse')}>HSE y cumplimiento</a>
          <a onClick={() => go('arriendo')}>Arriendo</a>
        </div>
        <div className="ftr-col">
          <div className="ftr-h">Contacto</div>
          <a onClick={() => go('contacto')}>Cotizar servicio</a>
          <a onClick={() => go('contacto')}>Cotizar arriendo</a>
          <a onClick={() => go('contacto')}>Contacto corporativo</a>
          <a>comercial@pertec.cl</a>
          <a>+56 55 000 0000</a>
        </div>
      </div>
      <div className="ftr-bar">
        <div>© 2026 PERTEC — Performance Technologies · Todos los derechos reservados</div>
        <div>Santiago · Antofagasta · Calama</div>
      </div>
    </footer>
  );
}

function PageHero({ bc, title, subtitle, go }) {
  return (
    <section className="phero">
      <div className="phero-inner">
        <div className="phero-bc">
          <a onClick={() => go('home')}>Inicio</a>
          {bc.map((b, i) => (
            <React.Fragment key={i}>
              <span>/</span>
              {b.go ? <a onClick={() => go(b.go)}>{b.label}</a> : <span style={{color:'#fff'}}>{b.label}</span>}
            </React.Fragment>
          ))}
        </div>
        <h1 className="phero-t">{title}</h1>
        {subtitle && <p className="phero-s">{subtitle}</p>}
      </div>
    </section>
  );
}

function WhatsAppFAB() {
  const cfg = useWaConfig();
  const href = buildWhatsAppUrl(cfg.numbers.fab, cfg.message);
  return (
    <a
      className="wa-fab"
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      aria-label="Contactar por WhatsApp"
    >
      <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
        <path fill="currentColor" d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
      </svg>
      <span className="wa-fab-tooltip">Escríbenos</span>
    </a>
  );
}

function BackToTopFAB() {
  const [show, setShow] = useState(false);
  useLucide(show);
  useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 320);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const goTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  return (
    <button
      type="button"
      className={`back-top-fab ${show ? 'is-visible' : ''}`}
      onClick={goTop}
      aria-label="Volver arriba"
    >
      <i data-lucide="arrow-up"></i>
    </button>
  );
}

// RotatingImage: ciclo de imágenes con cross-fade. images = [url, url, ...].
// Si hay 1 sola o ninguna, no rota. Stagger: usa el índice del consumidor
// como offset para que las cards no parpadeen sincronizadas.
function RotatingImage({ images, alt = '', className = '', interval = 3500, staggerKey = 0 }) {
  const list = (images || []).filter(Boolean);
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    if (list.length <= 1) return;
    const offset = (staggerKey * 700) % interval;
    let intId = null;
    const startId = setTimeout(() => {
      setIdx((i) => (i + 1) % list.length);
      intId = setInterval(() => setIdx((i) => (i + 1) % list.length), interval);
    }, offset);
    return () => {
      clearTimeout(startId);
      if (intId) clearInterval(intId);
    };
  }, [list.length, interval, staggerKey]);
  if (list.length === 0) return null;
  return (
    <div className={`rot-img ${className}`} style={{ position: 'relative', width: '100%', height: '100%' }}>
      {list.map((url, i) => (
        <img
          key={url + '_' + i}
          src={url}
          alt={alt}
          loading="lazy"
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%', objectFit: 'cover',
            opacity: i === idx ? 1 : 0,
            transition: 'opacity .55s ease',
          }}
        />
      ))}
    </div>
  );
}

window.RotatingImage = RotatingImage;

window.Reveal = Reveal;
window.Header = Header;
window.Footer = Footer;
window.PageHero = PageHero;
window.WhatsAppFAB = WhatsAppFAB;
window.BackToTopFAB = BackToTopFAB;
window.DownloadCatalogButton = DownloadCatalogButton;
window.useLucide = useLucide;
window.useWaConfig = useWaConfig;
window.loadWaConfig = loadWaConfig;
window.invalidateWaConfig = invalidateWaConfig;
window.NAV = NAV;
window.buildWhatsAppUrl = buildWhatsAppUrl;
window.buildMailtoUrl = buildMailtoUrl;
