// =========================================================
// Store: persistent state for cart, user, orders
// =========================================================

const STORE_KEY = "nms_state_v1";
const ADMIN_PASS = "nepal2026"; // demo passcode — change in production

const defaultState = {
  cart: [],       // [{ id, qty }]
  user: null,     // { name, email, picture, phone, address, landmark, secondaryPhone, mapLink }
  orders: [],     // [{ id, items, total, status, createdAt, user, deliveryFee, ... }]
  products: null, // null = use seed PRODUCTS; once edited, becomes an array
  adminAuthed: false,
};

function loadState() {
  try {
    const raw = localStorage.getItem(STORE_KEY);
    if (!raw) return { ...defaultState };
    const parsed = JSON.parse(raw);
    return { ...defaultState, ...parsed };
  } catch (e) {
    return { ...defaultState };
  }
}

function saveState(state) {
  try { localStorage.setItem(STORE_KEY, JSON.stringify(state)); } catch (e) {}
}

// React hook to share global state via simple subscriber model
const listeners = new Set();
let _state = loadState();

function setStateGlobal(updater) {
  _state = typeof updater === "function" ? updater(_state) : { ..._state, ...updater };
  saveState(_state);
  listeners.forEach(fn => fn(_state));
}

function useStore() {
  const [, force] = React.useState(0);
  React.useEffect(() => {
    const fn = () => force(x => x + 1);
    listeners.add(fn);
    return () => listeners.delete(fn);
  }, []);
  return [_state, setStateGlobal];
}

// ===== Product helpers (read from store, fall back to seed) =====
function getProducts() {
  return _state.products || PRODUCTS;
}
function getProductById(id) {
  return getProducts().find(p => p.id === id);
}
function getCountByCat() {
  const list = getProducts();
  const acc = {};
  CATS.forEach(c => { acc[c.id] = list.filter(p => p.cat === c.id).length; });
  return acc;
}
function upsertProduct(product) {
  setStateGlobal(s => {
    const list = s.products || PRODUCTS;
    const idx = list.findIndex(p => p.id === product.id);
    const next = idx >= 0
      ? list.map((p, i) => i === idx ? { ...p, ...product } : p)
      : [{ ...product }, ...list];
    return { ...s, products: next };
  });
}
function deleteProduct(id) {
  setStateGlobal(s => {
    const list = s.products || PRODUCTS;
    return { ...s, products: list.filter(p => p.id !== id) };
  });
}
function resetProducts() {
  setStateGlobal(s => ({ ...s, products: null }));
}
function generateProductId() {
  const list = getProducts();
  let n = list.length + 1;
  let id;
  do {
    id = "p" + String(n).padStart(2, "0");
    n++;
  } while (list.some(p => p.id === id));
  return id;
}

// ===== Admin auth =====
function adminLogin(pass) {
  if (pass === ADMIN_PASS) {
    setStateGlobal(s => ({ ...s, adminAuthed: true }));
    return { ok: true };
  }
  return { ok: false, error: "Incorrect passcode" };
}
function adminLogout() {
  setStateGlobal(s => ({ ...s, adminAuthed: false }));
}

// ===== Cart helpers =====
function cartCount(state) {
  return (state.cart || []).reduce((s, i) => s + i.qty, 0);
}
function cartSubtotal(state) {
  return (state.cart || []).reduce((s, i) => {
    const p = getProductById(i.id);
    return s + (p ? p.price * i.qty : 0);
  }, 0);
}
function deliveryFee(subtotal) {
  if (subtotal === 0) return 0;
  if (subtotal >= 20000) return 0;
  return 350;
}
function addToCart(id, qty = 1) {
  setStateGlobal(s => {
    const existing = s.cart.find(i => i.id === id);
    const cart = existing
      ? s.cart.map(i => i.id === id ? { ...i, qty: i.qty + qty } : i)
      : [...s.cart, { id, qty }];
    return { ...s, cart };
  });
}
function updateQty(id, qty) {
  setStateGlobal(s => ({
    ...s,
    cart: qty <= 0 ? s.cart.filter(i => i.id !== id) : s.cart.map(i => i.id === id ? { ...i, qty } : i)
  }));
}
function removeFromCart(id) {
  setStateGlobal(s => ({ ...s, cart: s.cart.filter(i => i.id !== id) }));
}
function clearCart() {
  setStateGlobal(s => ({ ...s, cart: [] }));
}

// ===== Auth =====
function simulatedGmailLogin(email, displayName) {
  // Validates that email is gmail.com
  if (!/@gmail\.com$/i.test(email)) return { ok: false, error: "Only @gmail.com addresses are accepted." };
  const name = displayName || email.split("@")[0].replace(/[._-]+/g, " ").replace(/\b\w/g, c => c.toUpperCase());
  const user = { name, email: email.toLowerCase(), picture: name.slice(0, 1).toUpperCase() };
  setStateGlobal(s => ({ ...s, user: { ...(s.user || {}), ...user } }));
  return { ok: true };
}
function logout() {
  setStateGlobal(s => ({ ...s, user: null }));
}
function updateUserProfile(partial) {
  setStateGlobal(s => ({ ...s, user: { ...(s.user || {}), ...partial } }));
}

// ===== Orders =====
function placeOrder(userProfile) {
  const state = _state;
  const items = state.cart.map(i => {
    const p = getProductById(i.id);
    return {
      id: i.id,
      qty: i.qty,
      name: p?.name,
      ne: p?.ne,
      price: p?.price,
    };
  });
  const sub = cartSubtotal(state);
  const fee = deliveryFee(sub);
  const id = "NMS-" + Date.now().toString(36).toUpperCase().slice(-5) + "-" + Math.floor(Math.random() * 90 + 10);
  const order = {
    id,
    createdAt: new Date().toISOString(),
    items,
    subtotal: sub,
    deliveryFee: fee,
    total: sub + fee,
    status: "placed",
    paymentMethod: "cash",
    user: { ...userProfile },
  };
  setStateGlobal(s => ({
    ...s,
    orders: [order, ...s.orders],
    cart: [],
    user: { ...(s.user || {}), ...userProfile },
  }));
  return order;
}

function updateOrderStatus(orderId, status) {
  setStateGlobal(s => ({
    ...s,
    orders: s.orders.map(o => o.id === orderId ? { ...o, status } : o),
  }));
}

// ===== Seed demo orders so admin view has content =====
function seedDemoOrdersIfEmpty() {
  if (_state.orders && _state.orders.length > 0) return;
  const demo = [
    {
      id: "NMS-K2A4F-21",
      createdAt: new Date(Date.now() - 1000 * 60 * 60 * 6).toISOString(),
      items: [
        { id: "p01", qty: 1, name: PRODUCT_BY_ID.p01.name, ne: PRODUCT_BY_ID.p01.ne, price: PRODUCT_BY_ID.p01.price },
        { id: "p35", qty: 2, name: PRODUCT_BY_ID.p35.name, ne: PRODUCT_BY_ID.p35.ne, price: PRODUCT_BY_ID.p35.price },
      ],
      subtotal: 4500 + 850 * 2, deliveryFee: 350, total: 4500 + 850 * 2 + 350,
      status: "confirmed", paymentMethod: "cash",
      user: { name: "Aakash Shrestha", email: "aakash.shrestha@gmail.com",
        phone: "9841234567", address: "Naxal, Ward 1, Kathmandu Metro, Bagmati",
        landmark: "Near Naxal Bhagwati Temple", secondaryPhone: "9802345678" }
    },
    {
      id: "NMS-J9P3D-08",
      createdAt: new Date(Date.now() - 1000 * 60 * 60 * 26).toISOString(),
      items: [
        { id: "p23", qty: 1, name: PRODUCT_BY_ID.p23.name, ne: PRODUCT_BY_ID.p23.ne, price: PRODUCT_BY_ID.p23.price },
      ],
      subtotal: 24800, deliveryFee: 0, total: 24800,
      status: "delivered", paymentMethod: "cash",
      user: { name: "Priya Tamang", email: "priya.tamang@gmail.com",
        phone: "9818765432", address: "Lakeside, Ward 6, Pokhara Metro, Gandaki",
        landmark: "Opposite Pokhara Pizza House", mapLink: "https://maps.google.com/?q=28.21,83.96" }
    },
    {
      id: "NMS-H7N9X-14",
      createdAt: new Date(Date.now() - 1000 * 60 * 60 * 48).toISOString(),
      items: [
        { id: "p13", qty: 1, name: PRODUCT_BY_ID.p13.name, ne: PRODUCT_BY_ID.p13.ne, price: PRODUCT_BY_ID.p13.price },
        { id: "p38", qty: 1, name: PRODUCT_BY_ID.p38.name, ne: PRODUCT_BY_ID.p38.ne, price: PRODUCT_BY_ID.p38.price },
        { id: "p37", qty: 1, name: PRODUCT_BY_ID.p37.name, ne: PRODUCT_BY_ID.p37.ne, price: PRODUCT_BY_ID.p37.price },
      ],
      subtotal: 18500 + 1450 + 1200, deliveryFee: 0, total: 18500 + 1450 + 1200,
      status: "placed", paymentMethod: "cash",
      user: { name: "Rojan Karki", email: "rojan.karki@gmail.com",
        phone: "9745667890", address: "Birauta, Ward 17, Pokhara Metro, Gandaki",
        landmark: "Behind Birauta Chowk", secondaryPhone: "9851112233" }
    },
    {
      id: "NMS-G4M2L-55",
      createdAt: new Date(Date.now() - 1000 * 60 * 60 * 70).toISOString(),
      items: [
        { id: "p02", qty: 1, name: PRODUCT_BY_ID.p02.name, ne: PRODUCT_BY_ID.p02.ne, price: PRODUCT_BY_ID.p02.price },
      ],
      subtotal: 8200, deliveryFee: 350, total: 8550,
      status: "delivered", paymentMethod: "cash",
      user: { name: "Sushma Gurung", email: "sushma.gurung@gmail.com",
        phone: "9869001122", address: "Kalimati, Ward 13, Kathmandu Metro, Bagmati",
        landmark: "Kalimati Vegetable Market side" }
    },
  ];
  setStateGlobal(s => ({ ...s, orders: demo }));
}

Object.assign(window, {
  useStore, setStateGlobal, STORE_KEY,
  cartCount, cartSubtotal, deliveryFee,
  addToCart, updateQty, removeFromCart, clearCart,
  simulatedGmailLogin, logout, updateUserProfile,
  placeOrder, updateOrderStatus, seedDemoOrdersIfEmpty,
  getProducts, getProductById, getCountByCat,
  upsertProduct, deleteProduct, resetProducts, generateProductId,
  adminLogin, adminLogout, ADMIN_PASS
});
