/* ============================================================
   App root — routing + global state
   ============================================================ */
function App() {
  const [authed, setAuthed] = useState(false);
  const [route, setRoute] = useState({ name: 'home', params: {} });
  const [cart, setCart] = useState([]);
  const [user, setUser] = useState(CURRENT_USER);
  const [lastOrder, setLastOrder] = useState(null);

  const navigate = (name, params = {}) => {
    setRoute({ name, params });
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const login = () => { setAuthed(true); navigate('home'); };
  const logout = () => { setAuthed(false); setCart([]); setRoute({ name: 'home', params: {} }); };

  const addToCart = (product, color, size, qty) => {
    const key = `${product.id}-${color}-${size}`;
    setCart(prev => {
      const ex = prev.find(i => i.key === key);
      if (ex) return prev.map(i => i.key === key ? { ...i, qty: i.qty + qty } : i);
      return [...prev, { key, product, color, size, qty }];
    });
  };
  const updateQty = (key, delta) => setCart(prev => prev.map(i => i.key === key ? { ...i, qty: Math.max(1, i.qty + delta) } : i));
  const removeItem = (key) => setCart(prev => prev.filter(i => i.key !== key));

  const placeOrder = ({ method, loc, subtotal, over }) => {
    const remaining = user.pointsTotal - user.pointsUsed;
    const order = {
      id: 'EV-' + Math.floor(20490 + Math.random() * 90),
      method, loc, subtotal, over,
      count: cart.reduce((n, i) => n + i.qty, 0),
      remainingAfter: remaining - subtotal,
    };
    setUser(u => ({ ...u, pointsUsed: Math.min(u.pointsTotal, u.pointsUsed + subtotal) }));
    setLastOrder(order);
    setCart([]);
    navigate('confirmation');
  };

  const ctx = { authed, route, cart, user, navigate, login, logout, addToCart, updateQty, removeItem, placeOrder };

  if (!authed) {
    return <AppCtx.Provider value={ctx}><LoginScreen /></AppCtx.Provider>;
  }

  // Admin is full-screen (its own chrome)
  if (route.name === 'admin') {
    return <AppCtx.Provider value={ctx}><AdminScreen /></AppCtx.Provider>;
  }

  let screen;
  switch (route.name) {
    case 'home': screen = <HomeScreen />; break;
    case 'category': screen = <CategoryScreen cat={route.params.cat} />; break;
    case 'product': screen = <ProductScreen id={route.params.id} color={route.params.color} />; break;
    case 'cart': screen = <CartScreen />; break;
    case 'checkout': screen = <CheckoutScreen />; break;
    case 'confirmation': screen = <ConfirmationScreen order={lastOrder} />; break;
    case 'account': screen = <AccountScreen />; break;
    default: screen = <HomeScreen />;
  }

  return (
    <AppCtx.Provider value={ctx}>
      <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
        <StoreHeader />
        <div style={{ flex: 1, paddingBottom: 40 }}>{screen}</div>
        <StoreFooter />
      </div>
    </AppCtx.Provider>
  );
}

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