/* Shop (tienda), PDP, Cart drawer — combined */

const fmtARS = (n) => window.RC_DATA.ARS(n);

/* Carrusel horizontal de usos L3 con flechas prev/next */
/* Imágenes reales de portadas de "uso" (override del dummy picsum).
   Key: segment.id → { item: ruta }. Las imágenes deben ser 192x192px.
   Soltá los archivos en /uploads/usos/ y aparecen automáticamente.
   Si la ruta no existe todavía, cae al placeholder (picsum). */
const USO_IMAGES = {
  domesticas: {
    'Para autos y motos':  '/uploads/usos/domesticas-autos-y-motos.jpg',
    'Para jardín y patio': '/uploads/usos/domesticas-jardin-y-patio.jpg',
    'Para el hogar':       '/uploads/usos/domesticas-el-hogar.jpg',
    'Para piletas':        '/uploads/usos/domesticas-piletas.jpg?v=2',
  },
};

const UsoCarousel = ({ segment, category, onNavigate }) => {
  const scrollRef = React.useRef(null);
  const [canLeft,  setCanLeft]  = React.useState(false);
  const [canRight, setCanRight] = React.useState(true);
  const STEP = 202 * 3; // 3 tiles por click

  const updateArrows = () => {
    const el = scrollRef.current;
    if (!el) return;
    setCanLeft(el.scrollLeft > 4);
    setCanRight(el.scrollLeft < el.scrollWidth - el.clientWidth - 4);
  };

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

  const scroll = (dir) => {
    scrollRef.current?.scrollBy({ left: dir * STEP, behavior: 'smooth' });
  };

  const ArrowBtn = ({ dir, enabled, label }) => (
    <button
      onClick={() => scroll(dir)}
      disabled={!enabled}
      aria-label={label}
      style={{
        position: 'absolute', [dir < 0 ? 'left' : 'right']: -14,
        top: '50%', transform: 'translateY(-50%)',
        zIndex: 2,
        width: 36, height: 36, borderRadius: '50%',
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        boxShadow: '0 2px 8px rgba(0,0,0,0.12)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: enabled ? 'var(--ink)' : 'var(--ink-4)',
        cursor: enabled ? 'pointer' : 'default',
        opacity: enabled ? 1 : 0.3,
        transition: 'opacity .15s',
      }}>
      <Icon name="chevronDown" size={16} style={{ transform: `rotate(${dir < 0 ? 90 : -90}deg)` }}/>
    </button>
  );

  return (
    <div style={{ position: 'relative', padding: '0 20px' }}>
      <style>{`.uso-scroll::-webkit-scrollbar{display:none}`}</style>
      <ArrowBtn dir={-1} enabled={canLeft}  label="Anterior" />
      <div
        ref={scrollRef}
        className="uso-scroll"
        onScroll={updateArrows}
        style={{
          display: 'flex', gap: 10,
          overflowX: 'auto', paddingBottom: 4,
          scrollSnapType: 'x mandatory',
          msOverflowStyle: 'none', scrollbarWidth: 'none',
        }}>
        {segment.items.map(item => (
          <a key={item} href="#"
            onClick={(e) => { e.preventDefault(); onNavigate(`/categoria/${category.slug}/${segment.slug}?uso=${encodeURIComponent(item)}`); }}
            style={{
              position: 'relative', flexShrink: 0,
              width: 192, height: 192,
              borderRadius: 'var(--r-md)', overflow: 'hidden', background: 'var(--ink)',
              textDecoration: 'none', scrollSnapAlign: 'start',
              transition: 'opacity .15s',
            }}
            onMouseEnter={e => e.currentTarget.style.opacity = '0.82'}
            onMouseLeave={e => e.currentTarget.style.opacity = '1'}>
            <img
              src={(USO_IMAGES[segment.id] && USO_IMAGES[segment.id][item]) || `https://picsum.photos/seed/rc-${segment.id}-${item.replace(/\s/g,'')}/384/384`}
              alt={item} loading="lazy"
              onError={e => {
                const t = e.currentTarget;
                const pic = `https://picsum.photos/seed/rc-${segment.id}-${item.replace(/\s/g,'')}/384/384`;
                if (!t.dataset.fb) { t.dataset.fb = '1'; t.src = pic; }
                else { t.style.display = 'none'; }
              }}
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(179,15,13,0.85) 0%, rgba(179,15,13,0.1) 65%, transparent 100%)' }} />
            <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '10px 12px', color: '#fff', textAlign: 'center' }}>
              <div style={{ fontSize: 12, fontWeight: 500, lineHeight: 1.25 }}>{item}</div>
            </div>
          </a>
        ))}
        {/* Card "Ver todos los usos" */}
        <a href="#"
          onClick={(e) => { e.preventDefault(); onNavigate(`/categoria/${category.slug}/${segment.slug}`); }}
          style={{
            flexShrink: 0, width: 192, height: 192,
            borderRadius: 'var(--r-md)', scrollSnapAlign: 'start',
            border: '1.5px dashed var(--line-2)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8,
            textDecoration: 'none', color: 'var(--ink-3)',
            transition: 'border-color .15s, color .15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.color = 'var(--accent)'; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-2)'; e.currentTarget.style.color = 'var(--ink-3)'; }}>
          <Icon name="arrowRight" size={20}/>
          <span style={{ fontSize: 12, fontWeight: 600, textAlign: 'center', lineHeight: 1.3 }}>Ver todos<br/>los usos</span>
        </a>
      </div>
      <ArrowBtn dir={1} enabled={canRight} label="Siguiente" />
    </div>
  );
};

/* Sticky buy bar that appears after scrolling past the main CTA */
const StickyBuyBar = ({ product, onAdd, added }) => {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 700);
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  if (!show) return null;
  return (
    <div data-sticky-buy-bar="true" style={{
      position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 60,
      background: 'var(--surface)', borderTop: '1px solid var(--line)',
      boxShadow: '0 -6px 24px rgba(0,0,0,0.08)',
      padding: '12px 24px',
      animation: 'slideUp .25s ease'
    }}>
      <style>{`@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }`}</style>
      <div className="container" style={{ display: 'flex', alignItems: 'center', gap: 16, padding: 0 }}>
        <div style={{ width: 44, height: 44, background: '#FFF', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {product.image && <img src={product.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 4 }} />}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{window.RC_DATA.formatProductName(product.name)}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
            <strong style={{ color: 'var(--ink)', fontSize: 14 }}>{fmtARS(product.price)}</strong>
            <span style={{ marginLeft: 8 }}>6× {fmtARS(Math.round(product.price / 6))} s/i</span>
          </div>
        </div>
        <button className={`btn btn-primary${added ? ' btn-add-zoom' : ''}`} style={{ padding: '12px 20px', fontSize: 14, whiteSpace: 'nowrap' }} onClick={onAdd}>
          {added ? <><Icon name="check" size={15} /> Agregado</> : <><Icon name="cart" size={15} /> Agregar al carrito</>}
        </button>
      </div>
    </div>);

};

/* ────────── TIENDA ────────── */
const ShopPage = ({ route, onNavigate, onAdd }) => {
  const { PRODUCTS, CATEGORIES, BRANDS } = window.RC_DATA;
  const parts = route.startsWith('/categoria/') ? route.split('/') : [];
  const slug    = parts[2] ? parts[2].split('?')[0] : null;
  const segSlug = parts[3] ? parts[3].split('?')[0] : null;
  const category = CATEGORIES.find((c) => c.slug === slug);
  const segment  = category?.segments?.find(s => s.slug === segSlug) || null;

  const [brands, setBrands] = React.useState([]);
  const [price, setPrice] = React.useState([0, 3000000]);
  const [sub, setSub] = React.useState([]);
  const [inStock, setInStock] = React.useState(false);
  const [sort, setSort] = React.useState('relevance');
  const [view, setView] = React.useState('grid');
  // Dynamic tech filters (by spec key)
  const [specFilters, setSpecFilters] = React.useState({}); // { Presión: ['160 bar','200 bar'], ... }
  const [openSpec, setOpenSpec] = React.useState(null);
  const [mobileFilters, setMobileFilters] = React.useState(false);

  // Track mobile so we can render the spec-filter dropdown as a bottom sheet
  // instead of an absolutely-positioned popover (which was getting clipped by
  // the chip row's overflow-x: auto on phones — that's why "no se veía nada").
  const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' && window.innerWidth < 900);
  React.useEffect(() => {
    const onR = () => setIsMobile(window.innerWidth < 900);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);

  // Refs for "peek" auto-centering of the horizontal mobile chip strips.
  const catChipsRef = React.useRef(null);
  const specChipsRef = React.useRef(null);
  const subChipsRef = React.useRef(null);

  // Centre the active category chip so prev/next peek in.
  React.useEffect(() => {
    if (!isMobile) return;
    const el = catChipsRef.current;
    if (!el) return;
    const active = el.querySelector('a.is-active');
    if (!active) return;
    const target = active.offsetLeft - (el.clientWidth - active.clientWidth) / 2;
    const center = () => el.scrollTo({ left: Math.max(0, target), behavior: 'auto' });
    // Two rAFs so layout has settled on mobile before measuring.
    const r1 = requestAnimationFrame(() => { center(); requestAnimationFrame(center); });
    return () => cancelAnimationFrame(r1);
  }, [isMobile, category]);

  // Centre whichever spec chip is currently open (or has filters applied).
  // NB: each chip button sits inside a `position: relative` wrapper div (needed
  // for the dropdown popover on desktop), which makes that wrapper the
  // button's offsetParent — so `offsetLeft` returns 0 instead of the chip's
  // position in the scroll strip. Use getBoundingClientRect so the math is
  // independent of the offsetParent chain.
  React.useEffect(() => {
    if (!isMobile) return;
    const el = specChipsRef.current;
    if (!el) return;
    const target = el.querySelector('[data-chip-open="true"]') || el.querySelector('[data-chip-active="true"]');
    if (!target) return;
    const doCenter = (smooth) => {
      const elBox = el.getBoundingClientRect();
      const tBox = target.getBoundingClientRect();
      const chipLeftInScroll = (tBox.left - elBox.left) + el.scrollLeft;
      const left = chipLeftInScroll - (el.clientWidth - tBox.width) / 2;
      el.scrollTo({ left: Math.max(0, left), behavior: smooth ? 'smooth' : 'auto' });
    };
    const r1 = requestAnimationFrame(() => {
      doCenter(true);
      requestAnimationFrame(() => doCenter(true));
    });
    return () => cancelAnimationFrame(r1);
  }, [openSpec, specFilters, isMobile]);

  // Centre the first active subcategory chip (or "Todas") so prev/next peek in.
  React.useEffect(() => {
    if (!isMobile) return;
    const el = subChipsRef.current;
    if (!el) return;
    let target = el.querySelector('button.is-active');
    if (!target) target = el.querySelector('button');
    if (!target) return;
    const left = target.offsetLeft - (el.clientWidth - target.clientWidth) / 2;
    const r1 = requestAnimationFrame(() => {
      el.scrollTo({ left: Math.max(0, left), behavior: 'smooth' });
      requestAnimationFrame(() => el.scrollTo({ left: Math.max(0, left), behavior: 'smooth' }));
    });
    return () => cancelAnimationFrame(r1);
  }, [isMobile, category, sub]);

  let items = PRODUCTS;
  if (category) items = items.filter((p) => p.cat === category.id);
  if (brands.length) items = items.filter((p) => brands.includes(p.brand));
  if (sub.length) items = items.filter((p) => sub.includes(p.sub));
  if (inStock) items = items.filter((p) => p.stock > 0);
  items = items.filter((p) => p.price >= price[0] && p.price <= price[1]);

  // Apply spec filters
  for (const [key, vals] of Object.entries(specFilters)) {
    if (vals.length) items = items.filter((p) => p.specs && vals.includes(p.specs[key]));
  }

  if (sort === 'price-asc') items = [...items].sort((a, b) => a.price - b.price);
  if (sort === 'price-desc') items = [...items].sort((a, b) => b.price - a.price);
  if (sort === 'rating') items = [...items].sort((a, b) => b.rating - a.rating);

  // Build spec filter options from category pool (not from filtered items, so counts stay stable)
  const specPool = category ? PRODUCTS.filter((p) => p.cat === category.id) : PRODUCTS;
  const specOptions = {};
  for (const p of specPool) {
    for (const [k, v] of Object.entries(p.specs || {})) {
      if (!v) continue;
      (specOptions[k] ||= new Map()).set(v, (specOptions[k]?.get(v) || 0) + 1);
    }
  }
  // Keep only specs with 2+ distinct values
  const realSpecKeys = Object.entries(specOptions).
  filter(([, m]) => m.size >= 2).
  sort((a, b) => b[1].size - a[1].size).
  map(([k]) => k);

  // Always-visible filter keys (dummy values when no real data)
  const dummyKeys = ['Voltaje', 'Presión', 'Caudal', 'Motor', 'Bomba', 'Potencia'];
  const dummyValues = {
    'Voltaje': ['220V', '380V', '12V'],
    'Presión': ['100 bar', '150 bar', '200 bar', '250 bar'],
    'Caudal': ['300 L/h', '450 L/h', '600 L/h', '900 L/h'],
    'Motor': ['Inducción', 'Universal', 'Explosión'],
    'Bomba': ['Pistones cerámicos', 'Axial', 'Cigüeñal'],
    'Potencia': ['1500 W', '2000 W', '3000 W', '7 HP']
  };
  // Merge: real keys first, then dummies not already present
  const activeSpecKeys = [...new Set([...realSpecKeys, ...dummyKeys])].slice(0, 6);

  const toggleSpec = (key, val) => {
    setSpecFilters((prev) => {
      const cur = prev[key] || [];
      const next = cur.includes(val) ? cur.filter((v) => v !== val) : [...cur, val];
      return { ...prev, [key]: next };
    });
  };
  const specFilterCount = Object.values(specFilters).reduce((n, v) => n + (v?.length || 0), 0);

  const FilterGroup = ({ title, children }) =>
  <div style={{ borderBottom: '1px solid var(--line)', paddingBottom: 20, marginBottom: 20 }}>
      <h4 className="mono" style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 14 }}>{title}</h4>
      {children}
    </div>;


  const Chk = ({ checked, onChange, label, count }) =>
  <label style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', cursor: 'pointer', fontSize: 14 }}>
      <span style={{
      width: 16, height: 16, border: '1.5px solid ' + (checked ? 'var(--ink)' : 'var(--line-2)'),
      borderRadius: 3, display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: checked ? 'var(--ink)' : 'transparent'
    }}>
        {checked && <Icon name="check" size={11} className="" />}
      </span>
      <span style={{ flex: 1, color: 'var(--ink-2)' }}>{label}</span>
      {count !== undefined && <span className="mono t-xs">{count}</span>}
      <input type="checkbox" checked={checked} onChange={onChange} style={{ display: 'none' }} />
    </label>;


  return (
    <div style={{ background: 'var(--bg)', minHeight: '80vh' }}>
      {/* Breadcrumb + title */}
      <div className="shop-head" style={{ background: 'var(--surface)', borderBottom: '1px solid var(--line)', padding: '32px 0 40px' }}>
        <div className="container">
          <div className="mono t-xs" style={{ textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 14 }}>
            <a href="#" onClick={(e) => {e.preventDefault();onNavigate('/');}}>Inicio</a>
            <span style={{ margin: '0 8px', color: 'var(--ink-4)' }}>/</span>
            <a href="#" onClick={(e) => {e.preventDefault();onNavigate('/tienda');}}>Tienda</a>
            {category && <>
              <span style={{ margin: '0 8px', color: 'var(--ink-4)' }}>/</span>
              <a href="#" onClick={(e) => {e.preventDefault();onNavigate(`/categoria/${category.slug}`);}}>{category.name}</a>
            </>}
            {segment && <>
              <span style={{ margin: '0 8px', color: 'var(--ink-4)' }}>/</span>
              <span>{segment.name}</span>
            </>}
          </div>
          <div className="shop-head-row" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', flexWrap: 'wrap', gap: 16 }}>
            <h1 className="h-1">{segment ? segment.name : category ? category.name : 'Catálogo completo'}</h1>
            <div className="mono t-small">{items.length} productos · Stock real</div>
          </div>
          {/* Mobile: horizontal category quick-nav chips */}
          <div className="shop-cat-chips" ref={catChipsRef}>
            <a href="#" onClick={(e) => {e.preventDefault();onNavigate('/tienda');}}
            className={!category ? 'is-active' : ''}>Todos</a>
            {CATEGORIES.map((c) =>
            <a key={c.id} href="#" onClick={(e) => {e.preventDefault();onNavigate(`/categoria/${c.slug}`);}}
            className={category?.id === c.id ? 'is-active' : ''}>{c.name}</a>
            )}
          </div>
          {/* Mobile: subcategory chips for the active category */}
          {category && category.sub?.length > 0 &&
          <div className="shop-sub-chips" ref={subChipsRef}>
            {(() => {
              // Build list of subs with their counts, hide empty ones.
              const subs = category.sub
                .map((s) => ({ s, n: PRODUCTS.filter((p) => p.cat === category.id && p.sub === s).length }))
                .filter((x) => x.n > 0);
              if (subs.length === 0) return null;
              return (
                <React.Fragment>
                  <button onClick={() => setSub([])}
                    className={sub.length === 0 ? 'is-active' : ''}
                    data-sub-chip="all">Todas</button>
                  {subs.map(({ s, n }) => {
                    const checked = sub.includes(s);
                    return (
                      <button key={s}
                        onClick={() => setSub((x) => x.includes(s) ? x.filter((v) => v !== s) : [...x, s])}
                        className={checked ? 'is-active' : ''}
                        data-sub-chip={s}>
                        {s} <span className="shop-sub-chip-count">({n})</span>
                      </button>);
                  })}
                </React.Fragment>);
            })()}
          </div>
          }
        </div>
      </div>

      {/* Tarjetas — segmentos si la categoría tiene árbol de usos, categorías globales si no */}
      {!isMobile && (
        <div className="container" style={{ padding: '24px 24px 0' }}>
          {category?.segments ? (
            segment ? (
              <UsoCarousel segment={segment} category={category} onNavigate={onNavigate} />
            ) : (
              /* EN L1 (ej: /hidrolavadoras) — mostrar los segmentos L2 */
              <div style={{ display: 'grid', gridTemplateColumns: `repeat(${category.segments.length}, minmax(0, 1fr))`, gap: 12 }}>
                {category.segments.map(seg => (
                  <a key={seg.id} href="#" className="cat-tile"
                    onClick={(e) => { e.preventDefault(); onNavigate(`/categoria/${category.slug}/${seg.slug}`); }}
                    style={{
                      position: 'relative', display: 'block', aspectRatio: '4 / 3',
                      borderRadius: 'var(--r-md)', overflow: 'hidden', background: 'var(--ink)',
                      textDecoration: 'none',
                    }}>
                    <img src={`https://picsum.photos/seed/rc-${seg.id}/600/450`} alt={seg.name} loading="lazy"
                      onError={e => { e.currentTarget.style.display = 'none'; }}
                      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(179,15,13,0.78) 0%, rgba(179,15,13,0.15) 55%, transparent 100%)' }} />
                    <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '12px 14px', color: '#fff', textAlign: 'center' }}>
                      <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em', lineHeight: 1.15 }}>{seg.name}</div>
                      {seg.items.length > 0 && <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.82)', marginTop: 2 }}>{seg.items.length} usos</div>}
                    </div>
                  </a>
                ))}
              </div>
            )
          ) : (
            /* Otras categorías: grid global de categorías (comportamiento original) */
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${CATEGORIES.length}, minmax(0, 1fr))`, gap: 12 }}>
              {CATEGORIES.map((c) => {
                const active = category?.id === c.id;
                return (
                  <a key={c.id} href="#" className="cat-tile"
                    onClick={(e) => { e.preventDefault(); onNavigate(`/categoria/${c.slug}`); }}
                    style={{
                      position: 'relative', display: 'block', aspectRatio: '4 / 3',
                      borderRadius: 'var(--r-md)', overflow: 'hidden', background: 'var(--ink)',
                      outline: active ? '2px solid var(--accent)' : 'none', outlineOffset: 2
                    }}>
                    <img src={`https://picsum.photos/seed/rc-${c.id}/600/450`} alt={c.name} loading="lazy"
                      onError={(e) => { e.currentTarget.style.display = 'none'; }}
                      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(179,15,13,0.78) 0%, rgba(179,15,13,0.15) 55%, rgba(179,15,13,0) 100%)' }} />
                    <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '12px 14px', color: '#fff', textAlign: 'center' }}>
                      <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em', lineHeight: 1.15 }}>{c.name}</div>
                      <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.82)', marginTop: 2 }}>{c.count} productos</div>
                    </div>
                  </a>);
              })}
            </div>
          )}
        </div>
      )}

      <div className="container shop-grid" style={{ padding: '28px 24px' }}>
        {/* Mobile filter toggle (hidden on mobile in favor of the toolbar chip) */}
        <button className="show-mobile btn btn-ghost shop-filter-fullbtn" onClick={() => setMobileFilters(true)}
        style={{ marginBottom: 12, width: '100%', justifyContent: 'center', alignItems: 'center' }}>
          <Icon name="filter" size={14} /> Filtros {specFilterCount + brands.length + sub.length + (inStock ? 1 : 0) > 0 ? `(${specFilterCount + brands.length + sub.length + (inStock ? 1 : 0)})` : ''}
        </button>
        {/* Sidebar filters */}
        <aside className={'shop-side' + (mobileFilters ? ' open' : '')}>
          <button className="show-mobile" onClick={() => setMobileFilters(false)}
          style={{ position: 'absolute', top: 12, right: 12, padding: 10 }}>
            <Icon name="close" size={18} />
          </button>
          <FilterGroup title="Categorías">
            <button onClick={() => onNavigate('/tienda')}
            style={{ display: 'flex', width: '100%', padding: '6px 0', fontSize: 14, color: !category ? 'var(--accent)' : 'var(--ink-2)', fontWeight: !category ? 600 : 400 }}>
              Todos los productos
            </button>
            {CATEGORIES.map((c) => {
              const isActive = category?.id === c.id;
              const isOpen = isActive;
              return (
                <div key={c.id}>
                  <button onClick={() => onNavigate(`/categoria/${c.slug}`)}
                  style={{
                    display: 'flex', justifyContent: 'space-between', width: '100%', padding: '6px 0',
                    fontSize: 14, color: isActive ? 'var(--accent)' : 'var(--ink-2)',
                    fontWeight: isActive ? 600 : 500
                  }}>
                    <span style={{ color: isActive ? 'rgb(179, 15, 13)' : 'var(--ink-2)' }}>{c.name}</span>
                    <span className="t-xs" style={{ color: 'var(--ink-4)' }}>{c.count}</span>
                  </button>
                  {isOpen && c.sub?.length > 0 &&
                  <div style={{ paddingLeft: 14, borderLeft: '1px solid var(--line)', marginLeft: 2, marginTop: 2, marginBottom: 6 }}>
                      {c.sub.map((s) => {
                      const checked = sub.includes(s);
                      const count = PRODUCTS.filter((p) => p.cat === c.id && p.sub === s).length;
                      if (count === 0) return null;
                      return (
                        <button key={s} onClick={() => setSub((x) => x.includes(s) ? x.filter((v) => v !== s) : [...x, s])}
                        style={{
                          display: 'flex', justifyContent: 'space-between', width: '100%', padding: '5px 8px',
                          fontSize: 13, color: checked ? 'var(--accent)' : 'var(--ink-3)',
                          fontWeight: checked ? 600 : 400,
                          background: checked ? 'rgba(227,6,19,0.06)' : 'transparent',
                          borderRadius: 4
                        }}>
                            <span>{s}</span>
                            <span className="t-xs">{count}</span>
                          </button>);

                    })}
                    </div>
                  }
                </div>);

            })}
          </FilterGroup>

          <FilterGroup title="Marca">
            {[...BRANDS].sort((a, b) => {
              // POWERCLEAN always first; everything else alphabetical.
              if (a === 'POWERCLEAN') return -1;
              if (b === 'POWERCLEAN') return 1;
              return a.localeCompare(b);
            }).map((b) =>
            <Chk key={b} checked={brands.includes(b)}
            onChange={() => setBrands((x) => x.includes(b) ? x.filter((v) => v !== b) : [...x, b])}
            label={b} />
            )}
          </FilterGroup>

          <FilterGroup title="Precio">
            <div className="mono t-small" style={{ marginBottom: 10 }}>{fmtARS(price[0])} — {fmtARS(price[1])}</div>
            <input type="range" min="0" max="3000000" step="50000" value={price[1]}
            onChange={(e) => setPrice([0, parseInt(e.target.value)])}
            style={{ width: '100%' }} />
          </FilterGroup>

          <FilterGroup title="Disponibilidad">
            <Chk checked={inStock} onChange={() => setInStock(!inStock)} label="Solo con stock" />
          </FilterGroup>

          <button className="btn btn-ghost" style={{ width: '100%' }}
          onClick={() => {setBrands([]);setSub([]);setPrice([0, 3000000]);setInStock(false);setSpecFilters({});}}>
            Limpiar filtros
          </button>
        </aside>

        <div>
          {/* Tech spec filter bar (chips with dropdowns) */}
          {activeSpecKeys.length > 0 &&
          <div ref={specChipsRef} className="shop-spec-chips" style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, flexWrap: 'wrap', padding: '14px 16px', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)' }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--accent)', fontWeight: 600 }}>Filtrar</span>
              {activeSpecKeys.map((key) => {
              const activeVals = specFilters[key] || [];
              const realMap = specOptions[key];
              const values = realMap ?
              [...realMap.entries()].sort((a, b) => b[1] - a[1]) :
              (dummyValues[key] || []).map((v) => [v, null]);
              const isOpen = openSpec === key;
              return (
                <div key={key} style={{ position: 'relative' }}>
                    <button onClick={() => setOpenSpec((o) => o === key ? null : key)}
                  data-chip-open={isOpen ? 'true' : 'false'}
                  data-chip-active={activeVals.length > 0 ? 'true' : 'false'}
                  style={{
                    padding: '8px 14px', border: '1.5px solid ' + (activeVals.length ? '#B30F0D' : 'var(--line-2)'),
                    background: activeVals.length ? '#B30F0D' : 'var(--surface)',
                    color: activeVals.length ? '#fff' : 'var(--ink-2)',
                    borderRadius: 6, fontSize: 13, fontWeight: 500,
                    display: 'inline-flex', alignItems: 'center', gap: 6
                  }}>
                      {key}
                      {activeVals.length > 0 && <span style={{ background: 'rgba(255,255,255,0.25)', borderRadius: 999, padding: '1px 7px', fontSize: 11, fontWeight: 600 }}>{activeVals.length}</span>}
                      <Icon name="chevronDown" size={12} className={isOpen ? 'rot' : ''} />
                    </button>
                    {isOpen && !isMobile &&
                  <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, zIndex: 10, minWidth: 220, maxHeight: 320, overflow: 'auto', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', boxShadow: 'var(--shadow-3)', padding: 8 }}>
                        {values.map(([v, n]) =>
                    <Chk key={v} checked={activeVals.includes(v)} onChange={() => toggleSpec(key, v)} label={v} count={n ?? undefined} />
                    )}
                      </div>
                  }
                  </div>);

            })}
              {/* Mobile bottom-sheet dropdown for the currently-open spec — */}
              {/* rendered OUTSIDE the chip row so overflow:auto can't clip it. */}
              {isMobile && openSpec && (() => {
                const realMap = specOptions[openSpec];
                const values = realMap
                  ? [...realMap.entries()].sort((a, b) => b[1] - a[1])
                  : (dummyValues[openSpec] || []).map((v) => [v, null]);
                const activeVals = specFilters[openSpec] || [];
                return (
                  <div style={{ position: 'fixed', inset: 0, zIndex: 80 }}>
                    <div onClick={() => setOpenSpec(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.45)' }} />
                    <div style={{
                      position: 'absolute', left: 0, right: 0, bottom: 0,
                      background: 'var(--surface)',
                      borderTopLeftRadius: 18, borderTopRightRadius: 18,
                      maxHeight: '75vh',
                      display: 'flex', flexDirection: 'column',
                      boxShadow: '0 -12px 32px rgba(11,18,32,0.18)',
                      animation: 'spec-sheet-up .25s cubic-bezier(.2,.7,.2,1)'
                    }}>
                      <style>{`@keyframes spec-sheet-up { from { transform: translateY(100%); } to { transform: translateY(0); } }`}</style>
                      <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
                        <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--line-2)' }} />
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 18px 12px', borderBottom: '1px solid var(--line)' }}>
                        <div style={{ fontSize: 16, fontWeight: 700 }}>{openSpec}</div>
                        <button onClick={() => setOpenSpec(null)} style={{ color: 'var(--ink-4)', padding: 6 }}>
                          <Icon name="close" size={18} />
                        </button>
                      </div>
                      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 12px 16px' }}>
                        {values.map(([v, n]) =>
                          <Chk key={v} checked={activeVals.includes(v)} onChange={() => toggleSpec(openSpec, v)} label={v} count={n ?? undefined} />
                        )}
                      </div>
                      <div style={{ padding: '12px 18px', borderTop: '1px solid var(--line)', display: 'flex', gap: 10 }}>
                        <button onClick={() => setSpecFilters((p) => ({ ...p, [openSpec]: [] }))}
                          className="btn btn-ghost" style={{ flex: 1, justifyContent: 'center' }}>
                          Limpiar
                        </button>
                        <button onClick={() => setOpenSpec(null)}
                          className="btn btn-dark" style={{ flex: 1, justifyContent: 'center' }}>
                          Aplicar {activeVals.length > 0 && `(${activeVals.length})`}
                        </button>
                      </div>
                    </div>
                  </div>);

              })()}
              {specFilterCount > 0 &&
            <button onClick={() => setSpecFilters({})}
            style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)', textDecoration: 'underline', textUnderlineOffset: 3 }}>
                  Limpiar ({specFilterCount})
                </button>
            }
            </div>
          }

          {/* Toolbar */}
          <div className="shop-toolbar" style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '12px 16px', background: 'var(--surface)', border: '1px solid var(--line)',
            borderRadius: 'var(--r-md)', marginBottom: 16, flexWrap: 'wrap', gap: 10
          }}>
            {/* Mobile-only Filtros chip — sits inline with sort */}
            <button className="shop-toolbar-filter-chip" onClick={() => setMobileFilters(true)}>
              <Icon name="filter" size={13} />
              Filtros
              {specFilterCount + brands.length + sub.length + (inStock ? 1 : 0) > 0 &&
              <span className="shop-filter-badge">{specFilterCount + brands.length + sub.length + (inStock ? 1 : 0)}</span>}
            </button>
            <div className="t-small shop-toolbar-count">Mostrando <b style={{ color: 'var(--ink)' }}>{items.length}</b> de {PRODUCTS.length}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span className="t-xs" style={{ color: 'var(--ink-3)' }}>Ordenar por</span>
              <select value={sort} onChange={(e) => setSort(e.target.value)}
              style={{ padding: '8px 10px', border: '1px solid var(--line-2)', borderRadius: 6, fontSize: 13, background: '#fff' }}>
                <option value="relevance">Relevancia</option>
                <option value="price-asc">Menor precio</option>
                <option value="price-desc">Mayor precio</option>
                <option value="rating">Mejor valorados</option>
              </select>
              <div style={{ display: 'flex', border: '1px solid var(--line-2)', borderRadius: 6 }}>
                <button onClick={() => setView('grid')}
                style={{ padding: 8, color: view === 'grid' ? 'var(--ink)' : 'var(--ink-4)' }}><Icon name="grid" size={14} /></button>
                <button onClick={() => setView('list')}
                style={{ padding: 8, color: view === 'list' ? 'var(--ink)' : 'var(--ink-4)' }}><Icon name="list" size={14} /></button>
              </div>
            </div>
          </div>

          {/* Grid — adapta automáticamente al ancho del contenedor */}
          {view === 'grid' ?
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 18 }} className="shop-grid-3">
              {items.map((p) => <ProductCard key={p.id} product={p} onNavigate={onNavigate} onAdd={onAdd} variant="industrial" />)}
            </div> :

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {items.map((p) =>
            <a key={p.id} href="#" onClick={(e) => {e.preventDefault();onNavigate(`/producto/${p.id}`);}}
            className="shop-list-row">
                  <div style={{ aspectRatio: '1/1', background: '#FFF', border: '1px solid var(--line)', borderRadius: 'var(--r-sm)', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    {p.image ? <img src={p.image} alt={p.name} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 10 }} /> : <span className="mono t-xs">{p.brand}</span>}
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <h3 style={{ fontSize: 15, fontWeight: 600, marginTop: 4, overflowWrap: 'anywhere' }}>{window.RC_DATA.formatProductName(p.name)}</h3>
                    <p className="t-body" style={{ marginTop: 6, fontSize: 13, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.desc}</p>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    {p.was && <div className="t-xs" style={{ textDecoration: 'line-through' }}>{fmtARS(p.was)}</div>}
                    <div style={{ fontSize: 20, fontWeight: 800, whiteSpace: 'nowrap' }}>{fmtARS(p.price)}</div>
                    <div className="t-xs" style={{ whiteSpace: 'nowrap' }}>6 x {fmtARS(Math.round(p.price / 6))}</div>
                    <button className="btn btn-dark" style={{ marginTop: 10, padding: '8px 14px', fontSize: 12 }}
                onClick={(e) => {
                  e.preventDefault();e.stopPropagation();
                  const el = e.currentTarget;
                  el.classList.remove('btn-add-zoom');
                  void el.offsetWidth;
                  el.classList.add('btn-add-zoom');
                  onAdd(p);
                }}>
                      <Icon name="cart" size={13} /> Agregar
                    </button>
                  </div>
                </a>
            )}
            </div>
          }
          {items.length === 0 &&
          <div style={{ padding: 60, textAlign: 'center', background: 'var(--surface)', border: '1px dashed var(--line-2)', borderRadius: 'var(--r-md)' }}>
              <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>Sin productos</div>
              <div className="t-small">Probá ajustando los filtros.</div>
            </div>
          }
        </div>
      </div>
    </div>);

};

/* ────────── PDP price toggle (tab selector) ────────── */
const PdpPriceToggle = ({ product, transferPrice, installment, offPct, fmtARS }) => {
  const [mode, setMode] = React.useState('transfer');
  const displayPrice = mode === 'transfer' ? transferPrice : product.price;
  return (
    <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
      <div style={{ display: 'inline-flex', gap: 4, padding: 4, background: 'var(--bg-2)', borderRadius: 999, marginBottom: 12 }}>
        {[
        { v: 'list', l: 'Precio normal' },
        { v: 'transfer', l: 'Transferencia −15%' }].
        map((o) => {
          const active = mode === o.v;
          return (
            <button key={o.v} onClick={() => setMode(o.v)}
            style={{
              padding: '6px 14px', borderRadius: 999, fontSize: 12, fontWeight: 600,
              background: active ? o.v === 'transfer' ? '#a00e0c' : 'var(--ink)' : 'transparent',
              color: active ? '#fff' : 'var(--ink-3)',
              transition: 'all .2s', whiteSpace: 'nowrap'
            }}>{o.l}</button>);

        })}
      </div>
      {product.was && mode === 'list' &&
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</span>
          {offPct > 0 && <span style={{ fontSize: 14, fontWeight: 500, color: '#a00e0c' }}>{offPct}% OFF</span>}
        </div>
      }
      <div style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.02em', color: mode === 'transfer' ? '#a00e0c' : 'var(--ink)', lineHeight: 1.05, marginTop: product.was && mode === 'list' ? 4 : 0 }}>
        {fmtARS(displayPrice)}
      </div>
      <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 6 }}>12 cuotas sin interés de {fmtARS(installment)}</div>
    </div>);

};

/* ────────── PDP ────────── */
/* PDP lightbox — visor fullscreen con pinch-to-zoom + pan + swipe (mobile) */
function PdpLightbox({ imgs, index, setIndex, onClose, alt }) {
  const total = imgs.length;
  const src = imgs[index] || imgs[0];
  const [z, setZ] = React.useState({ scale: 1, x: 0, y: 0 });
  const [animate, setAnimate] = React.useState(false);
  const g = React.useRef({});
  const movedRef = React.useRef(false);

  // Reset del zoom cada vez que cambia la imagen mostrada.
  React.useEffect(() => { setAnimate(true); setZ({ scale: 1, x: 0, y: 0 }); }, [index]);

  const distance = (t) => Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY);
  const midpoint = (t) => ({ x: (t[0].clientX + t[1].clientX) / 2, y: (t[0].clientY + t[1].clientY) / 2 });
  const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));

  const onTouchStart = (e) => {
    movedRef.current = false;
    setAnimate(false);
    if (e.touches.length === 2) {
      g.current = { mode: 'pinch', d0: distance(e.touches), s0: z.scale, m0: midpoint(e.touches), x0: z.x, y0: z.y };
    } else if (e.touches.length === 1) {
      if (z.scale > 1) g.current = { mode: 'pan', px: e.touches[0].clientX - z.x, py: e.touches[0].clientY - z.y };
      else g.current = { mode: 'swipe', sx: e.touches[0].clientX };
    }
  };

  const onTouchMove = (e) => {
    const m = g.current;
    if (!m.mode) return;
    if (m.mode === 'pinch' && e.touches.length === 2) {
      const ratio = distance(e.touches) / (m.d0 || 1);
      const scale = clamp(m.s0 * ratio, 1, 4);
      const mid = midpoint(e.touches);
      movedRef.current = true;
      setZ({ scale, x: m.x0 + (mid.x - m.m0.x), y: m.y0 + (mid.y - m.m0.y) });
    } else if (m.mode === 'pan' && e.touches.length === 1) {
      movedRef.current = true;
      setZ((s) => ({ scale: s.scale, x: e.touches[0].clientX - m.px, y: e.touches[0].clientY - m.py }));
    } else if (m.mode === 'swipe' && e.touches.length === 1) {
      if (Math.abs(e.touches[0].clientX - m.sx) > 10) movedRef.current = true;
    }
  };

  const onTouchEnd = (e) => {
    const m = g.current;
    if (m.mode === 'swipe' && total > 1) {
      const endX = (e.changedTouches[0] && e.changedTouches[0].clientX) || m.sx;
      const dx = endX - m.sx;
      if (Math.abs(dx) > 40) setIndex(dx < 0 ? (index + 1) % total : (index - 1 + total) % total);
    }
    if (m.mode === 'pinch' || m.mode === 'pan') {
      setAnimate(true);
      setZ((s) => (s.scale <= 1.05 ? { scale: 1, x: 0, y: 0 } : s));
    }
    if (e.touches.length === 0) g.current = {};
  };

  const arrowBase = { position: 'absolute', top: '50%', transform: 'translateY(-50%)', width: 52, height: 52, borderRadius: 26, background: 'rgba(255,255,255,0.95)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', border: 'none', zIndex: 2 };

  return (
    <div
      onClick={() => { if (movedRef.current) { movedRef.current = false; return; } onClose(); }}
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onTouchEnd}
      style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(0,0,0,0.85)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32, cursor: 'zoom-out', touchAction: 'none', overflow: 'hidden' }}>
      <button onClick={(e) => { e.stopPropagation(); onClose(); }} aria-label="Cerrar"
        style={{ position: 'absolute', top: 24, right: 24, width: 48, height: 48, borderRadius: 24, background: '#fff', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', border: 'none', boxShadow: '0 4px 14px rgba(0,0,0,0.2)', zIndex: 3 }}>
        <Icon name="close" size={22} />
      </button>

      {total > 1 &&
      <button className="pdp-lightbox-arrow" onClick={(e) => { e.stopPropagation(); setIndex((index - 1 + total) % total); }} aria-label="Anterior" style={{ ...arrowBase, left: 24 }}>
        <Icon name="chevronLeft" size={22} />
      </button>}

      {total > 1 &&
      <button className="pdp-lightbox-arrow" onClick={(e) => { e.stopPropagation(); setIndex((index + 1) % total); }} aria-label="Siguiente" style={{ ...arrowBase, right: 24 }}>
        <Icon name="chevronRight" size={22} />
      </button>}

      <img
        src={src}
        alt={alt}
        draggable={false}
        onClick={(e) => e.stopPropagation()}
        style={{
          maxWidth: 'min(92vw, 1200px)', maxHeight: '88vh', objectFit: 'contain', userSelect: 'none', touchAction: 'none',
          transform: `translate(${z.x}px, ${z.y}px) scale(${z.scale})`, transformOrigin: 'center center',
          transition: animate ? 'transform .2s ease' : 'none', cursor: z.scale > 1 ? 'grab' : 'default', willChange: 'transform'
        }} />

      {total > 1 &&
      <div style={{ position: 'absolute', bottom: 32, left: '50%', transform: 'translateX(-50%)', display: 'flex', gap: 6, alignItems: 'center' }}>
        {imgs.map((_, i) =>
        <span key={i} style={{ width: index === i ? 22 : 6, height: 3, borderRadius: 2, background: index === i ? '#fff' : 'rgba(255,255,255,0.4)', transition: 'width .2s ease, background .2s ease' }} />)}
      </div>}
    </div>);
}

const ProductPage = ({ id, onNavigate, onAdd, pdp = {} }) => {
  const { pdpGallery = 'thumbs-left', pdpPrice = 'two-col', pdpStock = 'bullet', pdpTabs = 'sticky', pdpActions = 'inline', pdpSpecs = 'table', pdpFaq = 'accordion', pdpBenefits = 'checklist' } = pdp;
  const { PRODUCTS, CATEGORIES } = window.RC_DATA;
  const product = PRODUCTS.find((p) => p.id === id);
  const [gallery, setGallery] = React.useState(0);
  const [qty, setQty] = React.useState(1);
  const [added, setAdded] = React.useState(false);
  const [lightboxOpen, setLightboxOpen] = React.useState(false);
  // Swipe gesture state for the mobile gallery
  const touchStartX = React.useRef(0);
  const swipedRef = React.useRef(false);

  // Lightbox keyboard nav
  React.useEffect(() => {
    if (!lightboxOpen) return;
    const onKey = (e) => {
      if (e.key === 'Escape') setLightboxOpen(false);
      if (e.key === 'ArrowLeft') setGallery((g) => (g - 1 + (product?.images?.length || 1)) % (product?.images?.length || 1));
      if (e.key === 'ArrowRight') setGallery((g) => (g + 1) % (product?.images?.length || 1));
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [lightboxOpen, product]);
  if (!product) return <div className="container" style={{ padding: 60 }}>Producto no encontrado.</div>;
  const cat = CATEGORIES.find((c) => c.id === product.cat);
  const related = PRODUCTS.filter((p) => p.cat === product.cat && p.id !== product.id).slice(0, 3);

  const galleryLabels = ['Vista frontal', 'Vista lateral', 'Detalle motor', 'En uso'];

  const handleAdd = (e) => {
    onAdd({ ...product, qty });
    setAdded(true);
    setTimeout(() => setAdded(false), 1600);
    // Zoom-in animation via Web Animations API (works regardless of CSS cache)
    const btn = e?.currentTarget;
    if (btn?.animate) {
      btn.animate(
        [
        { transform: 'scale(1)', offset: 0 },
        { transform: 'scale(1.3)', offset: 0.4 },
        { transform: 'scale(0.94)', offset: 0.7 },
        { transform: 'scale(1)', offset: 1 }],

        { duration: 800, easing: 'cubic-bezier(.34, 1.56, .64, 1)' }
      );
    }
  };

  return (
    <div>
      {/* Breadcrumb */}
      <div className="container" style={{ padding: '24px 24px 8px' }}>
        <div className="mono t-xs" style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}>
          <a href="#" onClick={(e) => {e.preventDefault();onNavigate('/');}}>Inicio</a>
          <span style={{ margin: '0 8px', color: 'var(--ink-4)' }}>/</span>
          <a href="#" onClick={(e) => {e.preventDefault();onNavigate(`/categoria/${cat.slug}`);}}>{cat.name}</a>
        </div>
      </div>

      <div className="container pdp-grid" style={{ padding: '12px 24px 40px' }}>
        {/* Mobile-only: title + meta above gallery */}
        <div className="pdp-mobile-meta" style={{ display: 'none', gridColumn: '1 / -1', marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <div className="mono t-xs" style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              {product.brand} · {cat.name}
            </div>
            <div className="mono t-xs" style={{ color: 'var(--ink-4)' }}>SKU {product.sku}</div>
          </div>
          <h1 style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.2, margin: 0 }}>
            {window.RC_DATA.formatProductName(product.name)}
          </h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, fontSize: 13, flexWrap: 'wrap' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <Stars value={product.rating} />
              <span style={{ fontWeight: 700 }}>{Number(product.rating).toFixed(1)}</span>
              <a href="#" onClick={(e) => {e.preventDefault();const el = document.getElementById('pdp-faq');if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 70, behavior: 'smooth' });}} style={{ color: 'var(--ink-3)', textDecoration: 'underline', textDecorationColor: 'var(--line-2)' }}>
                {product.reviews} reseñas
              </a>
            </div>
            <span style={{ color: 'var(--ink-4)' }}>·</span>
            <span style={{ color: 'var(--ink-3)' }}>+{product.reviews * 3} vendidos este mes</span>
          </div>
        </div>

        {/* Gallery */}
        <div className="pdp-gallery-col" style={{ position: 'sticky', top: 20, alignSelf: 'start' }}>
          {(() => {
            const imgs = product.images?.length ? product.images : [product.image];
            const Thumb = ({ i }) =>
            <button key={i} onClick={() => setGallery(i)}
            style={{ aspectRatio: '1/1', borderRadius: 'var(--r-md)', border: '2px solid ' + (gallery === i ? 'var(--ink)' : 'var(--line)'), cursor: 'pointer', background: '#FFF', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
                {imgs[i] ? <img src={imgs[i]} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 8 }} /> : <span className="mono t-xs">{product.brand}</span>}
              </button>;

            const MainImage = () =>
            <div style={{ flex: 1, minWidth: 0, position: 'relative', aspectRatio: '1/1', background: '#FFF', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'zoom-in' }}
            onTouchStart={(e) => { touchStartX.current = e.touches[0].clientX; swipedRef.current = false; }}
            onTouchEnd={(e) => {
              if (imgs.length < 2) return;
              const dx = e.changedTouches[0].clientX - touchStartX.current;
              if (Math.abs(dx) > 40) {
                swipedRef.current = true;
                if (dx < 0) setGallery((g) => (g + 1) % imgs.length);
                else setGallery((g) => (g - 1 + imgs.length) % imgs.length);
              }
            }}
            onClick={(e) => {if (e.target.closest('button')) return;if (swipedRef.current) {swipedRef.current = false;return;}setLightboxOpen(true);}}>
                <button className="pdp-gallery-arrow" aria-label="Anterior" onClick={() => setGallery((gallery - 1 + imgs.length) % imgs.length)}
              style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', width: 38, height: 38, borderRadius: 999, background: '#FFF', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', zIndex: 2, boxShadow: '0 2px 6px rgba(0,0,0,0.04)' }}>
                  <Icon name="chevronLeft" size={16} />
                </button>
                <button className="pdp-gallery-arrow" aria-label="Siguiente" onClick={() => setGallery((gallery + 1) % imgs.length)}
              style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', width: 38, height: 38, borderRadius: 999, background: '#FFF', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', zIndex: 2, boxShadow: '0 2px 6px rgba(0,0,0,0.04)' }}>
                  <Icon name="chevronRight" size={16} />
                </button>
                {imgs[gallery] ?
              <img src={imgs[gallery]} alt={product.name} style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 32, transition: 'transform .3s' }} /> :
              <span className="mono t-xs">{product.brand}</span>}
                <div style={{ position: 'absolute', bottom: 14, left: '50%', transform: 'translateX(-50%)', display: 'flex', gap: 6, alignItems: 'center' }}>
                  {imgs.map((_, i) =>
                <span key={i} style={{
                  width: gallery === i ? 18 : 6,
                  height: 3, borderRadius: 2,
                  background: gallery === i ? 'var(--ink)' : 'rgba(11,18,32,0.25)',
                  transition: 'width .2s ease, background .2s ease'
                }} />
                )}
                </div>
              </div>;


            if (pdpGallery === 'thumbs-bottom') {
              return (
                <div>
                  <MainImage />
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8, marginTop: 10 }}>
                    {imgs.slice(0, 5).map((_, i) => <Thumb key={i} i={i} />)}
                  </div>
                </div>);

            }
            if (pdpGallery === 'no-thumbs') {
              return <MainImage />;
            }
            // thumbs-left (default)
            return (
              <div className="pdp-thumbs-left" style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <div className="pdp-thumbs-col" style={{ display: 'flex', flexDirection: 'column', gap: 8, flexShrink: 0, width: 72 }}>
                  {imgs.slice(0, 5).map((_, i) => <Thumb key={i} i={i} />)}
                </div>
                <MainImage />
              </div>);

          })()}
        </div>

        {/* Info */}
        <div className="pdp-info-col">
          {/* Meta: brand + SKU */}
          <div className="pdp-desktop-meta" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div className="mono t-xs" style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              {product.brand} · {cat.name}
            </div>
            <div className="mono t-xs" style={{ color: 'var(--ink-4)' }}>SKU {product.sku}</div>
          </div>

          {/* Title */}
          <h1 className="pdp-desktop-title" style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.2 }}>{window.RC_DATA.formatProductName(product.name)}</h1>

          {/* Rating + social proof */}
          <div className="pdp-desktop-meta" style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 10, fontSize: 13, flexWrap: 'wrap' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <Stars value={product.rating} />
              <span style={{ fontWeight: 700 }}>{Number(product.rating).toFixed(1)}</span>
              <a href="#" onClick={(e) => {e.preventDefault();const el = document.getElementById('pdp-faq');if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 70, behavior: 'smooth' });}} style={{ color: 'var(--ink-3)', textDecoration: 'underline', textDecorationColor: 'var(--line-2)' }}>
                {product.reviews} reseñas
              </a>
            </div>
            <span style={{ color: 'var(--ink-4)' }}>·</span>
            <span style={{ color: 'var(--ink-3)' }}>+{product.reviews * 3} vendidos este mes</span>
          </div>

          {/* Price block — variants */}
          {(() => {
            const installment = Math.round(product.price / 12);
            const transferPrice = Math.round(product.price * 0.85);
            const offPct = product.was ? Math.round((product.was - product.price) / product.was * 100) : 0;

            if (pdpPrice === 'bank') {
              return (
                <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                  {product.was &&
                  <div style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</div>
                  }
                  <div style={{ fontSize: 34, fontWeight: 700, letterSpacing: '-0.02em', color: '#a00e0c', lineHeight: 1.05, marginTop: 2 }}>{fmtARS(transferPrice)}</div>
                  <div style={{ fontSize: 12, fontWeight: 700, color: '#a00e0c', letterSpacing: '0.04em', textTransform: 'uppercase', marginTop: 4 }}>· Transferencia · 15% OFF</div>
                  <div style={{ fontSize: 15, color: 'var(--ink-2)', marginTop: 12 }}>
                    Lista: <span style={{ fontWeight: 700, color: 'var(--ink)' }}>{fmtARS(product.price)}</span>
                  </div>
                  <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 2 }}>12 cuotas sin interés de {fmtARS(installment)}</div>
                </div>);

            }

            if (pdpPrice === 'hero-transfer') {
              return (
                <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: '#a00e0c', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Pagando con transferencia</span>
                    <span style={{ background: '#a00e0c', color: '#fff', fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 4, letterSpacing: '0.04em' }}>−15%</span>
                  </div>
                  <div style={{ fontSize: 42, fontWeight: 800, letterSpacing: '-0.025em', color: '#a00e0c', lineHeight: 1, marginTop: 6 }}>{fmtARS(transferPrice)}</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 14, paddingTop: 14, borderTop: '1px dashed var(--line)', flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500 }}>Precio</span>
                    <span style={{ fontSize: 18, fontWeight: 700, color: 'var(--ink)' }}>{fmtARS(product.price)}</span>
                    {product.was && <span style={{ fontSize: 13, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</span>}
                  </div>
                  <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 6 }}>12 cuotas sin interés de {fmtARS(installment)}</div>
                </div>);

            }

            if (pdpPrice === 'toggle') {
              return <PdpPriceToggle product={product} transferPrice={transferPrice} installment={installment} offPct={offPct} fmtARS={fmtARS} />;
            }

            if (pdpPrice === 'savings') {
              const savings = product.was ? product.was - product.price : 0;
              const savingsTransfer = product.price - transferPrice;
              return (
                <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                  {product.was &&
                  <div style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</div>
                  }
                  <div style={{ fontSize: 34, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)', lineHeight: 1.05, marginTop: 2 }}>{fmtARS(product.price)}</div>
                  {savings > 0 &&
                  <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6, fontSize: 13, fontWeight: 600, color: '#a00e0c', marginTop: 6 }}>
                      Ahorrás {fmtARS(savings)} <span style={{ color: 'var(--ink-4)', fontWeight: 500 }}>({offPct}% OFF)</span>
                    </div>
                  }
                  <div style={{ marginTop: 14, padding: '12px 14px', background: 'rgba(160, 14, 12, 0.06)', border: '1px solid rgba(160, 14, 12, 0.18)', borderRadius: 'var(--r-md)' }}>
                    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10 }}>
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 700, color: '#a00e0c', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Por transferencia</div>
                        <div style={{ fontSize: 22, fontWeight: 800, color: '#a00e0c', letterSpacing: '-0.01em', marginTop: 2 }}>{fmtARS(transferPrice)}</div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Ahorrás</div>
                        <div style={{ fontSize: 16, fontWeight: 800, color: '#a00e0c' }}>{fmtARS(savingsTransfer)}</div>
                      </div>
                    </div>
                  </div>
                  <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 8 }}>12 cuotas sin interés de {fmtARS(installment)}</div>
                </div>);

            }

            if (pdpPrice === 'inline-strip') {
              return (
                <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                  {product.was &&
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
                      <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</span>
                      {offPct > 0 && <span style={{ fontSize: 14, fontWeight: 500, color: '#a00e0c' }}>{offPct}% OFF</span>}
                    </div>
                  }
                  <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)', lineHeight: 1.05 }}>{fmtARS(product.price)}</div>
                  <div style={{
                    marginTop: 12, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 0,
                    border: '1px solid var(--line)', borderRadius: 'var(--r-md)', overflow: 'hidden'
                  }}>
                    <div style={{ padding: '10px 14px' }}>
                      <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>12 sin interés</div>
                      <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', marginTop: 2 }}>{fmtARS(installment)}</div>
                    </div>
                    <div style={{ padding: '10px 14px', borderLeft: '1px solid var(--line)', background: 'rgba(160, 14, 12, 0.04)' }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: '#a00e0c', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Transf. −15%</div>
                      <div style={{ fontSize: 14, fontWeight: 700, color: '#a00e0c', marginTop: 2 }}>{fmtARS(transferPrice)}</div>
                    </div>
                  </div>
                </div>);

            }

            if (pdpPrice === 'two-col') {
              return (
                <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                  {product.was &&
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10 }}>
                      <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</span>
                      {offPct > 0 && <span style={{ fontSize: 14, fontWeight: 500, color: '#a00e0c' }}>{offPct}% OFF</span>}
                    </div>
                  }
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                    <div>
                      <div style={{ fontSize: 10, fontWeight: 500, color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 2 }}>Precio</div>
                      <div style={{ fontSize: 26, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.01em', lineHeight: 1.1 }}>{fmtARS(product.price)}</div>
                    </div>
                    <div style={{ paddingLeft: 8, borderLeft: '1px solid var(--line)' }}>
                      <div style={{ fontSize: 10, fontWeight: 500, color: '#a00e0c', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 2 }}>Transf. −15%</div>
                      <div style={{ fontSize: 26, fontWeight: 700, color: '#a00e0c', letterSpacing: '-0.01em', lineHeight: 1.1 }}>{fmtARS(transferPrice)}</div>
                    </div>
                  </div>
                  <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 10 }}>12 cuotas sin interés de {fmtARS(installment)}</div>
                </div>);

            }

            if (pdpPrice === 'big') {
              return (
                <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                  {product.was &&
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                      <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</span>
                      {offPct > 0 && <span style={{ fontSize: 14, fontWeight: 600, color: '#a00e0c' }}>{offPct}% OFF</span>}
                    </div>
                  }
                  <div style={{ fontSize: 44, fontWeight: 800, letterSpacing: '-0.03em', color: 'var(--ink)', lineHeight: 1, marginTop: 4 }}>{fmtARS(product.price)}</div>
                  <div style={{ fontSize: 17, color: '#a00e0c', fontWeight: 600, marginTop: 8 }}>12 cuotas sin interés de {fmtARS(installment)}</div>
                  <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 2 }}>ó {fmtARS(transferPrice)} por transferencia</div>
                </div>);

            }

            // minimal (default)
            return (
              <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                {product.was &&
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
                    <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{fmtARS(product.was)}</span>
                    {offPct > 0 && <span style={{ fontSize: 14, fontWeight: 500, color: '#a00e0c' }}>{offPct}% OFF</span>}
                  </div>
                }
                <div style={{ fontSize: 34, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--ink)', lineHeight: 1.05 }}>{fmtARS(product.price)}</div>
                <div style={{ fontSize: 16, color: '#a00e0c', fontWeight: 400, marginTop: 6 }}>12 cuotas sin interés de {fmtARS(installment)}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 8 }}>
                  <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--ink-4)' }}>{fmtARS(transferPrice)}</span>
                  <span style={{ fontSize: 14, fontWeight: 500, color: '#a00e0c' }}>Transferencia 15% OFF</span>
                </div>
              </div>);

          })()}

          {/* Stock — variants */}
          {product.stock > 0 && pdpStock !== 'hidden' && (() => {
            const urgent = product.stock < 8;
            const text = urgent ? `¡Últimas ${product.stock} unidades!` : 'En stock';
            const color = urgent ? 'var(--accent)' : '#a00e0c';
            if (pdpStock === 'card') {
              return (
                <div style={{ marginTop: 14, padding: '12px 14px', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 18, background: 'rgba(160, 14, 12, 0.08)', color, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name="check" size={16} strokeWidth={2.4} />
                  </div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 700, color }}>{text}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>Comprando ahora despachamos en <strong style={{ color: 'var(--ink-2)' }}>24 hs</strong></div>
                  </div>
                </div>);

            }
            if (pdpStock === 'pill') {
              return (
                <div style={{ marginTop: 14, display: 'inline-flex', alignItems: 'center', gap: 6, background: 'rgba(160, 14, 12, 0.08)', color, padding: '6px 12px', borderRadius: 999, fontSize: 13, fontWeight: 700 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 3, background: color }} />
                  {text}
                  <span style={{ fontWeight: 500, color: 'var(--ink-2)', marginLeft: 4 }}>· despacho 24 hs</span>
                </div>);

            }
            return (
              <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ width: 8, height: 8, borderRadius: 4, background: color, flexShrink: 0 }} />
                <div style={{ fontSize: 13, fontWeight: 600, color }}>
                  {text}
                  <span style={{ fontWeight: 500, color: 'var(--ink-2)', marginLeft: 6 }}>— Comprando ahora lo despachamos en <strong>24 hs</strong></span>
                </div>
              </div>);

          })()}

          {/* Actions — variants */}
          {(() => {
            const renderAddBtn = (flex, key) =>
            <button key={key} className={`btn btn-primary pdp-add-btn${added ? ' btn-add-zoom' : ''}`} style={{ flex, padding: '14px 18px', fontSize: 15, fontWeight: 700 }} onClick={handleAdd}>
                {added ? <><Icon name="check" size={16} /> Agregado al carrito</> : <><Icon name="cart" size={16} /> Agregar al carrito</>}
              </button>;

            const renderQtyStepper = (key) =>
            <div key={key} style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--line-2)', borderRadius: 'var(--r-md)' }}>
                <button onClick={() => setQty(Math.max(1, qty - 1))} style={{ padding: 14 }}><Icon name="minus" size={13} /></button>
                <span style={{ padding: '0 14px', fontWeight: 700, minWidth: 36, textAlign: 'center' }}>{qty}</span>
                <button onClick={() => setQty(qty + 1)} style={{ padding: 14 }}><Icon name="plus" size={13} /></button>
              </div>;

            const renderWaBtn = (flex, key) =>
            <button
              key={key}
              onMouseEnter={(e) => {e.currentTarget.style.background = '#25D366';e.currentTarget.style.color = '#fff';}}
              onMouseLeave={(e) => {e.currentTarget.style.background = 'transparent';e.currentTarget.style.color = '#25D366';}}
              style={{
                flex, padding: '12px 18px', fontSize: 13, fontWeight: 600,
                background: 'transparent', color: '#25D366', border: '1.5px solid #25D366',
                borderRadius: 'var(--r-md)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                cursor: 'pointer', transition: 'background .2s ease, color .2s ease'
              }}>
                <Icon name="whatsapp" size={15} /> Consultar por WhatsApp
              </button>;


            if (pdpActions === 'minimal') {
              return (
                <div style={{ marginTop: 14, display: 'flex', gap: 10 }}>
                  {renderQtyStepper('q')}
                  {renderAddBtn(1, 'a')}
                </div>);

            }
            if (pdpActions === 'inline') {
              return (
                <div>
                  <div style={{ marginTop: 14, display: 'flex', gap: 10 }}>
                    {renderQtyStepper('q')}
                    {renderAddBtn(1, 'a')}
                  </div>
                  <div style={{ marginTop: 10, display: 'flex', gap: 10 }}>
                    {renderWaBtn(1, 'w')}
                  </div>
                </div>);

            }
            // stacked (default)
            return (
              <div>
                <div style={{ marginTop: 14, display: 'flex', gap: 10 }}>
                  {renderQtyStepper('q')}
                  {renderAddBtn(1, 'a')}
                </div>
                <div style={{ marginTop: 8 }}>
                  {renderWaBtn(undefined, 'w')}
                </div>
              </div>);

          })()}

          {/* Shipping calculator */}
          <div style={{ marginTop: 16, padding: '14px 16px', border: '1px solid var(--line)', borderRadius: 'var(--r-md)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <Icon name="truck" size={17} strokeWidth={1.5} />
              <div style={{ fontSize: 13, fontWeight: 700 }}>Calculá el envío</div>
              <a href="#" style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-3)', textDecoration: 'underline' }}>No sé mi CP</a>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <input type="text" placeholder="Ingresá tu código postal" style={{ flex: 1, padding: '10px 12px', fontSize: 13, border: '1px solid var(--line-2)', borderRadius: 6, outline: 'none' }} />
              <button className="btn btn-ghost" style={{ padding: '10px 16px', fontSize: 12 }}>Calcular</button>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 8, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <Icon name="check" size={12} /> <strong style={{ color: '#a00e0c', fontWeight: 700 }}>Envío gratis</strong> a CABA y GBA en 48 hs
            </div>
          </div>

          {/* Key specs preview removed */}


          {/* Includes in box */}
        </div>
      </div>

      {/* Lightbox modal — pinch-to-zoom + pan + swipe (mobile) */}
      {lightboxOpen && (() => {
        const imgs = product.images?.length ? product.images : [product.image].filter(Boolean);
        return <PdpLightbox imgs={imgs} index={gallery} setIndex={setGallery} onClose={() => setLightboxOpen(false)} alt={product.name} />;
      })()}

      {/* Sticky mini buy bar (shows on scroll past CTA) */}
      <StickyBuyBar product={product} onAdd={handleAdd} added={added} />

      {/* Tabs nav — placed right after the hero (below the shipping calculator)
            so it spans every section that follows. */}
      {pdpTabs !== 'hidden' && <StickyTabsNav reviewsCount={product.reviews} mode={pdpTabs} />}

      {/* Características + Descripción — unified with hero (no borders, same bg) */}
      <section id="pdp-descripcion" style={{ scrollMarginTop: 120 }}>
        <div className="container" style={{ padding: '8px 24px 32px', display: 'grid', gap: 14 }}>
          {/* Descripción — same card style as before */}
          <div className="pdp-card pdp-card-desc" style={{
            background: 'var(--surface)',
            border: '1px solid var(--line)',
            borderRadius: 'var(--r-lg)',
            padding: '26px 28px'
          }}>
            <h2 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.01em', margin: '0 0 18px' }}>
              Descripción
            </h2>
            <div style={{ fontSize: 15, lineHeight: 1.65, color: 'var(--ink-2)', textAlign: 'justify' }}>
              <p style={{ margin: '0 0 14px' }}>
                <strong style={{ color: '#a00e0c', textTransform: 'uppercase', letterSpacing: '0.01em' }}>
                  {product.name}
                </strong>{' '}— Equipo profesional fabricado bajo estándares industriales,
                ideal para uso intensivo en talleres, lavaderos, empresas de limpieza y obras.
              </p>
              <p style={{ margin: '0 0 14px' }}>
                Motor eléctrico monofásico 220V, alta presión y caudal sostenido. Bomba con pistones
                cerámicos de alta durabilidad. Estructura reforzada y manija ergonómica para traslado.
              </p>
              <p style={{ margin: '0 0 14px' }}>
                <strong style={{ color: '#a00e0c' }}>Garantía oficial 12 meses</strong>. Servicio técnico
                propio en Haedo, con repuestos originales en stock y asesoramiento por WhatsApp.
              </p>
              <p style={{ margin: 0, color: 'var(--ink-3)' }}>
                Envío gratis a CABA y GBA en 48hs. Al interior por Andreani o transporte a cotizar.
              </p>
            </div>
          </div>

          {/* Características */}
          <div className="pdp-card" style={{
            background: 'var(--surface)',
            border: '1px solid var(--line)',
            borderRadius: 'var(--r-lg)',
            padding: '26px 28px'
          }}>
            <h2 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.01em', margin: '0 0 20px' }}>
              Características del producto
            </h2>
            <SpecsBlock product={product} variant="cards" />
          </div>
        </div>
      </section>

      {/* Related — unified with section above (no border, same bg) */}
      <section id="pdp-relacionados" style={{ scrollMarginTop: 120 }}>
        <div className="container" style={{ padding: '8px 24px 40px' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
            <h2 style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em', margin: 0 }}>Productos relacionados</h2>
            <a href="#" onClick={(e) => {e.preventDefault();onNavigate(`/categoria/${product.cat}`);}}
            style={{ fontSize: 13, color: 'var(--ink-3)', textDecoration: 'underline', textUnderlineOffset: 3 }}>
              Ver más
            </a>
          </div>
          <RelatedCarousel items={related} onNavigate={onNavigate} onAdd={onAdd} />
        </div>
      </section>

      {/* Features sections (alternating) */}
      <section id="pdp-caracteristicas" style={{ scrollMarginTop: 120 }}>
        <FeatureSections product={product} />
      </section>

      {/* FAQ */}
      <section id="pdp-especificaciones" style={{ scrollMarginTop: 120, background: 'var(--bg)' }}>
        <div className="container" style={{ padding: '56px 24px' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 24 }}>
            <h2 style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.02em', margin: 0 }}>Ficha técnica completa</h2>
            <a href="#" onClick={(e) => {e.preventDefault();window.print();}}
            style={{ fontSize: 13, color: 'var(--ink-3)', textDecoration: 'underline', textUnderlineOffset: 3 }}>
              Descargar ficha técnica
            </a>
          </div>
          <FullSpecSheet product={product} />
        </div>
      </section>

      {/* FAQ */}
      <section id="pdp-faq" style={{ scrollMarginTop: 120, background: '#FFFFFF' }}>
        <div className="container" style={{ padding: '56px 24px' }}>
          <h2 style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.02em', marginBottom: 24 }}>Preguntas frecuentes</h2>
          <FAQBlock variant={pdpFaq} />
        </div>
      </section>

      {/* Testimonios */}
      <section id="pdp-testimonios" style={{ scrollMarginTop: 120, background: 'var(--bg-2)', borderTop: '1px solid var(--line)' }}>
        <div className="container" style={{ padding: '56px 24px' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 14, marginBottom: 28 }}>
            <h2 style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.02em' }}>Lo que dicen quienes ya lo compraron</h2>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <Stars value={product.rating} />
              <span style={{ fontSize: 14, fontWeight: 700 }}>{Number(product.rating).toFixed(1)}</span>
              <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>· {product.reviews} reseñas</span>
            </div>
          </div>
          <ProductTestimonials product={product} />
        </div>
      </section>

    </div>);

};

/* ────────── PRODUCT TESTIMONIALS ────────── */
const PRODUCT_TESTIMONIAL_POOL = [
{ name: 'Martín G.', role: 'Lavadero de autos · Morón', rating: 5, text: 'La uso todos los días. Tira con fuerza y se nota la diferencia con las de ferretería. Llegó al día siguiente y me asesoraron por WhatsApp para elegir bien.' },
{ name: 'Laura P.', role: 'Empresa de limpieza · CABA', rating: 5, text: 'Cambió cómo trabajamos. Reemplazó una vieja que teníamos hace 10 años. Mucha más potencia y service propio cuando hace falta.' },
{ name: 'Diego R.', role: 'Taller mecánico · La Matanza', rating: 5, text: 'Es el único lugar donde consigo repuestos originales sin demora. La hidrolavadora aguanta caños, jantes y motores sin chistar.' },
{ name: 'Sofía M.', role: 'Detailing · Lanús', rating: 5, text: 'Me la recomendaron y no me defraudó. Comprimida, fácil de mover y muy potente para el tamaño. La caja viene con todo.' },
{ name: 'Federico T.', role: 'Contratista de obra · Tigre', rating: 5, text: 'Después de probar varias marcas, esta no se calienta y mantiene la presión. Service en Haedo respondió rapidísimo cuando consulté.' },
{ name: 'Verónica K.', role: 'Consorcio · Caballito', rating: 4, text: 'Excelente para limpiar veredas y patios comunes. Algo pesada para mover sola, pero la potencia lo justifica.' }];


const ProductTestimonials = ({ product }) => {
  // Pick 3 testimonials deterministically based on product id
  const seed = parseInt(String(product.id).replace(/\D/g, ''), 10) || 0;
  const pool = [...PRODUCT_TESTIMONIAL_POOL];
  const selected = [];
  for (let i = 0; i < 3 && pool.length; i++) {
    const idx = (seed + i * 7) % pool.length;
    selected.push(pool.splice(idx, 1)[0]);
  }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
      {selected.map((r) =>
      <div key={r.name}
      style={{
        padding: 26, background: '#FFF',
        border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
        display: 'flex', flexDirection: 'column',
        transition: 'transform .25s ease, box-shadow .25s ease'
      }}
      onMouseEnter={(e) => {e.currentTarget.style.transform = 'translateY(-2px)';e.currentTarget.style.boxShadow = '0 8px 24px rgba(10,26,47,0.08)';}}
      onMouseLeave={(e) => {e.currentTarget.style.transform = 'translateY(0)';e.currentTarget.style.boxShadow = 'none';}}>
          <Stars value={r.rating} size={14} />
          <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 14, flex: 1 }}>"{r.text}"</p>
          <div style={{ marginTop: 20, paddingTop: 14, borderTop: '1px dashed var(--line)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
            width: 38, height: 38, borderRadius: '50%',
            background: '#a00e0c', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 700, fontSize: 14
          }}>
              {r.name[0]}
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{r.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{r.role}</div>
            </div>
          </div>
        </div>
      )}
    </div>);

};

/* ────────── RELATED — compact horizontal card ────────── */
const RelatedRowCard = ({ product, onNavigate }) => {
  const { ARS } = window.RC_DATA;
  const [hovering, setHovering] = React.useState(false);
  const discount = product.was ? Math.round((product.was - product.price) / product.was * 100) : 0;
  const installments = 12;
  const installmentValue = Math.round(product.price / installments);
  const transferPrice = Math.round(product.price * 0.85);

  // Reuse name formatting style from ProductCard (strip voltage, capitalize, uppercase codes)
  const formatName = (raw) => {
    if (!raw) return '';
    let s = raw.replace(/\b\d{2,3}\s*v\b/gi, '').replace(/\s+/g, ' ').trim();
    s = s.toLowerCase();
    s = s.charAt(0).toUpperCase() + s.slice(1);
    s = s.replace(/\bpowerclean\b/gi, 'Powerclean');
    s = s.replace(/\b[a-z]+\d+[a-z0-9-]*\b/gi, (m) => m.toUpperCase());
    s = s.replace(/\b\d+[a-z]+[a-z0-9-]*\b/gi, (m) => m.toUpperCase());
    return s;
  };
  const displayName = formatName(product.name);

  return (
    <a href="#" onClick={(e) => {e.preventDefault();onNavigate(`/producto/${product.id}`);}}
    onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)}
    className="pdp-related-card"
    style={{
      display: 'grid',
      gridTemplateColumns: '38% 1fr',
      gap: 12,
      background: 'var(--surface)',
      borderRadius: 'var(--r-md)',
      padding: 12,
      border: '1px solid var(--line)',
      transition: 'box-shadow .2s, transform .2s, border-color .2s',
      transform: hovering ? 'translateY(-2px)' : 'translateY(0)',
      boxShadow: hovering ? '0 6px 16px rgba(10,26,47,0.07)' : '0 1px 0 rgba(10,26,47,0.03)',
      borderColor: hovering ? 'var(--line-2)' : 'var(--line)',
      textDecoration: 'none', color: 'inherit'
    }}>
      {/* Image — vertically centered, square */}
      <div style={{
        aspectRatio: '1/1', background: '#FFFFFF',
        borderRadius: 6,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative', overflow: 'hidden',
        alignSelf: 'start'
      }}>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-4)', opacity: 0.45, pointerEvents: 'none' }}>
          <Icon name="pressure" size={28} strokeWidth={1.2} />
          <span className="mono" style={{ fontSize: 8, letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 4, opacity: 0.7 }}>{product.brand}</span>
        </div>
        {product.image &&
        <img src={product.image} alt="" loading="lazy"
        onError={(e) => {e.currentTarget.style.display = 'none';}}
        style={{
          position: 'relative', maxWidth: '88%', maxHeight: '88%',
          objectFit: 'contain', objectPosition: 'center',
          transition: 'transform .3s ease',
          transform: hovering ? 'scale(1.04)' : 'scale(1)'
        }} />
        }
      </div>

      {/* Info — justified column. Title at top, price block in middle, badge pinned to bottom. */}
      <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, justifyContent: 'space-between' }}>
        {/* Top: title (reserves 2 lines so the row below aligns across cards) */}
        <h3 style={{
          fontSize: 13, fontWeight: 500, color: 'var(--ink-2)',
          lineHeight: 1.3, letterSpacing: '0.1px',
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
          overflow: 'hidden', margin: 0, minHeight: 34
        }}>{displayName}</h3>

        {/* Middle: price block (reserves was-line so prices align across cards) */}
        <div style={{ marginTop: 6 }}>
          <div style={{ height: 14, display: 'flex', alignItems: 'baseline', gap: 6 }}>
            {product.was &&
            <span style={{ fontSize: 11, color: 'var(--ink-4)', textDecoration: 'line-through' }}>{ARS(product.was)}</span>
            }
            {discount > 0 &&
            <span style={{ fontSize: 11, fontWeight: 700, color: '#a00e0c' }}>{discount}% OFF</span>
            }
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 1, alignItems: 'stretch' }}>
            <div>
              <div style={{ fontSize: 9, fontWeight: 600, color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 1 }}>Precio</div>
              <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.01em', lineHeight: 1.1 }}>{ARS(product.price)}</div>
            </div>
            <div style={{ paddingLeft: 8, borderLeft: '1px solid var(--line)' }}>
              <div style={{ fontSize: 9, fontWeight: 600, color: '#a00e0c', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 1 }}>Transf. −15%</div>
              <div style={{ fontSize: 15, fontWeight: 700, color: '#a00e0c', letterSpacing: '-0.01em', lineHeight: 1.1 }}>{ARS(transferPrice)}</div>
            </div>
          </div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 10, lineHeight: 1.3 }}>
            {installments} cuotas sin interés de {ARS(installmentValue)}
          </div>
        </div>

        {/* Bottom: badge, pinned by space-between */}
        <div style={{ marginTop: 8 }}>
          <span style={{
            display: 'inline-block',
            background: '#a00e0c', color: '#fff',
            fontSize: 10, fontWeight: 600,
            padding: '2px 8px', borderRadius: 3
          }}>
            Llega gratis hoy
          </span>
        </div>
      </div>
    </a>);

};

/* ────────── RELATED CAROUSEL ────────── */
const RelatedCarousel = ({ items, onNavigate, onAdd }) => {
  const scrollerRef = React.useRef(null);
  const [canPrev, setCanPrev] = React.useState(false);
  const [canNext, setCanNext] = React.useState(true);

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

  React.useEffect(() => {updateScroll();}, [updateScroll, items]);

  const scrollBy = (dir) => {
    const el = scrollerRef.current;
    if (!el) return;
    const card = el.querySelector('[data-rel-card]');
    const step = card ? card.getBoundingClientRect().width + 16 : el.clientWidth * 0.8;
    el.scrollBy({ left: dir * step, behavior: 'smooth' });
  };

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

      <div ref={scrollerRef} onScroll={updateScroll}
      className="hide-scrollbar pdp-related-scroller"
      style={{
        display: 'grid', gridAutoFlow: 'column',
        gridAutoColumns: 'calc((100% - 24px) / 3)',
        gap: 12, overflowX: 'auto',
        scrollSnapType: 'x mandatory', scrollBehavior: 'smooth',
        padding: '4px 0 8px',
        scrollbarWidth: 'none', msOverflowStyle: 'none'
      }}>
        {items.map((p) =>
        <div key={p.id} data-rel-card style={{ scrollSnapAlign: 'start' }}>
            <RelatedRowCard product={p} onNavigate={onNavigate} />
          </div>
        )}
      </div>
    </div>);

};

/* ────────── STICKY TABS NAV (PDP) ────────── */
// Behaves like the "peek" variant of the home category tabs: the active tab
// is auto-scrolled to the centre so prev/next tabs visibly peek in from each
// side. No fades / scrollbar / arrow affordances here — the centering itself
// is the cue.
const StickyTabsNav = ({ reviewsCount, mode = 'sticky' }) => {
  const [active, setActive] = React.useState('pdp-descripcion');
  const [headerH, setHeaderH] = React.useState(72);
  const items = [
  { id: 'pdp-descripcion', label: 'Descripción' },
  { id: 'pdp-caracteristicas', label: 'Características' },
  { id: 'pdp-especificaciones', label: 'Especificaciones' },
  { id: 'pdp-faq', label: 'Preguntas frecuentes' },
  { id: 'pdp-testimonios', label: 'Testimonios' }];


  React.useEffect(() => {
    const measure = () => {
      const h = document.querySelector('header');
      if (h) setHeaderH(h.offsetHeight);
    };
    measure();
    window.addEventListener('resize', measure);
    // Re-measure a few times after mount in case fonts/announce strip shift layout
    const t1 = setTimeout(measure, 100);
    const t2 = setTimeout(measure, 500);
    const t3 = setTimeout(measure, 1200);
    return () => {
      window.removeEventListener('resize', measure);
      clearTimeout(t1);clearTimeout(t2);clearTimeout(t3);
    };
  }, []);

  React.useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + headerH + 80;
      let cur = items[0].id;
      for (const it of items) {
        const el = document.getElementById(it.id);
        if (el && el.offsetTop <= y) cur = it.id;
      }
      setActive(cur);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [headerH]);

  const go = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - (headerH + 60);
    window.scrollTo({ top: y, behavior: 'smooth' });
  };

  const scrollRef = React.useRef(null);

  // Mobile: scroll the tab nav horizontally to keep active tab CENTERED — this
  // is the "peek" effect: prev/next tabs visibly poke in from each side as a
  // cue that the row is swipeable. Real mobile browsers (iOS Safari) race the
  // initial layout, so we centre on mount via rAF (instant), then re-centre on
  // every active change AND on resize / orientation change.
  const centerActive = React.useCallback((smooth) => {
    const container = scrollRef.current;
    if (!container) return;
    const activeBtn = container.querySelector('button[data-active="true"]');
    if (!activeBtn) return;
    const target = activeBtn.offsetLeft - (container.clientWidth - activeBtn.clientWidth) / 2;
    container.scrollTo({ left: Math.max(0, target), behavior: smooth ? 'smooth' : 'auto' });
  }, []);

  // Initial centre + listen to resize/orientation.
  React.useEffect(() => {
    const raf1 = requestAnimationFrame(() => {
      centerActive(false);
      requestAnimationFrame(() => centerActive(false));
    });
    const onResize = () => centerActive(false);
    window.addEventListener('resize', onResize);
    window.addEventListener('orientationchange', onResize);
    return () => {
      cancelAnimationFrame(raf1);
      window.removeEventListener('resize', onResize);
      window.removeEventListener('orientationchange', onResize);
    };
  }, [centerActive]);

  // Smooth-centre when active tab changes.
  React.useEffect(() => {centerActive(true);}, [active, centerActive]);

  return (
    <div style={{
      position: mode === 'sticky' ? 'sticky' : 'relative',
      top: mode === 'sticky' ? headerH : undefined,
      zIndex: 30,
      background: 'var(--bg-2)',
      borderTop: '1px solid var(--line)',
      borderBottom: '1px solid var(--line)',
      marginTop: 32
    }} data-sticky-tabs="true">
      <div className="container" style={{ padding: '0 14px' }}>
        <div
          ref={scrollRef}
          style={{
            display: 'flex',
            gap: 4,
            overflowX: 'auto',
            scrollBehavior: 'smooth',
            scrollbarWidth: 'none'
          }}>
          {items.map((it) =>
          <button key={it.id} onClick={() => go(it.id)} data-active={active === it.id ? 'true' : 'false'}
          style={{
            padding: '16px 16px',
            fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap',
            color: active === it.id ? 'var(--ink)' : 'var(--ink-3)',
            borderBottom: '2px solid ' + (active === it.id ? 'var(--ink)' : 'transparent'),
            marginBottom: -1,
            transition: 'color .15s',
            flex: '0 0 auto'
          }}>{it.label}</button>
          )}
        </div>
      </div>
    </div>);

};

/* ────────── FEATURE SECTIONS (alternating) ────────── */
const FeatureSections = ({ product }) => {
  const blocks = [
  {
    eyebrow: 'USO CONTINUO',
    title: 'Ideal para trabajo profesional',
    body: product.desc || 'Diseñado para soportar largas jornadas de trabajo sin perder rendimiento. Construcción robusta pensada para profesionales que exigen lo máximo de sus equipos.',
    icon: 'zap',
    tint: '#FEF3E9',
    bg: '#FFF'
  },
  {
    eyebrow: 'TECNOLOGÍA',
    title: 'Componentes de alta durabilidad',
    body: 'Materiales y tecnología seleccionados para resistir el uso intensivo. Cada componente está pensado para ofrecer años de servicio confiable.',
    icon: 'settings',
    tint: '#E9F0FB',
    bg: 'var(--bg-2)'
  },
  {
    eyebrow: 'VERSATILIDAD',
    title: 'Se adapta a cualquier tarea',
    body: 'Accesorios intercambiables de acople rápido que permiten cambiar entre aplicaciones sin herramientas. Un solo equipo, múltiples usos.',
    icon: 'rotate',
    tint: '#EDF6EC',
    bg: '#FFF'
  },
  {
    eyebrow: 'ACCESORIOS',
    title: 'Todo incluido para empezar a trabajar',
    body: 'Viene completo con todos los accesorios necesarios. Desembalá, conectá y empezá a trabajar — sin compras adicionales.',
    icon: 'box',
    tint: '#F3EEFB',
    bg: 'var(--bg-2)'
  }];


  const hasRealImg = product.image && typeof product.image === 'string' && product.image.length > 0;

  return (
    <>
      {blocks.map((b, i) => {
        const reverse = i % 2 === 1;
        // Use the product image on the first block if available; placeholders for the rest
        const showRealImg = i === 0 && hasRealImg;
        return (
          <div key={i} style={{ background: b.bg, borderBottom: i < blocks.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <div className="container pdp-feature-row" style={{ padding: '64px 24px' }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr',
                gap: 48,
                alignItems: 'center',
                direction: reverse ? 'rtl' : 'ltr'
              }}>
                <div style={{ direction: 'ltr', display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 340 }}>
                  {showRealImg ?
                  <img src={product.image} alt="" style={{ maxWidth: '100%', maxHeight: 420, objectFit: 'contain' }}
                  onError={(e) => {e.target.style.display = 'none';e.target.nextSibling && (e.target.nextSibling.style.display = 'flex');}} /> :
                  null}
                  <div style={{
                    display: showRealImg ? 'none' : 'flex',
                    width: '100%', maxWidth: 460, aspectRatio: '4/3',
                    background: b.tint,
                    borderRadius: 16,
                    alignItems: 'center', justifyContent: 'center',
                    position: 'relative', overflow: 'hidden'
                  }}>
                    {/* Subtle grid pattern */}
                    <div style={{
                      position: 'absolute', inset: 0, opacity: 0.35,
                      backgroundImage: 'linear-gradient(rgba(0,0,0,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(0,0,0,0.04) 1px, transparent 1px)',
                      backgroundSize: '24px 24px'
                    }} />
                    {/* Big icon */}
                    <div style={{ position: 'relative', width: 140, height: 140, borderRadius: '50%', background: '#FFF', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 8px 28px rgba(0,0,0,0.06)' }}>
                      <Icon name={b.icon} size={56} strokeWidth={1.3} />
                    </div>
                    {/* Placeholder label */}
                    <div className="mono" style={{ position: 'absolute', bottom: 16, right: 20, fontSize: 10, letterSpacing: '0.15em', color: 'var(--ink-4)', textTransform: 'uppercase' }}>
                      Imagen · {b.eyebrow.toLowerCase()}
                    </div>
                  </div>
                </div>
                <div style={{ direction: 'ltr', maxWidth: 460 }}>
                  <div className="mono" style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.12em', color: 'var(--accent)', textTransform: 'uppercase', marginBottom: 14 }}>
                    {b.eyebrow}
                  </div>
                  <h3 style={{ fontSize: 28, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.15, marginBottom: 14 }}>
                    {b.title}
                  </h3>
                  <p style={{ fontSize: 15, lineHeight: 1.65, color: 'var(--ink-2)' }}>
                    {b.body}
                  </p>
                </div>
              </div>
            </div>
          </div>);

      })}
    </>);

};

/* ────────── SPECS BLOCK (variants) ────────── */
const SpecsBlock = ({ product, variant = 'table' }) => {
  const s = product.specs || {};
  let rows;
  if (product.cat === 'hidro') {
    rows = [
    ['Motor', (s['Motor'] || '—') + ' Monofásico 220V'],
    ['Presión', s['Presión'] || s['Bares'] || s['Presion'] || '150 bar'],
    ['Caudal', s['Caudal'] || s['Flujo'] || '450 L/h'],
    ['Potencia', s['Potencia'] || s['Power'] || '2.200 W']];

  } else {
    rows = Object.entries(s);
  }

  if (variant === 'cards') {
    return (
      <div className="pdp-specs-cards" style={{ display: 'grid', gridTemplateColumns: `repeat(${rows.length}, minmax(0, 1fr))`, gap: 14, maxWidth: '100%' }}>
        {rows.map(([k, v]) =>
        <div key={k}
        onMouseEnter={(e) => {e.currentTarget.style.transform = 'scale(1.05)';e.currentTarget.style.boxShadow = '0 6px 20px rgba(10,26,47,0.08)';e.currentTarget.style.borderColor = 'var(--ink-3)';}}
        onMouseLeave={(e) => {e.currentTarget.style.transform = 'scale(1)';e.currentTarget.style.boxShadow = 'none';e.currentTarget.style.borderColor = 'var(--line)';}}
        style={{
          padding: '18px 18px', background: '#FFF',
          border: '1px solid var(--line)', borderRadius: 'var(--r-md)',
          transition: 'transform .25s ease, box-shadow .25s ease, border-color .25s ease',
          cursor: 'default'
        }}>
            <div className="mono" style={{ fontSize: 10, color: '#a00e0c', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 400 }}>{k}</div>
            <div style={{ fontSize: 20, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.01em', marginTop: 6, lineHeight: 1.2 }}>{v}</div>
          </div>
        )}
      </div>);

  }

  if (variant === 'stripes') {
    return (
      <div style={{ maxWidth: 720 }}>
        {rows.map(([k, v], i) =>
        <div key={k} style={{
          display: 'grid', gridTemplateColumns: '220px 1fr', gap: 16,
          padding: '14px 18px',
          background: i % 2 === 0 ? 'var(--bg-2)' : 'transparent',
          borderRadius: 6
        }}>
            <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>{k}</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>{v}</div>
          </div>
        )}
      </div>);

  }

  if (variant === 'minimal') {
    return (
      <div style={{ maxWidth: 720, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px 32px' }}>
        {rows.map(([k, v]) =>
        <div key={k} style={{ display: 'flex', alignItems: 'baseline', gap: 8, paddingBottom: 12, borderBottom: '1px dashed var(--line)' }}>
            <span style={{ fontSize: 13, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', flex: 1 }}>{k}</span>
            <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>{v}</span>
          </div>
        )}
      </div>);

  }

  // table (default)
  return (
    <div style={{ background: '#FFF', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', overflow: 'hidden', maxWidth: 720 }}>
      <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)', background: 'var(--bg-2)' }}>
        <div className="mono t-xs" style={{ textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--accent)', fontWeight: 700 }}>Datos técnicos</div>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <tbody>
          {rows.map(([k, v], i) =>
          <tr key={k} style={{ borderBottom: i === rows.length - 1 ? 'none' : '1px solid var(--line)' }}>
              <td style={{ padding: '16px 20px', fontSize: 13, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', width: 220, fontWeight: 500 }}>{k}</td>
              <td style={{ padding: '16px 20px', fontSize: 14, fontWeight: 700 }}>{v}</td>
            </tr>
          )}
        </tbody>
      </table>
    </div>);

};

/* ────────── FAQ BLOCK (variants) ────────── */
const FAQ_ITEMS = [
{ q: '¿Hacen envíos a todo el país?', a: 'Sí. Envío gratis en CABA y GBA (48 hs). Al interior por Andreani, Correo Argentino o transporte a cotizar según destino y volumen.' },
{ q: '¿Tienen servicio técnico propio?', a: 'Sí. Contamos con taller propio en Haedo con más de 15 años de experiencia. Atendemos tanto garantías como reparaciones fuera de garantía.' },
{ q: '¿En cuántas cuotas puedo pagar?', a: 'Hasta 6 cuotas sin interés con tarjeta. 15% OFF adicional pagando por transferencia bancaria. También aceptamos Mercado Pago y efectivo en local.' },
{ q: '¿El producto incluye garantía?', a: 'Sí. Todos nuestros equipos incluyen garantía oficial del fabricante. Los plazos varían según el modelo — consultá las especificaciones del producto.' }];


const FAQBlock = ({ variant = 'accordion' }) => {
  if (variant === 'cards') {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16, maxWidth: 1080 }}>
        {FAQ_ITEMS.map((f, i) =>
        <div key={i} style={{ padding: 22, background: '#FFF', border: '1px solid var(--line)', borderRadius: 'var(--r-md)' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', fontWeight: 700 }}>0{i + 1}</span>
              <h4 style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>{f.q}</h4>
            </div>
            <p style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6, marginTop: 10 }}>{f.a}</p>
          </div>
        )}
      </div>);

  }

  if (variant === 'chat') {
    return (
      <div style={{ maxWidth: 720, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {FAQ_ITEMS.map((f, i) =>
        <React.Fragment key={i}>
            <div style={{ alignSelf: 'flex-start', maxWidth: '80%', padding: '12px 16px', background: 'var(--bg-2)', borderRadius: '14px 14px 14px 4px', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
              {f.q}
            </div>
            <div style={{ alignSelf: 'flex-end', maxWidth: '80%', padding: '12px 16px', background: '#a00e0c', color: '#fff', borderRadius: '14px 14px 4px 14px', fontSize: 14, lineHeight: 1.55 }}>
              {f.a}
            </div>
          </React.Fragment>
        )}
      </div>);

  }

  if (variant === 'columns') {
    const [active, setActive] = React.useState(0);
    const [hovered, setHovered] = React.useState(null);
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 32, maxWidth: 980 }}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {FAQ_ITEMS.map((f, i) => {
            const isActive = active === i;
            const isHover = hovered === i && !isActive;
            return (
              <button key={i}
              onClick={() => setActive(i)}
              onMouseEnter={() => setHovered(i)}
              onMouseLeave={() => setHovered(null)}
              style={{
                textAlign: 'left', padding: '14px 16px',
                fontSize: 14, fontWeight: isActive ? 700 : 500,
                color: isActive ? '#fff' : 'var(--ink-3)',
                borderLeft: '3px solid ' + (isActive || isHover ? '#a00e0c' : 'transparent'),
                background: isActive ? '#a00e0c' : 'transparent',
                cursor: 'pointer',
                transition: 'background .15s ease, color .15s ease, border-color .15s ease'
              }}>{f.q}</button>);

          })}
        </div>
        <div style={{ padding: '14px 0', fontSize: 16, lineHeight: 1.6, color: 'var(--ink-2)' }}>
          {FAQ_ITEMS[active]?.a}
        </div>
      </div>);

  }

  // accordion (default)
  return <FAQAccordion />;
};

/* ────────── FAQ ACCORDION ────────── */
const FAQAccordion = () => {
  const [open, setOpen] = React.useState(0);
  const faqs = [
  {
    q: '¿Hacen envíos a todo el país?',
    a: 'Sí. Envío gratis en CABA y GBA (48 hs). Al interior por Andreani, Correo Argentino o transporte a cotizar según destino y volumen.'
  },
  {
    q: '¿Tienen servicio técnico propio?',
    a: 'Sí. Contamos con taller propio en Haedo con más de 15 años de experiencia. Atendemos tanto garantías como reparaciones fuera de garantía.'
  },
  {
    q: '¿En cuántas cuotas puedo pagar?',
    a: 'Hasta 6 cuotas sin interés con tarjeta. 15% OFF adicional pagando por transferencia bancaria. También aceptamos Mercado Pago y efectivo en local.'
  },
  {
    q: '¿El producto incluye garantía?',
    a: 'Sí. Todos nuestros equipos incluyen garantía oficial del fabricante. Los plazos varían según el modelo — consultá las especificaciones del producto.'
  }];

  return (
    <div style={{ maxWidth: 820, border: '1px solid var(--line)', borderRadius: 'var(--r-md)', overflow: 'hidden', background: '#FFF' }}>
      {faqs.map((f, i) => {
        const isOpen = open === i;
        return (
          <div key={i} style={{ borderBottom: i < faqs.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <button onClick={() => setOpen(isOpen ? -1 : i)} style={{
              width: '100%', padding: '20px 24px', textAlign: 'left',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
              background: isOpen ? 'var(--bg-2)' : 'transparent',
              cursor: 'pointer', transition: 'background .15s'
            }}>
              <span style={{ fontSize: 15, fontWeight: 600 }}>{f.q}</span>
              <span style={{ width: 28, height: 28, borderRadius: 999, background: '#FFF', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transform: isOpen ? 'rotate(45deg)' : 'none', transition: 'transform .2s' }}>
                <Icon name="plus" size={14} strokeWidth={2} />
              </span>
            </button>
            {isOpen &&
            <div style={{ padding: '0 24px 22px', fontSize: 14, lineHeight: 1.65, color: 'var(--ink-2)', maxWidth: 640 }}>
                {f.a}
              </div>
            }
          </div>);

      })}
    </div>);

};

/* ────────── CART DRAWER ────────── */
const CartDrawer = ({ open, onClose, items, onUpdate, onRemove, onNavigate, onAdd }) => {
  const total = items.reduce((s, i) => s + i.price * i.qty, 0);
  const [showExtras, setShowExtras] = React.useState(false);
  React.useEffect(() => { if (!open) setShowExtras(false); }, [open]);
  if (!open) return null;

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 80 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)' }} />
      <div className="cart-drawer-panel" style={{
        position: 'absolute', right: 0, top: 0, bottom: 0,
        width: 'min(440px, 85vw)', background: 'var(--surface)',
        display: 'flex', flexDirection: 'column',
        animation: 'slideIn .25s ease', overflow: 'hidden'
      }}>
        <style>{`@keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }`}</style>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ fontSize: 18, fontWeight: 700 }}>Tu carrito {items.length > 0 && <span className="mono t-small" style={{ marginLeft: 6 }}>({items.length})</span>}</h3>
          <button onClick={onClose}><Icon name="close" size={20} /></button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '0 24px 24px' }}>
          {items.length === 0 ?
          <div style={{ textAlign: 'center', padding: 60 }}>
              <Icon name="cart" size={40} strokeWidth={1.3} />
              <div style={{ fontSize: 16, fontWeight: 600, marginTop: 16 }}>Tu carrito está vacío</div>
              <p className="t-body" style={{ marginTop: 6 }}>Agregá productos para comenzar.</p>
              <button className="btn btn-dark" style={{ marginTop: 20 }} onClick={() => {onClose();onNavigate('/tienda');}}>
                Explorar catálogo
              </button>
            </div> :
          items.map((it) =>
          <div key={it.id} style={{ display: 'grid', gridTemplateColumns: '64px 1fr auto', gap: 14, padding: '14px 0', borderBottom: '1px dashed var(--line)' }}>
              <div style={{ width: 64, height: 64, background: '#FFF', border: '1px solid var(--line)', borderRadius: 6, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {it.image ? <img src={it.image} alt={it.name} style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 4 }} /> : <span className="mono t-xs" style={{ fontSize: 9 }}>{it.brand}</span>}
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, marginTop: 2, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{it.name}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--line-2)', borderRadius: 4 }}>
                    <button style={{ padding: '4px 8px' }} onClick={() => onUpdate(it.id, Math.max(1, it.qty - 1))}><Icon name="minus" size={11} /></button>
                    <span style={{ padding: '0 8px', fontSize: 13, fontWeight: 600 }}>{it.qty}</span>
                    <button style={{ padding: '4px 8px' }} onClick={() => onUpdate(it.id, it.qty + 1)}><Icon name="plus" size={11} /></button>
                  </div>
                  <button onClick={() => onRemove(it.id)} className="t-xs" style={{ color: 'var(--ink-4)', textDecoration: 'underline' }}>Quitar</button>
                </div>
              </div>
              <div style={{ fontWeight: 700, whiteSpace: 'nowrap' }}>{fmtARS(it.price * it.qty)}</div>
            </div>
          )}
        </div>
        {items.length > 0 &&
        <div style={{ padding: 24, borderTop: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <span className="t-small">Subtotal</span>
              <span style={{ fontWeight: 600 }}>{fmtARS(total)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
              <span className="t-small">Envío</span>
              <span className="t-small" style={{ color: '#a00e0c', fontWeight: 600 }}>Calcular en checkout</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '14px 0 10px', borderTop: '1px solid var(--line)' }}>
              <span style={{ fontWeight: 700 }}>Total</span>
              <span style={{ fontSize: 20, fontWeight: 800 }}>{fmtARS(total)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingBottom: 14, borderBottom: '1px solid var(--line)', marginBottom: 16 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
                <span style={{ background: '#0f8a5b', color: '#fff', fontSize: 10, fontWeight: 800, letterSpacing: '0.04em', padding: '3px 6px', borderRadius: 4 }}>15% OFF</span>
                <span style={{ color: 'var(--ink-3)' }}>🔥 Abonando en 1 pago</span>
              </span>
              <span style={{ fontSize: 14, fontWeight: 700, color: '#0f8a5b' }}>{fmtARS(Math.round(total * 0.85))}</span>
            </div>
            <button className="btn btn-primary" style={{ width: '100%', padding: '14px' }}
          onClick={() => setShowExtras(true)}>
              Finalizar compra <Icon name="arrowRight" size={14} />
            </button>
            <button className="btn btn-ghost" style={{ width: '100%', marginTop: 8 }}>
              <Icon name="whatsapp" size={14} /> Comprar por WhatsApp
            </button>
          </div>
        }

        {/* Cross-sell superpuesto dentro del mismo panel del carrito */}
        <CrossSellSheet
          open={showExtras}
          cart={items}
          onAdd={onAdd}
          onRemove={onRemove}
          onNavigate={onNavigate}
          onClose={() => setShowExtras(false)}
          onContinue={() => { setShowExtras(false); onClose(); onNavigate('/checkout'); }} />
      </div>
    </div>);

};

/* ────────── BENEFITS BLOCK (SEO-friendly bullets) ────────── */
const BENEFIT_ITEMS = [
{ icon: 'shield', title: 'Garantía oficial 12 meses', desc: 'Cobertura del fabricante con respaldo directo de RC Powerclean.' },
{ icon: 'truck', title: 'Envío gratis CABA y GBA', desc: 'Despacho en 24/48 hs. Al interior por Andreani o transporte.' },
{ icon: 'wrench', title: 'Servicio técnico propio', desc: 'Taller en Haedo con repuestos originales en stock.' },
{ icon: 'credit', title: '12 cuotas sin interés', desc: 'Todas las tarjetas. 15% OFF pagando por transferencia.' },
{ icon: 'phone', title: 'Asesoramiento por WhatsApp', desc: 'Te ayudamos a elegir el equipo correcto para tu uso.' }];


const BenefitsBlock = ({ variant = 'checklist' }) => {
  // CARDS — small icon cards in a 2-col grid
  if (variant === 'cards') {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 12 }}>
        {BENEFIT_ITEMS.map((b) =>
        <div key={b.title} style={{ padding: 16, background: '#FFF', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <span style={{ width: 36, height: 36, borderRadius: 8, background: 'rgba(160,14,12,0.08)', color: '#a00e0c', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name={b.icon} size={18} />
            </span>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', lineHeight: 1.3 }}>{b.title}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3, lineHeight: 1.4 }}>{b.desc}</div>
            </div>
          </div>
        )}
      </div>);

  }

  // NUMBERED — large numbers, no icons
  if (variant === 'numbered') {
    return (
      <ol style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column' }}>
        {BENEFIT_ITEMS.map((b, i) =>
        <li key={b.title} style={{ display: 'grid', gridTemplateColumns: '48px 1fr', gap: 14, padding: '14px 0', borderBottom: i < BENEFIT_ITEMS.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <span className="mono" style={{ fontSize: 22, fontWeight: 800, color: '#a00e0c', letterSpacing: '-0.02em', lineHeight: 1 }}>{String(i + 1).padStart(2, '0')}</span>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', lineHeight: 1.3 }}>{b.title}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 3, lineHeight: 1.45 }}>{b.desc}</div>
            </div>
          </li>
        )}
      </ol>);

  }

  // PANEL — dark inverted panel
  if (variant === 'panel') {
    return (
      <div style={{ background: 'var(--ink)', color: '#fff', borderRadius: 'var(--r-md)', padding: '22px 22px 6px' }}>
        <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
          {BENEFIT_ITEMS.map((b, i) =>
          <li key={b.title} style={{ display: 'grid', gridTemplateColumns: '24px 1fr', gap: 12, padding: '12px 0', borderBottom: i < BENEFIT_ITEMS.length - 1 ? '1px solid rgba(255,255,255,0.1)' : 'none', alignItems: 'flex-start' }}>
              <span style={{ color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: 2 }}>
                <Icon name={b.icon} size={18} strokeWidth={1.5} />
              </span>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.3 }}>{b.title}</div>
                <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.7)', marginTop: 3, lineHeight: 1.45 }}>{b.desc}</div>
              </div>
            </li>
          )}
        </ul>
      </div>);

  }

  // STRIPES — to match SpecsBlock zebra
  if (variant === 'stripes') {
    return (
      <div style={{ borderRadius: 'var(--r-md)', overflow: 'hidden' }}>
        {BENEFIT_ITEMS.map((b, i) =>
        <div key={b.title} style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 14, padding: '16px 20px', background: i % 2 === 0 ? 'var(--bg-2)' : 'transparent', alignItems: 'center' }}>
            <span style={{ color: '#a00e0c', display: 'flex', alignItems: 'center' }}>
              <Icon name={b.icon} size={20} strokeWidth={1.6} />
            </span>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', lineHeight: 1.3 }}>{b.title}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2, lineHeight: 1.45 }}>{b.desc}</div>
            </div>
          </div>
        )}
      </div>);

  }

  // CHECKLIST (default) — red check icon + title + desc
  return (
    <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 14 }}>
      {BENEFIT_ITEMS.map((b) =>
      <li key={b.title} style={{ display: 'grid', gridTemplateColumns: '22px 1fr', gap: 12, alignItems: 'flex-start' }}>
          <span style={{ width: 22, height: 22, borderRadius: 11, background: '#a00e0c', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
            <Icon name="check" size={12} strokeWidth={2.6} />
          </span>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)', lineHeight: 1.35 }}>{b.title}</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 2, lineHeight: 1.5 }}>{b.desc}</div>
          </div>
        </li>
      )}
    </ul>);

};

/* ────────── FULL SPEC SHEET (Ficha técnica completa) ────────── */
const FullSpecSheet = ({ product }) => {
  const s = product.specs || {};
  const sku = product.sku || product.id;

  const groups = [
  {
    title: 'Motor',
    rows: [
    ['Tipo', s['Motor'] || 'Eléctrico universal con escobillas'],
    ['Potencia nominal', s['Potencia'] || '2.200 W'],
    ['Voltaje', '220V Monofásico'],
    ['Frecuencia', '50 Hz'],
    ['Revoluciones', '2.800 RPM'],
    ['Aislación', 'Clase F'],
    ['Protección térmica', 'Sí, rearme automático']]

  },
  {
    title: 'Bomba',
    rows: [
    ['Tipo', 'Axial con pistones cerámicos'],
    ['Cantidad de pistones', '3'],
    ['Material del cabezal', 'Aluminio forjado'],
    ['Sistema', 'By-pass automático'],
    ['Total stop', 'Sí'],
    ['Lubricación', 'Aceite ISO 32'],
    ['Vida útil estimada', '500 hs continuas']]

  },
  {
    title: 'Hidráulica',
    rows: [
    ['Presión máxima', s['Presión'] || s['Bares'] || '160 bar'],
    ['Presión de trabajo', '120 bar'],
    ['Caudal nominal', s['Caudal'] || '450 L/h'],
    ['Caudal máximo', '600 L/h'],
    ['Temperatura agua entrada', 'Máx 40°C'],
    ['Presión agua entrada', '0,1 – 10 bar'],
    ['Aspiración', 'Sí, hasta 0,5 m']]

  },
  {
    title: 'Construcción',
    rows: [
    ['Carcasa', 'Polipropileno reforzado'],
    ['Chasis', 'Acero pintado epoxi'],
    ['Manija', 'Ergonómica plegable'],
    ['Ruedas', '2 traseras antipinchazos'],
    ['Soporte accesorios', 'Integrado'],
    ['Color', 'Rojo / negro']]

  },
  {
    title: 'Accesorios incluidos',
    rows: [
    ['Manguera de alta presión', '8 m, trenzado de acero'],
    ['Pistola', 'Profesional con seguro'],
    ['Lanza', 'Multirregulable + lanza turbo'],
    ['Boquillas', '3 unidades (0°, 15°, 40°)'],
    ['Cable de alimentación', '5 m, 3 × 2,5 mm²'],
    ['Detergente', '250 ml de muestra'],
    ['Manual y certificado', 'Incluidos']]

  },
  {
    title: 'Dimensiones y peso',
    rows: [
    ['Largo', '42 cm'],
    ['Ancho', '34 cm'],
    ['Alto', '88 cm'],
    ['Peso neto', '18,5 kg'],
    ['Peso bruto', '21 kg'],
    ['Embalaje', '45 × 38 × 92 cm']]

  },
  {
    title: 'Datos comerciales',
    rows: [
    ['Marca', product.brand || 'Powerclean'],
    ['Modelo', sku],
    ['Origen', 'Industria nacional'],
    ['Certificación', 'IRAM / IEC 60335'],
    ['Garantía', '12 meses oficial'],
    ['Código de fábrica', `LT-${String(sku).slice(-3)}-X1`]]

  }];


  return (
    <div className="pdp-card" style={{
      background: 'var(--surface)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--r-lg)',
      padding: '28px 32px'
    }}>
      <div className="ficha-toc" style={{
        display: 'flex', flexWrap: 'wrap', gap: 8,
        paddingBottom: 18, marginBottom: 22,
        borderBottom: '1px solid var(--line)'
      }}>
        {groups.map((g) =>
        <a key={g.title} href={`#ft-${g.title}`}
        onClick={(e) => {
          e.preventDefault();
          const el = document.getElementById(`ft-${g.title}`);
          if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: 'smooth' });
        }}
        className="mono"
        style={{
          fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase',
          color: 'var(--ink-3)', padding: '6px 10px',
          border: '1px solid var(--line)', borderRadius: 4,
          textDecoration: 'none'
        }}>
            {g.title}
          </a>
        )}
      </div>

      {groups.map((g, gi) =>
      <div key={g.title} id={`ft-${g.title}`} style={{
        scrollMarginTop: 80,
        marginBottom: gi < groups.length - 1 ? 28 : 0
      }}>
          <h3 className="mono" style={{
          fontSize: 12, fontWeight: 700,
          letterSpacing: '0.1em', textTransform: 'uppercase',
          color: '#a00e0c',
          margin: '0 0 14px',
          paddingBottom: 8,
          borderBottom: '2px solid var(--ink)'
        }}>{g.title}</h3>
          <div className="ficha-rows" style={{
          display: 'grid',
          gridTemplateColumns: '180px 1fr 180px 1fr',
          columnGap: 24, rowGap: 0
        }}>
            {g.rows.map(([k, v], i) =>
          <React.Fragment key={k}>
                <div style={{
              fontSize: 13, color: 'var(--ink-3)',
              padding: '10px 0',
              borderBottom: '1px solid var(--line)'
            }}>{k}</div>
                <div style={{
              fontSize: 13, color: 'var(--ink), 0', fontWeight: 700,
              padding: '10px 0',
              borderBottom: '1px solid var(--line)',
              color: 'var(--ink)'
            }}>{v}</div>
              </React.Fragment>
          )}
          </div>
        </div>
      )}
    </div>);

};

Object.assign(window, { ShopPage, ProductPage, CartDrawer });