/* store-app.jsx — top-level state (cart, wishlist, quick view), cart drawer,
   cursor glow, and page assembly. */
const { Button: ABtn } = window.FluvexDesignsDesignSystem_072666;
const { CursorGlow: ACursorGlow, StoreIcon: AIcon } = window;
const {
  Hero, TrustBar, Marquee, BestSellers, Shop, Categories, Bundle, Gallery,
  Why, HowItWorks, Reviews, FAQ, FinalCTA, Footer, QuickView,
} = window;

/* ---- Cart drawer ---- */
function CartDrawer({ open, items, onClose, onQty, onRemove }) {
  React.useEffect(() => {
    if (open) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);
  const total = items.reduce((s, it) => s + it.product.price * it.qty, 0);
  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 190, background: "rgba(13,37,61,0.4)", backdropFilter: "blur(4px)", opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity 300ms ease" }} />
      <aside style={{ position: "fixed", top: 0, right: 0, bottom: 0, width: "min(400px, 92vw)", zIndex: 191, background: "#fff", boxShadow: "-20px 0 60px rgba(28,30,84,0.18)", transform: open ? "translateX(0)" : "translateX(102%)", transition: "transform 380ms cubic-bezier(.21,.68,.24,1)", display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "22px 24px", borderBottom: "1px solid var(--hairline)" }}>
          <span style={{ fontSize: "var(--heading-md-size)", fontWeight: 400, color: "var(--ink)", letterSpacing: "-0.3px" }}>Your cart</span>
          <button onClick={onClose} aria-label="Close" style={{ width: 34, height: 34, borderRadius: 9999, border: "1px solid var(--hairline)", background: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--ink)" strokeWidth="1.7" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
          </button>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "8px 24px" }}>
          {items.length === 0 && (
            <div style={{ textAlign: "center", color: "var(--ink-mute)", padding: "60px 0" }}>
              <div style={{ marginBottom: 12, display: "flex", justifyContent: "center" }}><AIcon name="cart" size={40} stroke="var(--hairline-input)" sw={1.4} /></div>
              Your cart is empty.
            </div>
          )}
          {items.map((it) => {
            const Mock = window.MOCKS[it.product.mock];
            return (
              <div key={it.product.id} style={{ display: "flex", gap: 14, padding: "16px 0", borderBottom: "1px solid var(--hairline)" }}>
                {/* Cart thumbnail — renders the SAME product mock component used on the
                    home-screen product card, but scaled down. Mocks are authored at
                    ~240px; here we render at native size and CSS-scale to fit the 72px
                    thumbnail so text and layout stay legible instead of getting cropped. */}
                <div style={{ width: 72, height: 72, borderRadius: 10, overflow: "hidden", flexShrink: 0, position: "relative", background: "linear-gradient(155deg,#f7f5ff,#efe9ff)", border: "1px solid var(--hairline)" }}>
                  {Mock ? (
                    <div style={{ position: "absolute", top: 0, left: 0, width: 240, height: 240, transform: "scale(0.3)", transformOrigin: "top left" }}>
                      <Mock />
                    </div>
                  ) : null}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: "var(--body-md-size)", fontWeight: 400, color: "var(--ink)", marginBottom: 2 }}>{it.product.title}</div>
                  <div className="tnum" style={{ fontSize: "var(--caption-size)", color: "var(--ink-mute)", marginBottom: 8 }}>${it.product.price}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--hairline)", borderRadius: 9999 }}>
                      <button onClick={() => onQty(it.product.id, -1)} style={{ width: 26, height: 26, border: "none", background: "none", cursor: "pointer", color: "var(--ink)", fontSize: 16 }}>−</button>
                      <span className="tnum" style={{ width: 22, textAlign: "center", fontSize: 13 }}>{it.qty}</span>
                      <button onClick={() => onQty(it.product.id, 1)} style={{ width: 26, height: 26, border: "none", background: "none", cursor: "pointer", color: "var(--ink)", fontSize: 15 }}>+</button>
                    </div>
                    <button onClick={() => onRemove(it.product.id)} style={{ border: "none", background: "none", cursor: "pointer", fontSize: "var(--caption-size)", color: "var(--ink-mute)", textDecoration: "underline" }}>Remove</button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ padding: 24, borderTop: "1px solid var(--hairline)" }}>
          <div className="tnum" style={{ display: "flex", justifyContent: "space-between", marginBottom: 16, fontSize: "var(--body-lg-size)", color: "var(--ink)" }}>
            <span>Subtotal</span><span style={{ fontWeight: 400 }}>${total.toFixed(2)}</span>
          </div>
          {/* Cart checkout.
              Stripe Payment Links = one URL per SKU. There is no built-in
              multi-item cart. So:
                • 1 item  → open that item's Stripe link in a new tab
                • N items → open each item's Stripe link in a sequence of new tabs
                            (customer completes each one). Every link is a real
                            https://buy.stripe.com/... URL and opens ONLY in a
                            new tab so it never gets iframed.
              ⚑ For a true single-basket checkout, swap to Stripe Checkout
                Session (backend) or a hosted cart like Snipcart/Foxy/Shopify. */}
          <button
            className="fx-shine fx-btn-lift"
            disabled={items.length === 0}
            onClick={() => {
              if (!items.length) return;
              const missing = items.filter((it) => !it.product.checkoutLink || it.product.checkoutLink.startsWith("#"));
              if (missing.length) {
                window.alert("Checkout link not connected yet for: " + missing.map((m) => m.product.title).join(", "));
                return;
              }
              items.forEach((it, i) => {
                setTimeout(() => window.open(it.product.checkoutLink, "_blank", "noopener,noreferrer"), i * 250);
              });
            }}
            style={{ width: "100%", fontSize: 16, padding: "13px 20px", borderRadius: 9999, border: "none", background: items.length ? "var(--primary)" : "var(--hairline-input)", color: "#fff", cursor: items.length ? "pointer" : "not-allowed", fontFamily: "var(--font-sans)" }}
          >
            {items.length > 1 ? `Checkout (${items.length} items) →` : "Checkout →"}
          </button>
          {items.length > 1 ? (
            <div style={{ textAlign: "center", fontSize: "var(--caption-size)", color: "var(--ink-mute)", marginTop: 10 }}>Each product uses its own secure Stripe checkout — a new tab will open per item.</div>
          ) : null}
          <div style={{ textAlign: "center", fontSize: "var(--caption-size)", color: "var(--ink-mute)", marginTop: 12 }}>Instant download after purchase</div>
        </div>
      </aside>
    </>
  );
}

/* ---- Toast ---- */
function Toast({ msg }) {
  return (
    <div style={{ position: "fixed", bottom: 24, left: "50%", transform: `translateX(-50%) translateY(${msg ? "0" : "20px"})`, opacity: msg ? 1 : 0, pointerEvents: "none", zIndex: 210, background: "var(--brand-dark-900)", color: "#fff", padding: "12px 22px", borderRadius: 9999, fontSize: "var(--body-md-size)", boxShadow: "0 12px 30px rgba(28,30,84,0.3)", transition: "opacity 260ms ease, transform 260ms cubic-bezier(.21,.68,.24,1)", display: "flex", alignItems: "center", gap: 10 }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#7ee0b0" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
      {msg}
    </div>
  );
}

function App() {
  const [cart, setCart] = React.useState([]);
  const [wishes, setWishes] = React.useState(new Set());
  const [quick, setQuick] = React.useState(null);
  const [cartOpen, setCartOpen] = React.useState(false);
  const [toast, setToast] = React.useState("");
  const toastTimer = React.useRef(null);

  const showToast = (m) => {
    setToast(m);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(""), 1800);
  };
  const addToCart = (p) => {
    setCart((c) => {
      const found = c.find((it) => it.product.id === p.id);
      if (found) return c.map((it) => it.product.id === p.id ? { ...it, qty: it.qty + 1 } : it);
      return [...c, { product: p, qty: 1 }];
    });
    showToast(`Added “${p.title}” to cart`);
  };
  const changeQty = (id, d) => setCart((c) => c.map((it) => it.product.id === id ? { ...it, qty: Math.max(1, it.qty + d) } : it));
  const removeItem = (id) => setCart((c) => c.filter((it) => it.product.id !== id));
  const toggleWish = (id) => setWishes((w) => { const n = new Set(w); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const cartCount = cart.reduce((s, it) => s + it.qty, 0);
  const openCart = () => setCartOpen(true);
  const pickFilter = () => {}; // filter handled inside Shop; anchor scroll is enough

  return (
    <div style={{ background: "var(--canvas)", overflowX: "hidden" }}>
      <ACursorGlow />
      <Hero cartCount={cartCount} onOpenCart={openCart} />
      <TrustBar />
      <BestSellers onQuick={setQuick} onAdd={addToCart} wishes={wishes} onWish={toggleWish} />
      <Shop onQuick={setQuick} onAdd={addToCart} wishes={wishes} onWish={toggleWish} />
      <Categories onPick={pickFilter} />
      <Bundle onAdd={addToCart} />
      <Gallery onQuick={setQuick} />
      <Marquee />
      <Why />
      <HowItWorks />
      <Reviews />
      <FAQ />
      <FinalCTA />
      <Footer />
      {quick && <QuickView product={quick} onClose={() => setQuick(null)} onAdd={addToCart} />}
      <CartDrawer open={cartOpen} items={cart} onClose={() => setCartOpen(false)} onQty={changeQty} onRemove={removeItem} />
      <Toast msg={toast} />
    </div>
  );
}

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