// MendiArt — Página principal (mobile)
// Marca: azul #1A2FA0, naranja #F05A0A

const C = {
  azul: '#1A2FA0',
  azulDark: '#0E1F7F',
  naranja: '#F05A0A',
  naranjaDark: '#D04A00',
  verde: '#25D366',
  bg: '#F7F7F7',
  text: '#1A1A1A',
  muted: '#6B7280',
  line: '#E7E8EE',
  chipGray: '#F1F2F6',
};

// ─── Iconos (line, 1.6 stroke) ───────────────────────────────
const Icon = {
  Search: ({s=22, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <circle cx="11" cy="11" r="7" stroke={c} strokeWidth="1.8"/>
      <path d="M20 20l-3.5-3.5" stroke={c} strokeWidth="1.8" strokeLinecap="round"/>
    </svg>
  ),
  Cart: ({s=22, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3 4h2.2l2.3 11.2a2 2 0 002 1.6h8.4a2 2 0 002-1.6L21.5 7H6" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx="9" cy="20" r="1.4" fill={c}/>
      <circle cx="18" cy="20" r="1.4" fill={c}/>
    </svg>
  ),
  Home: ({s=22, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3.5 11L12 4l8.5 7v9a1 1 0 01-1 1H14v-6h-4v6H4.5a1 1 0 01-1-1v-9z" stroke={c} strokeWidth="1.8" strokeLinejoin="round"/>
    </svg>
  ),
  Grid: ({s=22, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <rect x="3.5" y="3.5" width="7" height="7" rx="1.5" stroke={c} strokeWidth="1.8"/>
      <rect x="13.5" y="3.5" width="7" height="7" rx="1.5" stroke={c} strokeWidth="1.8"/>
      <rect x="3.5" y="13.5" width="7" height="7" rx="1.5" stroke={c} strokeWidth="1.8"/>
      <rect x="13.5" y="13.5" width="7" height="7" rx="1.5" stroke={c} strokeWidth="1.8"/>
    </svg>
  ),
  Check: ({s=22, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M4 12.5l4.5 4.5L20 6" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  Truck: ({s=24, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M2.5 6h11v10H2.5V6z" stroke={c} strokeWidth="1.6"/>
      <path d="M13.5 9.5H18l3 3.5v3h-7.5" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <circle cx="7" cy="17.5" r="1.8" stroke={c} strokeWidth="1.6"/>
      <circle cx="17" cy="17.5" r="1.8" stroke={c} strokeWidth="1.6"/>
    </svg>
  ),
  Store: ({s=24, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3 9l1.2-4h15.6L21 9" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <path d="M3 9v11h18V9" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <path d="M3 9c0 1.7 1.3 3 3 3s3-1.3 3-3m0 0c0 1.7 1.3 3 3 3s3-1.3 3-3m0 0c0 1.7 1.3 3 3 3s3-1.3 3-3" stroke={c} strokeWidth="1.6"/>
      <rect x="9.5" y="13.5" width="5" height="6.5" stroke={c} strokeWidth="1.6"/>
    </svg>
  ),
  Compat: ({s=24, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M9.5 7L4 12.5l5.5 5.5M14.5 7L20 12.5l-5.5 5.5" stroke={c} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  Wrench: ({s=24, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M14.5 3.5a4.5 4.5 0 015.5 5.5l-2.5-1L16 9.5l-1-1.5 1-1.5-1-2.5a4.5 4.5 0 00-.5-.5z" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <path d="M13.5 8.5l-9 9a2 2 0 102.8 2.8l9-9" stroke={c} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  Tag: ({s=24, c='#111'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3 7a2 2 0 012-2h5.586a1 1 0 01.707.293l8 8a2 2 0 010 2.828l-5.586 5.586a2 2 0 01-2.828 0l-8-8A1 1 0 013 13V7z" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <circle cx="7.5" cy="10.5" r="1.2" fill={c}/>
    </svg>
  ),
  Instagram: ({s=24, c='#fff'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <rect x="2" y="2" width="20" height="20" rx="5" stroke={c} strokeWidth="1.8"/>
      <circle cx="12" cy="12" r="5" stroke={c} strokeWidth="1.8"/>
      <circle cx="17.5" cy="6.5" r="1" fill={c}/>
    </svg>
  ),
  Facebook: ({s=24, c='#fff'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z" stroke={c} strokeWidth="1.8" strokeLinejoin="round"/>
    </svg>
  ),
  YouTube: ({s=24, c='#fff'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M22 8s-.3-2-1.2-2.8c-1.1-1.2-2.4-1.2-3-1.3C15.6 3.8 12 3.8 12 3.8s-3.6 0-5.8.1c-.6.1-1.9.1-3 1.3C2.3 6 2 8 2 8S1.8 10.3 1.8 12.5v2.1C1.8 16.8 2 19 2 19s.3 2 1.2 2.8c1.1 1.2 2.6 1.1 3.3 1.2C8.8 23.1 12 23.2 12 23.2s3.6 0 5.8-.2c.6-.1 1.9-.1 3-1.3.9-.8 1.2-2.8 1.2-2.8s.2-2.2.2-4.4v-2.1C22.2 10.3 22 8 22 8z" stroke={c} strokeWidth="1.8"/>
      <path d="M9.5 15.5v-7l7 3.5-7 3.5z" fill={c}/>
    </svg>
  ),
  Plus: ({s=18, c='#fff'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M12 5v14M5 12h14" stroke={c} strokeWidth="2.4" strokeLinecap="round"/>
    </svg>
  ),
  Minus: ({s=18, c='#fff'}) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M5 12h14" stroke={c} strokeWidth="2.4" strokeLinecap="round"/>
    </svg>
  ),
  WhatsApp: ({s=28, c='#fff'}) => (
    <svg width={s} height={s} viewBox="0 0 32 32" fill="none">
      <path d="M16 3C8.8 3 3 8.8 3 16c0 2.3.6 4.5 1.7 6.4L3 29l6.8-1.8A13 13 0 0016 29c7.2 0 13-5.8 13-13S23.2 3 16 3z" fill={c}/>
      <path d="M11.6 9.8c-.3-.7-.6-.7-.9-.7h-.8c-.3 0-.7.1-1.1.5-.4.4-1.5 1.5-1.5 3.6s1.6 4.2 1.8 4.5c.2.3 3 4.8 7.5 6.5 3.7 1.4 4.5 1.1 5.3 1.1.8-.1 2.6-1 3-2.1.4-1 .4-1.9.3-2.1-.1-.2-.4-.3-.9-.5-.5-.3-2.6-1.3-3-1.4-.4-.2-.7-.2-1 .3-.3.4-1.2 1.4-1.4 1.7-.3.3-.5.3-1 .1-.5-.3-1.9-.7-3.6-2.2-1.3-1.2-2.2-2.6-2.5-3.1-.3-.5 0-.7.2-1 .2-.2.5-.6.7-.9.2-.3.3-.5.5-.8.2-.3.1-.6 0-.9-.1-.2-1-2.4-1.4-3.3z" fill={C.verde}/>
    </svg>
  ),
};

// ─── Logo ─────────────────────────────────────────────────────
function Logo({ size = 'md', dark = false }) {
  const h = size === 'lg' ? 60 : size === 'sm' ? 30 : 44;
  return (
    <img
      src={dark ? 'logo-light.svg' : 'logo.svg'}
      alt="MendiArt"
      style={{ height: h, width: 'auto', display: 'block' }}
    />
  );
}

// ─── Cinta scrolleable (marquee continuo) ─────────────────────
const TICKER_DEFAULT = ['Envíos a todo Mendoza', 'Consultá por WhatsApp', 'Buscador de compatibilidad', 'Retiro en el día', 'Precios especiales para distribuidores', 'Servicio técnico de impresoras'];

function Ticker({ cintaMensajes }) {
  let items = TICKER_DEFAULT;
  if (cintaMensajes) {
    try {
      const parsed = typeof cintaMensajes === 'string' ? JSON.parse(cintaMensajes) : cintaMensajes;
      if (Array.isArray(parsed) && parsed.length > 0) items = parsed;
    } catch {}
  }
  const set = (key) => (
    <div key={key} style={{ display: 'flex', alignItems: 'center', gap: 28, paddingRight: 28 }}>
      {items.map((t, i) => (
        <React.Fragment key={key + i}>
          <span style={{
            fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
            color: '#fff', letterSpacing: 0.6, textTransform: 'uppercase',
            whiteSpace: 'nowrap',
          }}>{t}</span>
          <span style={{ width: 4, height: 4, borderRadius: 4, background: 'rgba(255,255,255,0.55)' }} />
        </React.Fragment>
      ))}
    </div>
  );
  return (
    <div style={{ background: C.naranja, overflow: 'hidden', position: 'relative', height: 32 }}>
      <div className="ticker-track" style={{
        display: 'flex', alignItems: 'center', height: '100%',
        animation: 'mendi-ticker 36s linear infinite', willChange: 'transform',
      }}>
        {set('a')}{set('b')}{set('c')}
      </div>
    </div>
  );
}

// ─── Navbar ──────────────────────────────────────────────────
function Navbar({ cartCount, onSearchClick, onCartClick }) {
  return (
    <div style={{
      background: '#fff', display: 'flex', alignItems: 'center',
      justifyContent: 'space-between', padding: '10px 16px',
      borderBottom: `1px solid ${C.line}`,
    }}>
      <Logo size="md" />
      <div style={{ display: 'flex', gap: 6 }}>
        <button onClick={onSearchClick} style={iconBtn}>
          <Icon.Search s={22} c={C.text} />
        </button>
        <button onClick={onCartClick} style={{ ...iconBtn, position: 'relative' }}>
          <Icon.Cart s={22} c={C.text} />
          {cartCount > 0 && (
            <span style={{
              position: 'absolute', top: 2, right: 2,
              minWidth: 18, height: 18, padding: '0 5px',
              background: C.naranja, color: '#fff',
              borderRadius: 10, fontSize: 10, fontWeight: 800,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: '2px solid #fff',
            }}>{cartCount}</span>
          )}
        </button>
      </div>
    </div>
  );
}
const iconBtn = {
  width: 40, height: 40, borderRadius: 12, border: 'none',
  background: 'transparent', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

// ─── Hero ────────────────────────────────────────────────────
function Hero({ onCatalog, slogan, subtitulo }) {
  const textoSlogan = slogan || 'Todo para imprimir mejor.';
  const textoSub = subtitulo || 'Papel fotográfico, tintas y cartuchos para tu impresora.';
  return (
    <div style={{
      background: C.azul, color: '#fff', padding: '20px 20px 22px',
      position: 'relative', overflow: 'hidden',
    }}>
      <svg width="100%" height="90" viewBox="0 0 390 90" preserveAspectRatio="none"
        style={{ position: 'absolute', right: -30, bottom: -10, opacity: 0.08 }}>
        <path d="M0 90L80 22l60 45 80-60 90 75 80-37v45H0z" fill="#fff"/>
      </svg>
      <div style={{
        fontFamily: 'inherit', fontSize: 10, fontWeight: 700,
        letterSpacing: 2, textTransform: 'uppercase', opacity: 0.7, marginBottom: 8,
      }}>Mendoza, Argentina</div>
      <h1 style={{
        fontFamily: 'inherit', fontSize: 30, fontWeight: 800,
        lineHeight: 1.05, margin: 0, letterSpacing: '-0.02em',
        textWrap: 'balance',
      }}>{textoSlogan}</h1>
      <p style={{
        fontFamily: 'inherit', fontSize: 13.5, lineHeight: 1.4,
        margin: '10px 0 16px', maxWidth: 280, color: 'rgba(255,255,255,0.78)',
      }}>{textoSub}</p>
      <button onClick={onCatalog} style={{
        background: C.naranja, color: '#fff', border: 'none',
        padding: '12px 20px', borderRadius: 999, fontSize: 13.5, fontWeight: 700,
        fontFamily: 'inherit', letterSpacing: 0.2, cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 8,
        boxShadow: '0 6px 16px rgba(240,90,10,0.35)',
      }}>
        Ver catálogo
        <svg width="13" height="13" viewBox="0 0 14 14"><path d="M2 7h10M8 3l4 4-4 4" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      {/* logo flotante — esquina inferior derecha del hero */}
      <div style={{
        position: 'absolute', right: 16, bottom: 14,
        background: '#fff', border: `2px solid ${C.naranja}`,
        borderRadius: 12, padding: '6px 10px',
        display: 'flex', alignItems: 'center',
        boxShadow: '0 4px 14px rgba(0,0,0,0.18)',
      }}>
        <Logo size="sm" />
      </div>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: 3, background: C.naranja,
      }} />
    </div>
  );
}

// ─── Beneficios ──────────────────────────────────────────────
function Benefits() {
  const items = [
    { ic: Icon.Truck, t: 'Envío a domicilio' },
    { ic: Icon.Store, t: 'Retiro en local' },
    { ic: Icon.Compat, t: 'Compatibilidad' },
    { ic: Icon.Wrench, t: 'Serv. técnico' },
    { ic: Icon.Tag, t: 'Precio distribuidor' },
  ];
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
      gap: 6, padding: '28px 8px 24px', background: '#fff',
      borderBottom: `1px solid ${C.line}`,
    }}>
      {items.map(({ ic: I, t }) => (
        <div key={t} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
          <div style={{
            width: '100%', aspectRatio: '1 / 1', borderRadius: 24,
            background: '#EEF0FA', display: 'flex',
            alignItems: 'center', justifyContent: 'center',
          }}>
            <I s={36} c={C.azul} />
          </div>
          <span style={{
            fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600,
            color: C.text, textAlign: 'center', lineHeight: 1.25,
          }}>{t}</span>
        </div>
      ))}
    </div>
  );
}

// ─── Buscador ────────────────────────────────────────────────
function SearchBar({ value, onChange }) {
  return (
    <div style={{ padding: '18px 16px 10px', background: '#fff' }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        height: 48, borderRadius: 14, padding: '0 14px',
        border: `1.5px solid ${C.azul}`, background: '#fff',
      }}>
        <Icon.Search s={20} c={C.azul} />
        <input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="Buscar producto o modelo…"
          style={{
            flex: 1, border: 'none', outline: 'none',
            fontFamily: 'inherit', fontSize: 14.5,
            color: C.text, background: 'transparent',
          }}
        />
        {value && (
          <button onClick={() => onChange('')} style={{
            ...iconBtn, width: 24, height: 24, color: C.muted,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke={C.muted} strokeWidth="1.8" strokeLinecap="round"/></svg>
          </button>
        )}
      </div>
    </div>
  );
}

// ─── Categorías chips ────────────────────────────────────────
function Categories({ active, onPick, cats }) {
  return (
    <div style={{
      display: 'flex', gap: 8, overflowX: 'auto',
      padding: '10px 16px 14px', background: '#fff',
      scrollbarWidth: 'none',
    }}>
      {cats.map(c => {
        const isActive = c === active;
        return (
          <button key={c} onClick={() => onPick(c)} style={{
            flexShrink: 0, height: 36, padding: '0 16px',
            borderRadius: 999, border: 'none', cursor: 'pointer',
            background: isActive ? C.azul : C.chipGray,
            color: isActive ? '#fff' : C.text,
            fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
            letterSpacing: 0.1,
            boxShadow: isActive ? '0 4px 10px rgba(26,47,160,0.22)' : 'none',
            transition: 'all 0.15s',
          }}>{c}</button>
        );
      })}
    </div>
  );
}

// ─── Producto: placeholder con stripes ───────────────────────
function ProductImage({ kind, tone }) {
  const palettes = {
    cyan: ['#E6F4FA', '#1A2FA0', 'cyan ink'],
    magenta: ['#FBEAF2', '#1A2FA0', 'magenta ink'],
    yellow: ['#FFF5DC', '#1A2FA0', 'yellow ink'],
    black: ['#E9EAF0', '#1A2FA0', 'black ink'],
    paper: ['#FAF7F0', '#1A2FA0', 'photo paper'],
    service: ['#EEF0FA', '#1A2FA0', 'service'],
    multi: ['#F2EAFB', '#1A2FA0', 'multipack'],
  };
  const [bg, fg, label] = palettes[tone] || palettes.cyan;
  return (
    <div style={{
      width: '100%', aspectRatio: '1 / 1', borderRadius: 12,
      background: bg, position: 'relative', overflow: 'hidden',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-start',
    }}>
      <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0 }}>
        <defs>
          <pattern id={`s-${tone}`} width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="6" stroke={fg} strokeWidth="0.6" opacity="0.18"/>
          </pattern>
        </defs>
        <rect width="100" height="100" fill={`url(#s-${tone})`}/>
      </svg>
      {kind === 'bottle' && (
        <svg width="36%" height="60%" viewBox="0 0 30 50" style={{ position: 'absolute', top: '18%', left: '32%' }}>
          <rect x="11" y="0" width="8" height="6" rx="1" fill={fg}/>
          <path d="M9 8h12v6l3 6v22a4 4 0 01-4 4h-10a4 4 0 01-4-4V20l3-6V8z" fill={fg} opacity="0.85"/>
        </svg>
      )}
      {kind === 'cartridge' && (
        <svg width="60%" height="44%" viewBox="0 0 60 40" style={{ position: 'absolute', top: '28%', left: '20%' }}>
          <rect x="2" y="6" width="50" height="28" rx="3" fill={fg} opacity="0.85"/>
          <rect x="50" y="14" width="8" height="12" rx="1" fill={fg}/>
        </svg>
      )}
      {kind === 'paper' && (
        <svg width="55%" height="65%" viewBox="0 0 50 60" style={{ position: 'absolute', top: '18%', left: '22%' }}>
          <rect x="6" y="4" width="38" height="50" rx="1" fill="#fff" stroke={fg} strokeWidth="1.2"/>
          <rect x="3" y="7" width="38" height="50" rx="1" fill="#fff" stroke={fg} strokeWidth="1.2"/>
          <rect x="0" y="10" width="38" height="50" rx="1" fill="#fff" stroke={fg} strokeWidth="1.5"/>
        </svg>
      )}
      {kind === 'service' && (
        <svg width="50%" height="50%" viewBox="0 0 40 40" style={{ position: 'absolute', top: '25%', left: '25%' }}>
          <Icon.Wrench s={80} c={fg} />
        </svg>
      )}
      <span style={{
        position: 'absolute', bottom: 8, left: 10,
        fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
        fontSize: 9, color: fg, opacity: 0.55, letterSpacing: 0.3,
      }}>{label}</span>
    </div>
  );
}

// ─── Imagen real o placeholder ───────────────────────────────
function ProductImg({ p, radius = 12 }) {
  const [error, setError] = React.useState(false);
  if (p.fotos && p.fotos.length > 0 && !error) {
    return (
      <div style={{
        width: '100%', aspectRatio: '1 / 1', borderRadius: radius,
        overflow: 'hidden', background: '#f5f5f5',
      }}>
        <img
          src={`${MEDIA}/${p.id}/${p.fotos[0]}`}
          alt={p.name}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
          onError={() => setError(true)}
        />
      </div>
    );
  }
  return <ProductImage kind={p.kind} tone={p.tone} />;
}

// ─── Card producto ───────────────────────────────────────────
function ProductCard({ p, qty, onAdd, onRemove, onConsult, onOpen }) {
  const outOfStock = !p.stock;
  return (
    <div style={{
      background: '#fff', borderRadius: 18, padding: 12,
      border: `1px solid ${C.line}`,
      display: 'flex', flexDirection: 'column', gap: 10,
      position: 'relative',
    }}>
      <button onClick={() => onOpen(p.id)} style={{
        all: 'unset', cursor: 'pointer',
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        <ProductImg p={p} radius={12} />
        {outOfStock && (
          <span style={{
            position: 'absolute', top: 18, left: 18,
            background: '#fff', color: C.text,
            padding: '4px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700,
            fontFamily: 'inherit',
            border: `1px solid ${C.line}`, letterSpacing: 0.2,
          }}>Sin stock</span>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 3, minHeight: 64 }}>
          <span style={{
            fontFamily: 'inherit', fontSize: 10, fontWeight: 700,
            color: C.naranja, textTransform: 'uppercase', letterSpacing: 0.8,
          }}>{p.cat}</span>
          <h3 style={{
            fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
            color: C.text, margin: 0, lineHeight: 1.2,
          }}>{p.name}</h3>
          <span style={{
            fontFamily: 'inherit', fontSize: 11, fontWeight: 500,
            color: C.muted, lineHeight: 1.3,
          }}>{p.compat}</span>
        </div>
      </button>
      {!outOfStock ? (
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{
              fontFamily: 'inherit', fontSize: 17, fontWeight: 800,
              color: C.azul, lineHeight: 1, letterSpacing: '-0.01em',
            }}>${p.price.toLocaleString('es-AR')}</span>
            <span style={{
              fontFamily: 'inherit', fontSize: 9, fontWeight: 500,
              color: C.muted, marginTop: 2,
            }}>IVA inc. · Sin IVA: ${p.price_sin_iva.toLocaleString('es-AR')}</span>
          </div>
          {qty > 0 ? (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 0,
              background: C.naranja, borderRadius: 999, padding: 2,
            }}>
              <button onClick={() => onRemove(p.id)} style={qtyBtn}>
                <Icon.Minus s={14} c="#fff" />
              </button>
              <span style={{
                color: '#fff', fontFamily: 'inherit',
                fontSize: 13, fontWeight: 700, minWidth: 18, textAlign: 'center',
              }}>{qty}</span>
              <button onClick={() => onAdd(p.id)} style={qtyBtn}>
                <Icon.Plus s={14} c="#fff" />
              </button>
            </div>
          ) : (
            <button onClick={() => onAdd(p.id)} style={{
              width: 36, height: 36, borderRadius: 999, border: 'none',
              background: C.naranja, color: '#fff', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 4px 10px rgba(240,90,10,0.35)',
            }}>
              <Icon.Plus s={18} c="#fff" />
            </button>
          )}
        </div>
      ) : (
        <button onClick={() => onConsult(p)} style={{
          height: 38, borderRadius: 12, border: `1.5px solid ${C.verde}`,
          background: '#fff', color: C.verde, cursor: 'pointer',
          fontFamily: 'inherit', fontSize: 12, fontWeight: 700,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          <svg width="14" height="14" viewBox="0 0 32 32"><path d="M16 3C8.8 3 3 8.8 3 16c0 2.3.6 4.5 1.7 6.4L3 29l6.8-1.8A13 13 0 0016 29c7.2 0 13-5.8 13-13S23.2 3 16 3z" fill={C.verde}/></svg>
          Consultar por WhatsApp
        </button>
      )}
    </div>
  );
}
const qtyBtn = {
  width: 28, height: 28, borderRadius: 999, border: 'none',
  background: 'transparent', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

// ─── Bottom nav ──────────────────────────────────────────────
function BottomNav({ active, onPick, cartCount }) {
  const items = [
    { id: 'home', t: 'Inicio', I: Icon.Home },
    { id: 'cat', t: 'Catálogo', I: Icon.Grid },
    { id: 'compat', t: 'Compatibilidad', I: Icon.Compat },
    { id: 'cart', t: 'Carrito', I: Icon.Cart, badge: cartCount },
  ];
  return (
    <div style={{
      background: '#fff', borderTop: `1px solid ${C.line}`,
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
      padding: '8px 4px env(safe-area-inset-bottom, 12px)',
    }}>
      {items.map(({ id, t, I, badge }) => {
        const isActive = id === active;
        const c = isActive ? C.azul : C.muted;
        return (
          <button key={id} onClick={() => onPick(id)} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '6px 0', position: 'relative',
          }}>
            <div style={{ position: 'relative' }}>
              <I s={22} c={c} />
              {badge > 0 && (
                <span style={{
                  position: 'absolute', top: -4, right: -8,
                  minWidth: 16, height: 16, padding: '0 4px',
                  background: C.naranja, color: '#fff',
                  borderRadius: 8, fontSize: 9, fontWeight: 800,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: '2px solid #fff', fontFamily: 'inherit',
                }}>{badge}</span>
              )}
            </div>
            <span style={{
              fontFamily: 'inherit', fontSize: 10, fontWeight: isActive ? 700 : 500,
              color: c, letterSpacing: 0.1,
            }}>{t}</span>
            {isActive && <div style={{
              position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)',
              width: 22, height: 3, borderRadius: 999, background: C.azul,
            }} />}
          </button>
        );
      })}
    </div>
  );
}

// ─── Vista Carrito ───────────────────────────────────────────
function CartView({ cart, products, waNum, onRemove, onAdd, onClear }) {
  const items = Object.entries(cart)
    .map(([id, qty]) => ({ p: products.find(x => x.id === id), qty }))
    .filter(({ p }) => p);

  const total = items.reduce((s, { p, qty }) => s + p.price * qty, 0);

  const pedirPorWA = () => {
    if (items.length === 0) return;
    const lineas = items.map(({ p, qty }) =>
      `• ${p.name} x${qty} — $${(p.price * qty).toLocaleString('es-AR')}`
    ).join('\n');
    const msg = encodeURIComponent(
      `Hola! Quiero hacer el siguiente pedido:\n\n${lineas}\n\nTotal: $${total.toLocaleString('es-AR')}`
    );
    if (waNum) window.open(`https://wa.me/${waNum}?text=${msg}`, '_blank');
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: C.bg }}>
      <div style={{
        background: '#fff', padding: '16px 16px 12px',
        borderBottom: `1px solid ${C.line}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <h2 style={{ fontFamily: 'inherit', fontSize: 18, fontWeight: 800, margin: 0, color: C.text }}>
          Carrito
        </h2>
        {items.length > 0 && (
          <button onClick={onClear} style={{
            border: 'none', background: 'none', cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 12, color: C.muted, padding: '4px 8px',
          }}>Vaciar</button>
        )}
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px' }}>
        {items.length === 0 ? (
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            justifyContent: 'center', height: '60%', gap: 12,
          }}>
            <Icon.Cart s={48} c={C.line} />
            <span style={{ fontFamily: 'inherit', fontSize: 14, color: C.muted }}>
              Tu carrito está vacío
            </span>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {items.map(({ p, qty }) => (
              <div key={p.id} style={{
                background: '#fff', borderRadius: 14, padding: '12px',
                border: `1px solid ${C.line}`, display: 'flex', gap: 12, alignItems: 'center',
              }}>
                <div style={{ width: 56, height: 56, borderRadius: 10, overflow: 'hidden', flexShrink: 0 }}>
                  <ProductImg p={p} radius={10} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
                    color: C.text, lineHeight: 1.2,
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  }}>{p.name}</div>
                  <div style={{ fontFamily: 'inherit', fontSize: 12, color: C.muted, marginTop: 2 }}>
                    ${p.price.toLocaleString('es-AR')} c/u
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 0,
                  background: C.naranja, borderRadius: 999, padding: 2, flexShrink: 0 }}>
                  <button onClick={() => onRemove(p.id)} style={qtyBtn}>
                    <Icon.Minus s={14} c="#fff" />
                  </button>
                  <span style={{ color: '#fff', fontFamily: 'inherit',
                    fontSize: 13, fontWeight: 700, minWidth: 18, textAlign: 'center' }}>{qty}</span>
                  <button onClick={() => onAdd(p.id)} style={qtyBtn}>
                    <Icon.Plus s={14} c="#fff" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {items.length > 0 && (
        <div style={{
          background: '#fff', borderTop: `1px solid ${C.line}`,
          padding: '14px 16px calc(24px + 72px)',
        }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            marginBottom: 14,
          }}>
            <span style={{ fontFamily: 'inherit', fontSize: 14, color: C.muted }}>Total</span>
            <span style={{ fontFamily: 'inherit', fontSize: 22, fontWeight: 800, color: C.azul }}>
              ${total.toLocaleString('es-AR')}
            </span>
          </div>
          <button onClick={pedirPorWA} style={{
            width: '100%', height: 52, borderRadius: 999, border: 'none',
            background: C.verde, color: '#fff', cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            boxShadow: '0 6px 16px rgba(37,211,102,0.35)',
          }}>
            <Icon.WhatsApp s={22} c="#fff" />
            Hacer pedido por WhatsApp
          </button>
        </div>
      )}
    </div>
  );
}

// ─── WhatsApp FAB ────────────────────────────────────────────
function WhatsAppFAB({ onClick }) {
  return (
    <button onClick={onClick} style={{
      position: 'absolute', right: 16, bottom: 92,
      width: 56, height: 56, borderRadius: 999, border: 'none',
      background: C.verde, cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 8px 20px rgba(37,211,102,0.4), 0 2px 6px rgba(0,0,0,0.15)',
      zIndex: 20,
    }}>
      <Icon.WhatsApp s={28} c="#fff" />
    </button>
  );
}

// ─── Toast ───────────────────────────────────────────────────
function Toast({ msg, visible }) {
  return (
    <div style={{
      position: 'absolute', left: '50%', bottom: 110,
      transform: `translateX(-50%) translateY(${visible ? 0 : 20}px)`,
      opacity: visible ? 1 : 0, transition: 'all 0.25s',
      background: C.text, color: '#fff',
      padding: '10px 16px', borderRadius: 999,
      fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
      pointerEvents: 'none', zIndex: 30, whiteSpace: 'nowrap',
      boxShadow: '0 8px 24px rgba(0,0,0,0.2)',
    }}>{msg}</div>
  );
}

// ─── API ─────────────────────────────────────────────────────
const API = 'https://sg.mendiart.com.ar';
const MEDIA = 'https://sg.mendiart.com.ar/media/productos';

function mapProduct(p) {
  const cat = (p.categoria || '').toLowerCase();
  const color = (p.color_tinta || '').toLowerCase();
  const nombre = (p.nombre_producto || '').toLowerCase();
  let kind = 'bottle';
  if (cat.includes('papel')) kind = 'paper';
  else if (cat.includes('cartucho')) kind = 'cartridge';
  else if (cat.includes('serv')) kind = 'service';
  let tone = 'cyan';
  if (kind === 'paper') tone = 'paper';
  else if (kind === 'service') tone = 'service';
  else if (color.includes('magenta')) tone = 'magenta';
  else if (color.includes('amarill') || color.includes('yellow')) tone = 'yellow';
  else if (color.includes('negro') || color.includes('black')) tone = 'black';
  else if (nombre.includes('pack') || nombre.includes('kit')) tone = 'multi';
  const iva = p.porcentaje_iva || 21;
  const price = Math.round(p.precio_venta || 0);
  const price_sin_iva = Math.round(price / (1 + iva / 100));
  return {
    id: p.id_producto,
    cat: p.categoria || 'General',
    name: p.nombre_producto,
    descripcion: p.descripcion_web || '',
    compat: p.compatible_con || '',
    marca: p.marca || '',
    calidad: p.calidad || '',
    cantidad_por_unidad: p.cantidad_por_unidad || '',
    color_tinta: p.color_tinta || '',
    price_sin_iva,
    fotos: Array.isArray(p.fotos) ? p.fotos : [],
    video_youtube_id: p.video_youtube_id || '',
    price,
    kind,
    tone,
    stock: (p.stock || 0) > 0,
  };
}

// ─── App ─────────────────────────────────────────────────────
function App() {
  const [active, setActive] = React.useState('');
  const [tab, setTab] = React.useState('home');
  const [search, setSearch] = React.useState('');
  const [cart, setCart] = React.useState({});
  const [toast, setToast] = React.useState({ msg: '', show: false });
  const [view, setView] = React.useState({ kind: 'home', productId: null });
  const [products, setProducts] = React.useState([]);
  const [categories, setCategories] = React.useState([]);
  const [config, setConfig] = React.useState({});
  const [loading, setLoading] = React.useState(true);
  const scrollRef = React.useRef(null);
  const catalogRef = React.useRef(null);

  React.useEffect(() => {
    Promise.all([
      fetch(`${API}/web/categorias`).then(r => r.json()),
      fetch(`${API}/web/productos`).then(r => r.json()),
      fetch(`${API}/web/config`).then(r => r.json()),
    ]).then(([cats, prods, cfg]) => {
      setCategories(cats);
      setProducts(prods.map(mapProduct));
      setConfig(cfg);
      if (cats.length > 0) setActive(cats[0]);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  React.useEffect(() => {
    if (config.meta_descripcion) {
      const meta = document.querySelector('meta[name="description"]');
      if (meta) meta.setAttribute('content', config.meta_descripcion);
    }
  }, [config.meta_descripcion]);

  const cartCount = Object.values(cart).reduce((a, b) => a + b, 0);

  const showToast = (msg) => {
    setToast({ msg, show: true });
    clearTimeout(window.__toastT);
    window.__toastT = setTimeout(() => setToast(t => ({ ...t, show: false })), 1800);
  };

  const waNum = (config.whatsapp || '').replace(/\D/g, '');

  const add = (id) => {
    setCart(c => ({ ...c, [id]: (c[id] || 0) + 1 }));
    const p = products.find(x => x.id === id);
    if (p && !cart[id]) showToast(`Agregado: ${p.name.split('·')[0].trim()}`);
  };
  const remove = (id) => {
    setCart(c => {
      const n = (c[id] || 0) - 1;
      const copy = { ...c };
      if (n <= 0) delete copy[id]; else copy[id] = n;
      return copy;
    });
  };
  const consult = (p) => {
    const msg = encodeURIComponent(`Hola, consulto por ${p.name}. ¿Tienen stock disponible?`);
    if (waNum) window.open(`https://wa.me/${waNum}?text=${msg}`, '_blank');
    else showToast(`Consulta sobre ${p.name.split('·')[0].trim()}…`);
  };
  const openProduct = (id) => setView({ kind: 'product', productId: id });
  const goHome = () => setView({ kind: 'home', productId: null });

  if (loading) {
    return (
      <div style={{
        height: '100%', display: 'flex', flexDirection: 'column',
        background: C.bg,
      }}>
        <Ticker />
        <Navbar cartCount={0} onSearchClick={() => {}} onCartClick={() => {}} />
        <div style={{
          flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexDirection: 'column', gap: 12,
        }}>
          <div style={{
            width: 36, height: 36, border: `3px solid ${C.azul}`,
            borderTopColor: 'transparent', borderRadius: '50%',
            animation: 'spin 0.8s linear infinite',
          }} />
          <span style={{ fontFamily: 'inherit', fontSize: 13, color: C.muted }}>Cargando catálogo…</span>
        </div>
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  // Cart view
  if (tab === 'cart' && view.kind !== 'product') {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', position: 'relative' }}>
        <div style={{ flex: 1, overflow: 'hidden' }}>
          <CartView
            cart={cart} products={products} waNum={waNum}
            onAdd={add} onRemove={remove}
            onClear={() => setCart({})}
          />
        </div>
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 10 }}>
          <BottomNav active={tab} onPick={setTab} cartCount={cartCount} />
        </div>
      </div>
    );
  }

  // Product view
  if (view.kind === 'product') {
    const p = products.find(x => x.id === view.productId);
    if (!p) { goHome(); return null; }
    return (
      <div style={{
        height: '100%', display: 'flex', flexDirection: 'column',
        background: '#fff', position: 'relative', overflow: 'hidden',
      }}>
        <ProductPage p={p} products={products} qty={cart[p.id] || 0}
          cartCount={cartCount}
          onBack={goHome}
          onAdd={add} onRemove={remove} onConsult={consult}
          onOpenProduct={openProduct}
          onCartClick={() => { setTab('cart'); goHome(); }} />
        <Toast msg={toast.msg} visible={toast.show} />
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 10 }}>
          <BottomNav active={tab} onPick={(t) => { setTab(t); goHome(); }} cartCount={cartCount} />
        </div>
      </div>
    );
  }

  const filtered = products.filter(p => {
    const matchesCat = !active || p.cat === active;
    const matchesSearch = search === '' ||
      p.name.toLowerCase().includes(search.toLowerCase()) ||
      (p.compat || '').toLowerCase().includes(search.toLowerCase());
    return matchesCat && matchesSearch;
  });

  const direccion = config.direccion || 'Sobremonte 448, Dorrego, Guaymallén, Mendoza';
  const horarios = config.horarios || 'Lun a Vie 9 a 19hs · Sáb 9 a 13hs';

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      background: C.bg, position: 'relative', overflow: 'hidden',
    }}>
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
        <Ticker cintaMensajes={config.cinta_mensajes} />
        <Navbar cartCount={cartCount}
          onSearchClick={() => {
            if (catalogRef.current && scrollRef.current) {
              const top = catalogRef.current.getBoundingClientRect().top
                - scrollRef.current.getBoundingClientRect().top
                + scrollRef.current.scrollTop;
              scrollRef.current.scrollTo({ top, behavior: 'smooth' });
            }
          }}
          onCartClick={() => setTab('cart')} />
        <Hero slogan={config.hero_slogan} subtitulo={config.hero_subtitulo} onCatalog={() => {
          if (catalogRef.current && scrollRef.current) {
            const top = catalogRef.current.getBoundingClientRect().top
              - scrollRef.current.getBoundingClientRect().top
              + scrollRef.current.scrollTop;
            scrollRef.current.scrollTo({ top, behavior: 'smooth' });
          }
          setTab('cat');
        }} />
        <Benefits />
        <div ref={catalogRef} />
        <SearchBar value={search} onChange={setSearch} />
        <Categories active={active} onPick={setActive} cats={categories} />

        <div style={{
          padding: '6px 16px 8px', display: 'flex',
          alignItems: 'baseline', justifyContent: 'space-between',
          background: '#fff',
        }}>
          <h2 style={{
            fontFamily: 'inherit', fontSize: 18, fontWeight: 800,
            color: C.text, margin: 0, letterSpacing: '-0.01em',
          }}>{active}</h2>
          <span style={{
            fontFamily: 'inherit', fontSize: 11, fontWeight: 600,
            color: C.muted, whiteSpace: 'nowrap',
          }}>{filtered.length} productos</span>
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10,
          padding: '8px 16px 24px', background: '#fff',
        }}>
          {filtered.map(p => (
            <ProductCard key={p.id} p={p}
              qty={cart[p.id] || 0}
              onAdd={add} onRemove={remove} onConsult={consult}
              onOpen={openProduct} />
          ))}
          {filtered.length === 0 && (
            <div style={{
              gridColumn: '1 / -1', padding: '40px 12px',
              textAlign: 'center', fontFamily: 'inherit',
              color: C.muted, fontSize: 13,
            }}>
              No encontramos productos{active && <> en <strong style={{ color: C.text }}>{active}</strong></>}
              {search && <> para «{search}»</>}.
            </div>
          )}
        </div>

        <div style={{ padding: '24px 20px 32px', background: C.azul, color: '#fff' }}>
          <Logo size="sm" dark />
          <p style={{
            fontFamily: 'inherit', fontSize: 12, lineHeight: 1.5,
            color: 'rgba(255,255,255,0.7)', margin: '12px 0 16px',
          }}>{direccion} · {horarios}</p>
          {(config.instagram || config.facebook || config.youtube || waNum) && (
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              {config.instagram && (
                <a href={config.instagram} target="_blank" rel="noopener noreferrer" style={{
                  width: 40, height: 40, borderRadius: 12,
                  background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon.Instagram s={20} c="#fff" />
                </a>
              )}
              {config.facebook && (
                <a href={config.facebook} target="_blank" rel="noopener noreferrer" style={{
                  width: 40, height: 40, borderRadius: 12,
                  background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon.Facebook s={20} c="#fff" />
                </a>
              )}
              {config.youtube && (
                <a href={config.youtube} target="_blank" rel="noopener noreferrer" style={{
                  width: 40, height: 40, borderRadius: 12,
                  background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon.YouTube s={20} c="#fff" />
                </a>
              )}
              {waNum && (
                <a href={`https://wa.me/${waNum}`} target="_blank" rel="noopener noreferrer" style={{
                  width: 40, height: 40, borderRadius: 12,
                  background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon.WhatsApp s={20} c="#fff" />
                </a>
              )}
            </div>
          )}
        </div>

        <div style={{ height: 80, background: C.azul }} />
      </div>

      <WhatsAppFAB onClick={() => {
        if (waNum) window.open(`https://wa.me/${waNum}`, '_blank');
        else showToast('Abriendo WhatsApp…');
      }} />
      <Toast msg={toast.msg} visible={toast.show} />

      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 10 }}>
        <BottomNav active={tab} onPick={setTab} cartCount={cartCount} />
      </div>
    </div>
  );
}

Object.assign(window, { App, C, Icon, ProductImage, ProductImg, MEDIA, qtyBtn, iconBtn });
