// App shell — router + cart state + i18n wrapper + scroll-progress.

const { I18nProvider, useI18n } = window.RBI18n;
const { AnnouncementBar, Header, MobileMenu, Newsletter, Footer } = window.RBChrome;
const { HomePage } = window.RBHome;
const { ShopPage } = window.RBShop;
const { ProductPage } = window.RBProduct;
const { CartPage } = window.RBCartPage;
const { ScrollProgress } = window.RBAnim;

function Shell() {
  const { t } = useI18n();
  const [route, setRoute] = React.useState({ page: 'home', params: {} });
  const [mobileMenu, setMobileMenu] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  const [cartItems, setCartItems] = React.useState([
    { p: window.RB.PRODUCTS[0], qty: 1, size:'M', color:'rose' },
    { p: window.RB.PRODUCTS[8], qty: 1, size:'M', color:'sand' }
  ]);

  React.useEffect(() => {
    window.RBNav = {
      go: (page, params = {}) => {
        setRoute({ page, params });
        setMobileMenu(false);
        window.scrollTo({ top: 0, behavior: 'instant' });
      }
    };
    window.RBCart = {
      add: (p, qty = 1) => {
        setCartItems(prev => {
          const i = prev.findIndex(l => l.p.id === p.id);
          if (i >= 0) {
            const next = [...prev];
            next[i] = { ...next[i], qty: next[i].qty + qty };
            return next;
          }
          return [...prev, { p, qty, size:'M', color:'rose' }];
        });
        setToast({ name: p, qty });
        setTimeout(() => setToast(null), 2600);
      }
    };
  }, []);

  // hash-based routing
  React.useEffect(() => {
    const fromHash = () => {
      const h = window.location.hash.replace(/^#\/?/, '');
      if (!h) return;
      const [page, ...rest] = h.split('/');
      const params = {};
      for (let i = 0; i < rest.length; i += 2) params[rest[i]] = rest[i+1];
      setRoute({ page: page || 'home', params });
    };
    fromHash();
    window.addEventListener('hashchange', fromHash);
    return () => window.removeEventListener('hashchange', fromHash);
  }, []);

  React.useEffect(() => {
    const hash = '#/' + route.page + Object.entries(route.params).map(([k,v]) => `/${k}/${v}`).join('');
    if (window.location.hash !== hash) window.history.replaceState(null, '', hash);
  }, [route]);

  const cartCount = cartItems.reduce((s, l) => s + l.qty, 0);
  const { lang } = useI18n();
  const dirSensitive = (lang === 'ar' ? 'right-6 md:right-10' : 'left-6 md:left-10');

  let page = null;
  const LABELS = {
    about:    { ar:'عن المتجر', en:'About' },
    contact:  { ar:'تواصل معنا', en:'Contact' },
    account:  { ar:'حسابي', en:'My account' },
    wishlist: { ar:'المفضلة', en:'Wishlist' },
    checkout: { ar:'إتمام الطلب', en:'Checkout' },
    lookbook: { ar:'لُكبوك ٢٠٢٦', en:'Lookbook 2026' }
  };

  switch (route.page) {
    case 'home':    page = <HomePage/>; break;
    case 'shop':
    case 'new':
    case 'sale':    page = <ShopPage initialCat={route.params.cat}/>; break;
    case 'product': page = <ProductPage productId={route.params.id}/>; break;
    case 'cart':    page = <CartPage items={cartItems} setItems={setCartItems}/>; break;
    case 'about':
    case 'contact':
    case 'account':
    case 'wishlist':
    case 'checkout':
    case 'lookbook':
      page = <SimplePage title={LABELS[route.page][lang]} note={route.page}/>; break;
    default:        page = <HomePage/>;
  }

  return (
    <div>
      <ScrollProgress/>
      <AnnouncementBar/>
      <Header cartCount={cartCount} onMobileMenu={() => setMobileMenu(true)}/>
      <MobileMenu open={mobileMenu} onClose={() => setMobileMenu(false)}/>

      {page}

      {route.page !== 'cart' && <Newsletter/>}
      <Footer/>

      {toast && (
        <div className={`fixed bottom-6 ${dirSensitive} z-50 bg-ink text-paper px-5 py-3.5 shadow-2xl flex items-center gap-3 max-w-sm animate-[toastIn_.4s_cubic-bezier(0.22,1,0.36,1)]`}>
          <style>{`@keyframes toastIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }`}</style>
          <window.RBIcons.IconCheck size={18} className="text-rose-300 shrink-0"/>
          <div className="text-sm">
            <p className="leading-tight">{lang === 'ar' ? 'تمت الإضافة للسلة' : 'Added to bag'}</p>
            <p className="text-xs text-paper/70 mt-0.5 truncate max-w-[200px]">{toast.name?.[lang]}</p>
          </div>
          <button onClick={() => window.RBNav.go('cart')} className="text-xs text-rose-300 hover:text-paper underline-grow ms-2">
            {lang === 'ar' ? 'عرض السلة' : 'View bag'}
          </button>
        </div>
      )}
    </div>
  );
}

function SimplePage({ title, note }) {
  const { lang } = useI18n();
  return (
    <main className="bg-paper min-h-[60vh] page-fade">
      <div className="bg-paper-warm/40 border-b hairline">
        <div className="max-w-[1480px] mx-auto px-5 md:px-10 py-14">
          <h1 className="ff-serif text-5xl md:text-7xl text-ink">{title}</h1>
        </div>
      </div>
      <div className="max-w-2xl mx-auto px-6 py-24 text-center">
        <p className="text-ink-soft leading-loose">
          {lang === 'ar'
            ? <>هذه صفحة <strong className="text-ink">{title}</strong> — جاهزة لإضافة محتواكِ الخاص.</>
            : <>This is the <strong className="text-ink">{title}</strong> page — ready for your content.</>}
        </p>
        <button onClick={() => window.RBNav.go('home')} className="mt-7 text-xs tracking-[0.3em] uppercase text-rose-500 underline-grow">
          {lang === 'ar' ? 'العودة للرئيسية' : 'Back home'} →
        </button>
      </div>
    </main>
  );
}

function App() {
  return (
    <I18nProvider>
      <Shell/>
    </I18nProvider>
  );
}

// Mount + hide boot loader
const rootEl = document.getElementById('root');
ReactDOM.createRoot(rootEl).render(<App/>);

requestAnimationFrame(() => {
  const boot = document.getElementById('boot');
  if (boot) {
    boot.style.opacity = '0';
    setTimeout(() => boot.remove(), 600);
  }
});
