/* ============================================================
   app.jsx — 主控元件:狀態、路由、組裝
   index.html 以 <App defaultTheme="banana" cardVariant="soft" /> 掛載
   ============================================================ */

function App({ defaultTheme = 'banana', cardVariant = 'soft' }) {
  const [route, setRoute] = useState('home');
  const [productId, setProductId] = useState('mountain-banana');
  const [cart, setCart] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [user, setUser] = useState(null);
  const [toast, setToast] = useState(null);
  const [lastOrder, setLastOrder] = useState(null);

  /* 套用主題 */
  useEffect(() => { document.documentElement.dataset.theme = defaultTheme; }, [defaultTheme]);

  /* 通知自動消失 */
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 2200);
    return () => clearTimeout(t);
  }, [toast]);

  /* 開啟側欄 / 遮罩時鎖定背景捲動 */
  useEffect(() => {
    const lock = cartOpen || searchOpen || menuOpen;
    document.body.style.overflow = lock ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [cartOpen, searchOpen, menuOpen]);

  const toTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });
  const showToast = (msg) => setToast(msg);

  const navigate = (r) => { setRoute(r); setMenuOpen(false); setSearchOpen(false); toTop(); };
  const openProduct = (id) => { setProductId(id); setRoute('product'); setMenuOpen(false); toTop(); };

  const addToCart = (id, qty = 1) => {
    const p = PRODUCTS.find((x) => x.id === id);
    if (!p) return;
    setCart((prev) => {
      const found = prev.find((x) => x.p.id === id);
      if (found) return prev.map((x) => (x.p.id === id ? { ...x, qty: x.qty + qty } : x));
      return [...prev, { p, qty }];
    });
    showToast('已加入購物車 🧺');
  };
  const setQty = (id, qty) => setCart((prev) => prev.map((x) => (x.p.id === id ? { ...x, qty: Math.max(1, qty) } : x)));
  const removeFromCart = (id) => setCart((prev) => prev.filter((x) => x.p.id !== id));

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

  const openCart = () => setCartOpen(true);
  const closeCart = () => setCartOpen(false);
  const openSearch = () => setSearchOpen(true);
  const closeSearch = () => setSearchOpen(false);
  const openMenu = () => setMenuOpen(true);
  const closeMenu = () => setMenuOpen(false);
  const goCheckout = () => { setCartOpen(false); setRoute('checkout'); toTop(); };

  const login = (u) => { setUser(u); showToast('登入成功 👋'); };
  const logout = () => { setUser(null); showToast('已登出'); };

  const placeOrder = () => {
    const subtotal = cart.reduce((s, it) => s + it.p.price * it.qty, 0);
    const shipping = subtotal >= 600 || subtotal === 0 ? 0 : 80;
    const no = '#' + (10300 + Math.floor((cartCount + subtotal) % 9000)).toString();
    setLastOrder({ no, total: subtotal + shipping });
    setCart([]);
    setRoute('success');
    toTop();
  };

  const value = {
    route, navigate, productId, openProduct,
    cart, addToCart, setQty, removeFromCart, cartCount,
    cartOpen, openCart, closeCart, goCheckout,
    searchOpen, openSearch, closeSearch,
    menuOpen, openMenu, closeMenu,
    user, login, logout,
    placeOrder, lastOrder,
    toast, showToast,
    cardVariant, theme: defaultTheme,
  };

  const screen = () => {
    switch (route) {
      case 'home':     return <HomeScreen />;
      case 'shop':     return <ShopScreen />;
      case 'product':  return <ProductScreen />;
      case 'about':    return <AboutScreen />;
      case 'account':  return <AccountScreen />;
      case 'checkout': return <CheckoutScreen />;
      case 'success':  return <SuccessScreen />;
      default:         return <HomeScreen />;
    }
  };

  return (
    <AppCtx.Provider value={value}>
      <Header />
      <MobileMenu />
      <main style={{ minHeight: '60vh' }}>{screen()}</main>
      <Footer />
      <CartDrawer />
      <SearchOverlay />
      <Toast />
    </AppCtx.Provider>
  );
}
