import { createContext, useContext, useEffect, useState, type ReactNode } from "react";

export type Role = "guest" | "customer" | "pending_vendor" | "vendor";
export type User = { email: string; name: string; role: Role } | null;

export type VendorProfile = {
  id: string;
  status: "pending" | "approved";
  appliedAt: number;
  storeSlug: string;
  businessName: string;
  businessType: string;
  category: string;
  rcNumber: string;
  taxId: string;
  contactName: string;
  contactEmail: string;
  contactPhone: string;
  altPhone: string;
  address: string;
  city: string;
  state: string;
  country: string;
  lat?: number;
  lng?: number;
  website: string;
  productInfo: string;
  bankName: string;
  accountName: string;
  accountNumber: string;
  is_verified?: boolean; // New verified field
  banner?: string;
  logo?: string;
  wallet_balance?: number;
  loyalty_coins?: number;
};

export type Withdrawal = {
  id: string;
  vendor_id: string;
  amount: number;
  status: "pending" | "approved" | "rejected";
  requestedAt: number;
  processedAt?: number;
  // Included when fetched by admin
  businessName?: string;
  bankName?: string;
  accountName?: string;
  accountNumber?: string;
  contactEmail?: string;
};

export type Address = {
  id: string;
  name: string;
  phone: string;
  street: string;
  city: string;
  state: string;
};

export type Product = {
  id: string;
  name: string;
  price: number;
  old?: number;
  disc?: string;
  seed: string;
  vendorEmail?: string;
  category?: string;
  description?: string;
  summary?: string;
  images?: string[];
  colors?: string[];
  sizes?: string[];
  is_flash?: boolean;
  is_top?: boolean;
  is_featured?: boolean;
};

export type InAppNotification = {
  id: number;
  user_email: string;
  role: string;
  title: string;
  message: string;
  type: string;
  is_read: boolean;
  link?: string;
  createdAt: number;
};

export type LoyaltyTransaction = {
  id: number;
  vendor_email: string;
  amount: number;
  type: string;
  description: string;
  order_id?: string;
  product_id?: string;
  createdAt: number;
};

export type CartItem = { id: string; name: string; price: number; seed: string; qty: number; images?: string[] };

export type OrderStatus =
  | "placed"
  | "processing"
  | "shipped"
  | "out_for_delivery"
  | "delivered";

export type Order = {
  id: string;
  items: CartItem[];
  subtotal: number;
  shipping: number;
  total: number;
  address: Address;
  paymentMethod: string;
  paymentRef: string;
  status: OrderStatus;
  driverPhone?: string;
  history: { status: OrderStatus; at: number }[];
  createdAt: number;
};

export type TopBanner = { id: string; title: string; image: string };

export type HeroBanner = { id: string; image: string; link?: string };

// Base seed catalogue so search returns real items on a fresh browser.
export const seedProducts: Product[] = [
  { id: "fs0", name: "Samsung Galaxy A26 4G Smartphone", price: 144499, old: 180000, disc: "-20%", seed: "fs0", category: "Phones & Tablets" },
  { id: "fs1", name: "HP 15.6 inches USB 4G Laptop", price: 419999, old: 500000, disc: "-17%", seed: "fs1", category: "Computing" },
  { id: "fs2", name: "Sunking HomePlus Solar Kit", price: 73110, old: 90000, disc: "-19%", seed: "fs2", category: "Electronics" },
  { id: "fs3", name: "Water Thermocool 3kg Washer", price: 216706, old: 260000, disc: "-17%", seed: "fs3", category: "Appliances" },
  { id: "fs4", name: 'Sunking 15" Rechargeable Fan', price: 76721, old: 90000, disc: "-15%", seed: "fs4", category: "Appliances" },
  { id: "fs5", name: "Ace 20000 mAh Power Bank", price: 7500, old: 10000, disc: "-25%", seed: "fs5", category: "Mobile Accessories" },
  { id: "ts0", name: "Hithium 15kWh Power Station", price: 199999, old: 260000, disc: "-22%", seed: "ts0", category: "Electronics" },
  { id: "ts1", name: 'Royal 10" QLED TV', price: 212000, old: 250000, disc: "-16%", seed: "ts1", category: "Electronics" },
  { id: "ts2", name: "Oraimo SpaceBuds 2 Pro", price: 12499, old: 20000, disc: "-38%", seed: "ts2", category: "Mobile Accessories" },
  { id: "ts3", name: "Samsung Galaxy A26 Shell Case", price: 128991, old: 150000, disc: "-14%", seed: "ts3", category: "Mobile Accessories" },
  { id: "ts4", name: "SunKit InfiKarn 2.5kva Inverter", price: 210244, old: 235000, disc: "-11%", seed: "ts4", category: "Electronics" },
  { id: "ts5", name: "Martini Rossi Red Vermouth", price: 10890, old: 14500, disc: "-25%", seed: "ts5", category: "Groceries" },
];

type StoreState = {
  user: User;
  addresses: Address[];
  vendorProducts: Product[];
  orders: Order[];
  cart: CartItem[];
  vendors: VendorProfile[];
  withdrawals: Withdrawal[];
  paystackKey: string;
  topBanners: TopBanner[];
  heroBanners: HeroBanner[];
  notifications: InAppNotification[];
};

type StoreCtx = StoreState & {
  hydrated: boolean;
  signIn: (email: string, name?: string) => void;
  signOut: () => void;
  applyVendor: (profile: Omit<VendorProfile, "id" | "status" | "appliedAt" | "storeSlug">) => void;
  adminApproveVendor: (id: string) => void;
  adminEditVendor: (id: string, updates: Partial<VendorProfile>) => void;
  adminDeleteVendor: (id: string) => void;
  verifyVendor: (id: string) => void; // New verify vendor function
  editVendorProfile: (id: string, updates: Partial<VendorProfile>) => void;
  addAddress: (a: Omit<Address, "id">) => Address;
  removeAddress: (id: string) => void;
  addProduct: (p: Omit<Product, "id" | "seed" | "vendorEmail">) => void;
  editProduct: (id: string, updates: Partial<Product>) => void; // New edit product method
  removeProduct: (id: string) => void;
  addToCart: (item: { id: string; name: string; price: number; seed: string; images?: string[] }) => void;
  updateQty: (id: string, delta: number) => void;
  removeItem: (id: string) => void;
  clearCart: () => void;
  placeOrder: (o: Omit<Order, "id" | "status" | "history" | "createdAt">) => Order;
  advanceOrder: (id: string) => void;
  setOrderStatus: (id: string, status: OrderStatus) => void;
  updateOrderDriverPhone: (id: string, driverPhone: string) => void;
  getAllProducts: () => Product[];
  setPaystackKey: (key: string) => void;
  setTopBanners: (banners: TopBanner[]) => void;
  setHeroBanners: (banners: HeroBanner[]) => void;
  fetchWithdrawals: (vendorEmail?: string) => Promise<void>;
  requestWithdrawal: (vendorEmail: string, amount: number) => Promise<{success: boolean, error?: string}>;
  adminUpdateWithdrawal: (id: string, action: "approve" | "reject") => Promise<{success: boolean, error?: string}>;
  fetchNotifications: (email?: string) => Promise<void>;
  markNotificationRead: (id: number) => Promise<void>;
  markAllNotificationsRead: (email: string) => Promise<void>;
  fetchLoyaltyData: (vendorEmail: string) => Promise<{ loyalty_coins: number; transactions: LoyaltyTransaction[] }>;
  featureProductWithLoyalty: (vendorEmail: string, productId: string) => Promise<{ success: boolean; error?: string }>;
};

const Ctx = createContext<StoreCtx | null>(null);
const KEY = "sulejamarket:v1";

const defaultTopBanners: TopBanner[] = [
  { id: "1", title: "Aircraft Deals", image: "https://picsum.photos/seed/tb0/120/120" },
  { id: "2", title: "Up to 70% Off", image: "https://picsum.photos/seed/tb1/120/120" },
  { id: "3", title: "New Ikon Deals", image: "https://picsum.photos/seed/tb2/120/120" },
  { id: "4", title: "Banger Deals", image: "https://picsum.photos/seed/tb3/120/120" },
  { id: "5", title: "Up to 50% Off", image: "https://picsum.photos/seed/tb4/120/120" },
  { id: "6", title: "Shoes on a Budget", image: "https://picsum.photos/seed/tb5/120/120" },
  { id: "7", title: "Rs.100 Store", image: "https://picsum.photos/seed/tb6/120/120" },
  { id: "8", title: "Groceries", image: "https://picsum.photos/seed/tb7/120/120" },
];

const defaultHeroBanners: HeroBanner[] = [
  { id: "h1", image: "https://images.unsplash.com/photo-1607082348824-0a96f2a4b9da?w=1200&h=500&fit=crop" },
  { id: "h2", image: "https://images.unsplash.com/photo-1607082349566-187342175e2f?w=1200&h=500&fit=crop" },
  { id: "h3", image: "https://images.unsplash.com/photo-1472851294608-062f824d29cc?w=1200&h=500&fit=crop" },
  { id: "h4", image: "https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=1200&h=500&fit=crop" },
  { id: "h5", image: "https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=1200&h=500&fit=crop" },
  { id: "h6", image: "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=1200&h=500&fit=crop" },
];

const empty: StoreState = { user: null, addresses: [], vendorProducts: [], orders: [], cart: [], vendors: [], withdrawals: [], paystackKey: "pk_test_fb0f7e3d7cbbf0141e7410e773cfaaec88769605", topBanners: defaultTopBanners, heroBanners: defaultHeroBanners, notifications: [] };

const nextStatus: Record<OrderStatus, OrderStatus | null> = {
  placed: "processing",
  processing: "shipped",
  shipped: "out_for_delivery",
  out_for_delivery: "delivered",
  delivered: null,
};

export function StoreProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<StoreState>(empty);
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    // Load local state first (cart, user, addresses, orders)
    let localOrders: Order[] = [];
    try {
      const raw = localStorage.getItem(KEY);
      if (raw) {
        const parsed = JSON.parse(raw);
        localOrders = parsed.orders || [];
        setState((s) => ({
          ...s,
          cart: parsed.cart || [],
          user: parsed.user || null,
          addresses: parsed.addresses || [],
          orders: localOrders,
        }));
      }
    } catch {}

    Promise.all([
      fetch("/api/store.php").then(r => r.json()),
      fetch("/api/orders.php").then(r => r.json())
    ])
      .then(([data, ordersData]) => {
        const fetchedOrders: Order[] = Array.isArray(ordersData) ? ordersData : [];
        
        setState((s) => {
          const mergedOrders = [...fetchedOrders];
          
          // Merge local orders to preserve driverPhone or locally created orders
          for (const locOrd of localOrders) {
            const idx = mergedOrders.findIndex(o => o.id === locOrd.id);
            if (idx >= 0) {
              if (locOrd.driverPhone && (!mergedOrders[idx].driverPhone || mergedOrders[idx].driverPhone !== locOrd.driverPhone)) {
                mergedOrders[idx] = { ...mergedOrders[idx], driverPhone: locOrd.driverPhone };
              }
            } else {
              mergedOrders.push(locOrd);
            }
          }

          return {
            ...s,
            vendors: data.vendors || [],
            vendorProducts: data.products || [],
            heroBanners: data.heroBanners || defaultHeroBanners,
            topBanners: data.topBanners || defaultTopBanners,
            orders: mergedOrders,
          };
        });
      })
      .catch((e) => console.error("Failed to load store from API", e))
      .finally(() => setHydrated(true));
  }, []);

  useEffect(() => {
    if (!hydrated) return;
    try {
      const { cart, user, addresses, orders } = state;
      localStorage.setItem(KEY, JSON.stringify({ cart, user, addresses, orders }));
    } catch {}
  }, [state.cart, state.user, state.addresses, state.orders, hydrated]);

  const value: StoreCtx = {
    ...state,
    hydrated,
    signIn: (email, name) =>
      setState((s) => ({
        ...s,
        user: s.user
          ? { ...s.user, email, name: name || s.user.name }
          : { email, name: name || email.split("@")[0], role: "customer" },
      })),
    signOut: () => setState((s) => ({ ...s, user: null })),
    applyVendor: (profile) =>
      setState((s) => {
        const id = `vnd_${Date.now()}`;
        let baseSlug = profile.businessName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
        if (!baseSlug) baseSlug = "store";
        let slug = baseSlug;
        let counter = 1;
        while (s.vendors.some(v => v.storeSlug === slug)) {
          slug = `${baseSlug}-${counter++}`;
        }
        const newVendor: VendorProfile = { ...profile, id, status: "pending", appliedAt: Date.now(), storeSlug: slug };
        
        fetch("/api/vendors.php?action=apply", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(newVendor)
        });

        return {
          ...s,
          vendors: [...s.vendors, newVendor],
          user: s.user && s.user.email === profile.contactEmail ? { ...s.user, role: "pending_vendor" } : s.user,
        };
      }),
    adminApproveVendor: (id) =>
      setState((s) => {
        const vendor = s.vendors.find((v) => v.id === id);
        if (!vendor) return s;
        const updatedVendors = s.vendors.map((v) => (v.id === id ? { ...v, status: "approved" as const } : v));
        const updatedUser =
          s.user && s.user.email === vendor.contactEmail ? { ...s.user, role: "vendor" as const } : s.user;
        
        fetch("/api/vendors.php?action=approve", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id })
        });

        return { ...s, vendors: updatedVendors, user: updatedUser };
      }),
    verifyVendor: (id) =>
      setState((s) => {
        const updatedVendors = s.vendors.map((v) => (v.id === id ? { ...v, is_verified: true } : v));
        
        fetch("/api/vendors.php?action=verify", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id })
        });

        return { ...s, vendors: updatedVendors };
      }),
    adminEditVendor: (id, updates) =>
      setState((s) => ({
        ...s,
        vendors: s.vendors.map((v) => (v.id === id ? { ...v, ...updates } : v)),
      })),
    editVendorProfile: (id, updates) =>
      setState((s) => {
        const updatedVendors = s.vendors.map((v) => (v.id === id ? { ...v, ...updates } : v));
        fetch("/api/vendors.php?action=edit_profile", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id, ...updates })
        });
        return { ...s, vendors: updatedVendors };
      }),
    adminDeleteVendor: (id) =>
      setState((s) => {
        const vendor = s.vendors.find((v) => v.id === id);
        if (!vendor) return s;
        const updatedVendors = s.vendors.filter((v) => v.id !== id);
        // Revert user role to customer if they are pending or vendor, only if they are the current logged-in user
        const updatedUser =
          s.user && s.user.email === vendor.contactEmail
            ? { ...s.user, role: "customer" as const }
            : s.user;
            
        fetch("/api/vendors.php?action=delete", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id })
        });

        return { ...s, vendors: updatedVendors, user: updatedUser };
      }),
    addAddress: (a) => {
      const addr: Address = { ...a, id: `addr_${Date.now()}` };
      setState((s) => ({ ...s, addresses: [...s.addresses, addr] }));
      return addr;
    },
    removeAddress: (id) =>
      setState((s) => ({ ...s, addresses: s.addresses.filter((x) => x.id !== id) })),
    addProduct: async (p) => {
      // Create an optimistic local ID, but we'll fetch the real one
      const optimisticId = `vp_${Date.now()}`;
      const optimisticProduct = { ...p, id: optimisticId, seed: optimisticId, vendorEmail: state.user?.email };
      
      // Update UI optimistically
      setState((s) => ({
        ...s,
        vendorProducts: [...s.vendorProducts, optimisticProduct as Product],
      }));

      try {
        const response = await fetch("/api/products.php?action=add", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(optimisticProduct)
        });
        const data = await response.json();
        
        if (data.success && data.id) {
          // Replace optimistic ID with the real DB ID
          setState((s) => ({
            ...s,
            vendorProducts: s.vendorProducts.map(prod => 
              prod.id === optimisticId ? { ...prod, id: data.id, seed: data.id } : prod
            )
          }));
        }
      } catch (err) {
        console.error("Failed to sync new product:", err);
      }
    },
    editProduct: (id, updates) => {
      setState((s) => ({
        ...s,
        vendorProducts: s.vendorProducts.map(p => p.id === id ? { ...p, ...updates } : p)
      }));

      const product = state.vendorProducts.find(p => p.id === id);
      if (product) {
        fetch("/api/products.php?action=edit", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ ...product, ...updates })
        });
      }
    },
    removeProduct: (id) => {
      fetch("/api/products.php?action=delete", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id })
      });
      setState((s) => ({ ...s, vendorProducts: s.vendorProducts.filter((x) => x.id !== id) }));
    },
    addToCart: (item) =>
      setState((s) => {
        const found = s.cart.find((x) => x.id === item.id);
        return {
          ...s,
          cart: found
            ? s.cart.map((x) => (x.id === item.id ? { ...x, qty: x.qty + 1 } : x))
            : [...s.cart, { ...item, qty: 1 }],
        };
      }),
    updateQty: (id, delta) =>
      setState((s) => ({
        ...s,
        cart: s.cart
          .map((x) => (x.id === id ? { ...x, qty: Math.max(0, x.qty + delta) } : x))
          .filter((x) => x.qty > 0),
      })),
    removeItem: (id) => setState((s) => ({ ...s, cart: s.cart.filter((x) => x.id !== id) })),
    clearCart: () => setState((s) => ({ ...s, cart: [] })),
    placeOrder: (o) => {
      const id = `ORD-${Date.now().toString(36).toUpperCase()}`;
      const now = Date.now();
      const order: Order = {
        ...o,
        id,
        status: "placed",
        history: [{ status: "placed", at: now }],
        createdAt: now,
      };
      
      fetch("/api/orders.php?action=place", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(order)
      });

      setState((s) => ({ ...s, orders: [order, ...s.orders] }));
      return order;
    },
    advanceOrder: (id) => {
      fetch("/api/orders.php?action=advance", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id })
      });
      
      setState((s) => ({
        ...s,
        orders: s.orders.map((o) => {
          if (o.id !== id) return o;
          const nx = nextStatus[o.status];
          if (!nx) return o;
          return { ...o, status: nx, history: [...o.history, { status: nx, at: Date.now() }] };
        }),
      }));
    },
    setOrderStatus: (id, status) => {
      fetch("/api/orders.php?action=update_status", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, status })
      });
      
      setState((s) => ({
        ...s,
        orders: s.orders.map((o) => {
          if (o.id !== id || o.status === status) return o;
          return { ...o, status, history: [...o.history, { status, at: Date.now() }] };
        }),
      }));
    },
    updateOrderDriverPhone: (id, driverPhone) => {
      fetch("/api/orders.php?action=update_driver_phone", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, driverPhone })
      });

      setState((s) => ({
        ...s,
        orders: s.orders.map((o) => (o.id === id ? { ...o, driverPhone } : o)),
      }));
    },
    getAllProducts: () => {
      const prods = state.vendorProducts.length > 0 ? state.vendorProducts : seedProducts;
      return [...prods].sort((a, b) => {
        const aFeatured = a.is_featured ? 2 : 0;
        const bFeatured = b.is_featured ? 2 : 0;
        const aVerified = state.vendors.find(v => v.contactEmail === a.vendorEmail)?.is_verified ? 1 : 0;
        const bVerified = state.vendors.find(v => v.contactEmail === b.vendorEmail)?.is_verified ? 1 : 0;
        return (bFeatured + bVerified) - (aFeatured + aVerified);
      });
    },
    setPaystackKey: (k) => setState(s => ({ ...s, paystackKey: k })),
    setTopBanners: (b) => {
      setState(s => ({ ...s, topBanners: b }));
      fetch("/api/banners.php?type=top", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(b)
      });
    },
    setHeroBanners: (b) => {
      setState(s => ({ ...s, heroBanners: b }));
      fetch("/api/banners.php?type=hero", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(b)
      });
    },
    fetchWithdrawals: async (vendorEmail?: string) => {
      const url = vendorEmail ? `/api/withdraw.php?vendorEmail=${encodeURIComponent(vendorEmail)}` : "/api/withdraw.php";
      try {
        const res = await fetch(url);
        const data = await res.json();
        if (Array.isArray(data)) {
          setState(s => ({ ...s, withdrawals: data }));
        }
      } catch (e) {}
    },
    requestWithdrawal: async (vendorEmail, amount) => {
      try {
        const res = await fetch("/api/withdraw.php?action=request", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ vendorEmail, amount })
        });
        const data = await res.json();
        if (data.success) {
          // Immediately subtract locally to reflect
          setState(s => ({
            ...s,
            vendors: s.vendors.map(v => v.contactEmail === vendorEmail ? { ...v, wallet_balance: (v.wallet_balance || 0) - amount } : v)
          }));
          return { success: true };
        }
        return { success: false, error: data.error };
      } catch (e: any) {
        return { success: false, error: e.message };
      }
    },
    adminUpdateWithdrawal: async (id, action) => {
      try {
        const res = await fetch(`/api/withdraw.php?action=${action}`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id })
        });
        const data = await res.json();
        if (data.success) {
          setState(s => ({
            ...s,
            withdrawals: s.withdrawals.map(w => w.id === id ? { ...w, status: action === "approve" ? "approved" : "rejected" } : w)
          }));
          return { success: true };
        }
        return { success: false, error: data.error };
      } catch (e: any) {
        return { success: false, error: e.message };
      }
    },
    fetchNotifications: async (email?: string) => {
      try {
        const targetEmail = email || state.user?.email || "";
        const role = state.user?.role || "customer";
        const url = targetEmail 
          ? `/api/notifications.php?email=${encodeURIComponent(targetEmail)}` 
          : `/api/notifications.php?role=${encodeURIComponent(role)}`;
        const res = await fetch(url);
        const data = await res.json();
        if (Array.isArray(data)) {
          setState(s => ({ ...s, notifications: data }));
        }
      } catch (e) {}
    },
    markNotificationRead: async (id: number) => {
      try {
        await fetch("/api/notifications.php?action=mark_read", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id })
        });
        setState(s => ({
          ...s,
          notifications: s.notifications.map(n => n.id === id ? { ...n, is_read: true } : n)
        }));
      } catch (e) {}
    },
    markAllNotificationsRead: async (email: string) => {
      try {
        await fetch("/api/notifications.php?action=mark_all_read", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email })
        });
        setState(s => ({
          ...s,
          notifications: s.notifications.map(n => ({ ...n, is_read: true }))
        }));
      } catch (e) {}
    },
    fetchLoyaltyData: async (vendorEmail: string) => {
      try {
        const res = await fetch(`/api/loyalty.php?vendorEmail=${encodeURIComponent(vendorEmail)}`);
        const data = await res.json();
        if (data.loyalty_coins !== undefined) {
          setState(s => ({
            ...s,
            vendors: s.vendors.map(v => v.contactEmail === vendorEmail ? { ...v, loyalty_coins: data.loyalty_coins } : v)
          }));
          return { loyalty_coins: data.loyalty_coins, transactions: data.transactions || [] };
        }
      } catch (e) {}
      return { loyalty_coins: 0, transactions: [] };
    },
    featureProductWithLoyalty: async (vendorEmail: string, productId: string) => {
      try {
        const res = await fetch("/api/loyalty.php?action=feature_product", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ vendorEmail, productId })
        });
        const data = await res.json();
        if (data.success) {
          setState(s => ({
            ...s,
            vendors: s.vendors.map(v => v.contactEmail === vendorEmail ? { ...v, loyalty_coins: data.loyalty_coins } : v),
            vendorProducts: s.vendorProducts.map(p => p.id === productId ? { ...p, is_featured: true, is_top: true } : p)
          }));
          return { success: true };
        }
        return { success: false, error: data.error };
      } catch (e: any) {
        return { success: false, error: e.message };
      }
    },
  };

  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

export function useStore() {
  const v = useContext(Ctx);
  if (!v) throw new Error("useStore must be used within StoreProvider");
  return v;
}

export function fmt(n: number) {
  return n.toLocaleString("en-NG");
}

export const statusLabel: Record<OrderStatus, string> = {
  placed: "Order placed",
  processing: "Processing",
  shipped: "Shipped",
  out_for_delivery: "Out for delivery",
  delivered: "Delivered",
};
