// ET Storefront concept — app shell (routing, cart, phone stage)
const { IOSDevice, AppHeader, BottomTab } = window;

const LS = { screen: "et-sf-screen", pid: "et-sf-pid", vibe: "et-sf-vibe", cart: "et-sf-cart" };
const load = (k, d) => { try { const v = localStorage.getItem(k); return v == null ? d : JSON.parse(v); } catch (e) { return d; } };

function useScale(designW, designH, topbar) {
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const fit = () => {
      const availH = window.innerHeight - topbar - 40;
      const availW = window.innerWidth - 40;
      setScale(Math.max(0.4, Math.min(availW / designW, availH / designH, 1)));
    };
    fit();
    window.addEventListener("resize", fit);
    return () => window.removeEventListener("resize", fit);
  }, [designW, designH, topbar]);
  return scale;
}

function App() {
  const [screen, setScreen] = React.useState(() => load(LS.screen, "home"));
  const [pid, setPid] = React.useState(() => load(LS.pid, "meteorite"));
  const [vibe, setVibe] = React.useState(() => load(LS.vibe, "all"));
  const [cart, setCart] = React.useState(() => {
    const raw = load(LS.cart, []);
    return raw.map((it) => ({ product: window.byId(it.id), qty: it.qty })).filter((it) => it.product);
  });
  const scrollerRef = React.useRef(null);

  React.useEffect(() => { localStorage.setItem(LS.screen, JSON.stringify(screen)); }, [screen]);
  React.useEffect(() => { localStorage.setItem(LS.pid, JSON.stringify(pid)); }, [pid]);
  React.useEffect(() => { localStorage.setItem(LS.vibe, JSON.stringify(vibe)); }, [vibe]);
  React.useEffect(() => { localStorage.setItem(LS.cart, JSON.stringify(cart.map((it) => ({ id: it.product.id, qty: it.qty })))); }, [cart]);

  const resetScroll = () => { const el = scrollerRef.current; if (el && el.parentElement) el.parentElement.scrollTop = 0; };

  const nav = (s, arg) => {
    if (s === "pdp" && arg) setPid(arg);
    if (s === "collection") setVibe(arg || "all");
    setScreen(s);
    requestAnimationFrame(resetScroll);
  };

  const addToCart = (product, qty = 1) => {
    setCart((c) => {
      const ex = c.find((it) => it.product.id === product.id);
      if (ex) return c.map((it) => (it.product.id === product.id ? { ...it, qty: it.qty + qty } : it));
      return [...c, { product, qty }];
    });
  };
  const setQty = (id, q) => setCart((c) => c.map((it) => (it.product.id === id ? { ...it, qty: q } : it)));
  const removeItem = (id) => setCart((c) => c.filter((it) => it.product.id !== id));
  const cartCount = cart.reduce((s, it) => s + it.qty, 0);

  const scale = useScale(402, 874, 96);

  let body = null;
  if (screen === "home") body = <window.HomeScreen nav={nav} addToCart={addToCart} />;
  else if (screen === "collection") body = <window.CollectionScreen nav={nav} initialVibe={vibe} />;
  else if (screen === "pdp") body = <window.PdpScreen nav={nav} addToCart={addToCart} productId={pid} />;
  else if (screen === "cart") body = <window.CartScreen nav={nav} cart={cart} setQty={setQty} removeItem={removeItem} />;

  const showTab = screen === "home" || screen === "collection";

  const tabs = [
    { id: "home", th: "หน้าแรก", en: "Home" },
    { id: "collection", th: "ตู้ทั้งหมด", en: "Shop" },
    { id: "pdp", th: "สินค้า", en: "Product" },
    { id: "cart", th: "ตะกร้า", en: "Cart" },
  ];

  return (
    <div className="et-stage">
      <div className="et-topbar">
        <div className="et-topbar__brand">
          <div className="et-topbar__title">ET · Storefront concept</div>
          <div className="et-topbar__sub">Round 002 · et.co.th — Shopify OS 2.0 theme · mobile-first</div>
        </div>
        <div className="et-screensel">
          {tabs.map((t) => (
            <button key={t.id} className={"et-screenpill" + (screen === t.id ? " is-on" : "")} onClick={() => nav(t.id, t.id === "pdp" ? pid : undefined)}>
              <span className="th">{t.th}</span>
              <span className="en">{t.en}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="et-stagebody">
        <div style={{ width: 402 * scale, height: 874 * scale }}>
          <div style={{ transform: `scale(${scale})`, transformOrigin: "top left", width: 402, height: 874 }}>
            <IOSDevice>
              <div ref={scrollerRef} className="et-page" style={{ minHeight: "100%", background: "var(--surface-page)" }}>
                {screen !== "pdp" ? <AppHeader nav={nav} cartCount={cartCount} onMenu={() => {}} /> : (
                  <div style={{ position: "sticky", top: 0, zIndex: 30, background: "var(--surface-page)", paddingTop: 48 }} />
                )}
                {body}
                {showTab ? <BottomTab active={screen} nav={nav} cartCount={cartCount} /> : null}
              </div>
            </IOSDevice>
          </div>
        </div>
      </div>
    </div>
  );
}

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