// Shared components: Nav, Footer, Logo, Icon, Reveal, ThemeProvider, Router
// All components attached to window for cross-script use.

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

// ============================================================
// Icon — minimal stroke icon set
// ============================================================
function Icon({ name, size = 20, stroke = 1.6, ...props }) {
  const paths = {
    pin: <><path d="M12 21s-7-7.5-7-12a7 7 0 0114 0c0 4.5-7 12-7 12z"/><circle cx="12" cy="9" r="2.5"/></>,
    fuel: <><path d="M5 21V5a2 2 0 012-2h7a2 2 0 012 2v16"/><path d="M3 21h13"/><path d="M16 8h2a2 2 0 012 2v7a1.5 1.5 0 003 0v-9l-3-3"/><path d="M8 7h5v4H8z"/></>,
    star: <path d="M12 3l2.6 5.5 6 .9-4.3 4.2 1 6L12 16.7 6.7 19.6l1-6L3.4 9.4l6-.9z"/>,
    arrow: <><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></>,
    arrowUp: <><path d="M7 17L17 7"/><path d="M9 7h8v8"/></>,
    sun: <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>,
    moon: <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/>,
    menu: <><path d="M3 7h18"/><path d="M3 17h18"/></>,
    close: <><path d="M6 6l12 12"/><path d="M18 6l-12 12"/></>,
    play: <path d="M8 5v14l11-7z" fill="currentColor"/>,
    plus: <><path d="M12 5v14"/><path d="M5 12h14"/></>,
    check: <path d="M5 12l5 5 9-10"/>,
    car: <><path d="M5 14l1.5-5h11L19 14"/><rect x="3" y="14" width="18" height="5" rx="1"/><circle cx="7.5" cy="19" r="1.5" fill="currentColor"/><circle cx="16.5" cy="19" r="1.5" fill="currentColor"/></>,
    fire: <path d="M12 2c1 4 5 5 5 10a5 5 0 11-10 0c0-2 1-3 2-4 0 2 1 3 2 3 0-3-2-5 1-9z"/>,
    coffee: <><path d="M4 8h13v6a4 4 0 01-4 4H8a4 4 0 01-4-4V8z"/><path d="M17 10h2a2 2 0 010 4h-2"/><path d="M7 4v2M11 4v2"/></>,
    burger: <><path d="M4 11h16"/><path d="M4 15h16"/><path d="M4 8a8 4 0 0116 0"/><path d="M4 17a4 2 0 008 0M12 17a4 2 0 008 0"/></>,
    chicken: <><path d="M7 14a5 5 0 1110 0v3H7z"/><path d="M9 9c0-2 1-4 3-4s3 2 3 4"/><path d="M11 5l1-2 1 2"/><path d="M7 17v3M17 17v3"/></>,
    leaf: <><path d="M5 19c8 0 14-6 14-14-8 0-14 6-14 14z"/><path d="M5 19l8-8"/></>,
    phone: <path d="M5 4h4l2 5-2 1a11 11 0 005 5l1-2 5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z"/>,
    user: <><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0116 0"/></>,
    cart: <><circle cx="9" cy="20" r="1.5" fill="currentColor"/><circle cx="17" cy="20" r="1.5" fill="currentColor"/><path d="M3 4h2l2 12h12l2-8H7"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></>,
    bolt: <path d="M13 3L4 14h6l-1 7 9-11h-6z"/>,
    wash: <><path d="M4 8c2 0 2 2 4 2s2-2 4-2 2 2 4 2 2-2 4-2"/><path d="M4 13c2 0 2 2 4 2s2-2 4-2 2 2 4 2 2-2 4-2"/><path d="M4 18c2 0 2 2 4 2s2-2 4-2 2 2 4 2 2-2 4-2"/></>,
    droplet: <path d="M12 3s7 7.5 7 12a7 7 0 11-14 0c0-4.5 7-12 7-12z"/>,
    chart: <><path d="M3 20h18"/><rect x="6" y="10" width="3" height="10"/><rect x="11" y="6" width="3" height="14"/><rect x="16" y="13" width="3" height="7"/></>,
    truck: <><rect x="2" y="7" width="11" height="9"/><path d="M13 10h4l3 3v3h-7z"/><circle cx="6" cy="18" r="1.5" fill="currentColor"/><circle cx="17" cy="18" r="1.5" fill="currentColor"/></>,
    sparkle: <><path d="M12 3v5M12 16v5M3 12h5M16 12h5M6 6l3 3M15 15l3 3M18 6l-3 3M9 15l-3 3"/></>,
    palm: <><path d="M12 21V8"/><path d="M12 8c-3-3-7-3-9-1 2-2 5-2 9 1z"/><path d="M12 8c3-3 7-3 9-1-2-2-5-2-9 1z"/><path d="M12 8c0-4 2-7 5-7-1 3-3 5-5 7z"/><path d="M12 8c0-4-2-7-5-7 1 3 3 5 5 7z"/></>,
    award: <><circle cx="12" cy="9" r="6"/><path d="M9 14l-2 7 5-3 5 3-2-7"/></>,
    sandwich: <><path d="M3 9h18l-1 3H4z"/><path d="M4 12h16v3H4z"/><path d="M3 15h18l-1 2H4z"/></>,
    cup: <><path d="M5 7h12l-1 13a2 2 0 01-2 2H8a2 2 0 01-2-2L5 7z"/><path d="M4 7h14M9 4l1-1h2l1 1"/></>,
    snowflake: <><path d="M12 3v18M3 12h18M5.6 5.6l12.8 12.8M18.4 5.6L5.6 18.4"/></>,
    barbell: <><path d="M2 10v4M5 8v8M9 6v12M15 6v12M19 8v8M22 10v4"/></>,
    flask: <><path d="M9 3h6M10 3v7l-5 9a2 2 0 002 3h10a2 2 0 002-3l-5-9V3"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" {...props}>
      {paths[name]}
    </svg>
  );
}

// ============================================================
// Logo
// ============================================================
function MMLogo({ size = 28, variant = '' }) {
  // variant='on-red' adds a white outline so the logo (which contains red letters incl. the X in MAX)
  // remains legible against red backgrounds. Implemented via drop-shadow stack.
  const onRed = variant === 'on-red';
  const filter = onRed
    ? 'drop-shadow(0 0 0.8px rgba(255,255,255,0.85))'
    : 'none';
  return (
    <div className="nav-logo" aria-label="miniMAX" style={{ display: 'flex', alignItems: 'center' }}>
      <img src="/site/assets/minimax-logo.png" alt="miniMAX"
        style={{ height: size * 1.4, width: 'auto', display: 'block', filter }}/>
    </div>
  );
}

// ============================================================
// Reveal — IntersectionObserver-driven animation
// ============================================================
function Reveal({ children, delay = 0, as: Tag = 'div', ...props }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShown(true); io.disconnect(); }
    }, { threshold: 0.15 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <Tag ref={ref} className={`reveal ${shown ? 'in' : ''} ${props.className || ''}`}
      style={{ transitionDelay: `${delay}ms`, ...(props.style || {}) }} {...props}>
      {children}
    </Tag>
  );
}

// ============================================================
// Parallax — scroll-driven Y translate
// ============================================================
function useParallax(speed = 0.3) {
  const ref = useRef(null);
  const [offset, setOffset] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const viewH = window.innerHeight;
      const center = r.top + r.height / 2 - viewH / 2;
      setOffset(-center * speed);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [speed]);
  return [ref, offset];
}

// ============================================================
// Theme Context
// ============================================================
const ThemeCtx = createContext({ theme: 'light', setTheme: () => {} });

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState(() => {
    if (typeof window === 'undefined') return 'light';
    return localStorage.getItem('mm-theme') || 'light';
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('mm-theme', theme);
  }, [theme]);
  return <ThemeCtx.Provider value={{ theme, setTheme }}>{children}</ThemeCtx.Provider>;
}

function ThemeToggle() {
  const { theme, setTheme } = useContext(ThemeCtx);
  return (
    <button className="btn btn-ghost btn-icon" aria-label="Toggle theme"
      onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
      style={{ padding: 0 }}>
      <Icon name={theme === 'light' ? 'moon' : 'sun'} size={18} />
    </button>
  );
}

// ============================================================
// Router (hash-based, in-page nav)
// ============================================================
const RouterCtx = createContext({ route: 'home', go: () => {} });

function RouterProvider({ children }) {
  const [route, setRoute] = useState(() => (window.location.hash || '#home').replace('#', ''));
  useEffect(() => {
    const onHash = () => {
      const r = (window.location.hash || '#home').replace('#', '');
      setRoute(r);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const go = useCallback((r) => { window.location.hash = r; }, []);
  return <RouterCtx.Provider value={{ route, go }}>{children}</RouterCtx.Provider>;
}

function NavLink({ to, children }) {
  const { route, go } = useContext(RouterCtx);
  const active = route === to || (to === 'home' && route === '');
  return (
    <a href={`#${to}`} className={`nav-link ${active ? 'active' : ''}`}
      onClick={(e) => { e.preventDefault(); go(to); }}>
      {children}
    </a>
  );
}

// ============================================================
// Nav
// ============================================================
function Nav({ openTweaks }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const { go } = useContext(RouterCtx);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <a href="#home" onClick={(e) => { e.preventDefault(); go('home'); }} style={{ display: 'flex' }}>
        <MMLogo size={22} />
      </a>
      <div className="nav-links">
        <NavLink to="home">Home</NavLink>
        <NavLink to="wash">Car Wash</NavLink>
        <NavLink to="brands">Food</NavLink>
        <NavLink to="fuel">Fuel</NavLink>
        <NavLink to="locations">Locations</NavLink>
        <NavLink to="rewards">Rewards</NavLink>
        <NavLink to="distribution">B2B</NavLink>
        <NavLink to="careers">Careers</NavLink>
        <NavLink to="about">About</NavLink>
      </div>
      <div className="nav-actions">
        <a href="#wash" onClick={(e) => { e.preventDefault(); go('wash'); }}
          className="btn btn-primary"
          style={{ textDecoration: 'none' }}>
          Wash Club
        </a>
        <ThemeToggle />
        <span className="btn btn-ghost" style={{ cursor: 'default', opacity: 0.6, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <Icon name="user" size={16} /> Sign in · Soon
        </span>
        <button className="btn btn-primary" onClick={() => go('locations')}>
          Find a store
        </button>
      </div>
      <button
        className="nav-hamburger"
        aria-label="Menu"
        aria-expanded={menuOpen}
        onClick={() => setMenuOpen(o => !o)}
      >
        <span style={{ transform: menuOpen ? 'rotate(45deg) translate(4px, 4px)' : 'none' }}/>
        <span style={{ opacity: menuOpen ? 0 : 1 }}/>
        <span style={{ transform: menuOpen ? 'rotate(-45deg) translate(4px, -4px)' : 'none' }}/>
      </button>
      {menuOpen && (
        <div className="nav-drawer" onClick={() => setMenuOpen(false)}>
          <div className="nav-drawer-panel" onClick={(e) => e.stopPropagation()}>
            {[
              ['home','Home'], ['wash','Car Wash'], ['brands','Food'], ['fuel','Fuel'],
              ['locations','Locations'], ['rewards','Rewards'],
              ['distribution','B2B'], ['careers','Careers'], ['about','About'],
            ].map(([to, label]) => (
              <a key={to} href={`#${to}`} onClick={(e) => { e.preventDefault(); go(to); setMenuOpen(false); }}>{label}</a>
            ))}
          </div>
        </div>
      )}
    </nav>
  );
}

// ============================================================
// Ticker
// ============================================================
function Ticker({ items }) {
  const list = items || [
    'AUSTIN UNLEADED $2.78', '★ SERVING TEXAS SINCE 1995 ★', '🍔 FLAMIN BURGER — NOW SERVING',
    '🍗 KRISPY KRUNCHY CHICKEN', '🥪 WHICH WICH SUPERIOR SANDWICHES',
    '☕ BREW MAX COFFEE', '🔥 FIERY GRILL', '🚗 MAX EXPRESS CAR WASH — GO UNLIMITED',
    'SHELL · VALERO · MINIMAX FUELS', '12 LOCATIONS · AUSTIN + HOUSTON',
  ];
  const trackItems = (
    <span>
      {list.map((t, i) => <span key={i}>{t}<span style={{opacity:.4}}>◆</span></span>)}
    </span>
  );
  return (
    <div className="ticker">
      <div className="ticker-track">{trackItems}{trackItems}{trackItems}</div>
    </div>
  );
}

// ============================================================
// Footer
// ============================================================
function Footer() {
  const { go } = useContext(RouterCtx);
  return (
    <footer className="footer grain">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="nav-logo" style={{ marginBottom: 20 }}>
              <img src="/site/assets/minimax-logo.png" alt="miniMAX"
                style={{ height: 40, width: 'auto', display: 'block' }}/>
            </div>
            <p style={{ color: 'rgba(255,255,255,0.6)', maxWidth: 320, lineHeight: 1.6, fontSize: 14 }}>
              Texas-built convenience. Premium fuel, hot food, and the cleanest cars on the highway. Since 1995.
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
              {['IG', 'X', 'TT', 'FB'].map(s => (
                <a key={s} href="#" style={{
                  width: 40, height: 40, borderRadius: 8,
                  border: '1px solid rgba(255,255,255,0.15)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 12, fontFamily: 'var(--font-mono)',
                }}>{s}</a>
              ))}
            </div>
          </div>
          <div>
            <h4>Food brands</h4>
            <ul style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 24, rowGap: 0 }}>
              <li><a href="#brands?b=kkc" onClick={(e)=>{e.preventDefault();go('brands?b=kkc');}}>Krispy Krunchy</a></li>
              <li><a href="#brands?b=fg" onClick={(e)=>{e.preventDefault();go('brands?b=fg');}}>Fiery Grill</a></li>
              <li><a href="#brands?b=fb" onClick={(e)=>{e.preventDefault();go('brands?b=fb');}}>Flamin Burger</a></li>
              <li><a href="#brands?b=km" onClick={(e)=>{e.preventDefault();go('brands?b=km');}}>Kona Moka</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>Which Wich</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>Brew MAX</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>Maximum Refreshment</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>Chill To The MAX</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>Tap.IT</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>Fit MAX</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>Flavor MAX</a></li>
              <li><a href="#brands" onClick={(e)=>{e.preventDefault();go('brands');}}>minis Bakery</a></li>
            </ul>
          </div>
          <div>
            <h4>Services</h4>
            <ul>
              <li><a href="#fuel" onClick={(e)=>{e.preventDefault();go('fuel');}}>Minimax Fuel</a></li>
              <li><a href="#wash" onClick={(e)=>{e.preventDefault();go('wash');}}>Max Express Wash</a></li>
              <li><a href="#rewards" onClick={(e)=>{e.preventDefault();go('rewards');}}>Max Rewards</a></li>
              <li><a href="#distribution" onClick={(e)=>{e.preventDefault();go('distribution');}}>Distribution</a></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><a href="#about" onClick={(e)=>{e.preventDefault();go('about');}}>About</a></li>
              <li><a href="#careers" onClick={(e)=>{e.preventDefault();go('careers');}}>Careers</a></li>
              <li><a href="#">Press</a></li>
              <li><a href="#">Investors</a></li>
            </ul>
          </div>
          <div>
            <h4>Support</h4>
            <ul>
              <li><a href="#locations" onClick={(e)=>{e.preventDefault();go('locations');}}>Find a Store</a></li>
              <li><a href="#">Contact</a></li>
              <li><a href="#">Help Center</a></li>
              <li><a href="#">Gift Cards</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Minimax Holdings, Inc. — Austin, TX</span>
          <span>Privacy · Terms · Accessibility · Do Not Sell</span>
        </div>
      </div>
      <div className="footer-mega">MINIMAX</div>
    </footer>
  );
}

// ============================================================
// Section header
// ============================================================
function SectionHeader({ eyebrow, title, kicker, align = 'left' }) {
  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: align === 'center' ? 'center' : 'flex-start',
      textAlign: align,
      marginBottom: 64,
      gap: 16,
    }}>
      {eyebrow && <span className="eyebrow">{eyebrow}</span>}
      <h2 className="display" style={{ fontSize: 'clamp(48px, 6vw, 96px)', margin: 0, maxWidth: 18 + 'ch' }}>
        {title}
      </h2>
      {kicker && <p style={{ color: 'var(--text-2)', fontSize: 18, lineHeight: 1.5, maxWidth: 560, margin: 0 }}>{kicker}</p>}
    </div>
  );
}

// ============================================================
// Stat block
// ============================================================
function Stat({ value, label, suffix }) {
  return (
    <div>
      <div className="display" style={{ fontSize: 'clamp(56px, 7vw, 96px)', lineHeight: 0.9, color: 'var(--mm-red)' }}>
        {value}<span style={{ color: 'var(--text)' }}>{suffix}</span>
      </div>
      <div className="eyebrow" style={{ marginTop: 8 }}>{label}</div>
    </div>
  );
}

// ============================================================
// Page wrapper
// ============================================================
function Page({ children }) {
  return <main className="page-enter" style={{ paddingTop: 80 }}>{children}</main>;
}

// Export to window
// ============================================================
// ImgPlaceholder — premium placeholder for missing imagery
// Use sparingly: aspect ratio + tone + label (and optional glyph)
// ============================================================
function ImgPlaceholder({
  ratio = '4/3',
  tone = 'ink',
  label,
  caption,
  glyph,
  width,
  height,
  style = {},
  className = '',
  children,
  ...props
}) {
  const dims = (width || height)
    ? { width, height }
    : { aspectRatio: ratio, width: '100%' };
  return (
    <div className={`img-ph ${className}`} data-tone={tone} style={{ ...dims, ...style }} {...props}>
      {caption && <span className="img-ph-caption">{caption}</span>}
      {glyph && <span className="img-ph-glyph">{glyph}</span>}
      {children}
      {label && (
        <span className="img-ph-label">
          <span>{label}</span>
          <span style={{ opacity: 0.6 }}>placeholder</span>
        </span>
      )}
    </div>
  );
}

// MINI/MAX wordmark — composable with size & variant
function Wordmark({ size = 56, variant = '', as: As = 'span', style = {}, ...props }) {
  return (
    <As className={`mm-wordmark ${variant}`} style={{ fontSize: size, ...style }} {...props}>
      <span className="mini">mini</span><span className="max">MAX</span>
    </As>
  );
}

// ============================================================
// MMMap — Leaflet map with multi-marker support, themed
// Used by location finders. Stores get red pins; user gets blue. Active store gets larger pin.
// ============================================================
function MMMap({ stores, active, setActive, userPos, mapTheme }) {
  const ref = useRef(null);
  const mapRef = useRef(null);
  const markersRef = useRef([]);
  const userMarkerRef = useRef(null);

  // Init map
  useEffect(() => {
    if (!window.L || !ref.current || mapRef.current) return;
    const L = window.L;
    const initialCenter = stores[0] ? [stores[0].lat, stores[0].lng] : [30.27, -97.74];
    const map = L.map(ref.current, {
      center: initialCenter, zoom: 11, zoomControl: true, scrollWheelZoom: false,
    });
    // Tile layer — dark or light per theme
    const dark = mapTheme === 'dark';
    L.tileLayer(
      dark
        ? 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'
        : 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
      { attribution: '&copy; OpenStreetMap &copy; CARTO', maxZoom: 19, subdomains: 'abcd' }
    ).addTo(map);
    mapRef.current = map;
    return () => { map.remove(); mapRef.current = null; };
  }, [mapTheme]);

  // Render store markers
  useEffect(() => {
    if (!mapRef.current || !window.L) return;
    const L = window.L;
    markersRef.current.forEach(m => m.remove());
    markersRef.current = [];
    stores.forEach((s, i) => {
      const isActive = i === active;
      const isComing = s.comingSoon;
      const color = isComing ? '#8A8A86' : (isActive ? '#E2231A' : '#C41A12');
      const size = isActive ? 36 : 28;
      const html = `<div style="width:${size}px;height:${size}px;background:${color};border-radius:50%;border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,0.35);display:flex;align-items:center;justify-content:center;color:#fff;font-family:'Bebas Neue',Impact,sans-serif;font-size:${isActive?15:12}px;letter-spacing:0.05em;cursor:pointer;${isActive?'transform:scale(1.1);':''}">${s.num}</div>`;
      const icon = L.divIcon({ html, className: 'mm-store-pin', iconSize: [size, size], iconAnchor: [size/2, size/2] });
      const marker = L.marker([s.lat, s.lng], { icon }).addTo(mapRef.current);
      marker.on('click', () => setActive(i));
      marker.bindTooltip(s.short + (isComing ? ' (Coming Soon)' : ''), { direction: 'top', offset: [0, -size/2] });
      markersRef.current.push(marker);
    });
  }, [stores, active]);

  // Render user marker (blue)
  useEffect(() => {
    if (!mapRef.current || !window.L) return;
    const L = window.L;
    if (userMarkerRef.current) { userMarkerRef.current.remove(); userMarkerRef.current = null; }
    if (userPos) {
      const html = '<div style="width:20px;height:20px;background:#1E80FF;border-radius:50%;border:3px solid #fff;box-shadow:0 0 0 4px rgba(30,128,255,0.25),0 2px 8px rgba(0,0,0,0.35);"></div>';
      const icon = L.divIcon({ html, className: 'mm-user-pin', iconSize: [20, 20], iconAnchor: [10, 10] });
      userMarkerRef.current = L.marker([userPos.lat, userPos.lng], { icon, zIndexOffset: 1000 }).addTo(mapRef.current);
      userMarkerRef.current.bindTooltip('You are here', { direction: 'top', offset: [0, -10] });
    }
  }, [userPos]);

  // Pan/fit to active store + user
  useEffect(() => {
    if (!mapRef.current || !window.L) return;
    const L = window.L;
    const activeStore = stores[active];
    if (userPos && activeStore) {
      const bounds = L.latLngBounds([[userPos.lat, userPos.lng], [activeStore.lat, activeStore.lng]]);
      mapRef.current.fitBounds(bounds, { padding: [50, 50], maxZoom: 13 });
    } else if (activeStore) {
      mapRef.current.setView([activeStore.lat, activeStore.lng], 13, { animate: true });
    }
  }, [active, userPos, stores]);

  return <div ref={ref} style={{ width: '100%', height: '100%', minHeight: 520, borderRadius: 'inherit' }}/>;
}

Object.assign(window, {
  Icon, MMLogo, Reveal, useParallax,
  ThemeProvider, ThemeCtx, ThemeToggle,
  RouterProvider, RouterCtx, NavLink,
  Nav, Ticker, Footer, SectionHeader, Stat, Page,
  ImgPlaceholder, Wordmark, MMMap,
});
