/* SUPERMEDIA storefront — App shell, routing & state */
const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  const [route, setRoute] = useStateApp({ view: 'home' });
  const [cart, setCart] = useStateApp([]);
  const [wishlist, setWishlist] = useStateApp([]);
  const [user, setUser] = useStateApp(window.__SM_USER || null);
  const [query, setQuery] = useStateApp('');
  const [toast, setToast] = useStateApp(null);
  const [cartAdded, setCartAdded] = useStateApp(null);

  const cartCount = cart.reduce((s, x) => s + x.qty, 0);

  useEffectApp(() => { window.scrollTo(0, 0); if (window.lucide) window.lucide.createIcons(); });

  // navigacija povezana sa istorijom pregledača — da dugme "Nazad" radi unutar sajta
  const navigate = (r) => { setRoute(r); try { window.history.pushState({ smroute: r }, ''); } catch (e) {} };
  useEffectApp(() => {
    const onPop = (e) => setRoute((e.state && e.state.smroute) || { view: 'home' });
    window.addEventListener('popstate', onPop);
    try { window.history.replaceState({ smroute: { view: 'home' } }, ''); } catch (e) {}
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  const nav = (r) => navigate(r);
  const openProduct = (p) => navigate({ view: 'product', id: p.id });
  const addToCart = (p, qty = 1) => {
    setCart(c => { const e = c.find(x => x.id === p.id); return e ? c.map(x => x.id === p.id ? { ...x, qty: x.qty + qty } : x) : [...c, { id: p.id, qty }]; });
    setCartAdded({ ...p, addedQty: qty });
  };
  const closeCartAdded = () => setCartAdded(null);
  const toggleWish = (p) => setWishlist(w => w.includes(p.id) ? w.filter(x => x !== p.id) : [...w, p.id]);
  const login = (u) => { setUser(u); setToast(`Dobrodošao, ${u.name.split(' ')[0]}!`); clearTimeout(window.__t); window.__t = setTimeout(() => setToast(null), 2200); };
  const logout = () => { setUser(null); try { localStorage.removeItem('sm_token'); } catch (e) {} navigate({ view: 'home' }); };
  const updateUser = (u) => setUser(prev => ({ ...prev, ...u }));
  const doSearch = () => navigate({ view: 'category', slug: null });

  const product = route.view === 'product' ? SM_DATA.PRODUCTS.find(p => p.id === route.id) : null;
  const activeNav = route.view === 'popusti' ? 'popusti' : route.view === 'blog' ? 'blog' : route.view === 'home' ? 'home' : '';
  const shared = { onNav: nav, onAdd: addToCart, onWish: toggleWish, wishlist, openProduct };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <Topbar cartCount={cartCount} wishCount={wishlist.length} user={user} query={query} setQuery={setQuery} onSearch={doSearch} onNav={nav} />
      <NavBar onNav={nav} active={activeNav} onAllProducts={() => navigate({ view: 'category', slug: null })} />
      <main style={{ flex: 1, background: 'var(--sm-bg)' }}>
        {route.view === 'home' && <Home {...shared} />}
        {route.view === 'cathub' && <CategoryHub slug={route.slug} {...shared} />}
        {(route.view === 'category') && <CategoryPage slug={route.slug} brand={route.brand} potkat={route.potkat} potkat2={route.potkat2} query={query} {...shared} />}
        {route.view === 'popusti' && <SuperPopusti {...shared} />}
        {route.view === 'blog' && <BlogIndex onNav={nav} />}
        {route.view === 'product' && product && <ProductPage product={product} {...shared} />}
        {route.view === 'cart' && <Cart cart={cart} setCart={setCart} onNav={nav} openProduct={openProduct} />}
        {route.view === 'checkout' && <Checkout cart={cart} setCart={setCart} user={user} onNav={nav} />}
        {route.view === 'wishlist' && <WishlistPage wishlist={wishlist} onWish={toggleWish} onAdd={addToCart} openProduct={openProduct} onNav={nav} />}
        {route.view === 'account' && <AccountPage user={user} onLogin={login} onLogout={logout} onUpdate={updateUser} onNav={nav} wishCount={wishlist.length} />}
        {route.view === 'page' && <Page pageKey={route.key} {...shared} />}
      </main>
      <Footer onNav={nav} />

      <GenieChat onNav={nav} />

      {toast && (
        <div style={{ position: 'fixed', left: '50%', bottom: 28, transform: 'translateX(-50%)', background: 'var(--sm-ink)', color: '#fff', padding: '14px 20px', borderRadius: 'var(--sm-radius-pill)', boxShadow: 'var(--sm-shadow-lg)', display: 'flex', alignItems: 'center', gap: 10, zIndex: 80, fontFamily: 'var(--sm-font-body)', fontSize: 15, fontWeight: 600 }}>
          <span style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--sm-success)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{I('check', 16)}</span>
          {toast}
          <a onClick={() => nav({ view: 'cart' })} style={{ color: 'var(--sm-purple-200)', fontWeight: 700, marginLeft: 6, cursor: 'pointer' }}>Korpa</a>
        </div>
      )}

      {/* added-to-cart confirmation — rectangular modal: continue shopping or go to cart */}
      {cartAdded && (
        <div onClick={closeCartAdded} style={{ position: 'fixed', inset: 0, zIndex: 3000, background: 'rgba(22,18,30,.5)', backdropFilter: 'blur(3px)', WebkitBackdropFilter: 'blur(3px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div onClick={e => e.stopPropagation()} style={{ width: 'min(420px, 100%)', background: '#fff', borderRadius: 'var(--sm-radius-xl)', boxShadow: 'var(--sm-shadow-lg)', padding: '30px 26px 26px', position: 'relative', animation: 'sm-pop .22s ease-out' }}>
            <button onClick={closeCartAdded} aria-label="Zatvori" style={{ position: 'absolute', top: 14, right: 14, width: 36, height: 36, borderRadius: '50%', border: 'none', background: 'var(--sm-gray-100)', color: 'var(--sm-text-muted)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{I('x', 19)}</button>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 8 }}>
              <span style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--sm-success-soft)', color: 'var(--sm-success)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{I('check', 30)}</span>
              <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 21, letterSpacing: '-.01em' }}>Dodato u korpu</div>
              <div style={{ fontSize: 14, color: 'var(--sm-text-muted)' }}>Želiš li da nastaviš kupovinu?</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '18px 0 4px', padding: 12, background: 'var(--sm-gray-50)', borderRadius: 'var(--sm-radius-md)', textAlign: 'left' }}>
              <div style={{ width: 56, height: 56, flex: 'none', background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-sm)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--sm-purple-300)' }}>{cartAdded.img ? <img src={cartAdded.img} alt="" style={{ maxWidth: '78%', maxHeight: '78%', objectFit: 'contain' }} /> : I(cartAdded.icon || 'package', 30, { strokeWidth: 1.5 })}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.1em', fontSize: 10.5, color: 'var(--sm-text-subtle)' }}>{cartAdded.brand}</div>
                <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.3, marginTop: 2, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{cartAdded.title}</div>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
              <Button variant="primary" size="lg" block onClick={() => { closeCartAdded(); nav({ view: 'cart' }); }} iconRight={I('arrow-right', 18)}>Idi u korpu</Button>
              <Button variant="outline" size="lg" block onClick={closeCartAdded}>Nastavi kupovinu</Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function BlogStub({ onNav }) {
  return (
    <div style={{ maxWidth: 1440, margin: '0 auto', padding: '50px 24px', textAlign: 'center' }}>
      <img src={SM_DATA.A + '/mascot-genie.png'} style={{ height: 130, marginBottom: 14 }} />
      <h1 style={{ fontSize: 30 }}>Blog uskoro</h1>
      <p style={{ color: 'var(--sm-text-muted)', fontSize: 16, maxWidth: 460, margin: '8px auto 22px' }}>Vodiči, saveti i recenzije — u izradi za ovaj demo. Vrati se na početnu da nastaviš kupovinu.</p>
      <Button variant="primary" size="lg" onClick={() => onNav({ view: 'home' })}>Nazad na početnu</Button>
    </div>
  );
}

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