// Main App — root + router + state
const { useState: uS, useEffect: uE } = React;

function App() {
  const [dataLoaded, setDataLoaded] = uS(false);
  uE(() => { (async () => { await window.loadSiteData(); setDataLoaded(true); })(); }, []);
  if (!dataLoaded) {
    return (
      <div style={{display:'flex',alignItems:'center',justifyContent:'center',height:'100vh',background:'#faf6ee',fontFamily:'serif',fontSize:28,letterSpacing:'.25em',color:'#2a2826'}}>
        HILLO BANAT
      </div>
    );
  }
  return <AppInner/>;
}

function AppInner() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "heroStyle": "fullscreen",
    "cardStyle": "classic",
    "gridCols": 4,
    "gridCount": 8,
    "defaultLang": "ar"
  }/*EDITMODE-END*/;

  // Override defaults from server settings
  const s = window.SITE_SETTINGS || {};
  if (s.hero_style) TWEAK_DEFAULTS.heroStyle = s.hero_style;
  if (s.card_style) TWEAK_DEFAULTS.cardStyle = s.card_style;
  if (s.grid_cols) TWEAK_DEFAULTS.gridCols = parseInt(s.grid_cols);
  if (s.grid_count) TWEAK_DEFAULTS.gridCount = parseInt(s.grid_count);
  if (s.default_lang) TWEAK_DEFAULTS.defaultLang = s.default_lang;

  const [tweaks, setTweaks] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = uS(tweaks.defaultLang || 'ar');
  const [page, setPage] = uS('home');
  const [pageProps, setPageProps] = uS({});
  const [drawer, setDrawer] = uS(false);
  const [wishlist, setWishlist] = uS(() => {
    try { return JSON.parse(localStorage.getItem('hb_wish') || '[]'); } catch { return []; }
  });
  const [toastNode, showToast] = useToast();

  uE(() => {
    document.documentElement.setAttribute('dir', I18N[lang].dir);
    document.documentElement.setAttribute('lang', lang);
  }, [lang]);

  uE(() => {
    localStorage.setItem('hb_wish', JSON.stringify(wishlist));
  }, [wishlist]);

  const navigate = (p, props = {}) => {
    setPage(p);
    setPageProps(props);
    setDrawer(false);
  };

  const toggleWish = (id) => {
    setWishlist(prev => {
      const has = prev.includes(id);
      if (!has) showToast(I18N[lang].product.addedWish);
      return has ? prev.filter(i => i !== id) : [...prev, id];
    });
  };

  const onWaOrder = (product) => {
    const msg = lang === 'ar'
      ? `مرحباً، أرغب بطلب: ${product.name.ar} (${product.id}) - ${fmtPrice(product.price, 'ar')}`
      : `Hi, I want to order: ${product.name.en} (${product.id}) - ${fmtPrice(product.price, 'en')}`;
    window.open(waUrl(msg), '_blank');
  };

  const wishCount = wishlist.length;

  let pageEl = null;
  if (page === 'home') pageEl = <HomePage lang={lang} navigate={navigate} wishlist={wishlist} toggleWish={toggleWish} onWaOrder={onWaOrder} tweaks={tweaks}/>;
  else if (page === 'shop') pageEl = <ShopPage lang={lang} navigate={navigate} wishlist={wishlist} toggleWish={toggleWish} onWaOrder={onWaOrder} tweaks={tweaks} initialCat={pageProps.cat}/>;
  else if (page === 'product') pageEl = <ProductPage lang={lang} navigate={navigate} productId={pageProps.id} wishlist={wishlist} toggleWish={toggleWish} onWaOrder={onWaOrder} tweaks={tweaks}/>;
  else if (page === 'about') pageEl = <AboutPage lang={lang} navigate={navigate}/>;
  else if (page === 'contact') pageEl = <ContactPage lang={lang} navigate={navigate}/>;
  else if (page === 'wishlist') pageEl = <WishlistPage lang={lang} navigate={navigate} wishlist={wishlist} toggleWish={toggleWish} onWaOrder={onWaOrder} tweaks={tweaks}/>;

  return (
    <div data-screen-label={page}>
      <Header lang={lang} setLang={setLang} page={page} navigate={navigate} wishlistCount={wishCount} onMenu={() => setDrawer(true)}/>
      <MobileDrawer open={drawer} onClose={() => setDrawer(false)} lang={lang} setLang={setLang} navigate={navigate}/>
      {pageEl}
      <Footer lang={lang} navigate={navigate}/>
      <FloatingWA lang={lang}/>
      {toastNode}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Hero">
          <TweakRadio label="Hero style" value={tweaks.heroStyle}
            onChange={v => setTweaks({ heroStyle: v })}
            options={[
              { value: 'fullscreen', label: 'Full-screen' },
              { value: 'split', label: 'Editorial split' },
              { value: 'grid', label: 'Triptych grid' },
            ]}/>
        </TweakSection>
        <TweakSection title="Product card">
          <TweakRadio label="Card style" value={tweaks.cardStyle}
            onChange={v => setTweaks({ cardStyle: v })}
            options={[
              { value: 'classic', label: 'Classic (info row + swatches)' },
              { value: 'minimal', label: 'Minimal (image + name)' },
              { value: 'editorial', label: 'Editorial (centered italic)' },
              { value: 'bordered', label: 'Bordered card' },
            ]}/>
        </TweakSection>
        <TweakSection title="Grid">
          <TweakSelect label="Columns" value={tweaks.gridCols}
            onChange={v => setTweaks({ gridCols: parseInt(v) })}
            options={[
              { value: 2, label: '2 columns' },
              { value: 3, label: '3 columns' },
              { value: 4, label: '4 columns' },
              { value: 5, label: '5 columns' },
            ]}/>
          <TweakSlider label="Items per home section" value={tweaks.gridCount}
            min={4} max={12} step={4}
            onChange={v => setTweaks({ gridCount: v })}/>
        </TweakSection>
        <TweakSection title="Language">
          <TweakRadio label="Default language" value={tweaks.defaultLang}
            onChange={v => { setTweaks({ defaultLang: v }); setLang(v); }}
            options={[
              { value: 'ar', label: 'العربية (RTL)' },
              { value: 'en', label: 'English (LTR)' },
            ]}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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