// Browser history integration — push a new entry on every nav so the
// browser back button restores the previous route + scroll position.
function __ppPushNav(next) {
  try {
    const cur = window.history.state || {};
    window.history.replaceState({ ...cur, scroll: window.scrollY }, "");
    window.history.pushState({ __pp: true, ...next, scroll: 0 }, "");
  } catch (e) { /* noop */ }
}
window.__ppPushNav = __ppPushNav;

function App() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "lang": "en",
    "pinkAccent": "#C2546A",
    "pinkBlush": "#F6D9D4",
    "pinkBar": "#F2C9C2",
    "displayFont": "Cormorant Garamond",
    "cnDisplayFont": "Long Cang"
  }/*EDITMODE-END*/;
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);
  const setTweak = (k, v) => setTweaks(prev => ({ ...prev, [k]: v }));
  const [route, setRoute] = React.useState("home");
  const [activeId, setActiveId] = React.useState(null);
  const [activeCollection, setActiveCollection] = React.useState(null); // collection slug
  const [cart, setCart] = React.useState([]);
  const [cartOpen, setCartOpen] = React.useState(false);

  // Apply tweaks → CSS vars
  React.useEffect(()=>{
    const r = document.documentElement.style;
    r.setProperty("--pp-pink-deep", tweaks.pinkAccent);
    r.setProperty("--pp-blush", tweaks.pinkBlush);
    r.setProperty("--pp-blush-bar", tweaks.pinkBar);
    r.setProperty("--font-display", `"${tweaks.displayFont}", Georgia, serif`);
    r.setProperty("--font-cn-display", `"${tweaks.cnDisplayFont}", "Songti SC", serif`);
  }, [tweaks]);

  const lang = tweaks.lang;
  const setLang = (v) => setTweak("lang", v);
  const t = useT(lang);

  const cartCount = cart.reduce((s,it)=>s+it.qty,0);
  const product = activeId ? PRODUCTS.find(p=>p.id===activeId) : null;
  const isMobile = useIsMobile(768);

  const prevRouteRef = React.useRef("home");
  const prevScrollRef = React.useRef(0);

  // History integration: handle browser back/forward + initial entry.
  React.useEffect(()=>{
    if ("scrollRestoration" in window.history) {
      window.history.scrollRestoration = "manual";
    }
    if (!window.history.state || !window.history.state.__pp) {
      window.history.replaceState({ __pp:true, route, activeId, activeCollection, scroll:0 }, "");
    }
    const onPop = (e) => {
      const s = e.state;
      if (!s || !s.__pp) return;
      setRoute(s.route || "home");
      setActiveId(s.activeId ?? null);
      setActiveCollection(s.activeCollection ?? null);
      requestAnimationFrame(()=>window.scrollTo({top: s.scroll || 0}));
    };
    window.addEventListener("popstate", onPop);
    return ()=>window.removeEventListener("popstate", onPop);
  }, []);

  function pick(pid){
    if (route !== "product") {
      prevRouteRef.current = route;
      prevScrollRef.current = window.scrollY;
    }
    __ppPushNav({ route:"product", activeId:pid, activeCollection });
    setActiveId(pid);
    setRoute("product");
    window.scrollTo({top:0,behavior:"smooth"});
  }
  function pickCollection(slug){
    __ppPushNav({ route:"collection", activeId:null, activeCollection:slug });
    setActiveCollection(slug);
    setActiveId(null);
    setRoute("collection");
    window.scrollTo({top:0,behavior:"smooth"});
  }
  function back(){
    // Delegate to the browser so the URL/history stack stays in sync with UI state.
    if (window.history.length > 1) {
      window.history.back();
    } else {
      setRoute(prevRouteRef.current || "home");
      setActiveId(null);
      requestAnimationFrame(()=>window.scrollTo({top: prevScrollRef.current || 0}));
    }
  }
  function addToCart(p, opts){
    setCart(prev=>{
      const idx = prev.findIndex(it => it.product.id===p.id && it.size.id===opts.size.id && it.variant===opts.variant);
      if (idx>=0){ const n=[...prev]; n[idx]={...n[idx], qty:n[idx].qty+opts.qty}; return n; }
      return [...prev, { product:p, ...opts }];
    });
    setCartOpen(true);
  }

  if (isMobile) {
    return (
      <>
        <MobileApp
          lang={lang} setLang={setLang} t={t}
          route={route} setRoute={setRoute}
          activeId={activeId} setActiveId={setActiveId}
          activeCollection={activeCollection} setActiveCollection={setActiveCollection}
          cart={cart} addToCart={addToCart}
          cartOpen={cartOpen} setCartOpen={setCartOpen}
        />
        <CartDrawer open={cartOpen} items={cart} lang={lang} t={t}
          onClose={()=>setCartOpen(false)}
          onChangeQty={(i,q)=>setCart(prev=>prev.map((it,j)=>j===i?{...it,qty:q}:it))}
          onRemove={(i)=>setCart(prev=>prev.filter((_,j)=>j!==i))}
        />
      </>
    );
  }

  return (
    <>
      <Header lang={lang} setLang={setLang} route={route} onNav={(r)=>{ __ppPushNav({ route:r, activeId:null, activeCollection }); setRoute(r); setActiveId(null); window.scrollTo({top:0}); }} onPickCollection={pickCollection} cartCount={cartCount} onOpenCart={()=>setCartOpen(true)} />

      {route==="home" && (
        <>
          <Hero t={t} lang={lang} tweaks={tweaks} onShop={()=>document.getElementById("grid")?.scrollIntoView({behavior:"smooth"})}/>
          <FeatureStrip t={t} lang={lang}/>
          <CollectionsGrid t={t} lang={lang} onPickCollection={pickCollection}/>
          <div id="grid"><ShopGrid t={t} lang={lang} products={PRODUCTS} onPick={pick}/></div>
          <AboutBlock t={t} lang={lang}/>
        </>
      )}

      {route==="shop" && (
        <div style={{padding:"56px 32px"}}><div style={{maxWidth:1280,margin:"0 auto"}}>
          <h1 style={{fontFamily: lang==="zh"?"var(--font-cn-display)":"var(--font-display)", fontWeight:500, fontSize:56, marginBottom:32}}>{lang==="zh"?"全部花束":"All Bouquets"}</h1>
          <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:20}}>
            {PRODUCTS.map(p=> <ProductCard key={p.id} p={p} lang={lang} onPick={pick}/>)}
          </div>
        </div></div>
      )}

      {route==="collections" && (
        <CollectionsIndexPage t={t} lang={lang} onPickCollection={pickCollection}/>
      )}

      {route==="collection" && activeCollection && (
        <CollectionPage t={t} lang={lang} slug={activeCollection} onPick={pick}/>
      )}

      {route==="product" && product && (
        <ProductDetail p={product} t={t} lang={lang} onAdd={addToCart} onBack={back} onPick={pick} allProducts={PRODUCTS} />
      )}

      <Footer t={t} lang={lang}/>

      <CartDrawer open={cartOpen} items={cart} lang={lang} t={t}
        onClose={()=>setCartOpen(false)}
        onChangeQty={(i,q)=>setCart(prev=>prev.map((it,j)=>j===i?{...it,qty:q}:it))}
        onRemove={(i)=>setCart(prev=>prev.filter((_,j)=>j!==i))}
      />

    </>
  );
}
window.App = App;
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
