// storefront-shared.jsx — header, marquee, footer, cursor, shared atoms

const { useState, useEffect, useRef, createContext, useContext, useMemo, useCallback } = React;

// ─── Context ────────────────────────────────────────────────────────
const StoreCtx = createContext(null);
function useStore() { return useContext(StoreCtx); }

// ─── Tokens ─────────────────────────────────────────────────────────
const C = {
  fg: '#0A0A0A',
  fgMuted: '#9A9A9A',
  border: '#EAEAEA',
  borderSoft: '#F2F2F2',
  bg: '#FFFFFF',
  bgWarm: '#F7F5F0',
  accent: '#FA3F3F',
  accentInk: '#FFFFFF',
};

// ─── Logo ───────────────────────────────────────────────────────────
function Wordmark({ size = 22, color = C.fg, sub = true, invert = false }) {
  // size = visual height in px of the COMMANDO mark
  const src = invert ? 'assets/commando-horizontal.png' : 'assets/commando-horizontal.png';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:10, lineHeight: 1 }}>
      <img
        src={src}
        alt="COMMANDO"
        style={{
          height: size,
          width: 'auto',
          display: 'block',
          filter: color === '#fff' || invert ? 'invert(1)' : 'none',
        }}
      />
      {sub && <span style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: Math.max(9, Math.round(size * 0.40)),
        color: C.accent, letterSpacing:'0.18em', textTransform:'uppercase', fontWeight: 500,
        paddingBottom: 2,
      }}>/ apparel</span>}
    </div>
  );
}

// ─── Icon set (lucide-style strokes) ────────────────────────────────
const Icon = {
  search: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>,
  user: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  bag: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"/><path d="M3 6h18"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>,
  menu: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>,
  close: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>,
  arrowR: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  arrowUR: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17 17 7M7 7h10v10"/></svg>,
  sparkles: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2 2M16.4 16.4l2 2M5.6 18.4l2-2M16.4 7.6l2-2"/><path d="M12 8a4 4 0 0 0 4 4 4 4 0 0 0-4 4 4 4 0 0 0-4-4 4 4 0 0 0 4-4Z"/></svg>,
  pin: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s7-7.5 7-13a7 7 0 0 0-14 0c0 5.5 7 13 7 13Z"/><circle cx="12" cy="9" r="2.5"/></svg>,
  calendar: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
  upload: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M17 8 12 3 7 8"/><path d="M12 3v12"/></svg>,
  camera: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M14 4h-4l-1.5 2H5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-3.5L14 4Z"/><circle cx="12" cy="13" r="4"/></svg>,
  check: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>,
  msg: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"/></svg>,
  home: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9 12 2l9 7v11a2 2 0 0 1-2 2h-4v-7h-6v7H5a2 2 0 0 1-2-2Z"/></svg>,
  heart: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 0 0-7.8 7.8l1.1 1L12 21l7.7-7.7 1.1-1a5.5 5.5 0 0 0 0-7.7Z"/></svg>,
  share: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.6 13.5 6.8 4M15.4 6.5l-6.8 4"/></svg>,
};

// ─── Marquee bar ────────────────────────────────────────────────────
function Marquee({ items, color = C.fg, bg = C.bg, divider = '·' }) {
  const phrase = items.join(`  ${divider}  `);
  return (
    <div style={{
      background: bg, color, borderTop: `1px solid ${C.border}`, borderBottom: `1px solid ${C.border}`,
      overflow:'hidden', whiteSpace:'nowrap', paddingTop: 14, paddingBottom: 18,
    }}>
      <div style={{
        animation:'cmd-marquee 40s linear infinite',
        fontFamily:'JetBrains Mono, monospace', fontSize: 12, letterSpacing:'0.22em',
        lineHeight: 1,
        textTransform:'uppercase', willChange:'transform', width:'max-content',
      }}>
        {[0,1,2].map(i => (
          <span key={i} style={{ paddingRight: 64 }}>{phrase}</span>
        ))}
      </div>
    </div>
  );
}

// ─── Header (desktop + mobile) ──────────────────────────────────────
function Header({ mobile }) {
  const s = useStore();
  const cartCount = s.cart.reduce((n, it) => n + it.qty, 0);
  if (mobile) {
    return (
      <header style={{
        position:'sticky', top:0, zIndex:30, background:'#fff',
        borderBottom:`1px solid ${C.border}`,
        padding:'10px 16px', display:'flex', alignItems:'center', justifyContent:'space-between',
      }}>
        <button onClick={() => s.setNav('open-mobile')} style={iconBtn}>{Icon.menu(22)}</button>
        <button onClick={() => s.go('home')} style={{ background:'transparent', border:0, padding:0, cursor:'pointer' }}>
          <Wordmark size={28} sub={false} />
        </button>
        <button onClick={() => s.setCartOpen(true)} style={{ ...iconBtn, position:'relative' }}>
          {Icon.bag(22)}
          {cartCount > 0 && <CartBadge n={cartCount} />}
        </button>
      </header>
    );
  }
  return (
    <header style={{
      position:'sticky', top:0, zIndex:30, background:'rgba(255,255,255,0.94)',
      backdropFilter:'blur(12px)', borderBottom:`1px solid ${C.border}`,
    }}>
      <div style={{
        display:'grid', gridTemplateColumns:'1fr auto 1fr', alignItems:'center',
        padding:'14px 32px', gap: 32,
      }}>
        <div style={{ display:'flex', alignItems:'center', gap:24 }}>
          <button onClick={() => s.go('home')} style={{ background:'transparent', border:0, padding:0, cursor:'pointer' }}>
            <Wordmark size={22} />
          </button>
        </div>
        <nav style={{ display:'flex', gap: 36, justifyContent:'center', alignItems:'center' }}>
          {['Explora','Mujer','Hombre','Accesorios'].map(l => (
            <a key={l} className="cmd-navlink" onClick={() => s.go('home')}>{l}</a>
          ))}
        </nav>
        <div style={{ display:'flex', gap:14, justifyContent:'flex-end', alignItems:'center' }}>
          <button style={iconBtn}>{Icon.search(18)}</button>
          <button onClick={() => s.go(s.loggedIn ? 'cuenta' : 'cuenta-entrar')} style={iconBtn} data-cursor-label="Cuenta">{Icon.user(18)}</button>
          <button onClick={() => s.setCartOpen(true)} style={{ ...iconBtn, position:'relative' }}>
            {Icon.bag(18)}
            {cartCount > 0 && <CartBadge n={cartCount} />}
          </button>
          <button className="cmd-cta-pill" style={{ padding:'10px 14px', fontSize: 11, letterSpacing:'0.14em' }} onClick={() => cartCount > 0 ? s.go('bolsa') : s.go('home')}>
            {cartCount > 0
              ? `Bolsa · $${s.cart.reduce((sum, it) => sum + it.price * it.qty, 0).toLocaleString('es-MX')}`
              : 'Comprar'}
          </button>
        </div>
      </div>
    </header>
  );
}

const iconBtn = {
  background:'transparent', border:0, padding:8, cursor:'pointer', color: C.fg,
  display:'inline-flex', alignItems:'center', justifyContent:'center', borderRadius:0,
};

function CartBadge({ n }) {
  return (
    <span style={{
      position:'absolute', top:2, right:2, minWidth:16, height:16, padding:'0 4px',
      background: C.accent, color:'#fff', borderRadius:8,
      fontFamily:'JetBrains Mono, monospace', fontSize:10, fontWeight:700,
      display:'inline-flex', alignItems:'center', justifyContent:'center',
    }}>{n}</span>
  );
}

// ─── Mobile bottom nav ──────────────────────────────────────────────
function MobileBottomNav() {
  const s = useStore();
  const cartCount = s.cart.reduce((n, it) => n + it.qty, 0);
  const items = [
    { k:'tienda', label:'Explora', icon:Icon.home, on:() => s.go('home') },
    { k:'buscar', label:'Buscar', icon:Icon.search, on:() => s.go('home') },
    { k:'cart', label:'Bolsa', icon:Icon.bag, on:() => s.go('bolsa') },
    { k:'user', label:'Cuenta', icon:Icon.user, on:() => s.go(s.loggedIn ? 'cuenta' : 'cuenta-entrar') },
  ];
  const stop = (e) => e.stopPropagation();
  return (
    <nav
      onTouchStart={stop}
      onTouchMove={stop}
      onTouchEnd={stop}
      style={{
        position:'fixed', bottom:0, left:0, right:0, zIndex:30, background:'#fff',
        borderTop:`1px solid ${C.border}`,
        display:'grid', gridTemplateColumns:'repeat(4, 1fr)',
        padding:'10px 4px calc(14px + env(safe-area-inset-bottom, 0px))',
        touchAction:'none',
      }}
    >
      {items.map(it => (
        <button key={it.k} onClick={it.on} style={{
          background:'transparent', border:0, padding:'4px 0', cursor:'pointer',
          display:'flex', flexDirection:'column', alignItems:'center', gap:4,
          color: C.fg, position:'relative',
        }}>
          <span style={{ position:'relative' }}>
            {it.icon(20)}
          </span>
          <span style={{
            fontFamily:'JetBrains Mono, monospace', fontSize:9, letterSpacing:'0.12em',
            textTransform:'uppercase', color: C.fg,
          }}>{it.label}</span>
        </button>
      ))}
    </nav>
  );
}

// ─── Section divider ────────────────────────────────────────────────
function SectionRule({ num, title, kicker, mobile }) {
  return (
    <div style={{ borderTop:`1px solid ${C.fg}`, padding: mobile ? '20px 16px 12px' : '32px 32px 20px' }}>
      <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap:16 }}>
        <h2 style={{
          margin:0, fontFamily:'Anton, sans-serif', fontSize: mobile ? 32 : 56,
          textTransform:'uppercase', letterSpacing:'-0.01em', lineHeight:0.95,
        }}>{title}</h2>
        {kicker && (
          <span style={{
            fontFamily:'JetBrains Mono, monospace', fontSize:11, letterSpacing:'0.18em',
            color: C.fgMuted, textTransform:'uppercase',
          }}>{kicker}</span>
        )}
      </div>
    </div>
  );
}

// ─── Footer ─────────────────────────────────────────────────────────
const SOCIAL_LINKS = [
  { k:'ig', label:'Instagram', href:'https://www.instagram.com/commandostudio',
    svg: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.8" fill="currentColor" stroke="none"/></svg> },
  { k:'tt', label:'TikTok', href:'https://www.tiktok.com/@commandostudio',
    svg: <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M16.5 3v3.1a4.9 4.9 0 0 0 4.5 2.6V12a8.4 8.4 0 0 1-4.5-1.3v6a5.6 5.6 0 1 1-5.6-5.6c.3 0 .6 0 .9.1V14a2.9 2.9 0 1 0 2 2.7V3h2.7z"/></svg> },
  { k:'sp', label:'Spotify', href:'https://open.spotify.com/user/commandostudio',
    svg: <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm4.4 14.5a.7.7 0 0 1-1 .2c-2.6-1.6-6-2-10-1a.7.7 0 0 1-.3-1.4c4.4-1 8.1-.6 11 1.2.4.2.5.6.3 1zm1.2-2.7a.9.9 0 0 1-1.2.3c-3-1.8-7.5-2.3-11-1.3a.9.9 0 1 1-.5-1.7c4-1.2 9-.6 12.4 1.5a.9.9 0 0 1 .3 1.2zm.1-2.8c-3.6-2.1-9.5-2.3-12.9-1.2a1.1 1.1 0 1 1-.6-2.1c4-1.2 10.5-1 14.6 1.4a1.1 1.1 0 1 1-1.1 1.9z"/></svg> },
  { k:'fb', label:'Facebook', href:'https://www.facebook.com/ComandoStudio',
    svg: <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M13.5 21v-7.5h2.5l.4-3h-2.9V8.6c0-.9.3-1.5 1.5-1.5h1.5V4.4a20 20 0 0 0-2.3-.1c-2.3 0-3.7 1.4-3.7 3.8v2.4H8v3h2.5V21h3z"/></svg> },
];

function Footer({ mobile }) {
  const s = useStore();
  const cols = [
    { h: 'Nosotros', l: [
      { label:'Nosotros',       href:'https://commandostudio.com/mx/#nosotros' },
      { label:'Sitio principal', href:'https://commandostudio.com' },
    ] },
    { h: 'Más', l: [
      { label:'Contacto',   href:'mailto:hola@commandostudio.com' },
      { label:'Privacidad', href:'https://commandostudio.com/privacidad/' },
      { label:'Términos',   href:'https://commandostudio.com/terminos/' },
    ] },
  ];

  return (
    <footer style={{
      background: C.fg, color:'#fff',
      padding: mobile ? '40px 16px 28px' : '64px 32px 32px',
      flexShrink: 0,
    }}>
      <div style={{
        display:'grid', gap: mobile ? 32 : 48,
        gridTemplateColumns: mobile ? '1fr 1fr' : '1.4fr 1fr 1fr',
        marginBottom: mobile ? 32 : 56,
      }}>
        {/* ─── Col 1: Brand + contact + newsletter ─── */}
        <div style={{ gridColumn: mobile ? '1 / -1' : 'auto' }}>
          <div style={{ display:'flex', alignItems:'center', gap: mobile ? 14 : 18, marginBottom: mobile ? 22 : 28, flexWrap:'wrap' }}>
            <img src="assets/commando-vertical.png" alt="COMMANDO" style={{
              height: mobile ? 64 : 110, width:'auto', display:'block',
              filter:'invert(1)',
            }}/>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.22em', textTransform:'uppercase', color: C.accent }}>
              / apparel · est. 26
            </div>
          </div>

          <a href="tel:5585250802" style={{
            display:'block', color: C.accent, textDecoration:'none',
            fontFamily:'JetBrains Mono, monospace', fontSize: mobile ? 15 : 17,
            letterSpacing:'0.14em', marginBottom: 8, transition:'opacity .2s',
          }} onMouseEnter={e => e.currentTarget.style.opacity = 0.75}
            onMouseLeave={e => e.currentTarget.style.opacity = 1}>
            55 8525 0802
          </a>
          <a href="mailto:hola@commandostudio.com" style={{
            display:'block', color:'rgba(255,255,255,0.85)', textDecoration:'none',
            fontFamily:'Roboto, sans-serif', fontSize: 14, letterSpacing:'0.04em',
            marginBottom: mobile ? 18 : 24, transition:'color .2s',
          }} onMouseEnter={e => e.currentTarget.style.color = '#fff'}
            onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.85)'}>
            hola@commandostudio.com
          </a>

          <a href="#" className="cmd-newsletter-pill"
            onClick={(e) => { e.preventDefault(); s.setNewsletterOpen(true); }}
            style={{
              display:'inline-flex', alignItems:'center', gap:10,
              padding:'14px 22px', borderRadius: 999,
              fontFamily:'JetBrains Mono, monospace', fontSize: 12,
              letterSpacing:'0.22em', textTransform:'uppercase',
              textDecoration:'none', position:'relative', overflow:'hidden',
              border:'1.5px solid rgba(255,255,255,0.4)', color:'#fff',
            }}>
            <span className="cmd-newsletter-pill__label">Únete al newsletter</span>
            <span className="cmd-newsletter-pill__icon" style={{ display:'inline-flex' }}>
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </span>
          </a>
        </div>

        {/* ─── Link columns ─── */}
        {cols.map(col => (
          <div key={col.h}>
            <div style={{
              fontFamily:'Anton, sans-serif', fontSize: 28,
              fontWeight: 700, textTransform:'uppercase',
              letterSpacing:'0.01em', color:'#fff', marginBottom: 22,
              lineHeight: 1,
            }}>{col.h}</div>
            <ul style={{ listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap: 14 }}>
              {col.l.map(item => (
                <li key={item.label}>
                  <a className="cmd-footer-link" href={item.href}
                    target={item.href && item.href.startsWith('http') ? '_blank' : undefined}
                    rel={item.href && item.href.startsWith('http') ? 'noopener noreferrer' : undefined}
                    style={{
                      fontFamily:'JetBrains Mono, monospace', fontSize: 12,
                      letterSpacing:'0.18em', textTransform:'uppercase',
                    }}>{item.label}</a>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </footer>
  );
}

// ─── Country picker pill ────────────────────────────────────────────
function CountryPill() {
  const s = useStore();
  const COUNTRIES = [
    { k:'MX', label:'MX (MXN)', active: true },
    { k:'EU', label:'EU (EUR)' },
    { k:'US', label:'US (USD)' },
  ];
  const [open, setOpen] = useState(false);
  return (
    <div style={{ position:'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        background:'transparent', color:'#fff',
        border:'1.5px solid rgba(255,255,255,0.4)', borderRadius: 999,
        padding:'10px 18px', cursor:'pointer',
        fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.2em', textTransform:'uppercase',
        display:'inline-flex', alignItems:'center', gap: 10,
      }} data-cursor-label="País">
        MX (MXN)
        <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : 'none', transition:'transform .2s' }}>
          <path d="M6 9l6 6 6-6"/>
        </svg>
      </button>
      {open && (
        <div style={{
          position:'absolute', right: 0, top:'calc(100% + 8px)',
          background:'#fff', color: C.fg, minWidth: 180,
          boxShadow:'0 20px 50px rgba(0,0,0,0.3)', zIndex: 10,
          padding: '6px 0',
        }}>
          {COUNTRIES.map(c => (
            <button key={c.k} onClick={() => { setOpen(false); if (!c.active) s.setNotifyCountry(c); }} style={{
              width:'100%', textAlign:'left', padding:'10px 16px',
              background:'transparent', border:0, cursor:'pointer',
              fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.16em', textTransform:'uppercase',
              color: c.active ? C.fg : C.fgMuted,
              display:'flex', justifyContent:'space-between', alignItems:'center', gap: 12,
            }} onMouseEnter={e => e.currentTarget.style.background = '#F2F1EE'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span>{c.label}</span>
              {c.active ? <span style={{ color: C.accent }}>●</span> : <span style={{ fontSize: 9, opacity: 0.6 }}>Próx.</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Footer copyright strip (separate so FAB can stop before it) ──────
function FooterCopyright({ mobile }) {
  return (
    <div style={{
      background: C.fg, color: '#fff',
      padding: mobile ? '40px 16px 24px' : '24px 32px 28px',
      borderTop: 'none',
      flexShrink: 0,
      position: 'relative',
    }}>
      {mobile ? (
        // ─── Mobile: centered stack — socials → pill → copyright line ───
        <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap: 22 }}>
          <div style={{ display:'flex', gap: 12, justifyContent:'center' }}>
            {SOCIAL_LINKS.map(s => (
              <a key={s.k} href={s.href} target="_blank" rel="noopener noreferrer"
                className="cmd-social-pill" aria-label={s.label}>
                <span className="cmd-social-pill__icon">{s.svg}</span>
              </a>
            ))}
          </div>
          <CountryPill/>
          <div style={{
            textAlign:'center',
            fontFamily:'JetBrains Mono, monospace', fontSize: 11,
            letterSpacing:'0.10em', textTransform:'uppercase',
            color:'rgba(255,255,255,0.55)', lineHeight: 1.65,
            paddingTop: 4,
          }}>
            Commando Apparel — Est. 26 · 2026 © Todos los Derechos Reservados.<br/>
            <span style={{ color:'#fff', whiteSpace:'nowrap' }}>Hecho por DIXEEBE.</span>
          </div>
        </div>
      ) : (
        <div style={{
          display:'flex', flexDirection:'row',
          justifyContent:'space-between', alignItems:'center', gap: 24,
        }}>
          <div style={{ display:'flex', gap: 12, alignItems:'center', flexShrink: 0 }}>
            {SOCIAL_LINKS.map(s => (
              <a key={s.k} href={s.href} target="_blank" rel="noopener noreferrer"
                className="cmd-social-pill" aria-label={s.label}>
                <span className="cmd-social-pill__icon">{s.svg}</span>
              </a>
            ))}
            <div style={{ width: 1, height: 28, background:'rgba(255,255,255,0.18)', margin:'0 6px' }}/>
            <CountryPill/>
          </div>
          <div style={{
            textAlign:'right', flexShrink: 0,
            fontFamily:'JetBrains Mono, monospace', fontSize: 12,
            letterSpacing:'0.14em', textTransform:'uppercase',
            color:'rgba(255,255,255,0.72)', lineHeight: 1.65,
          }}>
            <div>Commando Apparel — Est. 26 · 2026 © Todos los Derechos Reservados.</div>
            <div style={{ color:'#fff', marginTop: 2 }}>Hecho por DIXEEBE.</div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Mobile menu drawer ────────────────────────────────────────────────
function MobileMenuDrawer() {
  const s = useStore();
  const open = s.nav === 'open-mobile';
  const items = ['Explora','Mujer','Hombre','Accesorios'];
  return (
    <React.Fragment>
      <div onClick={() => s.setNav(null)} style={{
        position:'absolute', inset:0, zIndex:80,
        background: open ? 'rgba(0,0,0,0.45)' : 'transparent',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .25s',
      }}/>
      <aside style={{
        position:'absolute', top:0, left:0, bottom:0, width: '88%', maxWidth: 380,
        background:'#fff', zIndex:81, display:'flex', flexDirection:'column',
        transform: open ? 'translateX(0)' : 'translateX(-100%)',
        transition: 'transform .35s cubic-bezier(.2,.8,.2,1)',
        boxShadow:'20px 0 40px rgba(0,0,0,0.08)',
      }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'18px 20px', borderBottom:`1px solid ${C.border}` }}>
          <Wordmark size={22} sub={false}/>
          <button onClick={() => s.setNav(null)} style={iconBtn}>{Icon.close(22)}</button>
        </div>
        <nav style={{ flex:1, overflow:'auto', padding:'12px 0' }}>
          {items.map(l => (
            <a key={l} onClick={() => { s.setNav(null); s.go('home'); }} style={{
              display:'block', padding:'18px 24px',
              fontFamily:'Anton, sans-serif', fontSize:36, lineHeight:1,
              textTransform:'uppercase', letterSpacing:'-0.01em', color: C.fg,
              borderBottom:`1px solid ${C.borderSoft}`, cursor:'pointer',
            }}>{l}</a>
          ))}
          <div style={{ padding:'24px', display:'flex', flexDirection:'column', gap:10 }}>
            {[
              { label:'Cuenta', go: s.loggedIn ? 'cuenta' : 'cuenta-entrar' },
              { label:'Estudios', go:'estudios' },
              { label:'Lookbook', go:'lookbook' },
              { label:'Contacto', go:null, onClick: () => { window.location.href = 'mailto:hola@commandostudio.com'; } },
            ].map(item => (
              <a key={item.label} className="cmd-navlink" onClick={() => {
                s.setNav(null);
                if (item.onClick) item.onClick();
                else if (item.go) s.go(item.go);
              }} style={{ padding:'8px 0' }}>{item.label}</a>
            ))}
          </div>
        </nav>
      </aside>
    </React.Fragment>
  );
}

// ─── Custom cursor (desktop only) ─────────────────────────────
function CustomCursor() {
  const wrapRef = useRef(null);
  const dotRef = useRef(null);
  const verRef = useRef(null);
  useEffect(() => {
    const wrap = wrapRef.current;
    const dot = dotRef.current;
    const ver = verRef.current;
    if (!wrap || !dot || !ver) return;
    let raf = 0; let pending = false; let lastX = 0, lastY = 0; let lastTarget = null;
    let curActive = false;
    const apply = () => {
      pending = false;
      wrap.style.transform = `translate3d(${lastX}px, ${lastY}px, 0)`;
      const t = lastTarget && lastTarget.closest && lastTarget.closest('[data-cursor-label]');
      setActiveDOM(!!t);
    };
    const setActiveDOM = (next) => {
      if (next === curActive) return;
      curActive = next;
      if (next) {
        dot.style.transform = 'translate(-50%,-50%) scale(0)';
        dot.style.opacity = '0';
        ver.style.transform = 'translate(-50%,-50%) scale(1)';
        ver.style.opacity = '1';
      } else {
        dot.style.transform = 'translate(-50%,-50%) scale(1)';
        dot.style.opacity = '1';
        ver.style.transform = 'translate(-50%,-50%) scale(0.28)';
        ver.style.opacity = '0';
      }
    };
    const onMove = (e) => {
      lastX = e.clientX;
      lastY = e.clientY;
      lastTarget = e.target;
      if (!pending) {
        pending = true;
        raf = requestAnimationFrame(apply);
      }
    };
    document.addEventListener('mousemove', onMove, { passive: true });
    return () => {
      document.removeEventListener('mousemove', onMove);
      cancelAnimationFrame(raf);
    };
  }, []);
  return (
    <div ref={wrapRef} style={{
      position:'fixed', top:0, left:0, pointerEvents:'none', zIndex:200,
      width: 0, height: 0,
      transform: 'translate3d(-9999px,-9999px,0)',
      willChange: 'transform',
    }}>
      <div ref={dotRef} style={{
        position:'absolute', top:0, left:0,
        width: 18, height: 18, borderRadius:'50%',
        background: C.fg, border: '2px solid #fff',
        boxShadow: '0 0 0 1px rgba(0,0,0,0.25)',
        transition: 'transform .22s cubic-bezier(.2,.8,.2,1), opacity .18s',
        transform: 'translate(-50%,-50%) scale(1)',
        opacity: 1, willChange:'transform, opacity',
      }}/>
      <div ref={verRef} style={{
        position:'absolute', top:0, left:0,
        width: 64, height: 64, borderRadius:'50%',
        background: C.accent, color:'#fff',
        display:'flex', alignItems:'center', justifyContent:'center',
        fontFamily:'JetBrains Mono, monospace', fontSize: 12, letterSpacing:'0.2em',
        textTransform:'uppercase', fontWeight: 700,
        transition: 'transform .25s cubic-bezier(.2,.8,.2,1), opacity .18s',
        transform: 'translate(-50%,-50%) scale(0.28)',
        opacity: 0, willChange:'transform, opacity',
      }}>Ver</div>
    </div>
  );
}

// ─── Cart Drawer ────────────────────────────────────────────────────
function CartDrawer() {
  const s = useStore();
  const subtotal = s.cart.reduce((sum, it) => sum + it.price * it.qty, 0);
  return (
    <>
      <div onClick={() => s.setCartOpen(false)} style={{
        position:'absolute', inset:0, zIndex:80,
        background: s.cartOpen ? 'rgba(0,0,0,0.45)' : 'transparent',
        opacity: s.cartOpen ? 1 : 0, pointerEvents: s.cartOpen ? 'auto' : 'none',
        transition: 'opacity .25s',
      }}/>
      <aside style={{
        position:'absolute', top:0, right:0, bottom:0, width: 'min(440px, 92%)',
        background: '#fff', zIndex:81, display:'flex', flexDirection:'column',
        transform: s.cartOpen ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform .35s cubic-bezier(.2,.8,.2,1)',
        boxShadow: '-20px 0 40px rgba(0,0,0,0.08)',
      }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'20px 24px', borderBottom:`1px solid ${C.border}`}}>
          <div style={{ display:'flex', alignItems:'baseline', gap:12 }}>
            <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:11, letterSpacing:'0.2em', textTransform:'uppercase' }}>00 / Tu bolsa</span>
            <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:11, color: C.fgMuted }}>{s.cart.length} ítem{s.cart.length === 1 ? '' : 's'}</span>
          </div>
          <button style={iconBtn} onClick={() => s.setCartOpen(false)}>{Icon.close(20)}</button>
        </div>
        <div style={{ flex:1, overflow:'auto', padding:'8px 24px' }}>
          {s.cart.length === 0 && (
            <div style={{ textAlign:'center', padding:'80px 16px' }}>
              <div style={{ fontFamily:'Anton, sans-serif', fontSize:36, lineHeight:0.95, textTransform:'uppercase', marginBottom:8 }}>Tu bolsa<br/>está vacía.</div>
              <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:12, color: C.fgMuted, letterSpacing:'0.16em', textTransform:'uppercase' }}>Aún no has empezado.</div>
            </div>
          )}
          {s.cart.map((it, i) => {
            const prod = (window.PRODUCTS || []).find(p => p.id === it.id);
            const colorObj = prod && prod.colors.find(c => c.name === it.color);
            const thumbImg = prod && resolveProductImage(prod, colorObj || prod.colors[0], 'front');
            return (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'72px 1fr auto', gap:14, padding:'16px 0', borderBottom:`1px solid ${C.borderSoft}` }}>
              <div style={{ width:72, height:90, background: thumbImg ? '#F4F2EC' : it.colorHex, position:'relative', overflow:'hidden' }}>
                {thumbImg ? (
                  <img src={thumbImg} alt={it.name} loading="lazy" style={{
                    position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', display:'block',
                  }}/>
                ) : (
                  <div style={{ position:'absolute', inset:0, background:`repeating-linear-gradient(45deg, transparent 0 8px, rgba(255,255,255,0.06) 8px 9px)`}}/>
                )}
              </div>
              <div>
                <div style={{ fontFamily:'Anton, sans-serif', fontSize:18, textTransform:'uppercase', letterSpacing:'0.01em' }}>{it.name}</div>
                <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:10, letterSpacing:'0.18em', color: C.fgMuted, textTransform:'uppercase', marginTop:4 }}>
                  {it.color} / Talla {it.size}
                </div>
                <div style={{ display:'flex', gap:8, marginTop:10, alignItems:'center' }}>
                  <button onClick={() => s.qty(i, -1)} style={qtyBtn}>−</button>
                  <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:12, minWidth:18, textAlign:'center' }}>{it.qty}</span>
                  <button onClick={() => s.qty(i, 1)} style={qtyBtn}>+</button>
                </div>
              </div>
              <div style={{ textAlign:'right' }}>
                <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:13 }}>${(it.price * it.qty).toLocaleString('es-MX')}</div>
                <button onClick={() => s.removeItem(i)} style={{ background:'transparent', border:0, padding:0, marginTop:8, fontFamily:'JetBrains Mono, monospace', fontSize:10, color: C.fgMuted, letterSpacing:'0.14em', textTransform:'uppercase', cursor:'pointer', textDecoration:'underline' }}>Quitar</button>
              </div>
            </div>
          );})}
        </div>
        <div style={{ padding:'20px 24px', borderTop:`1px solid ${C.border}` }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:14 }}>
            <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:11, letterSpacing:'0.2em', textTransform:'uppercase' }}>Subtotal</span>
            <span style={{ fontFamily:'Anton, sans-serif', fontSize:28, letterSpacing:'-0.01em' }}>${subtotal.toLocaleString('es-MX')} <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:11, color: C.fgMuted }}>MXN</span></span>
          </div>
          <button className="cmd-btn-primary" disabled={s.cart.length === 0} onClick={() => { s.setCartOpen(false); s.go('bolsa'); }}>VER BOLSA COMPLETA</button>
          <div style={{ marginTop:10, fontFamily:'JetBrains Mono, monospace', fontSize:10, color: C.fgMuted, letterSpacing:'0.14em', textTransform:'uppercase', textAlign:'center' }}>
            Envío gratis desde $1,499 · 3 MSI desde $1,000
          </div>
        </div>
      </aside>
    </>
  );
}
const qtyBtn = {
  width:24, height:24, border:`1px solid ${C.border}`, background:'#fff',
  cursor:'pointer', fontFamily:'JetBrains Mono, monospace', fontSize:13, lineHeight:1,
};

// ─── Chat FAB ───────────────────────────────────────────────────────
function ChatFAB({ mobile }) {
  const s = useStore();
  const btnRef = useRef(null);
  const [hideAtFooter, setHideAtFooter] = useState(false);

  useEffect(() => {
    // Find OUR own scroller (each App instance has its own data-app-root + data-app-scroll)
    const btn = btnRef.current;
    if (!btn) return;
    const root = btn.closest('[data-app-root]');
    const scroller = root ? root.querySelector('[data-app-scroll]') : null;
    if (!scroller) return;
    const findFooter = () => scroller.querySelector('footer');
    const check = () => {
      const f = findFooter();
      if (!f) return;
      const fr = f.getBoundingClientRect();
      const sr = scroller.getBoundingClientRect();
      const footerInView = fr.top < sr.bottom - (mobile ? 60 : 24);
      setHideAtFooter(footerInView);
    };
    scroller.addEventListener('scroll', check, { passive: true });
    window.addEventListener('resize', check, { passive: true });
    const raf = requestAnimationFrame(check);
    return () => {
      scroller.removeEventListener('scroll', check);
      window.removeEventListener('resize', check);
      cancelAnimationFrame(raf);
    };
  }, [mobile, s.route]);

  const hideFab = hideAtFooter || (mobile && s.chatOpen);

  return (
    <React.Fragment>
      <button ref={btnRef} onClick={() => s.setChatOpen(!s.chatOpen)} style={{
        position:'absolute',
        bottom: mobile ? 80 : 24,
        right: mobile ? 18 : 28,
        zIndex: 65,
        width: mobile ? 52 : 58, height: mobile ? 52 : 58, borderRadius:'50%',
        background: C.accent, color:'#fff', border:0, cursor:'pointer',
        boxShadow:'0 14px 36px rgba(250,63,63,0.45), 0 4px 12px rgba(0,0,0,0.2)',
        display:'flex', alignItems:'center', justifyContent:'center',
        animation: 'cmd-fab-pulse 2.6s ease-in-out infinite',
        pointerEvents: hideFab ? 'none' : 'auto',
        opacity: hideFab ? 0 : 1,
        transform: hideFab ? 'translateY(20px) scale(0.85)' : 'translateY(0) scale(1)',
        transition: 'opacity .25s, transform .3s cubic-bezier(.2,.8,.2,1)',
      }} data-cursor-label="Chat">
        {Icon.msg(mobile ? 20 : 24)}
        <span style={{
          position:'absolute', top:-3, right:-3, minWidth:18, height:18, padding:'0 5px', borderRadius:9,
          background: C.fg, color:'#fff', fontSize:9, fontWeight:700,
          fontFamily:'JetBrains Mono, monospace', letterSpacing:'0.05em',
          display:'flex', alignItems:'center', justifyContent:'center',
          border:'2px solid #fff',
        }}>1</span>
      </button>
      <ChatPanel mobile={mobile} />
    </React.Fragment>
  );
}

function ChatPanel({ mobile }) {
  const s = useStore();
  const open = s.chatOpen;
  const w = mobile ? '100%' : 380;
  return (
    <aside style={{
      position:'absolute', right: mobile ? 0 : 24, bottom: mobile ? 0 : 100, zIndex:64,
      width: w, maxWidth: '100%',
      height: mobile ? '85%' : 520,
      background:'#FAFAFA', borderRadius: mobile ? '24px 24px 0 0' : 14, overflow:'hidden',
      boxShadow:'0 30px 60px rgba(0,0,0,0.22), 0 0 0 1px rgba(0,0,0,0.05)',
      transform: open ? 'translateY(0) scale(1)' : 'translateY(20px) scale(0.96)',
      opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
      transition:'transform .28s cubic-bezier(.2,.8,.2,1), opacity .25s',
      display:'flex', flexDirection:'column',
    }}>
      <div style={{ padding:'14px 16px', background:'#fff', borderBottom:`1px solid ${C.border}`, display:'flex', alignItems:'center', gap:12 }}>
        <div style={{ width:36, height:36, borderRadius:'50%', background:C.accent, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'JetBrains Mono, monospace', fontSize:11, fontWeight:700, letterSpacing:'0.06em' }}>CMD</div>
        <div style={{ flex:1 }}>
          <div style={{ fontFamily:'Anton, sans-serif', fontSize:16, textTransform:'uppercase', letterSpacing:'0.01em', lineHeight:1 }}>Coach digital</div>
          <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9, letterSpacing:'0.18em', textTransform:'uppercase', color:'#2a9d4a', marginTop:3, display:'flex', alignItems:'center', gap:5 }}>
            <span style={{ width:6, height:6, borderRadius:'50%', background:'#2a9d4a' }}/> En línea
          </div>
        </div>
        <button onClick={() => s.setChatOpen(false)} style={iconBtn}>{Icon.close(18)}</button>
      </div>
      <div style={{ flex:1, overflowY:'auto', padding:'16px 14px', display:'flex', flexDirection:'column', gap:10 }}>
        <ChatBubble who="agent" text="¡hola! ¿en qué te ayudo hoy?" time="hace unos segundos"/>
        <ChatBubble who="user" text="qué combina con el hoodie negro para el después de bootcamp"/>
        <ChatBubble who="agent" text={'con el negro te jala el jogger negro si quieres mantener la línea, o el jogger gris jaspeado si quieres romperlo 🖤'}/>
        <ChatBubble who="agent" text={'y si te late, te lo aparto en tu estudio para que pases a probarlo antes de comprar'}/>
        <ChatBubble who="user" text="apártalo en Polanco porfa"/>
        <ChatBubble who="agent" text={'listo ✨ hoodie negro + jogger negro apartados en Polanco por 48h. te mandé el detalle al correo.'}/>
        <div style={{ display:'flex', gap:6, marginTop:4, flexWrap:'wrap' }}>
          <button className="cmd-chip-action">ver mi apartado</button>
          <button className="cmd-chip-action">agregar a la bolsa</button>
        </div>
      </div>
      <div style={{
        padding: mobile ? '14px 16px 28px' : '12px 14px 16px',
        background:'#fff', borderTop:`1px solid ${C.border}`,
        display:'flex', gap: 10, alignItems:'center',
      }}>
        <input placeholder="escribe…" style={{
          flex:1, background:'#F2F2F2', border:0, borderRadius: 22,
          padding: mobile ? '14px 18px' : '11px 14px',
          fontFamily:'Roboto, sans-serif', fontSize: 14, outline:'none',
        }}/>
        <button style={{
          ...iconBtn, background: C.accent, color:'#fff', borderRadius:'50%',
          width: mobile ? 42 : 36, height: mobile ? 42 : 36, flexShrink: 0,
        }}>{Icon.arrowR(mobile ? 18 : 16)}</button>
      </div>
    </aside>
  );
}

function ChatBubble({ who, text, time }) {
  const isAgent = who === 'agent';
  return (
    <div style={{ display:'flex', flexDirection:'column', alignItems: isAgent ? 'flex-start' : 'flex-end' }}>
      <div style={{
        maxWidth:'82%',
        background: isAgent ? '#fff' : C.accent,
        color: isAgent ? C.fg : '#fff',
        padding:'10px 14px',
        borderRadius: isAgent ? '4px 16px 16px 16px' : '16px 4px 16px 16px',
        fontFamily:'Roboto, sans-serif', fontSize:13, lineHeight:1.45,
        boxShadow: isAgent ? '0 1px 2px rgba(0,0,0,0.04)' : 'none',
      }}>{text}</div>
      {time && <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:8, letterSpacing:'0.18em', textTransform:'uppercase', color:C.fgMuted, marginTop:3 }}>{time}</div>}
    </div>
  );
}

Object.assign(window, {
  StoreCtx, useStore, C, Icon, iconBtn,
  Wordmark, Marquee, Header, MobileBottomNav, SectionRule, Footer, FooterCopyright, MobileMenuDrawer, CustomCursor,
  CartDrawer, ChatFAB, ChatBubble,
});
