// ─────────── East Wind Social Club — app shell ───────────

function Toast({ toast }) {
  if (!toast) return null;
  return (
    <div className="ew-toast" key={toast.t}>
      <div className="ew-toast__media" style={{ background: toast.cardBg }}><ProductVisual product={toast} /></div>
      <div className="ew-toast__copy">
        <span className="ew-toast__msg">Added to your hand</span>
        <strong>{toast.name}</strong>
        <span className="ew-toast__sub">Size {toast.size}</span>
      </div>
      <span className="ew-toast__check">✓</span>
    </div>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#B8323A",
  "paper": "#F6F0DC",
  "announce": true,
  "cardLift": true,
  "heroEyebrow": "Spring Drop 01 · Est. MMXXVI",
  "heroLede": "A label for everyone who plays — elevated tees and crews carrying the 東 wind, the tiles, and the table you can't wait to get back to."
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useState({ name: "home" });
  const [catalog, setCatalog] = useState(PRODUCTS);
  const [catalogError, setCatalogError] = useState("");
  const [cart, setCart] = useState({ id: null, items: [], totalQuantity: 0, subtotal: 0, currencyCode: "USD" });
  const [cartOpen, setCartOpen] = useState(false);
  const [cartBusy, setCartBusy] = useState(false);
  const [cartError, setCartError] = useState("");
  const [scrolled, setScrolled] = useState(false);
  const [toast, setToast] = useState(null);
  const toastTimer = useRef(null);
  const mainRef = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--signal", t.accent);
    r.setProperty("--signal-deep", t.accent);
    r.setProperty("--paper", t.paper);
  }, [t.accent, t.paper]);

  useEffect(() => {
    let active = true;

    ShopifyStore.getProducts()
      .then(products => {
        if (!active) return;
        if (!products.length) throw new Error("No products are published to the Headless sales channel.");
        setCatalog(products);
        setCatalogError("");
      })
      .catch(error => {
        if (active) setCatalogError(error.message || "Shopify products could not be loaded.");
      });

    const storedCartId = ShopifyStore.getStoredCartId();
    if (storedCartId) {
      ShopifyStore.getCart(storedCartId)
        .then(restoredCart => {
          if (!active) return;
          if (restoredCart) setCart(restoredCart);
          else ShopifyStore.storeCartId(null);
        })
        .catch(() => ShopifyStore.storeCartId(null));
    }

    return () => { active = false; };
  }, []);

  const nav = (r) => {
    setRoute(r);
    setCartOpen(false);
    window.scrollTo({ top: 0, behavior: "auto" });
  };
  const openProduct = (product) => nav({ name: "product", productId: product.id });

  const addToCart = async (product, size, qty = 1, color = product.colors?.[0] || product.colorway) => {
    if (cartBusy) return;
    const variant = ShopifyStore.findVariant(product, size, color);
    if (!variant) {
      setCartError("That color and size combination is not available.");
      setCartOpen(true);
      return;
    }
    if (!variant.availableForSale) {
      setCartError("That variant is currently sold out.");
      setCartOpen(true);
      return;
    }

    setCartBusy(true);
    setCartError("");
    try {
      const nextCart = cart.id
        ? await ShopifyStore.addLine(cart.id, variant.id, qty)
        : await ShopifyStore.createCart(variant.id, qty);
      ShopifyStore.storeCartId(nextCart.id);
      setCart(nextCart);
      setToast({ ...product, size, colorway: color, image: variant.image || product.image, t: Date.now() });
      clearTimeout(toastTimer.current);
      toastTimer.current = setTimeout(() => setToast(null), 2600);
      setCartOpen(true);
    } catch (error) {
      setCartError(error.message || "We couldn't add that item. Please try again.");
      setCartOpen(true);
    } finally {
      setCartBusy(false);
    }
  };
  const quickAdd = (product) => {
    const size = product.sizes?.find(value => value.toLowerCase() === "m") || product.sizes?.[0] || "One Size";
    addToCart(product, size, 1, product.colors?.[0] || product.colorway);
  };

  const changeQty = async (key, delta) => {
    if (cartBusy || !cart.id) return;
    const item = cart.items.find(line => line.key === key);
    if (!item) return;
    const quantity = item.qty + delta;
    setCartBusy(true);
    setCartError("");
    try {
      const nextCart = quantity <= 0
        ? await ShopifyStore.removeLine(cart.id, item.lineId)
        : await ShopifyStore.updateLine(cart.id, item.lineId, quantity);
      setCart(nextCart);
    } catch (error) {
      setCartError(error.message || "We couldn't update your cart.");
    } finally {
      setCartBusy(false);
    }
  };

  const removeItem = async (key) => {
    if (cartBusy || !cart.id) return;
    const item = cart.items.find(line => line.key === key);
    if (!item) return;
    setCartBusy(true);
    setCartError("");
    try {
      setCart(await ShopifyStore.removeLine(cart.id, item.lineId));
    } catch (error) {
      setCartError(error.message || "We couldn't remove that item.");
    } finally {
      setCartBusy(false);
    }
  };

  const checkout = async () => {
    if (cartBusy || !cart.id) return;
    setCartBusy(true);
    setCartError("");
    try {
      const checkoutUrl = await ShopifyStore.getCheckoutUrl(cart.id);
      window.location.assign(checkoutUrl);
    } catch (error) {
      setCartError(error.message || "Checkout is temporarily unavailable.");
      setCartBusy(false);
    }
  };

  const catalogById = Object.fromEntries(catalog.map(product => [product.id, product]));
  const cartItems = cart.items.map(item => ({ ...(catalogById[item.handle] || {}), ...item }));
  const cartCount = cart.totalQuantity || cartItems.reduce((sum, item) => sum + item.qty, 0);

  let page;
  if (route.name === "home") page = <HomePage products={catalog} onNav={nav} onOpen={openProduct} onQuickAdd={quickAdd} eyebrow={t.heroEyebrow} lede={t.heroLede} />;
  else if (route.name === "shop") page = <ShopPage products={catalog} catalogError={catalogError} onOpen={openProduct} onQuickAdd={quickAdd} />;
  else if (route.name === "the-line") page = <TheLinePage products={catalog} onOpen={openProduct} onQuickAdd={quickAdd} onNav={nav} />;
  else if (route.name === "cities") page = <CitiesPage products={catalog} onNav={nav} focus={route.focus} />;
  else if (route.name === "contact") page = <ContactPage onNav={nav} />;
  else if (route.name === "product" && catalogById[route.productId]) page = <ProductPage product={catalogById[route.productId]} products={catalog} cartBusy={cartBusy} onAdd={addToCart} onOpen={openProduct} onNav={nav} />;
  else if (route.name === "story") page = <StoryPage onNav={nav} />;
  else if (route.name === "club") page = <ClubPage onNav={nav} />;
  else page = <HomePage products={catalog} onNav={nav} onOpen={openProduct} onQuickAdd={quickAdd} eyebrow={t.heroEyebrow} lede={t.heroLede} />;

  return (
    <div className={"ew-app" + (t.cardLift ? "" : " no-hover")}>
      {t.announce && <AnnouncementBar />}
      <Header route={route} onNav={nav} cartCount={cartCount} onCart={() => setCartOpen(true)} scrolled={scrolled} />
      <main ref={mainRef} className="ew-main">{page}</main>
      <Footer onNav={nav} />
      <CartDrawer open={cartOpen} items={cartItems} subtotal={cart.subtotal} currencyCode={cart.currencyCode} busy={cartBusy} error={cartError}
        onClose={() => setCartOpen(false)} onQty={changeQty} onRemove={removeItem} onCheckout={checkout} onNav={nav} />
      <Toast toast={toast} />

      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={t.accent}
          options={["#B8323A", "#9C5566", "#5F7155", "#0F2A44"]}
          onChange={v => setTweak("accent", v)} />
        <TweakColor label="Paper" value={t.paper}
          options={["#F6F0DC", "#F2EAD3", "#FBF8F0", "#EDE6D2"]}
          onChange={v => setTweak("paper", v)} />
        <TweakSection label="Layout" />
        <TweakToggle label="Announcement bar" value={t.announce} onChange={v => setTweak("announce", v)} />
        <TweakToggle label="Card hover lift" value={t.cardLift} onChange={v => setTweak("cardLift", v)} />
        <TweakSection label="Copy" />
        <TweakText label="Hero eyebrow" value={t.heroEyebrow} onChange={v => setTweak("heroEyebrow", v)} />
        <TweakText label="Hero subhead" value={t.heroLede} onChange={v => setTweak("heroLede", v)} />
      </TweaksPanel>
    </div>
  );
}

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