// Root app: routing + cart state
const { useState: useStateApp, useEffect: useEffectApp } = React;

// Lightweight stubs replacing tweaks_panel.jsx (removed from production)
function useTweaks(defaults) {
  return [defaults, () => {}];
}
function TweaksPanel() { return null; }
function TweakSection() { return null; }
function TweakRadio() { return null; }
function TweakSuggestionBar() { return null; }

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "sage",
  "cols": 4,
  "heroStyle": "forest",
  "navStyle": "centered"
}/*EDITMODE-END*/;

// Palette variants
const PALETTES = {
  sage: { paper:'#f4f1ea', ink:'#1a1f18', moss:'#5a6b4a', forest:'#2d3a26', accent:'#b8a271', stone:'#d9d3c5' },
  warm: { paper:'#f2ede1', ink:'#241a12', moss:'#7a6a3f', forest:'#3d2f1a', accent:'#c9a26b', stone:'#d8ccb0' },
  mono: { paper:'#f5f4f1', ink:'#1a1a1a', moss:'#4a4a48', forest:'#2a2a28', accent:'#8a8a86', stone:'#d5d3ce' },
};

const parsePathname = () => {
  let pathname = window.location.pathname;
  if (!pathname.endsWith('/')) {
    pathname += '/';
  }

  if (pathname === '/' || pathname === '/index.html/') {
    return { page: 'home', productId: 'p01', category: 'All' };
  }

  if (pathname.startsWith('/products/')) {
    const slug = pathname.split('/')[2];
    if (slug) {
      if (slug === 'pushparchana' || slug === 'bamboo-vase') {
        const p = window.BAMBOO_PRODUCTS.find(x => x.id === 'p30');
        if (p) return { page: 'product', productId: p.id, category: 'All' };
      }
      const p = window.BAMBOO_PRODUCTS.find(x => window.slugify(x.name) === slug);
      if (p) {
        return { page: 'product', productId: p.id, category: 'All' };
      }
    }
  }

  if (pathname.startsWith('/collections/')) {
    const slug = pathname.split('/')[2];
    if (slug) {
      const c = window.BAMBOO_CATEGORIES.find(x => window.slugify(x) === slug);
      if (c) {
        return { page: 'shop', productId: 'p01', category: c };
      }
    }
    return { page: 'shop', productId: 'p01', category: 'All' };
  }

  if (pathname === '/shop/') {
    return { page: 'shop', productId: 'p01', category: 'All' };
  }
  if (pathname === '/about/') {
    return { page: 'about', productId: 'p01', category: 'All' };
  }
  if (pathname === '/contact/') {
    return { page: 'contact', productId: 'p01', category: 'All' };
  }
  if (pathname === '/cart/') {
    return { page: 'cart', productId: 'p01', category: 'All' };
  }
  if (pathname === '/wishlist/') {
    return { page: 'wishlist', productId: 'p01', category: 'All' };
  }
  if (pathname === '/404/') {
    return { page: '404', productId: 'p01', category: 'All' };
  }

  return { page: '404', productId: 'p01', category: 'All' };
};

const navigateTo = (path) => {
  window.history.pushState({}, '', path);
  window.dispatchEvent(new Event('popstate'));
};
window.navigateTo = navigateTo;

function App() {
  const [page, setPageState] = useStateApp(() => {
    const { page: initialPage } = parsePathname();
    return initialPage;
  });
  const [productId, setProductIdState] = useStateApp(() => {
    const { productId: initialProductId } = parsePathname();
    return initialProductId;
  });
  const [activeCategory, setActiveCategory] = useStateApp(() => {
    const { category: initialCategory } = parsePathname();
    return initialCategory;
  });
  const [cart, setCart] = useStateApp(() => {
    try { return JSON.parse(localStorage.getItem('bs-cart') || '[]'); } catch { return []; }
  });
  const [wishlist, setWishlist] = useStateApp(() => {
    try { return JSON.parse(localStorage.getItem('bs-wishlist') || '[]'); } catch { return []; }
  });
  const [toast, setToast] = useStateApp('');
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffectApp(() => {
    const handlePopState = () => {
      const { page: newPage, productId: newPid, category: newCat } = parsePathname();
      setPageState(newPage);
      if (newPage === 'product' && newPid) {
        setProductIdState(newPid);
      }
      setActiveCategory(newCat || 'All');
    };

    window.addEventListener('popstate', handlePopState);

    // Hash compatibility redirect: maps legacy hash URLs to clean paths
    const hash = window.location.hash;
    if (hash) {
      let redirectPath = '/';
      const cleanHash = hash.replace(/^#\/?/, '');
      const parts = cleanHash.split('/');
      const pageType = parts[0];
      const param = parts[1];

      if (pageType === 'shop') {
        redirectPath = '/shop/';
      } else if (pageType === 'product' && param) {
        const p = window.BAMBOO_PRODUCTS.find(x => x.id === param);
        if (p) {
          redirectPath = `/products/${window.slugify(p.name)}/`;
        }
      } else if (pageType === 'about') {
        redirectPath = '/about/';
      } else if (pageType === 'contact') {
        redirectPath = '/contact/';
      } else if (pageType === 'cart') {
        redirectPath = '/cart/';
      }

      window.location.hash = '';
      window.history.replaceState({}, '', redirectPath);
    }

    return () => window.removeEventListener('popstate', handlePopState);
  }, []);

  useEffectApp(() => { localStorage.setItem('bs-page', page); }, [page]);
  useEffectApp(() => { localStorage.setItem('bs-pid', productId); }, [productId]);
  useEffectApp(() => { localStorage.setItem('bs-cart', JSON.stringify(cart)); }, [cart]);
  useEffectApp(() => { localStorage.setItem('bs-wishlist', JSON.stringify(wishlist)); }, [wishlist]);

  // Scroll to top on page or product change
  useEffectApp(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [page, productId]);

  // Dynamic document title, canonical link, and structured Product schema updates for SPA SEO
  useEffectApp(() => {
    let title = "Bamboos Culture | Bamboo Products in India";
    let canonical = "https://bamboosculture.com/";
    
    // Clean up any previously injected dynamic product schema
    const oldProductSchema = document.getElementById('dynamic-product-schema');
    if (oldProductSchema) oldProductSchema.remove();

    if (page === 'shop') {
      if (activeCategory !== 'All') {
        title = `${activeCategory} Collection | Bamboos Culture`;
        canonical = `https://bamboosculture.com/collections/${window.slugify(activeCategory)}/`;
      } else {
        title = "Shop Handcrafted Bamboo Products | Bamboos Culture";
        canonical = "https://bamboosculture.com/shop/";
      }
    } else if (page === 'product') {
      const p = window.BAMBOO_PRODUCTS.find(x => x.id === productId);
      if (p) {
        const slug = window.slugify(p.name);
        title = `${p.name} | Handcrafted Bamboo Goods | Bamboos Culture`;
        canonical = `https://bamboosculture.com/products/${slug}/`;
        
        // Inject Product Structured Data Schema (JSON-LD)
        const schemaScript = document.createElement('script');
        schemaScript.id = 'dynamic-product-schema';
        schemaScript.type = 'application/ld+json';
        schemaScript.text = JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Product",
          "name": p.name,
          "image": `https://bamboosculture.com/${p.image}`,
          "description": p.desc,
          "sku": p.id,
          "brand": {
            "@type": "Brand",
            "name": "Bamboos Culture"
          },
          "offers": {
            "@type": "Offer",
            "url": canonical,
            "priceCurrency": "INR",
            "price": p.price,
            "priceValidUntil": "2027-12-31",
            "itemCondition": "https://schema.org/NewCondition",
            "availability": "https://schema.org/InStock",
            "seller": {
              "@type": "Organization",
              "name": "Bamboos Culture"
            }
          }
        });
        document.head.appendChild(schemaScript);
      }
    } else if (page === 'about') {
      title = "About Our Story & Craft | Bamboos Culture";
      canonical = "https://bamboosculture.com/about/";
    } else if (page === 'cart') {
      title = "Your Shopping Cart | Bamboos Culture";
      canonical = "https://bamboosculture.com/cart/";
    } else if (page === 'contact') {
      title = "Contact Bamboos Culture | Nashik, Maharashtra, India";
      canonical = "https://bamboosculture.com/contact/";
    } else if (page === 'wishlist') {
      title = "Your Wishlist | Bamboos Culture";
      canonical = "https://bamboosculture.com/wishlist/";
    } else if (page === '404') {
      title = "Page Not Found | Bamboos Culture";
      canonical = "https://bamboosculture.com/404/";
    }
    
    document.title = title;
    
    let link = document.querySelector("link[rel='canonical']");
    if (!link) {
      link = document.createElement("link");
      link.setAttribute("rel", "canonical");
      document.head.appendChild(link);
    }
    link.setAttribute("href", canonical);
  }, [page, productId, activeCategory]);

  // Apply palette
  useEffectApp(() => {
    const pal = PALETTES[tweaks.palette] || PALETTES.sage;
    const root = document.documentElement;
    Object.entries(pal).forEach(([k, v]) => root.style.setProperty('--' + k, v));
  }, [tweaks.palette]);

  // Hide splash screen
  useEffectApp(() => {
    const splash = document.getElementById('splash-screen');
    if (splash) {
      setTimeout(() => {
        splash.classList.add('fade-out');
        setTimeout(() => splash.remove(), 600);
      }, 400);
    }
  }, []);

  const setPage = (p) => {
    if (p === 'shop') {
      navigateTo('/shop/');
    } else if (p === 'about') {
      navigateTo('/about/');
    } else if (p === 'contact') {
      navigateTo('/contact/');
    } else if (p === 'cart') {
      navigateTo('/cart/');
    } else if (p === 'wishlist') {
      navigateTo('/wishlist/');
    } else {
      navigateTo('/');
    }
  };

  const openProduct = (id) => {
    const p = window.BAMBOO_PRODUCTS.find(x => x.id === id);
    if (p) {
      navigateTo(`/products/${window.slugify(p.name)}/`);
    } else {
      navigateTo('/');
    }
  };

  const addToCart = (id, qty = 1) => {
    setCart(prev => {
      const existing = prev.find(c => c.id === id);
      if (existing) return prev.map(c => c.id === id ? { ...c, qty: c.qty + qty } : c);
      return [...prev, { id, qty }];
    });
    const prod = window.BAMBOO_PRODUCTS.find(p => p.id === id);
    setToast(`Added ${prod?.name} to cart`);
    setTimeout(() => setToast(''), 2500);
  };

  const toggleWishlist = (id) => {
    let active = false;
    setWishlist(prev => {
      if (prev.includes(id)) {
        return prev.filter(x => x !== id);
      } else {
        active = true;
        return [...prev, id];
      }
    });
    const prod = window.BAMBOO_PRODUCTS.find(p => p.id === id);
    setToast(active ? `Added ${prod?.name} to wishlist` : `Removed ${prod?.name} from wishlist`);
    setTimeout(() => setToast(''), 2500);
  };

  const cartCount = cart.reduce((s, c) => s + c.qty, 0);
  const forceScrolled = page !== 'home';

  return (
    <React.Fragment>
      <Nav page={page} setPage={setPage} cartCount={cartCount} wishlistCount={wishlist.length} forceScrolled={forceScrolled} />
      <main key={page}>
        {page === 'home' && <HomePage setPage={setPage} openProduct={openProduct} wishlist={wishlist} toggleWishlist={toggleWishlist} />}
        {page === 'shop' && (
          <ShopPage
            setPage={setPage}
            openProduct={openProduct}
            cols={tweaks.cols}
            filter={activeCategory}
            setFilter={(cat) => {
              navigateTo(cat === 'All' ? '/shop/' : '/collections/' + window.slugify(cat) + '/');
            }}
            wishlist={wishlist}
            toggleWishlist={toggleWishlist}
          />
        )}
        {page === 'product' && (
          <ProductPage
            productId={productId}
            setPage={setPage}
            addToCart={addToCart}
            openProduct={openProduct}
            wishlist={wishlist}
            toggleWishlist={toggleWishlist}
          />
        )}
        {page === 'about' && <AboutPage setPage={setPage} />}
        {page === 'cart' && <CartPage cart={cart} setCart={setCart} setPage={setPage} openProduct={openProduct} />}
        {page === 'wishlist' && (
          <WishlistPage
            wishlist={wishlist}
            toggleWishlist={toggleWishlist}
            addToCart={addToCart}
            setPage={setPage}
            openProduct={openProduct}
          />
        )}
        {page === 'contact' && <ContactPage setPage={setPage} />}
        {page === '404' && (
          <div style={{ textAlign: 'center', padding: '120px 24px', background: 'var(--paper)', color: 'var(--ink)' }}>
            <h1 style={{ fontSize: '48px', fontFamily: 'Cormorant Garamond, serif' }}>404 — Page Not Found</h1>
            <p style={{ marginTop: '24px', opacity: 0.6, fontFamily: 'DM Sans, sans-serif' }}>The page you are looking for does not exist or has been moved.</p>
            <a
              href="/shop/"
              onClick={(e) => { e.preventDefault(); setPage('shop'); }}
              style={{
                display: 'inline-block',
                marginTop: '40px',
                padding: '12px 32px',
                background: 'var(--moss)',
                color: 'var(--paper)',
                textDecoration: 'none',
                fontFamily: 'DM Sans, sans-serif',
                fontSize: '14px',
                fontWeight: 'bold',
                letterSpacing: '1px'
              }}
            >
              Continue Shopping
            </a>
          </div>
        )}
      </main>
      <Toast msg={toast} />

      {page !== 'cart' && cartCount > 0 && (
        <div className="sticky-cart-tab" onClick={() => setPage('cart')}>
          <span className="cart-text">CART</span>
          <span className="cart-badge">{cartCount}</span>
        </div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Palette">
          <TweakRadio
            tweak="palette" value={tweaks.palette} onChange={setTweak}
            options={[
              { value: 'sage', label: 'Sage' },
              { value: 'warm', label: 'Warm' },
              { value: 'mono', label: 'Mono' },
            ]}
          />
        </TweakSection>
        <TweakSection title="Shop grid density">
          <TweakRadio
            tweak="cols" value={tweaks.cols} onChange={setTweak}
            options={[
              { value: 3, label: '3 col' },
              { value: 4, label: '4 col' },
            ]}
          />
        </TweakSection>
        <TweakSuggestionBar suggestions={[
          "Make the hero animation snappier",
          "Try a darker palette",
          "Add a bestsellers row above the featured products",
          "Show product prices in a smaller monospaced font",
        ]} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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