// app.jsx — root: state, theme wash, tweaks, mount
const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "poster",
  "washIntensity": "bold"
}/*EDITMODE-END*/;

function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 64;
  window.scrollTo({ top, behavior: 'smooth' });
}

// Center the shop's content in the viewport when it fits; otherwise sit it just
// under the header so the top is never clipped.
function scrollToShop() {
  const el = document.getElementById('shop');
  if (!el) return;
  const inner = el.querySelector('.shop-inner') || el;
  const rect = inner.getBoundingClientRect();
  const absTop = rect.top + window.scrollY;
  const headerH = 68;
  const avail = window.innerHeight - headerH;
  const h = rect.height;
  // center within the area below the fixed header when it fits; else pin under header
  const top = h <= avail ? absTop - headerH - (avail - h) / 2 : absTop - headerH - 12;
  window.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [colorId, setColorId] = useStateApp('olive');
  const [qty, setQty] = useStateApp(1);
  const [cart, setCart] = useStateApp([]);
  const [drawerOpen, setDrawerOpen] = useStateApp(false);
  const [checkoutOpen, setCheckoutOpen] = useStateApp(false);
  const [justAdded, setJustAdded] = useStateApp(false);
  const [scrolled, setScrolled] = useStateApp(false);

  const cw = useMemoApp(() => COLORWAYS.find((c) => c.id === colorId), [colorId]);

  // Apply the wash theme to the whole document whenever color / intensity changes.
  useEffectApp(() => {
    const th = cw.theme;
    const pct = t.washIntensity === 'bold' ? 100 : 42;
    const root = document.documentElement;
    const set = (k, v) => root.style.setProperty(k, v);
    set('--wash', `color-mix(in srgb, ${th.wash} ${pct}%, #ffffff)`);
    set('--paper', th.panel);
    set('--hat', th.hat);
    set('--hat-deep', th.hatDeep);
    set('--accent', th.accent);
    set('--on-hat', th.onHat);
    set('--glow', th.glow);
    set('--swatch', cw.swatch);
  }, [cw, t.washIntensity]);

  useEffectApp(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const frontImg = `${cw.dir}/${cw.files.front}`;

  const selectColor = (id) => {
    setColorId(id);
    // gentle nudge to shop if user is up in the hero
    if (window.scrollY < 200) requestAnimationFrame(scrollToShop);
  };

  const addToCart = (buyNow) => {
    setCart((prev) => {
      const ex = prev.find((it) => it.colorId === colorId);
      if (ex) return prev.map((it) => it.colorId === colorId ? { ...it, qty: Math.min(10, it.qty + qty) } : it);
      return [...prev, { colorId, name: PRODUCT.name, price: PRODUCT.price, qty, img: frontImg }];
    });
    if (buyNow) { setCheckoutOpen(true); }
    else {
      setJustAdded(true);
      setTimeout(() => setJustAdded(false), 1400);
      setDrawerOpen(true);
    }
  };

  const setItemQty = (id, q) => setCart((p) => p.map((it) => it.colorId === id ? { ...it, qty: q } : it));
  const removeItem = (id) => setCart((p) => p.filter((it) => it.colorId !== id));
  const cartCount = cart.reduce((s, it) => s + it.qty, 0);

  const startCheckout = () => {
    if (cart.length === 0) return;
    setDrawerOpen(false);
    setCheckoutOpen(true);
  };

  const finishOrder = () => {
    setCheckoutOpen(false);
    setCart([]);
    scrollToId('top');
  };

  return (
    <div className="app">
      <Header
        cw={cw}
        cartCount={cartCount}
        scrolled={scrolled}
        onShop={scrollToShop}
        onStory={() => scrollToId('story')}
        onHome={() => scrollToId('top')}
        onCart={() => setDrawerOpen(true)}
      />

      <Hero cw={cw} variant={t.heroVariant} onShop={scrollToShop} />

      <Shop
        cw={cw}
        colorways={COLORWAYS}
        onSelectColor={selectColor}
        qty={qty}
        setQty={setQty}
        onAdd={() => addToCart(false)}
        onBuy={() => addToCart(true)}
        justAdded={justAdded}
      />

      <Story cw={cw} />
      <Footer cw={cw} />

      <CartDrawer
        open={drawerOpen}
        items={cart}
        colorways={COLORWAYS}
        onClose={() => setDrawerOpen(false)}
        onQty={setItemQty}
        onRemove={removeItem}
        onCheckout={startCheckout}
      />

      <Checkout
        open={checkoutOpen}
        items={cart}
        colorways={COLORWAYS}
        onClose={() => setCheckoutOpen(false)}
        onDone={finishOrder}
      />

      <TweaksPanel>
        <TweakSection label="Homepage direction" />
        <TweakRadio
          label="Hero"
          value={t.heroVariant}
          options={['poster', 'split', 'marquee']}
          onChange={(v) => setTweak('heroVariant', v)}
        />
        <TweakSection label="Color wash" />
        <TweakRadio
          label="Intensity"
          value={t.washIntensity}
          options={['subtle', 'bold']}
          onChange={(v) => setTweak('washIntensity', v)}
        />
      </TweaksPanel>
    </div>
  );
}

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