/* global React, ReactDOM, TopBar, Home, PDP, CartDrawer, Menu, Founders, Search, shopifyCheckoutUrl */
const { createElement: m, useState, useRef, useCallback } = React;

const WL_KEY = "anaya_wl";
const readWL = () => {
  try { return JSON.parse(localStorage.getItem(WL_KEY) || "null") || { joined: false, taken: 38 }; }
  catch (e) { return { joined: false, taken: 38 }; }
};

function App() {
  const [view, setView] = useState("home");      // home | pdp
  const [cartQty, setCartQty] = useState(0);
  const [colorIdx, setColorIdx] = useState(0);
  const [lensIdx, setLensIdx] = useState(0);
  const [cartOpen, setCartOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [waitOpen, setWaitOpen] = useState(false);
  const [wl, setWl] = useState(readWL);            // founders-list state (persisted)
  const [prefill, setPrefill] = useState("");
  const [dark, setDark] = useState(true);          // topbar over hero
  const [toast, setToast] = useState("");
  const scrollRef = useRef(null);
  const toastT = useRef(null);

  const flash = (msg) => {
    setToast(msg);
    clearTimeout(toastT.current);
    toastT.current = setTimeout(() => setToast(""), 1900);
  };

  const openWaitlist = (email = "") => {
    setPrefill(typeof email === "string" ? email : "");
    setMenuOpen(false);
    setTimeout(() => setWaitOpen(true), 80);
  };

  const joinWaitlist = ({ first, email }) => {
    const number = (wl.taken || 38) + 1;
    const next = { joined: true, first, email, number, taken: number };
    setWl(next);
    try { localStorage.setItem(WL_KEY, JSON.stringify(next)); } catch (e) {}
    flash("Willkommen auf der Founders List");
  };

  const onScroll = useCallback((ev) => {
    setDark(ev.target.scrollTop < 360);
  }, []);

  const goPDP = () => { setView("pdp"); setMenuOpen(false); setSearchOpen(false); setDark(false); };
  const goHome = () => { setView("home"); setDark(true); };

  const onSearchAction = (action) => {
    setSearchOpen(false);
    if (action === "shop") return goPDP();
    if (action === "founders") return openWaitlist();
    if (action === "service") return flash("Versand kostenlos · IOSS inklusive");
  };

  const addToCart = (q = 1, opts = {}) => {
    if (typeof opts.colorIdx === "number") setColorIdx(opts.colorIdx);
    if (typeof opts.lensIdx === "number") setLensIdx(opts.lensIdx);
    setCartQty((n) => n + q);
    flash("Zum Warenkorb hinzugefügt");
    setTimeout(() => setCartOpen(true), 380);
  };

  const goShopifyCheckout = () => {
    const url = shopifyCheckoutUrl(colorIdx, lensIdx, cartQty);
    if (!url) {
      flash("Shop-Verbindung wird geladen …");
      return;
    }
    setCartOpen(false);
    window.location.href = url;
  };

  return m("div", { className: "stage" + (searchOpen ? " search-active" : "") },
    !searchOpen && m(TopBar, {
      dark: view === "home" && dark,
      count: cartQty,
      onMenu: () => { setMenuOpen(true); },
      onCart: () => setCartOpen(true),
      onLogo: goHome,
      onSearch: () => { setMenuOpen(false); setSearchOpen(true); },
    }),

    m(Search, {
      open: searchOpen,
      onClose: () => setSearchOpen(false),
      onAction: onSearchAction,
    }),

    view === "home"
      ? m(Home, { onShop: goPDP, onFounders: openWaitlist, joined: wl.joined, scrollRef, onScroll })
      : m(PDP, {
        onAdd: addToCart, onBack: goHome, onFounders: openWaitlist,
        colorIdx, lensIdx, onColorIdx: setColorIdx, onLensIdx: setLensIdx,
      }),

    m(CartDrawer, {
      open: cartOpen, qty: cartQty, colorIdx, lensIdx,
      onClose: () => setCartOpen(false),
      onQty: (n) => setCartQty(n),
      onAdd: addToCart,
      onCheckout: goShopifyCheckout,
    }),

    m(Menu, { open: menuOpen, onClose: () => setMenuOpen(false), onShop: goPDP, onFounders: openWaitlist }),

    m(Founders, { open: waitOpen, onClose: () => setWaitOpen(false), state: wl, onJoin: joinWaitlist, prefillEmail: prefill }),

    m("div", { className: "toast" + (toast ? " show" : "") }, toast));
}

ReactDOM.createRoot(document.getElementById("root")).render(m(App));
