// storefront-app.jsx — root app, state, router, mounting

const { useState: uS, useEffect: uE, useRef: uR } = React;
const { useEffect, useRef } = React;

function StoreProvider({ children }) {
  const [route, setRoute] = uS(() => {
    if (typeof window !== 'undefined' && window.history.state && window.history.state.name) {
      return window.history.state;
    }
    return { name: 'home', params: {} };
  });

  // ── Browser history sync: back/forward navigates within the SPA ──
  uE(() => {
    if (!window.history.state || !window.history.state.name) {
      window.history.replaceState({ name: 'home', params: {} }, '');
    }
    const onPop = (e) => {
      const next = (e.state && e.state.name) ? e.state : { name: 'home', params: {} };
      setRoute(next);
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const [cart, setCart] = uS(() => [
    { id:'p01', name:'Hoodie Oversize',    price:1899, color:'Olive', colorHex:'#4F4F32', size:'M', qty:1 },
    { id:'p11', name:'Leggings Mix & Match', price:1299, color:'Negro', colorHex:'#1A1916', size:'M', qty:1 },
    { id:'p10', name:'Sports Bra Mix & Match', price: 999, color:'Azul claro', colorHex:'#BCCDDD', size:'S', qty:1 },
  ]);
  const [cartOpen, setCartOpen] = uS(false);
  const [tryOnOpen, setTryOnOpen] = uS(false);
  const [tryOnProduct, setTryOnProduct] = uS(null);
  const [reservaOpen, setReservaOpen] = uS(false);
  const [reservaProduct, setReservaProduct] = uS(null);
  const [chatOpen, setChatOpen] = uS(false);
  const [loggedIn, setLoggedIn] = uS(false);
  const [nav, setNav] = uS(null);
  const [notifyCountry, setNotifyCountry] = uS(null);
  const [newsletterOpen, setNewsletterOpen] = uS(false);
  const [lastOrderType, setLastOrderType] = uS(null);
  const [lastOrderStudio, setLastOrderStudio] = uS(null);
  const [lastOrderDate, setLastOrderDate] = uS(null);
  const [lastOrderMode, setLastOrderMode] = uS(null);
  const setLastOrder = (o) => {
    setLastOrderType(o.type || null);
    setLastOrderStudio(o.studioId || null);
    setLastOrderDate(o.pickupDate || null);
    setLastOrderMode(o.mode || null);
  };

  const go = (name, params = {}) => {
    const next = { name, params };
    setRoute(next);
    if (typeof window !== 'undefined') {
      window.history.pushState(next, '');
    }
  };
  const addToCart = (item) => {
    setCart(prev => {
      const idx = prev.findIndex(p => p.id === item.id && p.size === item.size && p.color === item.color);
      if (idx >= 0) {
        const next = [...prev]; next[idx] = { ...next[idx], qty: next[idx].qty + (item.qty || 1) }; return next;
      }
      return [...prev, item];
    });
  };
  const qty = (i, delta) => setCart(prev => {
    const next = [...prev]; next[i] = { ...next[i], qty: Math.max(1, next[i].qty + delta) }; return next;
  });
  const removeItem = (i) => setCart(prev => prev.filter((_, j) => j !== i));
  const updateItem = (i, patch) => setCart(prev => {
    const next = [...prev]; next[i] = { ...next[i], ...patch }; return next;
  });
  const clearCart = () => setCart([]);
  const openTryOn = (p) => { setTryOnProduct(p); setTryOnOpen(true); };
  const openReserva = (p) => { setReservaProduct(p); setReservaOpen(true); };

  const value = {
    route, go,
    cart, addToCart, qty, removeItem, updateItem, clearCart,
    cartOpen, setCartOpen,
    tryOnOpen, setTryOnOpen, tryOnProduct, openTryOn,
    reservaOpen, setReservaOpen, reservaProduct, openReserva,
    chatOpen, setChatOpen,
    loggedIn, setLoggedIn,
    nav, setNav,
    notifyCountry, setNotifyCountry,
    newsletterOpen, setNewsletterOpen,
    lastOrderType, lastOrderStudio, lastOrderDate, lastOrderMode, setLastOrder,
  };
  return <StoreCtx.Provider value={value}>{children}</StoreCtx.Provider>;
}

function App({ mobile }) {
  return (
    <StoreProvider>
      <AppInner mobile={mobile} />
    </StoreProvider>
  );
}

function AppInner({ mobile }) {
  const s = useStore();
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [s.route.name, s.route.params && s.route.params.slug]);
  return (
    <div data-app-root style={{
      width:'100%', minHeight:'100%', position:'relative',
      background: '#fff', color: C.fg,
      fontFamily:'Roboto, sans-serif',
      cursor: 'auto',
      display:'flex', flexDirection:'column',
    }} data-desktop-host={!mobile ? '' : undefined}>
      {/* scrollable page area */}
      <div ref={scrollRef} data-app-scroll style={{
        flex:1, minHeight:0, overflowY:'auto', overflowX:'hidden',
        paddingTop: mobile ? 90 : 0,
        paddingBottom: mobile ? 'calc(80px + env(safe-area-inset-bottom, 0px))' : 0,
        display:'flex', flexDirection:'column',
      }}>
        <AnnouncementBar mobile={mobile}/>
        <Header mobile={mobile} />
        <Marquee items={['comunidad','endorfinas','estilo de vida','disciplina','athl. div.','est. 2017','fitfamm']}/>

        <div data-fab-scope style={{ position:'relative' }}>
          <div key={s.route.name + JSON.stringify(s.route.params)} style={{ position:'relative' }}>
            {s.route.name === 'home' && <Landing mobile={mobile} />}
            {s.route.name === 'pdp' && <PDP slug={s.route.params.slug} mobile={mobile} />}
            {s.route.name === 'lookbook' && <Lookbook mobile={mobile} />}
            {s.route.name === 'bolsa' && <Bolsa mobile={mobile} />}
            {s.route.name === 'checkout' && <Checkout mobile={mobile} />}
            {s.route.name === 'confirmacion' && <Confirmacion mobile={mobile} />}
            {s.route.name === 'cuenta' && <Cuenta mobile={mobile} />}
            {s.route.name === 'cuenta-entrar' && <CuentaEntrar mobile={mobile} />}
            {s.route.name === 'estudios' && <Estudios mobile={mobile} />}
          </div>
        </div>

        <Footer mobile={mobile} />
        <FooterCopyright mobile={mobile} />
      </div>
      {mobile && <MobileBottomNav />}

      {/* FAB pinned to viewport — auto-hides when footer comes into view */}
      <ChatFAB mobile={mobile} />

      {/* Overlays — siblings of scroll area so they cover the visible viewport, not the full document */}
      <CartDrawer />
      <MobileMenuDrawer />
      <TryOnModal mobile={mobile} />
      <ReservaModal mobile={mobile} />
      <NotifyCountryModal mobile={mobile} />
      <NewsletterModal mobile={mobile} />

      {!mobile && <CustomCursor />}
    </div>
  );
}

function AnnouncementBar({ mobile }) {
  return (
    <div style={{
      background: C.fg, color:'#fff', textAlign:'center',
      padding:'8px 12px',
      fontFamily:'JetBrains Mono, monospace', fontSize: mobile ? 10 : 11,
      letterSpacing:'0.2em', textTransform:'uppercase',
    }}>
      Envío gratis desde $1,499 MXN · 3 MSI · Drop 03 en pre-launch
    </div>
  );
}

Object.assign(window, { App, AppInner, StoreProvider });

// ── Responsive root: detect viewport width and pass to App ──
function useIsMobile() {
  const [isMobile, setIsMobile] = uS(() =>
    typeof window !== 'undefined' && window.innerWidth < 768
  );
  uE(() => {
    const onResize = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return isMobile;
}

function AppResponsive() {
  const mobile = useIsMobile();
  return <App mobile={mobile} />;
}

Object.assign(window, { AppResponsive, useIsMobile });

// ── Mount (last babel script — guarantees all earlier babel modules ran) ──
const _rootEl = document.getElementById('app-root');
if (_rootEl) ReactDOM.createRoot(_rootEl).render(<AppResponsive />);
