// Store: route + cart + wishlist + user + orders + coupon + newsletter state
const { useState: useState2, useEffect: useEffect2, useMemo: useMemo2, useCallback: useCallback2, createContext: createContext2, useContext: useContext2 } = React;

const StoreCtx = createContext2(null);

const COUPONS = {
  SAANCHA10: { discountPct: 10, discountFlat: 0, freeShip: false },
  FIRSTPAIR: { discountPct: 0,  discountFlat: 1000, freeShip: false, minOrder: 8000 },
  FREESHIP:  { discountPct: 0,  discountFlat: 0, freeShip: true },
};

const PAGE_SLUGS = ['account','signin','wishlist','track','privacy','terms','returns','shipping','cancellation','about','story','craft','journal','faq','sizing','care','contact'];

function slugify(s) {
  return (s || '').toString().toLowerCase()
    .replace(/['']/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 60);
}

function routeToHash(r) {
  if (!r || r.name === 'home') return '/';
  if (r.name === 'category') {
    let h = '/shop/' + encodeURIComponent(r.group);
    if (r.sub) h += '/' + encodeURIComponent(r.sub);
    if (r.preset) h += '?preset=' + encodeURIComponent(r.preset);
    return h;
  }
  if (r.name === 'product') {
    const p = (typeof window !== 'undefined' && window.PRODUCTS) ? window.PRODUCTS.find(x => x.id === r.id) : null;
    return '/product/' + r.id + (p ? '/' + slugify(p.name) : '');
  }
  if (r.name === 'checkout') return '/checkout';
  if (r.name === 'confirmation') return '/order-confirmed';
  if (r.name === 'page') {
    let h = '/' + encodeURIComponent(r.slug || '');
    if (r.sub) h += '/' + encodeURIComponent(r.sub);
    if (r.orderId) h += '?id=' + encodeURIComponent(r.orderId);
    return h;
  }
  return '/';
}

function hashToRoute(hash) {
  const raw = (hash || '').replace(/^#/, '') || '/';
  const [path, query] = raw.split('?');
  const parts = path.split('/').filter(Boolean).map(decodeURIComponent);
  const params = {};
  if (query) {
    query.split('&').forEach(kv => {
      const [k, v] = kv.split('=');
      if (k) params[k] = decodeURIComponent(v || '');
    });
  }
  if (parts.length === 0) return { name: 'home' };
  if (parts[0] === 'shop' && parts[1]) {
    return { name: 'category', group: parts[1], sub: parts[2], preset: params.preset };
  }
  if (parts[0] === 'product' && parts[1]) {
    const id = parseInt(parts[1], 10);
    return Number.isFinite(id) ? { name: 'product', id } : { name: 'home' };
  }
  if (parts[0] === 'checkout') return { name: 'checkout' };
  if (parts[0] === 'order-confirmed' || parts[0] === 'confirmation') return { name: 'confirmation' };
  if (PAGE_SLUGS.includes(parts[0])) {
    const slug = parts[0] === 'signin' ? 'account' : parts[0];
    return { name: 'page', slug, sub: parts[1], orderId: params.id };
  }
  return { name: 'home' };
}

function StoreProvider({ children }) {
  // route: { name: 'home'|'category'|'product'|'cart'|'checkout'|'confirmation'|'search'|'page', ...params }
  const [route, setRoute] = useState2(() => hashToRoute(typeof location !== 'undefined' ? location.hash : ''));
  const [cart, setCart] = useState2([]); // [{id, qty, size, color}]
  const [wish, setWish] = useState2(new Set());
  const [drawer, setDrawer] = useState2(null); // 'cart' | 'menu' | null
  const [searchOpen, setSearchOpen] = useState2(false);
  const [order, setOrder] = useState2(null);
  const [user, setUser] = useState2(null); // null | {email, name, createdAt}
  const [orders, setOrders] = useState2([]); // array of full order objects
  const [coupon, setCoupon] = useState2(null); // {code, discountPct, discountFlat, freeShip} | null
  const [newsletter, setNewsletter] = useState2([]); // array of emails

  // Restore from localStorage on mount
  useEffect2(() => {
    try {
      const c = JSON.parse(localStorage.getItem('saancha_cart') || '[]');
      const w = JSON.parse(localStorage.getItem('saancha_wish') || '[]');
      setCart(c); setWish(new Set(w));
    } catch {}
    try {
      const u = JSON.parse(localStorage.getItem('saancha_user') || 'null');
      if (u) setUser(u);
    } catch {}
    try {
      const o = JSON.parse(localStorage.getItem('saancha_orders') || '[]');
      if (Array.isArray(o)) setOrders(o);
    } catch {}
    try {
      const nl = JSON.parse(localStorage.getItem('saancha_newsletter') || '[]');
      if (Array.isArray(nl)) setNewsletter(nl);
    } catch {}
    try {
      const cp = JSON.parse(localStorage.getItem('saancha_coupon') || 'null');
      if (cp) setCoupon(cp);
    } catch {}
  }, []);

  useEffect2(() => { localStorage.setItem('saancha_cart', JSON.stringify(cart)); }, [cart]);
  useEffect2(() => { localStorage.setItem('saancha_wish', JSON.stringify([...wish])); }, [wish]);
  useEffect2(() => { localStorage.setItem('saancha_orders', JSON.stringify(orders)); }, [orders]);
  useEffect2(() => { localStorage.setItem('saancha_newsletter', JSON.stringify(newsletter)); }, [newsletter]);
  useEffect2(() => { localStorage.setItem('saancha_coupon', JSON.stringify(coupon)); }, [coupon]);

  const navigate = useCallback2((r) => {
    const newHash = '#' + routeToHash(r);
    if (typeof location !== 'undefined' && location.hash !== newHash) {
      try { history.pushState(null, '', newHash); } catch {}
    }
    setRoute(r);
    setDrawer(null);
    setSearchOpen(false);
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, []);

  // Sync browser back/forward + manual hash edits
  useEffect2(() => {
    const onPop = () => setRoute(hashToRoute(location.hash));
    window.addEventListener('popstate', onPop);
    window.addEventListener('hashchange', onPop);
    return () => {
      window.removeEventListener('popstate', onPop);
      window.removeEventListener('hashchange', onPop);
    };
  }, []);

  const addToCart = useCallback2((product, opts = {}) => {
    setCart(c => {
      const key = `${product.id}::${opts.size || ''}::${opts.color || ''}`;
      const existing = c.find(i => `${i.id}::${i.size||''}::${i.color||''}` === key);
      if (existing) return c.map(i => i === existing ? { ...i, qty: i.qty + (opts.qty || 1) } : i);
      return [...c, { id: product.id, qty: opts.qty || 1, size: opts.size, color: opts.color }];
    });
  }, []);

  const updateQty = useCallback2((idx, qty) => {
    setCart(c => qty <= 0 ? c.filter((_, i) => i !== idx) : c.map((it, i) => i === idx ? { ...it, qty } : it));
  }, []);
  const removeLine = useCallback2((idx) => setCart(c => c.filter((_, i) => i !== idx)), []);
  const clearCart = useCallback2(() => setCart([]), []);

  const toggleWish = useCallback2((id) => {
    setWish(w => {
      const n = new Set(w);
      if (n.has(id)) n.delete(id); else n.add(id);
      return n;
    });
  }, []);

  const cartCount = useMemo2(() => cart.reduce((s, i) => s + i.qty, 0), [cart]);
  const cartTotal = useMemo2(() => cart.reduce((s, i) => {
    const p = window.PRODUCTS.find(x => x.id === i.id);
    return s + (p ? p.price * i.qty : 0);
  }, 0), [cart]);

  const placeOrder = useCallback2((details) => {
    const id = 'SAN' + Math.floor(100000 + Math.random() * 900000);
    const o = {
      id, items: cart.slice(), total: cartTotal,
      details, placedAt: new Date().toISOString(),
      status: 'placed',
    };
    setOrder(o);
    setOrders(prev => [...prev, o]);
    setCart([]);
    setCoupon(null);
    return o;
  }, [cart, cartTotal]);

  // Auth
  const signUp = useCallback2((email, password, name) => {
    const newUser = { email, name, createdAt: new Date().toISOString() };
    // Persist to users registry (keyed by email)
    try {
      const users = JSON.parse(localStorage.getItem('saancha_users') || '{}');
      if (users[email]) return null; // already exists
      users[email] = { ...newUser, passwordHash: btoa(password) };
      localStorage.setItem('saancha_users', JSON.stringify(users));
    } catch {}
    setUser(newUser);
    localStorage.setItem('saancha_user', JSON.stringify(newUser));
    return newUser;
  }, []);

  const signIn = useCallback2((email, password) => {
    try {
      const users = JSON.parse(localStorage.getItem('saancha_users') || '{}');
      const record = users[email];
      if (!record || record.passwordHash !== btoa(password)) return false;
      const u = { email: record.email, name: record.name, createdAt: record.createdAt };
      setUser(u);
      localStorage.setItem('saancha_user', JSON.stringify(u));
      return true;
    } catch { return false; }
  }, []);

  const signOut = useCallback2(() => {
    setUser(null);
    localStorage.removeItem('saancha_user');
  }, []);

  // Coupon
  const applyCoupon = useCallback2((code) => {
    const key = code.trim().toUpperCase();
    const def = COUPONS[key];
    if (!def) return { ok: false, reason: 'Coupon not valid' };
    if (def.minOrder && cartTotal < def.minOrder) {
      return { ok: false, reason: `Minimum order Rs ${def.minOrder.toLocaleString('en-PK')} required for this coupon` };
    }
    const cp = { code: key, ...def };
    setCoupon(cp);
    return { ok: true, coupon: cp };
  }, [cartTotal]);

  const cancelOrder = useCallback2((orderId) => {
    setOrders(prev => {
      const updated = prev.map(o => o.id === orderId ? { ...o, status: 'cancelled' } : o);
      localStorage.setItem('saancha_orders', JSON.stringify(updated));
      return updated;
    });
  }, []);

  // Newsletter
  const subscribeNewsletter = useCallback2((email) => {
    setNewsletter(prev => {
      if (prev.includes(email)) return prev;
      return [...prev, email];
    });
  }, []);

  const value = {
    route, navigate,
    cart, addToCart, updateQty, removeLine, clearCart, cartCount, cartTotal,
    wish, toggleWish, wishCount: wish.size,
    drawer, setDrawer,
    searchOpen, setSearchOpen,
    order, placeOrder, orders, cancelOrder,
    user, signUp, signIn, signOut,
    coupon, applyCoupon,
    newsletter, subscribeNewsletter,
  };
  return <StoreCtx.Provider value={value}>{children}</StoreCtx.Provider>;
}

const useStore = () => useContext2(StoreCtx);

// Category metadata
const CATS = [
  { group: 'shoes', label: 'Shoes', tag: 'دستکاری',
    subs: [
      { sub: 'buck', label: 'Buck Shoes' },
      { sub: 'dress', label: 'Dress Shoes' },
      { sub: 'loafer', label: 'Loafers' },
      { sub: 'slipon', label: 'Slip-Ons' },
      { sub: 'boat', label: 'Boat Shoes' },
    ]
  },
];

window.StoreProvider = StoreProvider;
window.useStore = useStore;
window.CATS = CATS;
