/* Home page with 3 hero variants */

const Marquee = () => {
  const items = [
    { i: 'wrench', t: 'Servicio técnico especializado' },
    { i: 'shield', t: 'Garantía oficial' },
    { i: 'box', t: '+1.400 productos en stock' },
    { i: 'nozzle', t: 'Repuestos originales siempre en stock' },
    { i: 'award', t: '+15 años en el mercado' },
  ];

  const doubled = [...items, ...items, ...items];
  return (
    <div style={{ background: 'var(--ink)', color: '#fff', padding: '14px 0', overflow: 'hidden' }} className="marquee-wrap">
      <div className="marquee-track">
        {doubled.map((it, i) =>
        <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, fontSize: 13, fontFamily: '"Galano", var(--font-sans)', fontWeight: 400, whiteSpace: 'nowrap' }}>
            <Icon name={it.i} size={14} /> {it.t}
            <span style={{ color: 'var(--accent)', margin: '0 0 0 40px' }}>✕</span>
          </span>
        )}
      </div>
    </div>);

};

/* ── Hero variants ────────────────────────────────────────────── */
const HeroIndustrial = ({ onNavigate }) => {
  const brands = ['HAWK', 'ANNOVI REVERBERI', 'INTERPUMP', 'POWERCLEAN', 'ELSEA', 'IPC'];
  const headlines = [
  { top: 'Alta presión.', bottom: 'Italiana.' },
  { top: 'Aspiración.', bottom: 'Industrial.' },
  { top: 'Service.', bottom: 'Propio.' },
  { top: 'Repuestos.', bottom: 'En stock.' }];


  return (
    <section style={{
      background: 'linear-gradient(180deg, #05111F 0%, #0A1A2F 60%, #0A1A2F 100%)',
      color: '#fff',
      position: 'relative',
      overflow: 'hidden',
      borderBottom: '1px solid rgba(255,255,255,0.06)'
    }} className="grain">
      {/* Blueprint grid */}
      <div style={{
        position: 'absolute', inset: 0,
        opacity: 0.08,
        backgroundImage:
        'linear-gradient(rgba(255,255,255,0.8) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.8) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.3) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.3) 1px, transparent 1px)',
        backgroundSize: '120px 120px, 120px 120px, 24px 24px, 24px 24px',
        maskImage: 'radial-gradient(ellipse 90% 70% at 50% 40%, black 40%, transparent 85%)',
        WebkitMaskImage: 'radial-gradient(ellipse 90% 70% at 50% 40%, black 40%, transparent 85%)'
      }} />
      {/* Red corner accent */}
      <div style={{
        position: 'absolute', top: 0, right: 0,
        width: '38%', height: '62%',
        background: 'radial-gradient(ellipse at top right, rgba(227,6,19,0.22), transparent 65%)',
        pointerEvents: 'none'
      }} />

      {/* Top tech strip */}
      <div style={{ position: 'relative', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
        <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 24px', fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
          <div style={{ display: 'flex', gap: 28, color: 'rgba(255,255,255,0.55)' }}>
            <span><span style={{ color: '#a00e0c' }}>●</span> ONLINE · Stock en tiempo real</span>
            <span className="hide-mobile">Haedo · Buenos Aires · Arg.</span>
          </div>
          <div style={{ display: 'flex', gap: 28, color: 'rgba(255,255,255,0.55)' }} className="hide-mobile">
            <span>EDICIÓN 04 / 2026</span>
            <span style={{ color: '#fff' }}>+5491125181264</span>
          </div>
        </div>
      </div>

      <div className="container" style={{ position: 'relative', paddingTop: 64, paddingBottom: 72 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 48, alignItems: 'stretch' }} className="hero-grid">

          {/* ── LEFT: editorial text block ── */}
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 32 }}>
              <div style={{ height: 1, width: 48, background: 'rgba(255,255,255,0.3)' }} />
              <span className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)' }}>
                Desde 2009 · Equipamiento pro
              </span>
            </div>

            <h1 style={{
              fontFamily: 'var(--font-sans)', fontWeight: 900,
              fontSize: 'clamp(56px, 8.5vw, 128px)',
              lineHeight: 0.88, letterSpacing: '-0.045em', color: '#fff',
              textTransform: 'uppercase'
            }}>
              Limpieza<br />
              <span style={{ fontStyle: 'normal', fontWeight: 300, letterSpacing: '-0.03em' }}>
                industrial
              </span><br />
              <span style={{ color: 'var(--accent)' }}>sin</span>{' '}
              <span className="hero-bold-outline" style={{ WebkitTextStroke: '2px rgba(255,255,255,0.95)', color: 'transparent' }}>excusas.</span>
            </h1>

            <p style={{ fontSize: 17, color: 'rgba(255,255,255,0.7)', marginTop: 32, maxWidth: 500, lineHeight: 1.55 }}>
              Hidrolavadoras, aspiradoras y lavatapizados para quienes trabajan cada día.
              Stock real de <strong style={{ color: '#fff', fontWeight: 700 }}>+1.400</strong> productos y servicio técnico propio en Haedo.
            </p>

            <div style={{ display: 'flex', gap: 10, marginTop: 32, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-lg" onClick={() => onNavigate('/tienda')}>
                Explorar catálogo <Icon name="arrowRight" size={16} />
              </button>
              <button className="btn btn-outline-white btn-lg">
                <Icon name="whatsapp" size={16} /> Asesorarme
              </button>
            </div>

            {/* Brands strip */}
            <div style={{ marginTop: 'auto', paddingTop: 48 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)', marginBottom: 14 }}>
                Representamos
              </div>
              <div style={{ display: 'flex', gap: 28, flexWrap: 'wrap', alignItems: 'center' }}>
                {brands.map((b, i) =>
                <span key={b} style={{
                  fontSize: 13, fontWeight: 700,
                  color: 'rgba(255,255,255,0.5)',
                  letterSpacing: '0.05em',
                  borderLeft: i === 0 ? 'none' : '1px solid rgba(255,255,255,0.1)',
                  paddingLeft: i === 0 ? 0 : 28
                }}>{b}</span>
                )}
              </div>
            </div>
          </div>

          {/* ── RIGHT: product studio card ── */}
          <div style={{
            position: 'relative',
            minHeight: 560,
            display: 'grid',
            gridTemplateRows: '1fr auto',
            gap: 14
          }} className="hide-mobile">

            {/* Main product "photo" */}
            <div className="ph-studio" data-label="Hidrolavadora NX180 / 11M · 220V" style={{
              borderRadius: 16,
              border: '1px solid rgba(255,255,255,0.08)',
              position: 'relative',
              overflow: 'hidden'
            }}>
              {/* Corner specs tag */}
              <div style={{
                position: 'absolute', top: 18, left: 18,
                padding: '6px 10px',
                background: 'rgba(227,6,19,0.95)',
                color: '#fff',
                fontSize: 10, fontWeight: 700,
                letterSpacing: '0.15em', textTransform: 'uppercase'
              }}>DESTACADO · 8% OFF</div>

              {/* Product SKU in corner */}
              <div className="mono" style={{
                position: 'absolute', top: 18, right: 18,
                fontSize: 10, color: 'rgba(255,255,255,0.4)',
                letterSpacing: '0.15em'
              }}>SKU · NX180-11M</div>

              {/* Central "product" — silhouette rectangle suggesting the hidrolavadora */}
              <div style={{
                position: 'absolute', inset: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center'
              }}>
                <div style={{
                  width: 180, height: 260,
                  background: 'linear-gradient(180deg, #141F33 0%, #0A1422 50%, #050A14 100%)',
                  border: '1px solid rgba(255,255,255,0.1)',
                  borderRadius: 12,
                  position: 'relative',
                  boxShadow: '0 40px 60px -20px rgba(0,0,0,0.6), inset 0 2px 0 rgba(255,255,255,0.08)'
                }}>
                  {/* product decal */}
                  <div style={{ position: 'absolute', top: 30, left: 0, right: 0, textAlign: 'center' }}>
                    <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--accent)', letterSpacing: '0.2em' }}>POWERCLEAN</div>
                    <div style={{ fontSize: 28, fontWeight: 900, color: '#fff', letterSpacing: '-0.02em', marginTop: 6 }}>NX180</div>
                    <div className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.4)', marginTop: 4, letterSpacing: '0.2em' }}>180 BAR · 11 L/MIN</div>
                  </div>
                  {/* nozzle line */}
                  <div style={{ position: 'absolute', bottom: 40, left: 30, right: 30, height: 2, background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent)' }} />
                  {/* label stripe */}
                  <div style={{ position: 'absolute', bottom: 20, left: 20, right: 20, height: 12, background: 'var(--accent)', clipPath: 'polygon(0 0, 100% 0, 95% 100%, 5% 100%)' }} />
                </div>
              </div>

              {/* Floating spec badges */}
              <div style={{
                position: 'absolute', bottom: 20, right: 20,
                padding: '14px 18px',
                background: 'rgba(10,26,47,0.8)', backdropFilter: 'blur(10px)',
                border: '1px solid rgba(255,255,255,0.12)',
                borderRadius: 10
              }}>
                <div className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.15em', textTransform: 'uppercase' }}>Desde</div>
                <div style={{ fontSize: 22, fontWeight: 800, color: '#fff', marginTop: 2 }}>$1.448.655</div>
                <div className="mono" style={{ fontSize: 10, color: '#a00e0c', marginTop: 2 }}>6 × $241.443 s/int</div>
              </div>

              {/* Spec annotations — leader lines */}
              <div style={{ position: 'absolute', top: '42%', left: 0, display: 'flex', alignItems: 'center', gap: 0 }}>
                <div style={{ padding: '6px 10px', background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)', borderLeft: '2px solid var(--accent)', fontSize: 11 }}>
                  <div className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.1em' }}>PRESIÓN</div>
                  <div style={{ fontSize: 14, fontWeight: 700 }}>180 bar</div>
                </div>
                <div style={{ width: 40, height: 1, background: 'rgba(255,255,255,0.2)' }} />
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} className="pulse" />
              </div>
              <div style={{ position: 'absolute', bottom: '32%', right: 0, display: 'flex', alignItems: 'center', gap: 0, flexDirection: 'row-reverse' }}>
                <div style={{ padding: '6px 10px', background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)', borderRight: '2px solid var(--accent)', fontSize: 11, textAlign: 'right' }}>
                  <div className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.1em' }}>CAUDAL</div>
                  <div style={{ fontSize: 14, fontWeight: 700 }}>11 L/min</div>
                </div>
                <div style={{ width: 40, height: 1, background: 'rgba(255,255,255,0.2)' }} />
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} className="pulse" />
              </div>
            </div>

            {/* Bottom meta strip */}
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1,
              background: 'rgba(255,255,255,0.08)',
              border: '1px solid rgba(255,255,255,0.08)',
              borderRadius: 10, overflow: 'hidden'
            }}>
              {[
              { k: 'Stock', v: '1.400+', u: 'productos' },
              { k: 'Envío', v: '24hs', u: 'CABA/GBA' },
              { k: 'Service', v: 'Propio', u: 'en Haedo' }].
              map((s) =>
              <div key={s.k} style={{ background: '#0A1A2F', padding: '14px 16px' }}>
                  <div className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.15em', textTransform: 'uppercase' }}>{s.k}</div>
                  <div style={{ fontSize: 20, fontWeight: 800, color: '#fff', marginTop: 2 }}>{s.v}</div>
                  <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>{s.u}</div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>);

};

const HeroEditorial = ({ onNavigate }) =>
<section style={{ background: 'var(--bg)', position: 'relative' }}>
    <div className="container" style={{ padding: '40px 24px 80px' }}>
      <div className="eyebrow" style={{ marginBottom: 28 }}>
        <span className="dot" />EDICIÓN OTOÑO 2026 — N° 04
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 40, alignItems: 'end' }} className="hero-grid">
        <h1 className="h-display-xl" style={{ letterSpacing: '-0.04em' }}>
          La potencia<br />
          tiene <span style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--accent)' }}>oficio.</span>
        </h1>
        <p className="t-lead" style={{ maxWidth: 360, lineHeight: 1.5, color: 'var(--ink-2)' }}>
          Equipos de limpieza industrial seleccionados uno por uno. Especificaciones claras, service propio y stock real — no stock de catálogo.
        </p>
      </div>
      {(() => {
      const pick = (catId) => window.RC_DATA.PRODUCTS.find((p) => p.cat === catId && p.image);
      const hidroHero = pick('hidro');
      const aspiHero = pick('aspi');
      const lavaHero = pick('lava');
      return (
        <div style={{ marginTop: 48, display: 'grid', gridTemplateColumns: '1.2fr 1fr 1fr', gap: 16, minHeight: 420 }} className="hero-grid-imgs">
        <div onClick={() => onNavigate('/categoria/hidrolavadoras')} style={{ borderRadius: 'var(--r-lg)', background: 'var(--ink)', position: 'relative', overflow: 'hidden', cursor: 'pointer' }}>
          {hidroHero?.image && <img src={hidroHero.image} alt={hidroHero.name} style={{ position: 'absolute', right: -40, bottom: -20, width: '85%', height: '85%', objectFit: 'contain', opacity: 0.95 }} />}
          <div style={{ position: 'absolute', inset: 0, padding: 24, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', background: 'linear-gradient(105deg, rgba(11,18,32,0.95) 0%, rgba(11,18,32,0.5) 55%, rgba(11,18,32,0) 100%)' }}>
            <Badge variant="red">Destacado</Badge>
            <div style={{ color: '#fff' }}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.6 }}>Hidrolavadoras</div>
              <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em', marginTop: 4 }}>Agua caliente a 80°C</div>
              <button className="btn" style={{ background: '#fff', color: 'var(--ink)', marginTop: 16 }}>
                Ver serie <Icon name="arrowRight" size={14} />
              </button>
            </div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: 16 }}>
          <div onClick={() => onNavigate('/categoria/aspiradoras')} style={{ borderRadius: 'var(--r-lg)', cursor: 'pointer', background: 'var(--bg-2)', position: 'relative', overflow: 'hidden' }}>
            {aspiHero?.image && <img src={aspiHero.image} alt={aspiHero.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', margin: "0px", padding: "25px" }} />}
            <div className="mono" style={{ position: 'absolute', top: 12, left: 14, fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Aspiradoras</div>
          </div>
          <div onClick={() => onNavigate('/categoria/lavatapizados')} style={{ borderRadius: 'var(--r-lg)', cursor: 'pointer', background: 'var(--bg-2)', position: 'relative', overflow: 'hidden' }}>
            {lavaHero?.image && <img src={lavaHero.image} alt={lavaHero.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', padding: 24 }} />}
            <div className="mono" style={{ position: 'absolute', top: 12, left: 14, fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Lavatapizados</div>
          </div>
        </div>
        <div style={{ padding: 24, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', display: 'flex', flexDirection: 'column' }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}><span className="dot" />Consejo del mes</div>
          <h3 style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.2 }}>
            Cómo elegir la hidrolavadora correcta
          </h3>
          <p className="t-body" style={{ marginTop: 12, flex: 1 }}>
            Potencia, caudal y fase eléctrica: los 3 datos que definen tu próximo equipo. Una guía rápida para no equivocarte.
          </p>
          <a href="#" style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            Leer guía <Icon name="arrowUpRight" size={14} />
          </a>
        </div>
      </div>);

    })()}
    </div>
  </section>;


const HeroBold = ({ onNavigate }) =>
<section style={{ background: 'var(--accent)', color: '#fff', position: 'relative', overflow: 'hidden' }}>
    <div className="container" style={{ padding: '100px 24px', textAlign: 'center' }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', marginBottom: 24, opacity: 0.8 }}>
        · · · Desde 2009 · · ·
      </div>
      <h1 style={{
      fontSize: 'clamp(60px, 12vw, 180px)', fontWeight: 900, lineHeight: 0.85, letterSpacing: '-0.04em',
      color: '#fff'
    }}>
        Powerclean.<br />
        <span className="hero-bold-outline" style={{ WebkitTextStroke: '2px #fff', color: 'transparent', fontStyle: 'italic' }}>
          No apto para tibios.
        </span>
      </h1>
      <p style={{ fontSize: 18, opacity: 0.9, marginTop: 32, maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
        Hidrolavadoras, aspiradoras industriales y repuestos originales. Service propio. Envío a todo el país.
      </p>
      <div style={{ display: 'flex', gap: 12, marginTop: 40, justifyContent: 'center', flexWrap: 'wrap' }}>
        <button className="btn btn-lg" style={{ background: 'var(--ink)', color: '#fff' }} onClick={() => onNavigate('/tienda')}>
          Ver catálogo <Icon name="arrowRight" size={16} />
        </button>
        <button className="btn btn-lg btn-outline-white">
          <Icon name="whatsapp" size={16} /> WhatsApp
        </button>
      </div>
    </div>
  </section>;


/* ── Category strip ─────────────────────────────── */
const CategoryStrip = ({ onNavigate }) => {
  const { CATEGORIES } = window.RC_DATA;
  const icons = { hidro: 'pressure', aspi: 'vacuum', lava: 'sofa', vapor: 'steam', rep: 'nozzle' };
  return (
    <section style={{ padding: '72px 0 40px' }}>
      <div className="container">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 32, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}><span className="dot" />01 / Categorías</div>
            <h2 className="h-1">Todo el equipamiento.<br />En un solo lugar.</h2>
          </div>
          <button onClick={() => onNavigate('/tienda')} className="btn btn-ghost">
            Catálogo completo <Icon name="arrowRight" size={14} />
          </button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 1, background: 'var(--line)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', overflow: 'hidden' }}>
          {CATEGORIES.map((c, i) =>
          <button key={c.id} onClick={() => onNavigate(`/categoria/${c.slug}`)}
          style={{
            padding: '32px 24px', background: 'var(--surface)',
            textAlign: 'left',
            display: 'flex', flexDirection: 'column', gap: 16, minHeight: 200,
            transition: 'background .2s'
          }}
          onMouseEnter={(e) => {e.currentTarget.style.background = 'var(--bg-2)';}}
          onMouseLeave={(e) => {e.currentTarget.style.background = 'var(--surface)';}}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start' }}>
                <Icon name={icons[c.id]} size={28} strokeWidth={1.4} />
                <span className="mono t-xs">0{i + 1}</span>
              </div>
              <div style={{ marginTop: 'auto' }}>
                <h3 style={{ fontSize: 19, fontWeight: 600, letterSpacing: '-0.01em' }}>{c.name}</h3>
                <div className="t-xs mono" style={{ marginTop: 4, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{c.count} productos</div>
              </div>
              <Icon name="arrowRight" size={18} />
            </button>
          )}
        </div>
      </div>
    </section>);

};

/* ── Featured products with tabs ─────────────────── */

/**
 * CategoryTabs — pill row for selecting a category. Multiple visual variants
 * exposed via the homeTabsStyle tweak.
 *
 * Pill-row variants (share the same scrollable layout, differ in affordance):
 *   default   — scrollable + hide-scrollbar, no extra cue.
 *   fades     — gradient mask on left/right edges (~56px).
 *   scrollbar — custom thin progress track + thumb below the row.
 *   arrow     — pulsing chevron at the right edge that hides at scroll end.
 *   peek      — active pill auto-centred so prev/next peek in from each side.
 *   wrap      — pills wrap to multiple rows; no scroll.
 *
 * Visual-restyle variants (same horizontal-scroll mechanic, different look):
 *   underline — text-only labels with an animated underline under active.
 *   chips     — outline-style chips; active = filled dark.
 *   icons     — pill row with category icon + name.
 *
 * Layout-change variants (radically different markup):
 *   dropdown  — single button "Hidrolavadoras ▾" opens a list popover.
 *   cards     — icon-on-top cards in a swipeable row.
 */
const CategoryTabs = ({ categories, tab, setTab, variant = 'default' }) => {
  // Icon mapping shared across icon variants
  const CAT_ICONS = { hidro: 'pressure', aspi: 'vacuum', lava: 'sofa', vapor: 'steam', rep: 'nozzle' };

  // ── Dropdown variant ────────────────────────────────────────────────────
  if (variant === 'dropdown') {
    return <CategoryDropdown categories={categories} tab={tab} setTab={setTab} icons={CAT_ICONS} />;
  }

  // ── Cards variant ───────────────────────────────────────────────────────
  if (variant === 'cards') {
    return <CategoryCards categories={categories} tab={tab} setTab={setTab} icons={CAT_ICONS} />;
  }

  // ── Pill-row variants (shared scrollable mechanic) ──────────────────────
  const scrollRef = React.useRef(null);
  const itemRefs = React.useRef({});
  const [progress, setProgress] = React.useState(0);
  const [overflows, setOverflows] = React.useState(false);
  const [atEnd, setAtEnd] = React.useState(false);

  const measure = React.useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    const max = el.scrollWidth - el.clientWidth;
    setOverflows(max > 4);
    if (max <= 4) { setProgress(0); setAtEnd(true); return; }
    setProgress(Math.min(1, Math.max(0, el.scrollLeft / max)));
    setAtEnd(el.scrollLeft >= max - 4);
  }, []);

  React.useEffect(() => {
    measure();
    const el = scrollRef.current;
    if (!el) return;
    el.addEventListener('scroll', measure, { passive: true });
    window.addEventListener('resize', measure);
    return () => {
      el.removeEventListener('scroll', measure);
      window.removeEventListener('resize', measure);
    };
  }, [measure, variant]);

  // Peek variant: centre the active pill so prev/next peek in.
  // Real mobile browsers (iOS Safari especially) can race the initial layout —
  // the first effect can fire before fonts/text have settled and clientWidth/
  // offsetLeft come back wrong. Centre on tab change AND on resize/orientation,
  // and run an instant initial centre via rAF so the row is already positioned
  // before paint instead of doing a smooth animation from 0.
  const didInitialCenter = React.useRef(false);
  React.useEffect(() => {
    if (variant !== 'peek') return;
    didInitialCenter.current = false;
    const center = (smooth) => {
      const el = scrollRef.current;
      const pill = itemRefs.current[tab];
      if (!el || !pill) return;
      const target = pill.offsetLeft - (el.clientWidth - pill.clientWidth) / 2;
      el.scrollTo({ left: Math.max(0, target), behavior: smooth ? 'smooth' : 'auto' });
    };
    // Run twice on mount: once immediately on next frame, once on the frame
    // after, so layout has settled (fonts, images). 'auto' = instant so
    // there's no visible jump animation.
    let raf1 = 0, raf2 = 0;
    raf1 = requestAnimationFrame(() => {
      center(false);
      raf2 = requestAnimationFrame(() => {
        center(false);
        didInitialCenter.current = true;
      });
    });
    const onResize = () => center(false);
    window.addEventListener('resize', onResize);
    window.addEventListener('orientationchange', onResize);
    return () => {
      if (raf1) cancelAnimationFrame(raf1);
      if (raf2) cancelAnimationFrame(raf2);
      window.removeEventListener('resize', onResize);
      window.removeEventListener('orientationchange', onResize);
    };
  }, [variant]);

  // Smooth-centre when the user changes tab (after the initial mount centre).
  React.useEffect(() => {
    if (variant !== 'peek') return;
    if (!didInitialCenter.current) return;
    const el = scrollRef.current;
    const pill = itemRefs.current[tab];
    if (!el || !pill) return;
    const target = pill.offsetLeft - (el.clientWidth - pill.clientWidth) / 2;
    el.scrollTo({ left: Math.max(0, target), behavior: 'smooth' });
  }, [tab, variant]);

  const isFades = variant === 'fades';
  const isScrollbar = variant === 'scrollbar';
  const isWrap = variant === 'wrap';
  const isPeek = variant === 'peek';
  const isArrow = variant === 'arrow';
  const isUnderline = variant === 'underline';
  const isChips = variant === 'chips';
  const isIcons = variant === 'icons';

  const FADE_W = 56;
  const showScrollbar = isScrollbar && overflows;
  const showArrow = isArrow && overflows && !atEnd;

  const outerStyle = {
    // Use `display: block` (not flex) for the scrollport. `display: flex` +
    // `overflow-x: auto` + a single child with `marginInline: auto` is a known
    // iOS Safari/Chrome-mobile gotcha: the auto margin absorbs the scrollable
    // overflow so the peek effect silently fails on real phones (worked fine
    // in narrow desktop previews because layout was different). Block + an
    // inline-flex child renders identically AND keeps scroll behaviour sane.
    display: 'block',
    overflowX: isWrap ? 'visible' : 'auto',
    WebkitOverflowScrolling: 'touch',
    scrollSnapType: isWrap || isPeek ? 'none' : 'x proximity',
    padding: '0 16px',
    scrollBehavior: 'smooth',
    whiteSpace: 'nowrap',
    // Centre the inline-flex pill row when it FITS (desktop). When it overflows
    // (mobile), text-align is ignored for the overflowing inline child and the
    // row starts at scrollLeft 0 — so peek still works. Best of both.
    textAlign: 'center',
    ...(isFades ? {
      maskImage:
        `linear-gradient(90deg, transparent 0, #000 ${FADE_W}px, #000 calc(100% - ${FADE_W}px), transparent 100%)`,
      WebkitMaskImage:
        `linear-gradient(90deg, transparent 0, #000 ${FADE_W}px, #000 calc(100% - ${FADE_W}px), transparent 100%)`
    } : {}),
    ...(isUnderline ? { borderBottom: '1px solid var(--line)' } : {})
  };

  // Underline + chips swap the filled-pill row background for a transparent one
  const innerStyle = {
    display: 'inline-flex',
    gap: isUnderline ? 0 : (isChips ? 8 : 4),
    padding: (isUnderline || isChips) ? 0 : 6,
    background: (isUnderline || isChips) ? 'transparent' : '#EEEEF6',
    borderRadius: isWrap ? 16 : 999,
    flexShrink: 0,
    // For peek: NO marginInline:auto — we want the inner row pinned to the
    // start so scrollLeft works predictably. For other variants (wrap, fit)
    // keep auto so it centres when it fits.
    ...(isPeek ? {} : { marginInline: 'auto' }),
    ...(isWrap ? { flexWrap: 'wrap', justifyContent: 'center' } : {})
  };

  const pillStyle = (active) => {
    // Underline: text only, bottom border on active
    if (isUnderline) return {
      padding: '14px 16px', borderRadius: 0, background: 'transparent',
      color: active ? 'var(--ink)' : 'var(--ink-3)',
      fontSize: 14, fontWeight: active ? 700 : 500,
      borderBottom: active ? '2px solid var(--ink)' : '2px solid transparent',
      marginBottom: -1, // overlap the row borderBottom
      transition: 'all .2s', whiteSpace: 'nowrap'
    };
    // Chips: outline buttons, filled when active
    if (isChips) return {
      padding: '9px 18px', borderRadius: 999,
      background: active ? 'var(--ink)' : 'transparent',
      color: active ? '#fff' : 'var(--ink-2)',
      border: '1.5px solid ' + (active ? 'var(--ink)' : 'var(--line-2)'),
      fontSize: 13, fontWeight: 600,
      transition: 'all .2s', whiteSpace: 'nowrap'
    };
    // Default pill (filled active, transparent inactive)
    return {
      padding: '10px 22px', borderRadius: 999,
      fontSize: 13, fontWeight: 600,
      background: active ? 'var(--ink)' : 'transparent',
      color: active ? '#fff' : 'var(--ink-3)',
      transition: 'all .2s',
      whiteSpace: 'nowrap',
      scrollSnapAlign: isPeek ? 'center' : 'none',
      ...(isIcons ? { padding: '8px 16px', display: 'inline-flex', alignItems: 'center', gap: 8 } : {})
    };
  };

  return (
    <div style={{ position: 'relative', marginBottom: 36 }} data-tabs-style={variant}>
      <div
        ref={scrollRef}
        className={"featured-tabs-scroll" + (isScrollbar ? "" : " hide-scrollbar")}
        style={outerStyle}>
        <div style={innerStyle}>
          {categories.map((c) => {
            const active = tab === c.id;
            return (
              <button
                key={c.id}
                ref={(el) => { itemRefs.current[c.id] = el; }}
                onClick={() => setTab(c.id)}
                style={pillStyle(active)}>
                {isIcons && <Icon name={CAT_ICONS[c.id] || 'box'} size={16} strokeWidth={active ? 2 : 1.6} />}
                <span>{c.name}</span>
              </button>);
          })}
        </div>
      </div>

      {/* Scrollbar variant — custom thin progress track */}
      {showScrollbar && (
        <div style={{
          marginTop: 10, marginInline: 'auto', maxWidth: 220, height: 3, borderRadius: 999,
          background: 'rgba(0,0,0,0.08)', overflow: 'hidden', position: 'relative'
        }}>
          <div style={{
            position: 'absolute', top: 0, bottom: 0,
            width: `${Math.max(20, 100 / Math.max(1, (scrollRef.current?.scrollWidth || 1) / Math.max(1, scrollRef.current?.clientWidth || 1)))}%`,
            left: `${progress * (100 - Math.max(20, 100 / Math.max(1, (scrollRef.current?.scrollWidth || 1) / Math.max(1, scrollRef.current?.clientWidth || 1))))}%`,
            background: 'var(--ink)', borderRadius: 999, transition: 'left .15s ease-out'
          }} />
        </div>
      )}

      {/* Arrow variant — pulsing chevron pointing at off-screen content */}
      {showArrow && (
        <React.Fragment>
          <style>{`
            @keyframes rc-tabs-arrow-pulse {
              0%, 100% { transform: translate(0, -50%); opacity: .85; }
              50%      { transform: translate(6px, -50%); opacity: 1; }
            }
          `}</style>
          <div
            aria-hidden="true"
            style={{
              position: 'absolute', right: 4, top: '50%',
              width: 34, height: 34, borderRadius: '50%',
              background: '#fff', boxShadow: '0 2px 10px rgba(0,0,0,0.18)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              pointerEvents: 'none', zIndex: 2,
              animation: 'rc-tabs-arrow-pulse 1.4s ease-in-out infinite'
            }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
              strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--ink)' }}>
              <polyline points="9 6 15 12 9 18" />
            </svg>
          </div>
        </React.Fragment>
      )}
    </div>
  );
};

// ── Dropdown variant ──────────────────────────────────────────────────────
const CategoryDropdown = ({ categories, tab, setTab, icons }) => {
  const [open, setOpen] = React.useState(false);
  const rootRef = React.useRef(null);
  const active = categories.find((c) => c.id === tab);

  React.useEffect(() => {
    if (!open) return;
    const onClick = (e) => {
      if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  return (
    <div ref={rootRef} style={{ position: 'relative', marginBottom: 36, padding: '0 16px', maxWidth: 420, marginInline: 'auto' }} data-tabs-style="dropdown">
      <button
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        style={{
          width: '100%', padding: '14px 18px',
          background: '#fff', border: '1px solid var(--line)', borderRadius: 12,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          fontSize: 15, fontWeight: 600, color: 'var(--ink)',
          boxShadow: open ? '0 4px 14px rgba(0,0,0,0.08)' : 'none',
          transition: 'box-shadow .15s'
        }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>
          {active && <Icon name={icons[active.id] || 'box'} size={18} strokeWidth={1.8}/>}
          {active ? active.name : 'Elegí una categoría'}
        </span>
        <span style={{ display: 'inline-flex', transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s', color: 'var(--ink-3)' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
            strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="6 9 12 15 18 9" />
          </svg>
        </span>
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', left: 16, right: 16,
          background: '#fff', border: '1px solid var(--line)', borderRadius: 12,
          boxShadow: '0 12px 32px rgba(0,0,0,0.12)', zIndex: 30,
          overflow: 'hidden'
        }}>
          {categories.map((c) => {
            const isActive = c.id === tab;
            return (
              <button
                key={c.id}
                onClick={() => { setTab(c.id); setOpen(false); }}
                style={{
                  width: '100%', textAlign: 'left',
                  padding: '12px 18px',
                  display: 'flex', alignItems: 'center', gap: 12,
                  background: isActive ? 'var(--bg-2)' : 'transparent',
                  color: 'var(--ink)',
                  fontSize: 14, fontWeight: isActive ? 600 : 500,
                  borderBottom: '1px solid var(--line)'
                }}>
                <Icon name={icons[c.id] || 'box'} size={18} strokeWidth={1.6} />
                <span style={{ flex: 1 }}>{c.name}</span>
                {isActive && (
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                    strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="20 6 9 17 4 12" />
                  </svg>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};

// ── Cards variant ─────────────────────────────────────────────────────────
const CategoryCards = ({ categories, tab, setTab, icons }) => {
  return (
    <div style={{ marginBottom: 36 }} data-tabs-style="cards">
      <div
        className="hide-scrollbar"
        style={{
          display: 'flex', gap: 12, overflowX: 'auto', WebkitOverflowScrolling: 'touch',
          padding: '4px 16px 16px', scrollSnapType: 'x proximity'
        }}>
        {categories.map((c) => {
          const active = c.id === tab;
          return (
            <button
              key={c.id}
              onClick={() => setTab(c.id)}
              style={{
                flex: '0 0 auto',
                width: 110,
                padding: '14px 10px',
                borderRadius: 14,
                background: active ? 'var(--ink)' : '#fff',
                color: active ? '#fff' : 'var(--ink)',
                border: '1px solid ' + (active ? 'var(--ink)' : 'var(--line)'),
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                transition: 'all .2s',
                scrollSnapAlign: 'center',
                boxShadow: active ? '0 6px 18px rgba(0,0,0,0.18)' : 'none'
              }}>
              <Icon name={icons[c.id] || 'box'} size={28} strokeWidth={active ? 1.8 : 1.5} />
              <span style={{
                fontSize: 12, fontWeight: 600, lineHeight: 1.2, textAlign: 'center',
                color: active ? '#fff' : 'var(--ink-2)'
              }}>
                {c.name}
              </span>
            </button>
          );
        })}
      </div>
    </div>
  );
};

const FeaturedTabs = ({ onNavigate, onAdd, home = {} }) => {
  const { homeCards = 4, homeCardImage = 'clean', homeCardSpecs = 'show', homeCardHover = 'lift', homeCardPrice = 'stacked', homeTabsStyle = 'default' } = home;
  const { PRODUCTS, CATEGORIES } = window.RC_DATA;
  const [tab, setTab] = React.useState('hidro');
  const products = PRODUCTS.filter((p) => p.cat === tab).slice(0, 12);
  const activeCat = CATEGORIES.find((c) => c.id === tab);
  const scrollerRef = React.useRef(null);
  const [canScrollPrev, setCanScrollPrev] = React.useState(false);
  const [canScrollNext, setCanScrollNext] = React.useState(true);

  // Mobile pagination: 4 products per page (2×2 grid)
  const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' && window.innerWidth < 900);
  const [mobilePage, setMobilePage] = React.useState(0);
  const pageSize = 4;
  const totalPages = Math.ceil(products.length / pageSize);
  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < 900);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  React.useEffect(() => { setMobilePage(0); }, [tab]);

  const visibleProducts = isMobile
    ? products.slice(mobilePage * pageSize, (mobilePage + 1) * pageSize)
    : products;

  const mobileCanPrev = mobilePage > 0;
  const mobileCanNext = mobilePage < totalPages - 1;

  const updateScrollState = React.useCallback(() => {
    const el = scrollerRef.current;
    if (!el) return;
    setCanScrollPrev(el.scrollLeft > 4);
    setCanScrollNext(el.scrollLeft < el.scrollWidth - el.clientWidth - 4);
  }, []);

  React.useEffect(() => {
    updateScrollState();
  }, [tab, updateScrollState]);

  const scrollBy = (dir) => {
    if (isMobile) {
      setMobilePage((p) => Math.max(0, Math.min(totalPages - 1, p + dir)));
      return;
    }
    const el = scrollerRef.current;
    if (!el) return;
    const card = el.querySelector('[data-card]');
    const step = card ? card.getBoundingClientRect().width + 16 : el.clientWidth * 0.8;
    el.scrollBy({ left: dir * step, behavior: 'smooth' });
  };

  return (
    <section style={{ padding: '80px 0 30px' }}>
      <div className="container">
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <div className="mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 14 }}>
            Nuestros equipos
          </div>
          <h2 style={{ fontSize: 'clamp(28px, 4vw, 40px)', fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
            Los más elegidos por nuestros clientes
          </h2>
        </div>

        <CategoryTabs
          categories={CATEGORIES}
          tab={tab}
          setTab={setTab}
          variant={homeTabsStyle}
        />

        {/* Carousel */}
        <div style={{ position: 'relative' }}>
          {/* Prev arrow */}
          <button
            onClick={() => scrollBy(-1)}
            aria-label="Anterior"
            disabled={isMobile ? !mobileCanPrev : !canScrollPrev}
            style={{
              position: 'absolute', left: -22, top: '40%', transform: 'translateY(-50%)',
              width: 44, height: 44, borderRadius: '50%',
              background: '#fff', color: 'var(--ink)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 4px 14px rgba(0,0,0,0.12)',
              border: '1px solid var(--line)',
              zIndex: 5,
              opacity: (isMobile ? mobileCanPrev : canScrollPrev) ? 1 : 0.35,
              cursor: (isMobile ? mobileCanPrev : canScrollPrev) ? 'pointer' : 'default',
              transition: 'opacity .2s',
            }}>
            <span style={{ display: 'inline-flex', transform: 'rotate(180deg)' }}>
              <Icon name="arrowRight" size={18}/>
            </span>
          </button>

          {/* Next arrow */}
          <button
            onClick={() => scrollBy(1)}
            aria-label="Siguiente"
            disabled={isMobile ? !mobileCanNext : !canScrollNext}
            style={{
              position: 'absolute', right: -22, top: '40%', transform: 'translateY(-50%)',
              width: 44, height: 44, borderRadius: '50%',
              background: '#fff', color: 'var(--ink)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 4px 14px rgba(0,0,0,0.12)',
              border: '1px solid var(--line)',
              zIndex: 5,
              opacity: (isMobile ? mobileCanNext : canScrollNext) ? 1 : 0.35,
              cursor: (isMobile ? mobileCanNext : canScrollNext) ? 'pointer' : 'default',
              transition: 'opacity .2s',
            }}>
            <Icon name="arrowRight" size={18}/>
          </button>

          {/* Scroll container */}
          <div
            ref={scrollerRef}
            onScroll={updateScrollState}
            className="hide-scrollbar home-products-scroller"
            style={{
              display: 'grid',
              gridAutoFlow: 'column',
              gridAutoColumns: `calc((100% - ${(homeCards - 1) * 16}px) / ${homeCards})`,
              gap: 16,
              overflowX: 'auto',
              scrollSnapType: 'x mandatory',
              scrollBehavior: 'smooth',
              padding: '4px 0 12px',
              scrollbarWidth: 'none',
              msOverflowStyle: 'none',
            }}>
            {visibleProducts.map((p, i) => (
              <div key={p.id} data-card style={{ scrollSnapAlign: 'start' }}>
                <ProductCard product={p} onNavigate={onNavigate} onAdd={onAdd} variant="industrial" priority={i < 2} cardImage={homeCardImage} cardSpecs={homeCardSpecs} cardHover={homeCardHover} priceStyle={homeCardPrice}/>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 40 }}>
          <button onClick={() => onNavigate(`/categoria/${activeCat?.slug || ''}`)}
          className="btn btn-ghost ver-todos-btn"
          style={{ padding: '14px 28px', borderRadius: 999, fontSize: 14 }}>
            {window.verTodosLabel ? window.verTodosLabel(activeCat?.name || 'productos') : `Ver todos los ${activeCat?.name || 'productos'}`} <Icon name="arrowRight" size={14} />
          </button>
        </div>
      </div>
    </section>);

};

/* ── Editorial banner (service + promo) ──────────── */
const PromoBanners = ({ onNavigate }) =>
<section style={{ padding: '40px 0' }}>
    <div className="container" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }} className="promo-grid">
      <div style={{ background: 'var(--ink)', color: '#fff', borderRadius: 'var(--r-lg)', padding: 40, position: 'relative', overflow: 'hidden', minHeight: 280 }}>
        <div style={{ position: 'absolute', right: -60, top: -60, width: 300, height: 300, borderRadius: '50%', background: 'var(--accent)', opacity: 0.15 }} />
        <div style={{ position: 'relative', maxWidth: 480 }}>
          <Badge variant="red">Oferta del mes</Badge>
          <h3 style={{ fontSize: 40, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.05, marginTop: 16 }}>
            Hidrolavadoras<br />hasta <span style={{ color: 'var(--accent)' }}>30% OFF</span>
          </h3>
          <p style={{ fontSize: 15, color: 'rgba(255,255,255,0.7)', marginTop: 14, maxWidth: 380 }}>
            Selección de modelos trifásicos y agua caliente. Stock limitado — hasta agotar.
          </p>
          <button className="btn btn-primary" style={{ marginTop: 24 }} onClick={() => onNavigate('/categoria/hidrolavadoras')}>
            Ver ofertas <Icon name="arrowRight" size={14} />
          </button>
        </div>
        <div className="mono" style={{ position: 'absolute', bottom: 20, right: 28, fontSize: 11, letterSpacing: '0.1em', color: 'rgba(255,255,255,0.4)' }}>
          — hasta 30/04
        </div>
      </div>
      <div style={{ background: 'var(--bg-2)', borderRadius: 'var(--r-lg)', padding: 32, minHeight: 280, display: 'flex', flexDirection: 'column' }}>
        <Icon name="wrench" size={32} strokeWidth={1.4} />
        <h3 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em', marginTop: 'auto' }}>
          Servicio técnico propio
        </h3>
        <p className="t-body" style={{ marginTop: 8 }}>
          Taller en Haedo. Reparamos todas las marcas.
        </p>
        <button className="btn btn-dark" style={{ marginTop: 20, alignSelf: 'start' }} onClick={() => onNavigate('/reparaciones')}>
          Pedir presupuesto <Icon name="arrowRight" size={14} />
        </button>
      </div>
    </div>
  </section>;


/* ── Why us stats ─────────────────── */
const CountUp = ({ target, prefix = '', suffix = '', duration = 1400, format = 'es-AR' }) => {
  const [value, setValue] = React.useState(0);
  const [started, setStarted] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (!ref.current || started) return;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        setStarted(true);
        obs.disconnect();
      }
    }, { threshold: 0.4 });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [started]);

  React.useEffect(() => {
    if (!started) return;
    const startTime = performance.now();
    let rafId;
    const tick = (now) => {
      const t = Math.min(1, (now - startTime) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setValue(Math.round(target * eased));
      if (t < 1) rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, [started, target, duration]);

  const formatted = new Intl.NumberFormat(format).format(value);
  return <span ref={ref}>{prefix}{formatted}{suffix}</span>;
};

const WhyUs = () => {
  const stats = [
    { target: 1400, prefix: '+', suffix: '',   l: 'Productos en stock' },
    { target: 15,   prefix: '+', suffix: '',   l: 'Años equipando pros' },
    { target: 8000, prefix: '+', suffix: '',   l: 'Clientes satisfechos' },
    { target: 24,   prefix: '',  suffix: 'hs', l: 'Despacho promedio' },
  ];
  const pillars = [
  { i: 'shield', t: 'Garantía oficial', d: 'Todos los equipos con respaldo directo del fabricante. 12 meses promedio.' },
  { i: 'truck', t: 'Logística propia', d: 'Envío gratis CABA/GBA en 48hs. Al interior por Andreani o transporte a cotizar.' },
  { i: 'wrench', t: 'Service en Haedo', d: 'Técnicos certificados. Presupuesto sin cargo. Reparamos todas las marcas.' },
  { i: 'credit', t: 'Financiación real', d: '6 cuotas sin interés Visa/Master. 5% OFF con transferencia bancaria.' }];

  return (
    <section className="whyus-section" style={{ padding: '10px 0 80px' }}>
      <div className="container">
        <h2 className="h-1" style={{ marginBottom: 4 }}>Garantía</h2>
        <p style={{ fontSize: 18, color: 'var(--ink-3)', marginBottom: 40 }}>El respaldo que necesitás.</p>

        <div className="whyus-pillars" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 24, marginBottom: 48 }}>
          {pillars.map((p) =>
          <div key={p.t} style={{ borderTop: '1px solid var(--line)', paddingTop: 20 }}>
              <Icon name={p.i} size={28} strokeWidth={1.4} />
              <h3 style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', marginTop: 16 }}>{p.t}</h3>
              <p className="t-body" style={{ marginTop: 6 }}>{p.d}</p>
            </div>
          )}
        </div>

        <div className="whyus-stats" style={{ background: '#a00e0c', color: '#fff', borderRadius: 'var(--r-lg)', padding: '40px 32px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 30, textAlign: 'center' }}>
          {stats.map((s) =>
          <div key={s.l}>
              <div style={{ fontFamily: '"Galano", var(--font-sans)', fontSize: 48, fontWeight: 800, letterSpacing: '-0.03em' }}>
                <CountUp target={s.target} prefix={s.prefix} suffix={s.suffix}/>
              </div>
              <div style={{ fontFamily: '"Galano", var(--font-sans)', fontSize: 11, fontWeight: 400, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#fff', marginTop: 4 }}>{s.l}</div>
            </div>
          )}
        </div>
      </div>
    </section>);

};

/* ── Testimonials ─────────────────── */
const Testimonials = () => {
  const { REVIEWS } = window.RC_DATA;
  return (
    <section style={{ padding: '40px 0 80px' }}>
      <div className="container">
        <h2 className="h-1" style={{ marginBottom: 4 }}>Testimonios</h2>
        <p style={{ fontSize: 18, color: 'var(--ink-3)', marginBottom: 40 }}>Quienes ya trabajan con nosotros.</p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
          {REVIEWS.map((r) =>
          <div key={r.name} style={{ padding: 28, border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', background: 'var(--surface)' }}>
              <Stars value={r.rating} size={14} />
              <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 14 }}>"{r.text}"</p>
              <div style={{ marginTop: 20, paddingTop: 14, borderTop: '1px dashed var(--line)', display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, color: 'var(--ink-3)' }}>
                  {r.name[0]}
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{r.name}</div>
                  <div className="mono t-xs" style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}>{r.role}</div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

};

const HomePage = ({ onNavigate, onAdd, home = {} }) => {
  const Hero = HeroSlider;
  return (
    <>
      <Hero onNavigate={onNavigate} />
      <Marquee />
      <FeaturedTabs onNavigate={onNavigate} onAdd={onAdd} home={home} />
      <WhyUs />
      <Testimonials />
    </>);

};

Object.assign(window, { HomePage, Marquee });