// Main App
const { Icon, CustomCursor, useSmoothScroll } = window.JC;
const { TopBar, Header, MenuDrawer, Hero, BrandMarquee, PackshotMarquee, CategoryMosaic, BestSellers, VideoManifesto, TestimonialCarousel, PillReviews, Story, InstagramGrid, Newsletter, Footer, Loader } = window.JS;
const { CollectionPage, ProductPage, CartDrawer, SearchDrawer } = window.JP;

const App = () => {
  const [loading, setLoading] = React.useState(true);
  const [view, setView] = React.useState("home"); // home | collection | product
  const [collectionData, setCollectionData] = React.useState({ id: "dubai", label: "Parfum Dubaï" });
  const [activeProduct, setActiveProduct] = React.useState(null);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [cartOpen, setCartOpen] = React.useState(false);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [items, setItems] = React.useState([
    { ...window.JENNATI.PRODUCTS[1], qty: 1 },
    { ...window.JENNATI.PRODUCTS[14], qty: 1 },
  ]);
  const [flyAnim, setFlyAnim] = React.useState(null);

  useSmoothScroll();

  const goCollection = (id, label) => {
    const labels = { dubai: "Parfum Dubaï", elnabil: "Parfum El Nabil", privee: "Collection Privée", maison: "Parfum Maison", brumes: "Brumes & capillaire", coffrets: "Coffrets", lattafa: "Parfum Dubaï" };
    setCollectionData({ id: id === "lattafa" ? "dubai" : id, label: label || labels[id] || "Parfums" });
    setView("collection");
    window.scrollTo(0, 0);
  };
  const goProduct = (p) => { setActiveProduct(p); setView("product"); window.scrollTo(0, 0); };
  const goHome = () => { setView("home"); window.scrollTo(0, 0); };

  const onAdd = (p, e) => {
    // flying animation
    if (e && e.currentTarget) {
      const r = e.currentTarget.getBoundingClientRect();
      setFlyAnim({ img: p.img, x: r.left + r.width/2, y: r.top + r.height/2, t: Date.now() });
      setTimeout(() => setFlyAnim(null), 750);
    }
    setItems(prev => {
      const idx = prev.findIndex(x => x.id === p.id);
      if (idx >= 0) {
        const copy = [...prev]; copy[idx] = { ...copy[idx], qty: copy[idx].qty + (p.qty || 1), justAdded: true };
        return copy;
      }
      return [{ ...p, qty: p.qty || 1, justAdded: true }, ...prev];
    });
    setTimeout(() => setItems(prev => prev.map(it => ({ ...it, justAdded: false }))), 1500);
    setTimeout(() => setCartOpen(true), 600);
  };
  const onQty = (idx, d) => setItems(prev => prev.map((it, i) => i === idx ? { ...it, qty: Math.max(1, it.qty + d) } : it));
  const onRemove = (idx) => setItems(prev => prev.filter((_, i) => i !== idx));

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

  return (
    <>
      {loading && <Loader done={() => setLoading(false)} />}
      <CustomCursor />
      <TopBar />
      <Header onOpenMenu={() => setMenuOpen(true)} onOpenCart={() => setCartOpen(true)} cartCount={cartCount} onSearch={() => setSearchOpen(true)} />
      <MenuDrawer open={menuOpen} onClose={() => setMenuOpen(false)} onPick={(catId) => { setMenuOpen(false); goCollection(catId); }} />
      <SearchDrawer open={searchOpen} onClose={() => setSearchOpen(false)} />
      <CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} items={items} onQty={onQty} onRemove={onRemove} />

      <main id="main" key={view} style={{
        animation: "viewIn 600ms cubic-bezier(0.4,0,0.2,1) both"
      }}>
        {view === "home" && (
          <>
            <Hero onCollection={() => goCollection("dubai", "Parfum Dubaï")} onStory={() => {
              document.querySelector("[data-screen-label='Histoire']")?.scrollIntoView({ behavior: "smooth" });
            }} />
            <BrandMarquee />
            <CategoryMosaic onPick={(id) => goCollection(id)} />
            <PillReviews />
            <BestSellers onPick={goProduct} onAdd={onAdd} onAll={() => goCollection("dubai", "Parfum Dubaï")} />
            <PackshotMarquee onPick={goProduct} />
            <VideoManifesto />
            <TestimonialCarousel />
            <Story />
            <InstagramGrid onPick={goProduct} />
            <BrandMarquee reverse bg="#EDE5D3" />
            <Newsletter />
          </>
        )}
        {view === "collection" && (
          <CollectionPage onPick={goProduct} onAdd={onAdd} onHome={goHome} catId={collectionData.id} catLabel={collectionData.label} />
        )}
        {view === "product" && (
          <ProductPage product={activeProduct} onAdd={onAdd} onBack={() => setView("collection")} />
        )}
      </main>
      <Footer />

      {/* Flying add-to-cart */}
      {flyAnim && (
        <div className="pointer-events-none fixed z-[60]" style={{
          left: flyAnim.x, top: flyAnim.y,
          width: 70, height: 70,
          transform: "translate(-50%, -50%)",
          animation: "flyToCart 700ms cubic-bezier(0.5, -0.3, 0.5, 1.3) forwards",
        }}>
          <img src={flyAnim.img} alt="" className="w-full h-full object-contain" />
        </div>
      )}

      <style>{`
        @keyframes viewIn {
          from { opacity: 0; transform: translateY(20px); }
          to { opacity: 1; transform: translateY(0); }
        }
        @keyframes flyToCart {
          0% { opacity: 1; transform: translate(-50%, -50%) scale(1) rotate(0deg); }
          70% { opacity: 0.9; }
          100% {
            opacity: 0;
            transform: translate(calc(${typeof window !== "undefined" ? window.innerWidth - 80 : 1200}px - 50%), calc(60px - 50%)) scale(0.2) rotate(20deg);
          }
        }
      `}</style>
    </>
  );
};

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