// Home page — premium hero, animated brand showcase, parallax, location finder
const { useState: useState_h, useEffect: useEffect_h, useRef: useRef_h, useContext: useContext_h, useMemo: useMemo_h } = React;

// ------------------------------------------------------------
// HERO — full-bleed with parallax red wedge + animated price ticker + cycling food
// ------------------------------------------------------------
function Hero() {
  const { go } = useContext_h(RouterCtx);
  const [scrollY, setScrollY] = useState_h(0);
  const [mouseX, setMouseX] = useState_h(0);
  const [mouseY, setMouseY] = useState_h(0);
  const heroRef = useRef_h(null);

  useEffect_h(() => {
    const onScroll = () => setScrollY(window.scrollY);
    const onMouse = (e) => {
      if (!heroRef.current) return;
      const r = heroRef.current.getBoundingClientRect();
      setMouseX(((e.clientX - r.left) / r.width - 0.5) * 2);
      setMouseY(((e.clientY - r.top) / r.height - 0.5) * 2);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('mousemove', onMouse);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('mousemove', onMouse);
    };
  }, []);

  // Live cycling fuel prices
  const [prices, setPrices] = useState_h({ unleaded: 2.78, plus: 3.08, premium: 3.38, diesel: 3.42 });
  useEffect_h(() => {
    const t = setInterval(() => {
      setPrices(p => ({
        unleaded: +(p.unleaded + (Math.random() - 0.5) * 0.02).toFixed(2),
        plus: +(p.plus + (Math.random() - 0.5) * 0.02).toFixed(2),
        premium: +(p.premium + (Math.random() - 0.5) * 0.02).toFixed(2),
        diesel: +(p.diesel + (Math.random() - 0.5) * 0.02).toFixed(2),
      }));
    }, 2400);
    return () => clearInterval(t);
  }, []);

  return (
    <section ref={heroRef} style={{
      position: 'relative',
      minHeight: 'calc(100vh - 40px)',
      paddingBlock: '80px 60px',
      overflow: 'hidden',
      background: 'var(--bg)',
    }}>
      {/* Background red wedge with parallax */}
      <div style={{
        position: 'absolute',
        top: 0, right: 0, bottom: 0,
        width: '54%',
        background: 'linear-gradient(135deg, var(--mm-red) 0%, var(--mm-red-deep) 100%)',
        clipPath: 'polygon(20% 0, 100% 0, 100% 100%, 0% 100%)',
        transform: `translateY(${scrollY * 0.18}px) translateX(${mouseX * 8}px)`,
        transition: 'transform .2s linear',
      }} />

      {/* Grain over wedge */}
      <div style={{
        position: 'absolute', top: 0, right: 0, bottom: 0, width: '54%',
        clipPath: 'polygon(20% 0, 100% 0, 100% 100%, 0% 100%)',
        opacity: 0.15, mixBlendMode: 'overlay',
        background: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200'%3E%3Cfilter id='n'%3E%3CfeTurbulence baseFrequency='0.9'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")",
      }} />

      {/* Diagonal silver lines decoration (parallax) */}
      <svg style={{
        position: 'absolute', top: '20%', right: '4%', opacity: 0.5,
        transform: `translateY(${-scrollY * 0.4}px) rotate(-12deg)`,
      }} width="180" height="180" viewBox="0 0 180 180">
        {Array.from({ length: 12 }).map((_, i) => (
          <line key={i} x1={i*16} y1={0} x2={i*16-100} y2={180} stroke="rgba(255,255,255,0.5)" strokeWidth="1.5"/>
        ))}
      </svg>

      <div className="container" style={{ position: 'relative', zIndex: 2, paddingTop: 60 }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1.1fr 1fr',
          gap: 80,
          alignItems: 'center',
          minHeight: '78vh',
        }}>
          {/* LEFT — copy */}
          <div>
            <div className="chip live" style={{ marginBottom: 32 }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.15em' }}>
                SERVING TEXAS SINCE 1995 · 11 LOCATIONS
              </span>
            </div>
            <h1 className="display" style={{
              fontSize: 'clamp(72px, 10vw, 168px)',
              margin: 0,
              lineHeight: 0.85,
              textTransform: 'lowercase',
              fontWeight: 400,
              letterSpacing: '-0.02em',
            }}>
              <span style={{ color: 'var(--mm-red)' }}>mini</span><span style={{
                color: 'var(--text)',
              }}>mal</span><br/>
              <span style={{
                color: 'transparent', WebkitTextStroke: '2.5px #9CA3AF',
              }}>time</span><br/>
              <span style={{ color: 'var(--mm-red)' }}>max</span><span style={{
                color: 'var(--text)',
              }}>imum</span><br/>
              <span style={{
                color: 'transparent', WebkitTextStroke: '2.5px #9CA3AF',
              }}>experience</span>
            </h1>
            <p style={{
              fontSize: 20,
              color: 'var(--text-2)',
              lineHeight: 1.5,
              maxWidth: 540,
              marginTop: 32,
              marginBottom: 40,
            }}>
              Premium fuel, fresh food from eleven in-house brands, professional Max Express car wash —
              all under one roof, designed around your convenience. <span className="serif" style={{ color: 'var(--text)' }}>Stop once. Win thrice.</span>
            </p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-primary" onClick={() => go('locations')}>
                <Icon name="pin" size={16} /> Find a Location
              </button>
              <button className="btn btn-ghost" onClick={() => go('wash')}>
                ✨ Join Wash Club <Icon name="arrow" size={16} />
              </button>
            </div>

            {/* Bottom stats strip */}
            <div style={{
              display: 'flex', gap: 48, marginTop: 64,
              paddingTop: 32, borderTop: '1px solid var(--border)',
            }}>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 40, color: 'var(--mm-red)', lineHeight: 1 }}>30+</div>
                <div className="eyebrow" style={{ marginTop: 6 }}>Years in TX</div>
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 40, lineHeight: 1 }}>11</div>
                <div className="eyebrow" style={{ marginTop: 6 }}>Food brands</div>
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 40, lineHeight: 1 }}>3</div>
                <div className="eyebrow" style={{ marginTop: 6 }}>Fuel partners</div>
              </div>
            </div>
          </div>

          {/* RIGHT — Live price card stack with parallax */}
          <div style={{ position: 'relative', height: 540 }}>
            {/* Card 1 — Live fuel prices */}
            <div style={{
              position: 'absolute',
              top: '6%', right: '5%', width: 380,
              background: 'var(--bg-elev)',
              borderRadius: 'var(--r-lg)',
              padding: 28,
              boxShadow: 'var(--shadow-lg)',
              border: '1px solid var(--border)',
              transform: `translate(${mouseX * -10}px, ${mouseY * -10 + scrollY * -0.05}px) rotate(-2deg)`,
              transition: 'transform .3s var(--ease-out)',
              zIndex: 3,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
                <span className="eyebrow">Austin · FM 969</span>
                {/* "LIVE / NOW" removed per design feedback — restore later when prices truly live */}
              </div>
              <div style={{ display: 'grid', gap: 14 }}>
                {[
                  { name: 'Unleaded 87', price: prices.unleaded, color: 'var(--mm-red)' },
                  { name: 'Plus 89', price: prices.plus },
                  { name: 'Premium 93', price: prices.premium },
                  { name: 'Diesel', price: prices.diesel },
                ].map((f, i) => (
                  <div key={i} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                    paddingBottom: 12, borderBottom: i < 3 ? '1px solid var(--border)' : 'none',
                  }}>
                    <span style={{ fontWeight: 500, fontSize: 14 }}>{f.name}</span>
                    <span style={{
                      fontFamily: 'var(--font-display)',
                      fontSize: 36, lineHeight: 1,
                      color: f.color || 'var(--text)',
                    }}>
                      ${f.price.toFixed(2)}
                      <span style={{ fontSize: 13, color: 'var(--text-3)', marginLeft: 4 }}>/gal</span>
                    </span>
                  </div>
                ))}
              </div>
              <div className="btn btn-dark" style={{ width: '100%', marginTop: 16, justifyContent: 'center', cursor: 'default', opacity: 0.7, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <Icon name="bolt" size={14} /> 2× points · Coming Soon
              </div>
            </div>

            {/* Card 2 — Now serving */}
            <div style={{
              position: 'absolute',
              bottom: '8%', left: '0%', width: 320,
              background: 'var(--mm-black)', color: '#fff',
              borderRadius: 'var(--r-lg)',
              padding: 24,
              boxShadow: 'var(--shadow-lg)',
              transform: `translate(${mouseX * 14}px, ${mouseY * 14 + scrollY * -0.1}px) rotate(3deg)`,
              transition: 'transform .3s var(--ease-out)',
              zIndex: 4,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
                <div>
                  <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.5)' }}>Now serving · FM 969</div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, marginTop: 4 }}>FLAMIN COMBO</div>
                </div>
                <div style={{
                  width: 48, height: 48, borderRadius: '50%',
                  background: 'var(--mm-yellow)', color: 'var(--mm-black)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name="burger" size={24} stroke={1.8} />
                </div>
              </div>
              <p style={{ margin: 0, fontSize: 14, color: 'rgba(255,255,255,0.7)', lineHeight: 1.5 }}>
                Double-patty smash burger, hand-cut fries, and a fountain drink. Lunch sorted.
              </p>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 18 }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 28 }}>$11.49</span>
                <span style={{
                  background: 'var(--surface-2)', color: 'var(--text-3)',
                  border: '1px solid var(--border)', padding: '8px 14px', borderRadius: 999,
                  fontWeight: 600, fontSize: 12, fontFamily: 'var(--font-mono)',
                  letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'default',
                }}>Coming Soon</span>
              </div>
            </div>

            {/* Card 3 — Wash */}
            <div style={{
              position: 'absolute',
              top: '40%', right: '40%', width: 200,
              background: 'var(--max-blue)',
              color: '#fff',
              borderRadius: 'var(--r-lg)',
              padding: 18,
              boxShadow: 'var(--shadow-lg)',
              transform: `translate(${mouseX * -6}px, ${mouseY * -6 + scrollY * -0.15}px) rotate(-6deg)`,
              transition: 'transform .3s var(--ease-out)',
              zIndex: 2,
            }}>
              <Icon name="wash" size={32} stroke={2} />
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, marginTop: 12, lineHeight: 1 }}>
                GO MAX.<br/>GO UNLIMITED.
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.15em', marginTop: 8, opacity: 0.85 }}>
                MAXWASH · FROM $19.99/MO
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ------------------------------------------------------------
// PILLARS — 4 service blocks (fuel, food, wash, rewards)
// ------------------------------------------------------------
function Pillars() {
  const { go } = useContext_h(RouterCtx);
  const pillars = [
    { id: 'fuel', icon: 'fuel', label: 'Minimax Fuel', desc: 'Top-tier detergent, lower per-gallon, fastest pumps in the lot.', go: 'fuel' },
    { id: 'food', icon: 'burger', label: 'Hot Food', desc: 'Four house brands. One kitchen. Always under 3 minutes.', go: 'brands' },
    { id: 'wash', icon: 'wash', label: 'Max Express Wash', desc: 'Triple-soak, ceramic shine, free vacs. Drive in, drive out.', go: 'wash' },
    { id: 'rewards', icon: 'star', label: 'Max Rewards', desc: 'Points on every gallon, every burrito, every wash. No tiers.', go: 'rewards' },
  ];
  return (
    <section className="section" style={{ background: 'var(--bg-alt)' }}>
      <div className="container">
        <SectionHeader
          eyebrow="Four pillars · One stop"
          title={<>Everything you need.<br/><span className="serif" style={{ color: 'var(--mm-red)', fontStyle: 'italic' }}>None of what you don't.</span></>}
        />
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 16,
        }}>
          {pillars.map((p, i) => (
            <Reveal key={p.id} delay={i * 80}>
              <div className="card" style={{ height: '100%', display: 'flex', flexDirection: 'column', cursor: 'pointer' }}
                   onClick={() => go(p.go)}>
                <div style={{
                  width: 56, height: 56, borderRadius: 14,
                  background: 'var(--mm-red-soft)',
                  color: 'var(--mm-red)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  marginBottom: 24,
                }}>
                  <Icon name={p.icon} size={28} stroke={1.6}/>
                </div>
                <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 36, lineHeight: 1 }}>{p.label}</h3>
                <p style={{ color: 'var(--text-2)', lineHeight: 1.55, fontSize: 15, marginTop: 12, marginBottom: 24, flex: 1 }}>{p.desc}</p>
                <span style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  fontSize: 13, fontWeight: 600, color: 'var(--mm-red)',
                }}>Explore <Icon name="arrow" size={14}/></span>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// ------------------------------------------------------------
// BRAND REVEAL — Animated cycling brand showcase
// ------------------------------------------------------------
function BrandReveal() {
  const brands = [
    { id: 'fb', name: 'Flamin Burger', short: 'FLAMIN', tagline: 'Two patties. One inferno.', bg: '#FFFFFF', ink: 'var(--mm-red)', accent: 'var(--mm-red)', icon: 'burger' },
    { id: 'kkc', name: 'Krispy Krunchy Chicken', short: 'KKC', tagline: 'Cajun crunch. Texas heat.', bg: 'var(--kkc-red)', ink: '#fff', accent: 'var(--kkc-yellow)', icon: 'chicken' },
    { id: 'fg', name: 'Fiery Grill', short: 'FIERY', tagline: 'Smoke + sear, cooked to char.', bg: 'var(--fg-char)', ink: '#fff', accent: 'var(--fg-orange)', icon: 'fire' },
    { id: 'km', name: 'Kona Moka', short: 'KONA', tagline: 'Slow-roast. Island calm.', bg: 'var(--km-teal)', ink: 'var(--km-sand)', accent: 'var(--km-coral)', icon: 'coffee' },
  ];
  const [active, setActive] = useState_h(0);
  const [auto, setAuto] = useState_h(true);
  useEffect_h(() => {
    if (!auto) return;
    const t = setInterval(() => setActive(a => (a + 1) % brands.length), 3500);
    return () => clearInterval(t);
  }, [auto, brands.length]);

  const b = brands[active];
  const { go } = useContext_h(RouterCtx);

  return (
    <section className="section" style={{ paddingBlock: 0, position: 'relative' }}
      onMouseEnter={() => setAuto(false)} onMouseLeave={() => setAuto(true)}>
      <div style={{
        position: 'relative',
        background: b.bg,
        color: b.ink,
        transition: 'background-color .8s var(--ease-out), color .8s var(--ease-out)',
        paddingBlock: 'var(--section-pad)',
        overflow: 'hidden',
      }}>
        {/* Decorative giant brand shortname */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)',
          fontSize: 'clamp(280px, 38vw, 640px)',
          color: 'transparent',
          WebkitTextStroke: `1px ${b.accent}`,
          opacity: 0.25,
          letterSpacing: '-0.04em',
          pointerEvents: 'none',
          transition: 'opacity .8s',
        }}>
          {b.short}
        </div>

        <div className="container" style={{ position: 'relative', zIndex: 2 }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 80,
            alignItems: 'center',
          }}>
            <div>
              <span className="eyebrow" style={{ color: b.accent }}>House brand · 0{active + 1} / 04</span>
              <h2 className="display" style={{
                fontSize: 'clamp(80px, 10vw, 160px)',
                margin: '24px 0',
                color: b.ink,
              }}>
                {b.name.split(' ').map((w, i) => <span key={i} style={{ display: 'block' }}>{w}</span>)}
              </h2>
              <p className="serif" style={{
                fontSize: 24,
                color: b.accent,
                margin: 0, marginBottom: 32,
              }}>
                "{b.tagline}"
              </p>
              <button className="btn" style={{ background: b.accent, color: b.bg }} onClick={() => go('brands?b=' + b.id)}>
                Explore {b.name} →
              </button>
            </div>

            {/* Visual side — large icon + brand stamp */}
            <div style={{
              position: 'relative',
              height: 480,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{
                width: 360, height: 360,
                borderRadius: '50%',
                border: `2px solid ${b.accent}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: b.accent,
                position: 'relative',
              }}>
                <Icon name={b.icon} size={180} stroke={1.2}/>
                {/* Spinning text ring */}
                <svg width="360" height="360" style={{ position: 'absolute', inset: 0, animation: 'spin 30s linear infinite' }}>
                  <defs>
                    <path id={`circ-${active}`} d="M180,180 m-160,0 a160,160 0 1,1 320,0 a160,160 0 1,1 -320,0"/>
                  </defs>
                  <text fill={b.accent} fontFamily="var(--font-mono)" fontSize="11" letterSpacing="6">
                    <textPath href={`#circ-${active}`}>
                      {`${b.name.toUpperCase()} · A MINIMAX HOUSE BRAND · `.repeat(3)}
                    </textPath>
                  </text>
                </svg>
              </div>
            </div>
          </div>

          {/* Brand selector dots */}
          <div style={{
            display: 'flex', gap: 8, marginTop: 48,
            justifyContent: 'center',
          }}>
            {brands.map((br, i) => (
              <button key={br.id}
                onClick={() => setActive(i)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 18px',
                  borderRadius: 999,
                  border: `1px solid ${i === active ? b.accent : 'rgba(255,255,255,0.2)'}`,
                  background: i === active ? b.accent : 'transparent',
                  color: i === active ? b.bg : b.ink,
                  fontFamily: 'var(--font-mono)',
                  fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
                  cursor: 'pointer',
                  transition: 'all .3s',
                }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 16 }}>0{i + 1}</span>
                {br.short}
              </button>
            ))}
          </div>
        </div>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </section>
  );
}

// ------------------------------------------------------------
// LOCATION FINDER — interactive lookup
// ------------------------------------------------------------
function LocationFinder() {
  const allStores = window.MM_STORES;
  const { theme } = useContext_h(ThemeCtx);
  const [query, setQuery] = useState_h('');
  const [active, setActive] = useState_h(0);
  const [userPos, setUserPos] = useState_h(null);
  const [geoErr, setGeoErr] = useState_h('');
  const [zipCenter, setZipCenter] = useState_h(null);

  useEffect_h(() => {
    const q = query.trim();
    const m = q.match(/^(\d{5})$/);
    if (!m) { setZipCenter(null); return; }
    setGeoErr('');  // ZIP search clears any prior geo error
    let cancelled = false;
    fetch(`https://api.zippopotam.us/us/${m[1]}`)
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (cancelled) return;
        if (d && d.places && d.places[0]) {
          setZipCenter({ lat: parseFloat(d.places[0].latitude), lng: parseFloat(d.places[0].longitude), zip: m[1] });
        } else {
          setZipCenter(null);
        }
      })
      .catch(() => { if (!cancelled) setZipCenter(null); });
    return () => { cancelled = true; };
  }, [query]);

  const distMi = (a, b) => {
    if (!a || !b) return null;
    const R = 3959;
    const dLat = (b.lat - a.lat) * Math.PI / 180;
    const dLng = (b.lng - a.lng) * Math.PI / 180;
    const lat1 = a.lat * Math.PI / 180, lat2 = b.lat * Math.PI / 180;
    const h = Math.sin(dLat/2)**2 + Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLng/2)**2;
    return 2 * R * Math.asin(Math.sqrt(h));
  };

  const stores = useMemo_h(() => {
    const q = query.trim().toLowerCase();
    const isZipQuery = /^\d{5}$/.test(query.trim());
    let list = allStores.filter(s => {
      if (!q || isZipQuery) return true;  // ZIP doesn't filter, it positions
      return s.short.toLowerCase().includes(q) ||
             s.addr.toLowerCase().includes(q) ||
             s.region.toLowerCase().includes(q) ||
             s.services.some(sv => sv.toLowerCase().includes(q));
    });
    const center = userPos || zipCenter;
    if (center) {
      list = list.map(s => ({ ...s, _miles: distMi(center, s) }))
                 .sort((a, b) => (a._miles ?? 999) - (b._miles ?? 999));
    }
    return list.slice(0, 6);
  }, [query, userPos, zipCenter, allStores]);

  const useMyLocation = () => {
    setGeoErr('');
    if (!navigator.geolocation) { setGeoErr('Geolocation not supported'); return; }
    navigator.geolocation.getCurrentPosition(
      (pos) => setUserPos({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
      (err) => setGeoErr(err.code === 1 ? 'Location permission denied' : 'Could not get location'),
      { enableHighAccuracy: false, timeout: 8000, maximumAge: 60000 }
    );
  };

  const activeStore = stores[active] || stores[0];
  const directionsUrl = activeStore
    ? `https://www.google.com/maps/dir/?api=1&destination=${activeStore.lat},${activeStore.lng}`
    : '#';

  return (
    <section className="section">
      <div className="container">
        <SectionHeader
          eyebrow="11 stores · Texas"
          title={<>Find your <span style={{ color: 'var(--mm-red)' }}>Minimax</span>.</>}
          kicker="Search by ZIP, city, or service. Or use your location."
        />
        <div style={{
          display: 'grid', gridTemplateColumns: '420px 1fr', gap: 24,
          background: 'var(--bg-alt)', borderRadius: 'var(--r-xl)',
          padding: 24, border: '1px solid var(--border)',
        }}>
          <div>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '14px 18px',
              background: 'var(--bg-elev)',
              border: '1px solid var(--border)',
              borderRadius: 999,
              marginBottom: 8,
            }}>
              <Icon name="search" size={16} />
              <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="ZIP, city, or service (e.g. 'wash')"
                style={{ border: 0, outline: 0, background: 'transparent', fontFamily: 'inherit', fontSize: 15, flex: 1, color: 'var(--text)' }}/>
              {query && (
                <button onClick={() => setQuery('')} aria-label="Clear"
                  style={{ background: 'transparent', border: 0, cursor: 'pointer', padding: 0, color: 'var(--text-3)', fontSize: 16 }}>×</button>
              )}
            </div>
            <button onClick={useMyLocation}
              className="btn btn-ghost"
              style={{
                width: '100%', justifyContent: 'center',
                fontSize: 13, padding: '10px 14px', marginBottom: 16,
                background: userPos ? 'var(--mm-red-soft)' : 'transparent',
                color: userPos ? 'var(--mm-red)' : 'var(--text-2)',
                border: `1px solid ${userPos ? 'var(--mm-red)' : 'var(--border)'}`,
              }}>
              <Icon name="pin" size={14}/>
              {userPos ? 'Using your location · sorted by distance' : 'Use my location → nearest first'}
            </button>
            {geoErr && (
              <div style={{ fontSize: 12, color: 'var(--mm-red)', marginBottom: 12, marginTop: -8, padding: '0 4px' }}>
                {geoErr}
              </div>
            )}
            {zipCenter && !userPos && (
              <div style={{ fontSize: 12, color: 'var(--mm-red)', marginBottom: 12, marginTop: -8, padding: '0 4px', fontFamily: 'var(--font-mono)', letterSpacing: '0.05em' }}>
                ● Sorted by distance from {zipCenter.zip}
              </div>
            )}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, maxHeight: 480, overflowY: 'auto', paddingRight: 4 }}>
              {stores.length === 0 && (
                <div style={{ padding: 16, fontSize: 13, color: 'var(--text-3)', textAlign: 'center' }}>
                  No stores match "{query}".
                </div>
              )}
              {stores.map((s, i) => (
                <button key={s.num} onClick={() => setActive(i)}
                  style={{
                    textAlign: 'left',
                    padding: 16,
                    borderRadius: 'var(--r-md)',
                    border: `1px solid ${i === active ? 'var(--mm-red)' : 'var(--border)'}`,
                    background: i === active ? 'var(--mm-red-soft)' : 'var(--bg-elev)',
                    cursor: 'pointer',
                    transition: 'all .2s',
                  }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>{s.short}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 4 }}>
                        {s._miles != null ? `${s._miles.toFixed(1)}mi` : (s.distance || '—')}
                        {' · '}
                        {s.comingSoon
                          ? <span style={{ color: 'var(--mm-red)', fontWeight: 600 }}>Coming Soon</span>
                          : (s.open ? <span style={{ color: '#1FCB6F' }}>Open</span> : <span style={{ color: 'var(--text-3)' }}>Closed</span>)
                        }
                      </div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 4, marginTop: 10, flexWrap: 'wrap' }}>
                    {s.services.map(sv => {
                      const cmap = {
                        Fuel: { bg: 'rgba(226,35,26,0.10)', fg: '#E2231A' },
                        Flamin: { bg: 'rgba(226,35,26,0.10)', fg: '#E2231A' },
                        KKC: { bg: 'rgba(255,158,0,0.14)', fg: '#C97600' },
                        'Which Wich': { bg: 'rgba(255,210,0,0.18)', fg: '#8A6800' },
                        Fiery: { bg: 'rgba(255,106,0,0.14)', fg: '#C24A00' },
                        'Brew MAX': { bg: 'rgba(76,46,32,0.14)', fg: '#5A2E1A' },
                        Kona: { bg: 'rgba(143,90,46,0.14)', fg: '#6B3F1E' },
                        Wash: { bg: 'rgba(75,85,99,0.16)', fg: '#374151' },
                      };
                      const c = cmap[sv] || { bg: 'var(--surface-2)', fg: 'var(--text-2)' };
                      return (
                        <span key={sv} style={{
                          fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em',
                          padding: '3px 8px', borderRadius: 4,
                          background: c.bg, color: c.fg, fontWeight: 600,
                          textTransform: 'uppercase',
                        }}>{sv}</span>
                      );
                    })}
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Map column — Google Maps embed centered on active store */}
          <div style={{
            position: 'relative',
            borderRadius: 'var(--r-xl)',
            overflow: 'hidden',
            background: 'var(--bg-elev)',
            minHeight: 520,
            border: '1px solid var(--border)',
          }}>
            <MMMap
              stores={stores}
              active={active}
              setActive={setActive}
              userPos={userPos || zipCenter}
              mapTheme={theme === 'dark' ? 'dark' : 'light'}
            />
            {activeStore && (
              <div style={{
                position: 'absolute', bottom: 20, left: 20, right: 20,
                background: 'var(--bg-elev)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-md)',
                padding: 16,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                boxShadow: 'var(--shadow)',
                pointerEvents: 'auto',
              }}>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{activeStore.short}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 4 }}>
                    {activeStore.addr}
                  </div>
                </div>
                <a className="btn btn-primary" target="_blank" rel="noopener noreferrer"
                  href={directionsUrl}
                  style={{ padding: '10px 18px', fontSize: 13, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
                  Directions <Icon name="arrowUp" size={14}/>
                </a>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// ------------------------------------------------------------
// BIG MARQUEE — type animation
// ------------------------------------------------------------
function BigMarquee() {
  return (
    <section style={{
      borderBlock: '1px solid var(--border)',
      paddingBlock: 60,
      overflow: 'hidden',
      background: 'var(--bg)',
    }}>
      <div style={{
        display: 'flex', whiteSpace: 'nowrap',
        animation: 'marquee 30s linear infinite',
      }}>
        {Array.from({ length: 4 }).map((_, k) => (
          <span key={k} style={{
            display: 'flex', alignItems: 'center', gap: 32,
            paddingRight: 32,
            fontFamily: 'var(--font-display)',
            fontSize: 'clamp(80px, 10vw, 160px)',
            lineHeight: 0.9,
          }}>
            <span>FUEL</span>
            <span style={{ color: 'var(--mm-red)' }}>·</span>
            <span style={{ WebkitTextStroke: '2px var(--text)', color: 'transparent' }}>FOOD</span>
            <span style={{ color: 'var(--mm-red)' }}>·</span>
            <span>WASH</span>
            <span style={{ color: 'var(--mm-red)' }}>·</span>
            <span style={{ WebkitTextStroke: '2px var(--text)', color: 'transparent' }}>REWARDS</span>
            <span style={{ color: 'var(--mm-red)' }}>·</span>
          </span>
        ))}
      </div>
    </section>
  );
}

// ------------------------------------------------------------
// REWARDS TEASER
// ------------------------------------------------------------
function RewardsTeaser() {
  const { go } = useContext_h(RouterCtx);
  const [points, setPoints] = useState_h(0);
  useEffect_h(() => {
    let i = 0;
    const t = setInterval(() => {
      i += 47;
      if (i > 1820) { setPoints(1820); clearInterval(t); return; }
      setPoints(i);
    }, 30);
    return () => clearInterval(t);
  }, []);
  return (
    <section className="section" style={{ background: 'var(--mm-black)', color: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'center' }}>
          <div>
            <span className="eyebrow" style={{ color: 'var(--mm-red)' }}>Max Rewards · Free</span>
            <h2 className="display" style={{ fontSize: 'clamp(72px, 9vw, 144px)', margin: '24px 0', color: '#fff' }}>
              Points on<br/>
              <span style={{ color: 'var(--mm-red)' }}>everything.</span>
            </h2>
            <p style={{ fontSize: 18, color: 'rgba(255,255,255,0.7)', maxWidth: 480, lineHeight: 1.6, marginBottom: 24 }}>
              No tiers. No expiration. No nonsense.
            </p>
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
              maxWidth: 480, marginBottom: 32,
            }}>
              {[
                { icon: 'fuel',   pts: '10pts',   label: 'per gallon' },
                { icon: 'burger', pts: '5pts',    label: 'per $1 in-store' },
                { icon: 'wash',   pts: '2× pts',  label: 'on Tuesdays' },
                { icon: 'star',   pts: 'No tiers',label: 'no expiration' },
              ].map((it, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 14px',
                  background: 'rgba(255,255,255,0.06)',
                  border: '1px solid rgba(255,255,255,0.1)',
                  borderRadius: 'var(--r-md)',
                }}>
                  <span style={{
                    width: 36, height: 36, borderRadius: 8,
                    background: 'rgba(226,35,26,0.2)',
                    color: 'var(--mm-red)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <Icon name={it.icon} size={18}/>
                  </span>
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, lineHeight: 1, color: '#fff' }}>{it.pts}</div>
                    <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 2 }}>{it.label}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn-primary" onClick={() => go('rewards')}>See preview <Icon name="arrow" size={16}/></button>
              <div className="btn" style={{ background: 'rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.6)', border: '1px solid rgba(255,255,255,0.2)', cursor: 'default', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <Icon name="phone" size={14}/> App · Coming Soon
              </div>
            </div>
          </div>
          <div>
            {/* Points card mock */}
            <div style={{
              background: 'linear-gradient(135deg, var(--mm-red) 0%, var(--mm-red-deep) 100%)',
              borderRadius: 'var(--r-xl)',
              padding: 36,
              aspectRatio: '1.6 / 1',
              position: 'relative',
              overflow: 'hidden',
              boxShadow: '0 30px 80px -20px rgba(226,35,26,0.5)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <MMLogo size={20} variant="on-red"/>
                <Icon name="award" size={32}/>
              </div>
              <div style={{ position: 'absolute', bottom: 36, left: 36, right: 36 }}>
                <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.7)' }}>Points balance</div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 80, lineHeight: 1, marginTop: 8 }}>
                  {points.toLocaleString()}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16, fontSize: 12, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>
                  <span>SAM HERNANDEZ</span>
                  <span>MEMBER · 2024</span>
                </div>
              </div>
              {/* deco lines */}
              <svg style={{ position: 'absolute', top: 0, right: -40, opacity: 0.15 }} width="240" height="240" viewBox="0 0 240 240">
                {Array.from({ length: 16 }).map((_, i) => (
                  <circle key={i} cx="120" cy="120" r={i*8+10} fill="none" stroke="#fff" strokeWidth="0.5"/>
                ))}
              </svg>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ------------------------------------------------------------
// HomePage assembly
// ------------------------------------------------------------
function HomePage() {
  return (
    <Page>
      <Hero/>
      <Ticker/>
      <Pillars/>
      <BrandReveal/>
      <BigMarquee/>
      <LocationFinder/>
      <RewardsTeaser/>
    </Page>
  );
}

Object.assign(window, { HomePage });
