/* global React */
// Store: products data + cart/auth/router state via React context

const { createContext, useContext, useState, useEffect, useCallback, useMemo } = React;

// ─── PRODUCT DATA ──────────────────────────────────────────────
// Fashion apparel, Indonesian-friendly. Images use Unsplash via picsum seeds fallback.
// We use Unsplash topic images with stable IDs for consistency.
const IMG = (seed, w = 800, h = 1000) => `https://images.unsplash.com/photo-${seed}?auto=format&fit=crop&w=${w}&h=${h}&q=80`;

const PRODUCTS = [
  { id: "p01", name: "Kira Oversized Cotton Shirt", category: "Shirts", collection: "Everyday",
    price: 489000, priceOld: 620000, colors: [{name:"Bone", hex:"#E7E2D7"},{name:"Clay", hex:"#BD7A5C"},{name:"Ink", hex:"#1E2230"}],
    sizes: ["XS","S","M","L","XL"], rating: 4.8, reviews: 214, stock: 12, tag: "Bestseller",
    images: [
      IMG("1602810318383-e386cc2a3ccf"),
      IMG("1591369822096-ffd140ec948f"),
      IMG("1604176354204-9268737828e4"),
      IMG("1618354691373-d851c5c3a990"),
    ],
    desc: "A relaxed-fit cotton shirt in heavyweight twill. Pre-washed for a soft, lived-in hand. Finished with corozo buttons and a single chest pocket.",
    specs: [["Material","100% organic cotton twill, 220 gsm"],["Fit","Oversized, drop shoulder"],["Origin","Made in Bandung, Indonesia"],["Care","Machine wash cold, tumble dry low"]],
  },
  { id: "p02", name: "Rami Wide-Leg Trousers", category: "Trousers", collection: "Workwear",
    price: 639000, colors: [{name:"Charcoal", hex:"#2E3138"},{name:"Sand", hex:"#C4A97A"},{name:"Olive", hex:"#626A4A"}],
    sizes: ["26","28","30","32","34"], rating: 4.7, reviews: 128, stock: 8,
    images: [
      IMG("1594633312681-425c7b97ccd1"),
      IMG("1584382296087-ac00c7263710"),
      IMG("1624378439575-d8705ad7ae80"),
    ],
    desc: "A roomy, tailored trouser with a high rise and clean front. Linen-cotton blend drapes beautifully without clinging.",
    specs: [["Material","55% linen, 45% cotton"],["Fit","High rise, wide leg"],["Origin","Made in Bandung, Indonesia"],["Care","Dry clean or hand wash"]],
  },
  { id: "p03", name: "Halo Merino Knit Sweater", category: "Knitwear", collection: "Autumn",
    price: 849000, priceOld: 1099000, colors: [{name:"Cream", hex:"#F0E9D9"},{name:"Stone", hex:"#A29B8F"},{name:"Slate", hex:"#545A66"}],
    sizes: ["S","M","L","XL"], rating: 4.9, reviews: 302, stock: 3, tag: "Low stock",
    images: [
      IMG("1620799140408-edc6dcb6d633"),
      IMG("1638470681321-09204b2ace92"),
      IMG("1580331451062-99ff652288d7"),
    ],
    desc: "A fine-gauge merino pullover knit in Italy. Crewneck with tonal ribbing. Warm, breathable, and surprisingly light.",
    specs: [["Material","100% extra-fine merino wool"],["Fit","Regular"],["Origin","Knit in Italy"],["Care","Hand wash cold, dry flat"]],
  },
  { id: "p04", name: "Pinto Canvas Tote", category: "Accessories", collection: "Everyday",
    price: 279000, colors: [{name:"Natural", hex:"#E4D9BD"},{name:"Black", hex:"#1B1B1B"}],
    sizes: ["One size"], rating: 4.6, reviews: 189, stock: 40,
    images: [
      IMG("1544441893-675973e31985"),
      IMG("1590874103328-eac38a683ce7"),
      IMG("1564422170194-896b89110ef8"),
    ],
    desc: "Structured canvas tote with leather handles. Fits a laptop, a book, and a bento. Made to patina with use.",
    specs: [["Material","16oz heavy canvas + veg-tan leather"],["Size","38 × 36 × 12 cm"],["Origin","Made in Bandung, Indonesia"]],
  },
  { id: "p05", name: "Sora Slip Dress", category: "Dresses", collection: "Evening",
    price: 759000, colors: [{name:"Ivory", hex:"#F2EDE1"},{name:"Midnight", hex:"#1F2A44"},{name:"Rust", hex:"#A14B2E"}],
    sizes: ["XS","S","M","L"], rating: 4.8, reviews: 94, stock: 15, tag: "New",
    images: [
      IMG("1595777457583-95e059d581b8"),
      IMG("1572804013309-59a88b7e92f1"),
      IMG("1618932260643-eee4a2f652a6"),
    ],
    desc: "A bias-cut slip dress in silk-touch satin. Adjustable straps, french-seamed throughout. Cool, cool, and cool.",
    specs: [["Material","92% viscose, 8% silk"],["Fit","Slim, bias cut"],["Care","Dry clean only"]],
  },
  { id: "p06", name: "Atlas Cropped Jacket", category: "Outerwear", collection: "Autumn",
    price: 1189000, colors: [{name:"Khaki", hex:"#948359"},{name:"Black", hex:"#161616"}],
    sizes: ["S","M","L","XL"], rating: 4.7, reviews: 61, stock: 6, tag: "Limited",
    images: [
      IMG("1551028719-00167b16eac5"),
      IMG("1544923246-77307dd654cb"),
      IMG("1591047139829-d91aecb6caea"),
    ],
    desc: "A cropped workwear jacket with four pockets and a clean silhouette. Weighty cotton canvas, softened with each wash.",
    specs: [["Material","100% cotton canvas, 340 gsm"],["Fit","Cropped, boxy"],["Care","Machine wash cold"]],
  },
  { id: "p07", name: "Nara Pleated Midi Skirt", category: "Skirts", collection: "Workwear",
    price: 529000, colors: [{name:"Black", hex:"#1A1A1A"},{name:"Olive", hex:"#5C6341"}],
    sizes: ["XS","S","M","L"], rating: 4.6, reviews: 77, stock: 11,
    images: [
      IMG("1582142306909-195724d33d1a"),
      IMG("1577900232427-18219b0f4d4d"),
    ],
    desc: "A fluid pleated midi in technical satin. Elastic back waist for an easy fit. Holds its pleats beautifully.",
    specs: [["Material","100% recycled polyester"],["Fit","Midi length"],["Care","Machine wash cold"]],
  },
  { id: "p08", name: "Lumen Linen Shirt Dress", category: "Dresses", collection: "Summer",
    price: 689000, colors: [{name:"White", hex:"#FBFAF5"},{name:"Sage", hex:"#A5B294"}],
    sizes: ["XS","S","M","L"], rating: 4.8, reviews: 142, stock: 9,
    images: [
      IMG("1585487000160-6ebcfceb0d03"),
      IMG("1596703263926-eb0762ee17e4"),
    ],
    desc: "A breezy, button-through midi in Belgian linen. Self-tie waist, roomy pockets, mother-of-pearl buttons.",
    specs: [["Material","100% Belgian linen"],["Fit","Relaxed"],["Care","Machine wash cold, iron while damp"]],
  },
  { id: "p09", name: "Ember Wool Overcoat", category: "Outerwear", collection: "Winter",
    price: 2490000, colors: [{name:"Camel", hex:"#B8956A"},{name:"Charcoal", hex:"#3A3C42"}],
    sizes: ["S","M","L","XL"], rating: 4.9, reviews: 48, stock: 4, tag: "Editor's pick",
    images: [
      IMG("1544022613-e87ca75a784a"),
      IMG("1548624313-0396c75c0fcc"),
    ],
    desc: "A timeless double-breasted overcoat in Italian wool. Half-canvas construction, silk-lined sleeves.",
    specs: [["Material","80% wool, 20% cashmere"],["Lining","100% viscose"],["Origin","Tailored in Italy"]],
  },
  { id: "p10", name: "Kaze Cotton Hoodie", category: "Knitwear", collection: "Everyday",
    price: 549000, colors: [{name:"Heather Gray", hex:"#A3A6AD"},{name:"Black", hex:"#121212"},{name:"Cream", hex:"#EFE7D4"}],
    sizes: ["XS","S","M","L","XL"], rating: 4.7, reviews: 266, stock: 28,
    images: [
      IMG("1556821840-3a63f95609a7"),
      IMG("1620799139834-6b8f844fbe61"),
    ],
    desc: "Heavyweight French terry hoodie with brushed interior. Kangaroo pocket, tonal drawcords, built to last.",
    specs: [["Material","100% organic cotton, 420 gsm"],["Fit","Regular"],["Care","Machine wash cold"]],
  },
  { id: "p11", name: "Oros Leather Loafers", category: "Accessories", collection: "Everyday",
    price: 1350000, colors: [{name:"Cognac", hex:"#7A4A2A"},{name:"Black", hex:"#0E0E0E"}],
    sizes: ["38","39","40","41","42","43","44"], rating: 4.8, reviews: 112, stock: 7,
    images: [
      IMG("1549298916-b41d501d3772"),
      IMG("1533867617858-e7b97e060509"),
    ],
    desc: "Hand-finished leather loafers with a soft, flexible sole. Goodyear welted so they can be resoled for life.",
    specs: [["Material","Full-grain calf leather"],["Sole","Goodyear welted leather"],["Origin","Made in Portugal"]],
  },
  { id: "p12", name: "Mira Silk Scarf", category: "Accessories", collection: "Everyday",
    price: 319000, colors: [{name:"Ochre", hex:"#C4873F"},{name:"Steel", hex:"#5A6470"},{name:"Rose", hex:"#D7927B"}],
    sizes: ["One size"], rating: 4.9, reviews: 58, stock: 25,
    images: [
      IMG("1601924994987-69e26d50dc26"),
    ],
    desc: "A lightweight square scarf, hand-rolled edges, digitally printed in a single run of 120.",
    specs: [["Material","100% silk twill"],["Size","70 × 70 cm"],["Origin","Printed in Bandung"]],
  },
];

const CATEGORIES = ["All", "Shirts", "Trousers", "Knitwear", "Dresses", "Outerwear", "Skirts", "Accessories"];
const COLLECTIONS = ["Autumn", "Winter", "Summer", "Evening", "Workwear", "Everyday"];

// ─── FORMATTERS ──────────────────────────────────────────────
const formatIDR = (n) => "Rp " + Math.round(n).toLocaleString("id-ID");
const SHIPPING_FEE = 35000;
const FREE_SHIPPING_THRESHOLD = 1000000;

// ─── STORE CONTEXT ───────────────────────────────────────────
const StoreCtx = createContext(null);

const LS_KEY = "morpheme_store_v1";
function readLS() {
  try { return JSON.parse(localStorage.getItem(LS_KEY) || "{}"); } catch { return {}; }
}
function writeLS(patch) {
  const cur = readLS();
  localStorage.setItem(LS_KEY, JSON.stringify({ ...cur, ...patch }));
}

function StoreProvider({ children }) {
  const initial = readLS();
  const [cart, setCart] = useState(initial.cart || []);
  const [wishlist, setWishlist] = useState(initial.wishlist || []);
  const [user, setUser] = useState(initial.user || null);
  const [address, setAddress] = useState(initial.address || null);
  const [orders, setOrders] = useState(initial.orders || []);
  const [toast, setToast] = useState(null);

  useEffect(() => { writeLS({ cart, wishlist, user, address, orders }); }, [cart, wishlist, user, address, orders]);

  const showToast = useCallback((msg, icon) => {
    setToast({ msg, icon, id: Date.now() });
    setTimeout(() => setToast((t) => (t && t.msg === msg ? null : t)), 2200);
  }, []);

  const addToCart = useCallback((product, opts) => {
    const { size, color, qty = 1 } = opts || {};
    setCart((prev) => {
      const key = `${product.id}|${size || ""}|${color?.name || ""}`;
      const found = prev.find((l) => l.key === key);
      if (found) return prev.map((l) => (l.key === key ? { ...l, qty: l.qty + qty } : l));
      return [...prev, { key, id: product.id, size, color, qty }];
    });
    showToast(`Added to bag — ${product.name}`, "bag");
  }, [showToast]);

  const updateQty = useCallback((key, qty) => {
    setCart((prev) => prev.map((l) => (l.key === key ? { ...l, qty: Math.max(1, qty) } : l)));
  }, []);

  const removeLine = useCallback((key) => {
    setCart((prev) => prev.filter((l) => l.key !== key));
  }, []);

  const clearCart = useCallback(() => setCart([]), []);

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

  const login = useCallback((email, name) => {
    const u = { email, name: name || email.split("@")[0].replace(/\b\w/g, (c) => c.toUpperCase()) };
    setUser(u);
    showToast(`Welcome back, ${u.name}`, "check");
  }, [showToast]);

  const logout = useCallback(() => setUser(null), []);

  const setOrderAddress = useCallback((addr) => setAddress(addr), []);

  const placeOrder = useCallback((payload) => {
    const order = {
      id: "MS-" + Math.random().toString(36).slice(2, 6).toUpperCase() + "-" + Date.now().toString(36).slice(-4).toUpperCase(),
      createdAt: new Date().toISOString(),
      items: cart,
      ...payload,
    };
    setOrders((prev) => [order, ...prev]);
    setCart([]);
    return order;
  }, [cart]);

  // Derived
  const cartLines = useMemo(() =>
    cart.map((l) => ({ ...l, product: PRODUCTS.find((p) => p.id === l.id) })).filter((l) => l.product)
  , [cart]);
  const cartCount = useMemo(() => cart.reduce((s, l) => s + l.qty, 0), [cart]);
  const cartSubtotal = useMemo(() => cartLines.reduce((s, l) => s + l.product.price * l.qty, 0), [cartLines]);
  const shippingFee = cartSubtotal === 0 || cartSubtotal >= FREE_SHIPPING_THRESHOLD ? 0 : SHIPPING_FEE;
  const cartTotal = cartSubtotal + shippingFee;

  const value = {
    products: PRODUCTS, categories: CATEGORIES, collections: COLLECTIONS,
    cart, cartLines, cartCount, cartSubtotal, shippingFee, cartTotal, FREE_SHIPPING_THRESHOLD,
    addToCart, updateQty, removeLine, clearCart,
    wishlist, toggleWishlist,
    user, login, logout,
    address, setOrderAddress,
    orders, placeOrder,
    toast, showToast,
    formatIDR,
  };

  return React.createElement(StoreCtx.Provider, { value }, children);
}

function useStore() { return useContext(StoreCtx); }

// ─── ROUTER (hash-based) ─────────────────────────────────────
function parseHash() {
  const h = (window.location.hash || "#/").slice(1) || "/";
  const [path, queryStr = ""] = h.split("?");
  const query = {};
  queryStr.split("&").filter(Boolean).forEach((p) => {
    const [k, v] = p.split("=");
    query[decodeURIComponent(k)] = decodeURIComponent(v || "");
  });
  const parts = path.split("/").filter(Boolean);
  return { path, parts, query };
}

function useRouter() {
  const [route, setRoute] = useState(parseHash());
  useEffect(() => {
    const onHash = () => { setRoute(parseHash()); window.scrollTo({ top: 0, behavior: "instant" }); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const navigate = useCallback((to) => {
    if (to.startsWith("#")) to = to.slice(1);
    window.location.hash = to;
  }, []);
  return { ...route, navigate };
}

Object.assign(window, { StoreProvider, useStore, useRouter, PRODUCTS, CATEGORIES, COLLECTIONS, formatIDR, FREE_SHIPPING_THRESHOLD });
