// Root app — composes everything, manages routing/state, wires up Tweaks

const { useState: useStateA, useEffect: useEffectA } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "cream",
  "gridLayout": "dense",
  "showNowPlaying": false,
  "showGrain": true,
  "accent": "#7a4a2b",
  "heroStyle": "minimal"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route,  setRoute]  = useStateA({ name: 'home' });
  const [cart,   setCart]   = useStateA([]);
  const [wish,   setWish]   = useStateA(new Set());
  const [recent, setRecent] = useStateA([]);
  const [drawer, setDrawer] = useStateA(null);
  const [filter, setFilter] = useStateA('all');
  const [sort,   setSort]   = useStateA('featured');
  const [products, setProducts] = useStateA([]);
  const [loading,  setLoading]  = useStateA(true);

  useCursor();

  // Fetch products from Fourthwall on mount
  useEffectA(() => {
    fetchFourthwallProducts()
      .then(ps => {
        setProducts(ps);
        window.PRODUCTS = ps; // keep global in sync for drawer search
      })
      .catch(err => console.error('Failed to load products:', err))
      .finally(() => setLoading(false));
  }, []);

  // Apply theme
  useEffectA(() => {
    document.documentElement.dataset.theme = t.theme;
    document.documentElement.dataset.grid  = t.gridLayout;
    document.documentElement.style.setProperty('--accent', t.accent);
  }, [t.theme, t.gridLayout, t.accent]);

  // Hide grain overlay
  useEffectA(() => {
    const g = document.querySelector('.grain');
    if (g) g.style.display = t.showGrain ? 'block' : 'none';
  }, [t.showGrain]);

  // Scroll to top on route change
  useEffectA(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [route]);

  // History: push URL on forward nav, listen for browser back/forward
  const navigate = (newRoute, url) => {
    history.pushState(newRoute, '', url);
    setRoute(newRoute);
  };

  useEffectA(() => {
    // Stamp the initial URL with state so browser back has something to return to
    const path = window.location.pathname;
    const pdpMatch = path.match(/^\/product\/(.+)$/);
    const colMatch = path.match(/^\/collection\/(.+)$/);
    if (pdpMatch)      { history.replaceState({ name: 'pdp',        id: pdpMatch[1] }, '', path); setRoute({ name: 'pdp',        id: pdpMatch[1] }); }
    else if (colMatch) { history.replaceState({ name: 'collection', id: colMatch[1] }, '', path); setRoute({ name: 'collection', id: colMatch[1] }); }
    else               { history.replaceState({ name: 'home' }, '', '/'); }

    const onPop = (e) => setRoute(e.state || { name: 'home' });
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const openProduct = (p) => {
    setRecent(prev => [p.id, ...prev.filter(id => id !== p.id)].slice(0, 8));
    navigate({ name: 'pdp', id: p.id }, `/product/${p.id}`);
  };
  const openCollection = (id) => navigate({ name: 'collection', id }, `/collection/${id}`);

  const onWish = (id) => {
    setWish(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  // colorway = { name, hex, url, images, price, sizes, shirtColors }
  const onAdd = (product, colorway, shirtColor, size) => {
    // URL opening is handled by handleBuy in pdp.jsx — don't double-open
    const key = `${product.id}:${colorway.name}:${shirtColor?.name || ''}:${size}`;
    setCart(prev => {
      const existing = prev.find(l => l.key === key);
      if (existing) return prev.map(l => l.key === key ? { ...l, qty: l.qty + 1 } : l);
      return [...prev, {
        key,
        id:        product.id,
        name:      product.name,
        type:      product.type,
        price:     colorway.price,
        silhouette: product.silhouette,
        colorway, shirtColor, size, qty: 1,
      }];
    });
  };

  const product   = route.name === 'pdp' ? products.find(p => p.id === route.id) : null;
  const cartCount = cart.reduce((s, l) => s + l.qty, 0);

  return (
    <>
      <Nav route={route} setRoute={setRoute}
           cartCount={cartCount}
           wishCount={wish.size}
           onOpenCart={() => setDrawer('cart')}
           onOpenSearch={() => setDrawer('search')}
           onOpenWish={() => setDrawer('wish')}
           openCollection={openCollection}/>

      {route.name === 'home' && (
        <HomePage products={products} loading={loading}
                  openProduct={openProduct} wish={wish} onWish={onWish}
                  openCollection={openCollection}
                  onShop={() => openCollection('tees')}/>
      )}
      {route.name === 'collection' && (
        <CollectionPage id={route.id} products={products}
                        openProduct={openProduct} wish={wish} onWish={onWish}
                        openCollection={openCollection}
                        onBack={() => history.back()}/>
      )}
      {route.name === 'pdp' && product && (
        <PDP product={product} products={products}
             onClose={() => history.back()}
             onAdd={onAdd} wish={wish} onWish={onWish}
             recentlyViewed={recent} openProduct={openProduct}/>
      )}
      {route.name === 'pdp' && !product && (
        <main style={{ paddingTop:80, minHeight:'80vh', display:'flex', alignItems:'center', justifyContent:'center' }}>
          {loading ? (
            <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:20 }}>
              <div style={{ width:28, height:28, borderRadius:'50%', border:'1px solid var(--accent)', borderTopColor:'transparent', animation:'spin 0.9s linear infinite' }}/>
              <div style={{ fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--fg-mute)' }}>Loading</div>
            </div>
          ) : (
            <div style={{ textAlign:'center', display:'flex', flexDirection:'column', alignItems:'center', gap:20 }}>
              <div style={{ fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--fg-mute)' }}>Product not found</div>
              <button onClick={() => navigate({ name:'home' }, '/')}
                      style={{ fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--accent)', cursor:'none', textDecoration:'underline', textUnderlineOffset:4 }}
                      onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
                Back to shop
              </button>
            </div>
          )}
        </main>
      )}

      <Footer setRoute={setRoute}/>

      {t.showNowPlaying && <NowPlaying/>}

      <Drawer mode={drawer} onClose={() => setDrawer(null)}
              cart={cart} setCart={setCart}
              wish={wish} onWish={onWish}
              openProduct={openProduct}/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Visual direction"/>
        <TweakRadio label="Palette"
                    value={t.theme}
                    options={[
                      { label: 'Cream', value: 'cream' },
                      { label: 'Dark',  value: 'dark' },
                      { label: 'Mono',  value: 'mono' },
                    ]}
                    onChange={(v) => setTweak('theme', v)}/>
        <TweakColor label="Accent"
                    value={t.accent}
                    options={['#c69464','#8b5a3c','#5b6e4a','#7e6594','#b04a3c']}
                    onChange={(v) => setTweak('accent', v)}/>
        <TweakSection label="Grid layout"/>
        <TweakRadio label="Grid"
                    value={t.gridLayout}
                    options={[
                      { label: 'Square',    value: 'square' },
                      { label: 'Editorial', value: 'editorial' },
                      { label: 'Dense',     value: 'dense' },
                    ]}
                    onChange={(v) => setTweak('gridLayout', v)}/>
        <TweakSection label="Cinematic touches"/>
        <TweakToggle label="Now Playing widget"
                     value={t.showNowPlaying}
                     onChange={(v) => setTweak('showNowPlaying', v)}/>
        <TweakToggle label="Film grain overlay"
                     value={t.showGrain}
                     onChange={(v) => setTweak('showGrain', v)}/>
      </TweaksPanel>
    </>
  );
}

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