// MobileApp.jsx — mobile app shell, replaces desktop App when mobile detected
const mobileRouteToPath = (r) => r === 'home' ? '/' : '/' + r.replace(':', '/');
const mobilePathToRoute = (p) => {
  const clean = p.replace(/^\/+/, '').replace(/\/+$/, '');
  if (clean === '') return 'home';
  // Convert /shop/line-id back to shop:line-id
  if (clean.startsWith('shop/')) return 'shop:' + clean.slice(5);
  // Convert /merch/line-id back to merch:line-id
  if (clean.startsWith('merch/')) return 'merch:' + clean.slice(6);
  return clean;
};

const MobileApp = () => {
  const [route, setRoute] = React.useState(() => mobilePathToRoute(window.location.pathname));
  const [openProduct, setOpenProduct] = React.useState(null);
  const [openMerch, setOpenMerch] = React.useState(null);
  const [merchLine, setMerchLine] = React.useState(null);
  const [cart, setCart] = React.useState(() => {
    try { const s = localStorage.getItem('obc_cart'); return s ? JSON.parse(s) : []; } catch { return []; }
  });
  const [cartOpen, setCartOpen] = React.useState(false);
  const [checkingOut, setCheckingOut] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const [user, setUser] = React.useState(null);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2400);
  };

  React.useEffect(() => { try { localStorage.setItem('obc_cart', JSON.stringify(cart)); } catch {} }, [cart]);

  const [, flagTick] = React.useState(0);
  React.useEffect(() => {
    window.OBC_API.getCurrentUser().then((u) => { if (u) setUser(u); });
    if (window.OBC_CONFIG_READY) window.OBC_CONFIG_READY.then(() => flagTick(n => n + 1));
  }, []);

  // Listen for back/forward
  React.useEffect(() => {
    const onPop = (e) => {
      if (e.state?.accountTab) return;
      const r = e.state?.route || mobilePathToRoute(window.location.pathname);
      setRoute(r);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    };
    window.addEventListener('popstate', onPop);
    history.replaceState({ route }, '', mobileRouteToPath(route));
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // Clear merch line filter when navigating away from merch
  React.useEffect(() => { if (route !== 'merch' && !route.startsWith('merch:')) setMerchLine(null); }, [route]);

  const handleAdd = (p, qty, optionsOrGrind) => {
    const opts = typeof optionsOrGrind === 'string' ? { grind: optionsOrGrind } : (optionsOrGrind || {});
    setCart((c) => {
      const itemKey = (item) => {
        if (item.p.category === 'merch' || item.designId) {
          return item.p.id + '|' + (item.designId || '') + '|' + (item.sizeId || '') + '|' + JSON.stringify(item.customizations || {});
        }
        return item.p.id + '|' + (item.grind || '');
      };
      const newKey = (p.category === 'merch' || opts.designId)
        ? p.id + '|' + (opts.designId || '') + '|' + (opts.sizeId || '') + '|' + JSON.stringify(opts.customizations || {})
        : p.id + '|' + (opts.grind || '');
      const idx = c.findIndex((it) => itemKey(it) === newKey);
      if (idx >= 0) {
        const next = [...c];
        next[idx] = { ...next[idx], qty: next[idx].qty + qty };
        return next;
      }
      return [...c, { p, qty, grind: opts.grind || null, designId: opts.designId || null, sizeId: opts.sizeId || null, variantId: opts.variantId || null, _variantId: opts.variantId || p._variantId || null, customizations: opts.customizations || null }];
    });
    setOpenProduct(null);
    setOpenMerch(null);
    showToast('> staged ' + p.name + ' x ' + qty);
  };

  React.useEffect(() => {
    const onPageShow = (e) => { if (e.persisted) setCheckingOut(false); };
    window.addEventListener('pageshow', onPageShow);
    return () => window.removeEventListener('pageshow', onPageShow);
  }, []);
  const handleCheckout = async () => {
    if (checkingOut || cart.length === 0) return;
    setCheckingOut(true);
    setCartOpen(false);
    showToast('> creating checkout...');
    try {
      var shopifyCart = await window.OBC_API.createCart(cart);
      if (shopifyCart && shopifyCart.checkoutUrl) {
        var checkoutHost = new URL(shopifyCart.checkoutUrl).hostname;
        if (checkoutHost === window.location.hostname) {
          console.error('[checkout] checkoutUrl points to own domain:', checkoutHost);
          showToast('> [ERR] checkout config error. contact support.');
          setCheckingOut(false);
          return;
        }
        window.location.href = shopifyCart.checkoutUrl;
      } else {
        showToast('> [ERR] checkout failed. try again.');
        setCheckingOut(false);
      }
    } catch (e) {
      console.error('[checkout]', e);
      showToast('> [ERR] checkout failed. try again.');
      setCheckingOut(false);
    }
  };

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);

  // navigate must be defined before any handlers that reference it
  const navigate = (r) => {
    setRoute(r);
    history.pushState({ route: r }, '', mobileRouteToPath(r));
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleLogout = () => {
    setUser(null);
    navigate('home');
    showToast('> [ session terminated ] logged out.');
  };

  const handleLogin = (u) => {
    setUser(u);
    navigate('account');
    showToast('> [ access granted ] welcome, ' + u.handle);
  };

  const handleRegister = (u) => {
    setUser(u);
    navigate('account');
    showToast('> [ account provisioned ] welcome, ' + u.handle);
  };

  // Map cart route to the cart drawer instead of a page
  const handleRoute = (r) => {
    if (r === 'cart') {
      setCartOpen(true);
    } else {
      navigate(r);
    }
  };

  const navMerchLine = (lineId) => {
    setMerchLine(lineId);
    handleRoute('merch');
  };

  return (
    <>
      <window.MobileHeader
        route={route}
        onHome={() => navigate('home')}
      />

      <div id="mobile-scene" style={{
        paddingTop: 48,   /* header height */
        paddingBottom: 56, /* tab bar height */
        minHeight: '100vh',
      }}>
        {route === 'home' && (
          <window.MobileHome
            onShop={(lineId) => { if (lineId) { navigate('shop:' + lineId); } else { navigate('shop'); } }}
            onProduct={setOpenProduct}
            onRoute={navigate}
          />
        )}
        {route.startsWith('shop') && (
          <window.MobileShop
            onOpen={setOpenProduct}
            onAdd={handleAdd}
            onBack={() => navigate('home')}
            initialLine={route.includes(':') ? route.split(':')[1] : null}
          />
        )}
        {(route === 'merch' || route.startsWith('merch:')) && window.OBC_FLAGS && window.OBC_FLAGS.merch_enabled && (
          <window.MobileMerchShop
            onOpen={setOpenMerch}
            onAdd={handleAdd}
            initialCategory={merchLine || (route.startsWith('merch:') ? route.split(':')[1] : null)}
            user={user}
          />
        )}
        {route === 'guide' && <window.MobileGuide />}
        {route === 'manifesto' && <window.MobileManifesto />}
        {route === 'origins' && <window.OriginNotes />}
        {route === 'operators' && <window.Operators />}
        {route === 'privacy' && <window.Privacy />}
        {route === 'login' && (
          user
            ? <window.MobileAccount user={user} onUserUpdate={setUser} onLogout={handleLogout} onShop={() => navigate('shop')} />
            : <window.MobileLogin onLoggedIn={handleLogin} onSwitchToRegister={() => navigate('register')} />
        )}
        {route === 'register' && (
          user
            ? <window.MobileAccount user={user} onUserUpdate={setUser} onLogout={handleLogout} onShop={() => navigate('shop')} />
            : <window.MobileRegister onRegistered={handleRegister} onSwitchToLogin={() => navigate('login')} />
        )}
        {route === 'account' && (
          user
            ? <window.MobileAccount user={user} onUserUpdate={setUser} onLogout={handleLogout} onShop={() => navigate('shop')} />
            : <window.MobileLogin onLoggedIn={handleLogin} onSwitchToRegister={() => navigate('register')} />
        )}
        <window.MobileFooter onRoute={navigate} onShopLine={(lineId) => navigate('shop:' + lineId)} onMerchLine={navMerchLine} user={user} />
      </div>

      <window.MobileTabBar
        route={route}
        setRoute={handleRoute}
        cartCount={cartCount}
        user={user}
      />

      {/* Overlays — cart drawer, product detail, checkout, toast */}
      {ReactDOM.createPortal(
        <>
          <window.MobileProductDetail
            p={openProduct}
            onClose={() => setOpenProduct(null)}
            onAdd={handleAdd}
            user={user}
          />
          {openMerch && <window.MobileMerchDetail
            item={openMerch}
            onClose={() => setOpenMerch(null)}
            onAdd={handleAdd}
            user={user}
          />}
          <window.MobileCart
            open={cartOpen}
            items={cart}
            onClose={() => setCartOpen(false)}
            onUpdateQty={(idx, delta) => setCart((c) => {
              const next = [...c];
              next[idx] = { ...next[idx], qty: next[idx].qty + delta };
              if (next[idx].qty <= 0) return next.filter((_, i) => i !== idx);
              return next;
            })}
            onClearAll={() => setCart([])}
            onCheckout={handleCheckout}
            checkingOut={checkingOut}
          />
          {toast && <div className="toast">{toast}</div>}
          <window.CookieBanner onPrivacy={() => navigate('privacy')} />
        </>,
        document.getElementById('overlays')
      )}
    </>
  );
};

window.MobileApp = MobileApp;
