// Global app state + cart/wishlist hooks, route store, currency format, helpers

const fmtPrice = (n) => `NT$${n.toLocaleString()}`;
const cx = (...xs) => xs.filter(Boolean).join(' ');

const STORAGE = {
  cart: 'friday.cart.v1',
  wish: 'friday.wish.v1',
  route: 'friday.route.v1',
  user: 'friday.user.v1',
  lang: 'friday.lang.v1',
};

const loadJSON = (k, fb) => {
  try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : fb; } catch { return fb; }
};
const saveJSON = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} };

// ---- AppContext: cart, wishlist, auth, drawer, route ----
const AppContext = React.createContext(null);
const useApp = () => React.useContext(AppContext);

const AppProvider = ({ children }) => {
  const [cart, setCart] = React.useState(() => loadJSON(STORAGE.cart, []));
  const [wish, setWish] = React.useState(() => loadJSON(STORAGE.wish, []));
  const [user, setUser] = React.useState(() => loadJSON(STORAGE.user, null));
  const [route, setRouteState] = React.useState(() => loadJSON(STORAGE.route, { name: 'home', params: {} }));
  const [lang, setLang] = React.useState(() => localStorage.getItem(STORAGE.lang) || 'zh');
  const [cartOpen, setCartOpen] = React.useState(false);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [authOpen, setAuthOpen] = React.useState(false);
  const [authMode, setAuthMode] = React.useState('login');
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  React.useEffect(() => saveJSON(STORAGE.cart, cart), [cart]);
  React.useEffect(() => saveJSON(STORAGE.wish, wish), [wish]);
  React.useEffect(() => saveJSON(STORAGE.user, user), [user]);
  React.useEffect(() => saveJSON(STORAGE.route, route), [route]);
  React.useEffect(() => localStorage.setItem(STORAGE.lang, lang), [lang]);

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

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2200);
  };

  const addToCart = (item) => {
    setCart((prev) => {
      const key = `${item.id}-${item.size}-${item.color}`;
      const found = prev.find(x => x.key === key);
      if (found) return prev.map(x => x.key === key ? { ...x, qty: x.qty + item.qty } : x);
      return [...prev, { key, ...item }];
    });
    showToast('已加入購物車');
    setCartOpen(true);
  };
  const updateQty = (key, qty) => {
    if (qty <= 0) return setCart(prev => prev.filter(x => x.key !== key));
    setCart(prev => prev.map(x => x.key === key ? { ...x, qty } : x));
  };
  const removeItem = (key) => setCart(prev => prev.filter(x => x.key !== key));
  const clearCart = () => setCart([]);

  const toggleWish = (id) => {
    setWish(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const login = (email) => {
    const u = { email, name: email.split('@')[0], points: 2480, tier: 'SILVER', joined: '2025.08.14' };
    setUser(u); setAuthOpen(false); showToast('登入成功');
  };
  const logout = () => { setUser(null); setRoute('home'); };

  const cartCount = cart.reduce((a, x) => a + x.qty, 0);
  const cartTotal = cart.reduce((a, x) => a + x.price * x.qty, 0);

  const value = {
    cart, cartCount, cartTotal, addToCart, updateQty, removeItem, clearCart,
    wish, toggleWish,
    user, login, logout,
    route, setRoute,
    lang, setLang,
    cartOpen, setCartOpen,
    searchOpen, setSearchOpen,
    authOpen, setAuthOpen, authMode, setAuthMode,
    mobileOpen, setMobileOpen,
    toast, showToast,
  };
  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
};

// Friday-drop countdown hook
const useCountdown = (targetFn) => {
  const [now, setNow] = React.useState(Date.now());
  const target = React.useMemo(() => targetFn(), []);
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  const diff = Math.max(0, target - now);
  return {
    d: Math.floor(diff / 86400000),
    h: Math.floor(diff / 3600000) % 24,
    m: Math.floor(diff / 60000) % 60,
    s: Math.floor(diff / 1000) % 60,
    done: diff <= 0,
  };
};

Object.assign(window, { AppContext, AppProvider, useApp, useCountdown, fmtPrice, cx });
