// ============================================================
// data.jsx — Mock seed data + persistence helpers
// ============================================================

const STORAGE_KEY = "inv_app_state_v1";

// Warehouses & Locations (F&B context)
const WAREHOUSES = [
  { id: "WH-A", name: "คลังหลัก กรุงเทพ", code: "WH-A", type: "ห้องเย็น", temp: "2-8°C" },
  { id: "WH-B", name: "คลังภาคกลาง อยุธยา", code: "WH-B", type: "อุณหภูมิห้อง", temp: "25°C" },
  { id: "WH-C", name: "คลังเชียงใหม่", code: "WH-C", type: "ห้องเย็น", temp: "2-8°C" },
  { id: "WH-D", name: "คลังภาคใต้ สงขลา", code: "WH-D", type: "อุณหภูมิห้อง", temp: "25°C" },
];

// Build location grid: each warehouse has zones A-D, racks 1-4 = 16 locations
function buildLocations() {
  const locs = [];
  WAREHOUSES.forEach(wh => {
    ["A", "B", "C", "D"].forEach(zone => {
      [1, 2, 3, 4].forEach(rack => {
        locs.push({
          id: `${wh.id}-${zone}${rack}`,
          warehouseId: wh.id,
          zone,
          rack,
          code: `${zone}${rack}`,
          capacity: 500,
        });
      });
    });
  });
  return locs;
}

const PRODUCTS = [
  { sku: "MLK-001", barcode: "8851234500011", name: "นมสดยูเอชที รสจืด 1L", category: "นม", unit: "ขวด", reorderPoint: 80, costPrice: 32, sellPrice: 45, supplier: "Dairy Plus Co.", shelfLife: 180 },
  { sku: "MLK-002", barcode: "8851234500028", name: "นมสดยูเอชที รสช็อกโกแลต 1L", category: "นม", unit: "ขวด", reorderPoint: 60, costPrice: 34, sellPrice: 48, supplier: "Dairy Plus Co.", shelfLife: 180 },
  { sku: "JCE-110", barcode: "8851234501100", name: "น้ำส้มคั้นสด 100% 500ml", category: "น้ำผลไม้", unit: "ขวด", reorderPoint: 120, costPrice: 18, sellPrice: 35, supplier: "FreshFruit Ltd.", shelfLife: 30 },
  { sku: "JCE-220", barcode: "8851234502200", name: "น้ำแอปเปิ้ลคั้นสด 500ml", category: "น้ำผลไม้", unit: "ขวด", reorderPoint: 100, costPrice: 22, sellPrice: 39, supplier: "FreshFruit Ltd.", shelfLife: 30 },
  { sku: "WTR-001", barcode: "8851234503001", name: "น้ำดื่ม 600ml (แพ็ค 12)", category: "น้ำดื่ม", unit: "แพ็ค", reorderPoint: 200, costPrice: 65, sellPrice: 90, supplier: "PureSpring Co.", shelfLife: 720 },
  { sku: "SDA-300", barcode: "8851234504003", name: "น้ำอัดลม โคล่า 325ml", category: "น้ำอัดลม", unit: "กระป๋อง", reorderPoint: 240, costPrice: 12, sellPrice: 20, supplier: "Bubble Beverage", shelfLife: 365 },
  { sku: "SDA-301", barcode: "8851234504010", name: "น้ำอัดลม รสส้ม 325ml", category: "น้ำอัดลม", unit: "กระป๋อง", reorderPoint: 180, costPrice: 12, sellPrice: 20, supplier: "Bubble Beverage", shelfLife: 365 },
  { sku: "SNK-501", barcode: "8851234505001", name: "มันฝรั่งทอด รสดั้งเดิม 80g", category: "ขนมขบเคี้ยว", unit: "ถุง", reorderPoint: 150, costPrice: 18, sellPrice: 30, supplier: "Crispy Snacks", shelfLife: 120 },
  { sku: "SNK-502", barcode: "8851234505018", name: "ข้าวเกรียบกุ้ง 60g", category: "ขนมขบเคี้ยว", unit: "ถุง", reorderPoint: 120, costPrice: 14, sellPrice: 25, supplier: "Crispy Snacks", shelfLife: 150 },
  { sku: "BSC-700", barcode: "8851234507000", name: "บิสกิตเนยสด แพ็คคู่", category: "ขนมขบเคี้ยว", unit: "ห่อ", reorderPoint: 100, costPrice: 22, sellPrice: 35, supplier: "GoldenBake Inc.", shelfLife: 180 },
  { sku: "CFE-810", barcode: "8851234508001", name: "กาแฟพร้อมดื่ม ลาเต้ 240ml", category: "กาแฟพร้อมดื่ม", unit: "ขวด", reorderPoint: 90, costPrice: 28, sellPrice: 42, supplier: "Bean Bros.", shelfLife: 90 },
  { sku: "CFE-811", barcode: "8851234508018", name: "กาแฟพร้อมดื่ม เอสเปรสโซ่ 240ml", category: "กาแฟพร้อมดื่ม", unit: "ขวด", reorderPoint: 70, costPrice: 28, sellPrice: 42, supplier: "Bean Bros.", shelfLife: 90 },
  { sku: "TEA-901", barcode: "8851234509000", name: "ชาเขียวพร้อมดื่ม 500ml", category: "ชา", unit: "ขวด", reorderPoint: 140, costPrice: 16, sellPrice: 25, supplier: "GreenLeaf Tea", shelfLife: 240 },
  { sku: "TEA-902", barcode: "8851234509017", name: "ชาดำเย็น 500ml", category: "ชา", unit: "ขวด", reorderPoint: 100, costPrice: 16, sellPrice: 25, supplier: "GreenLeaf Tea", shelfLife: 240 },
  { sku: "ICE-330", barcode: "8851234503300", name: "ไอศกรีมวานิลลา 1L", category: "ไอศกรีม", unit: "ถ้วย", reorderPoint: 60, costPrice: 85, sellPrice: 130, supplier: "FrostyCo", shelfLife: 365 },
];

const USERS = [
  { id: "U-001", username: "admin", name: "ปานวาด พรหมจารีย์", email: "admin@inv.co.th", role: "admin", status: "active", lastLogin: "2026-05-13 08:42", initials: "ปว", color: "#2563eb" },
  { id: "U-002", username: "supan", name: "ศุภพล ใจดี", email: "supan@inv.co.th", role: "user", status: "active", lastLogin: "2026-05-13 09:14", initials: "ศพ", color: "#16a34a" },
  { id: "U-003", username: "kanya", name: "กัญญา ทองมา", email: "kanya@inv.co.th", role: "user", status: "active", lastLogin: "2026-05-12 17:30", initials: "กญ", color: "#d97706" },
  { id: "U-004", username: "nopadol", name: "นพดล แสงทอง", email: "nopadol@inv.co.th", role: "user", status: "inactive", lastLogin: "2026-04-28 11:08", initials: "นด", color: "#737373" },
];

// Seed stock by location — assign products to specific locations
function buildInitialStock() {
  const stock = {}; // key = `${sku}|${locationId}` -> qty
  // Distribute each product into 1-3 locations across warehouses
  const distributions = [
    ["MLK-001", { "WH-A-A1": 240, "WH-B-A1": 180, "WH-C-A1": 120 }],
    ["MLK-002", { "WH-A-A2": 160, "WH-B-A2": 90 }],
    ["JCE-110", { "WH-A-B1": 280, "WH-D-A1": 150 }],
    ["JCE-220", { "WH-A-B2": 90, "WH-C-A2": 75 }],
    ["WTR-001", { "WH-B-C1": 420, "WH-D-B1": 380, "WH-C-B1": 220 }],
    ["SDA-300", { "WH-B-C2": 540, "WH-D-B2": 360 }],
    ["SDA-301", { "WH-B-C3": 380, "WH-D-B3": 280 }],
    ["SNK-501", { "WH-B-D1": 230, "WH-D-C1": 180 }],
    ["SNK-502", { "WH-B-D2": 195, "WH-D-C2": 140 }],
    ["BSC-700", { "WH-B-D3": 165, "WH-D-C3": 90 }],
    ["CFE-810", { "WH-A-A3": 140, "WH-C-A3": 80 }],
    ["CFE-811", { "WH-A-A4": 95, "WH-C-A4": 60 }],
    ["TEA-901", { "WH-A-B3": 260, "WH-D-A2": 145 }],
    ["TEA-902", { "WH-A-B4": 175, "WH-D-A3": 110 }],
    ["ICE-330", { "WH-A-C1": 45, "WH-C-C1": 30 }],
  ];
  distributions.forEach(([sku, locs]) => {
    Object.entries(locs).forEach(([locId, qty]) => {
      stock[`${sku}|${locId}`] = qty;
    });
  });
  return stock;
}

// Generate seed movements (last 30 days)
function buildSeedMovements() {
  const out = [];
  const now = new Date("2026-05-13T10:00:00");
  const types = ["receive", "issue"];
  const refs = ["PO", "SO"];
  const userIds = ["U-001", "U-002", "U-003"];
  const stockSnap = buildInitialStock();
  const skuLocs = {};
  Object.keys(stockSnap).forEach(k => {
    const [sku, loc] = k.split("|");
    if (!skuLocs[sku]) skuLocs[sku] = [];
    skuLocs[sku].push(loc);
  });
  const skus = Object.keys(skuLocs);
  let id = 10000;
  for (let d = 30; d >= 0; d--) {
    const day = new Date(now); day.setDate(now.getDate() - d);
    const count = 2 + Math.floor(Math.random() * 4);
    for (let i = 0; i < count; i++) {
      const t = types[Math.floor(Math.random() * types.length)];
      const sku = skus[Math.floor(Math.random() * skus.length)];
      const locs = skuLocs[sku];
      const loc = locs[Math.floor(Math.random() * locs.length)];
      const qty = 10 + Math.floor(Math.random() * 90);
      const u = userIds[Math.floor(Math.random() * userIds.length)];
      const dt = new Date(day); dt.setHours(8 + Math.floor(Math.random() * 10), Math.floor(Math.random() * 60));
      out.push({
        id: `MV-${id++}`,
        type: t,
        sku,
        locationId: loc,
        qty,
        ref: `${refs[t === "receive" ? 0 : 1]}-${20000 + Math.floor(Math.random() * 9999)}`,
        note: t === "receive" ? "รับจาก supplier" : "จ่ายให้ลูกค้า/หน้าร้าน",
        userId: u,
        date: dt.toISOString(),
      });
    }
  }
  return out.sort((a, b) => new Date(b.date) - new Date(a.date));
}

const SEED_STATE = {
  products: PRODUCTS,
  warehouses: WAREHOUSES,
  locations: buildLocations(),
  users: USERS,
  stock: buildInitialStock(),
  movements: buildSeedMovements(),
  currentUserId: null,
};

// Expose seed state for DB.seedAll()
window.SEED_STATE = SEED_STATE;

function loadState() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      // basic validation
      if (parsed && parsed.products && parsed.warehouses) return parsed;
    }
  } catch (e) {}
  return SEED_STATE;
}

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

function resetState() {
  try { localStorage.removeItem(STORAGE_KEY); } catch (e) {}
  const fresh = { ...SEED_STATE, stock: buildInitialStock(), movements: buildSeedMovements() };
  // Also reset Supabase if configured (fire-and-forget)
  if (window.DB?.isConfigured()) window.DB.seedAll(fresh).catch(console.error);
  return fresh;
}

// ============ Helpers ============

function getStockBySKU(state, sku) {
  let total = 0;
  Object.entries(state.stock).forEach(([k, qty]) => {
    if (k.startsWith(sku + "|")) total += qty;
  });
  return total;
}

function getStockByLocation(state, locationId) {
  let total = 0;
  Object.entries(state.stock).forEach(([k, qty]) => {
    if (k.endsWith("|" + locationId)) total += qty;
  });
  return total;
}

function getLocationsForSKU(state, sku) {
  const out = [];
  Object.entries(state.stock).forEach(([k, qty]) => {
    const [s, locId] = k.split("|");
    if (s === sku && qty > 0) out.push({ locationId: locId, qty });
  });
  return out;
}

function formatThaiDate(d) {
  const dt = typeof d === "string" ? new Date(d) : d;
  const months = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
  return `${dt.getDate()} ${months[dt.getMonth()]} ${dt.getFullYear() + 543 - 2500} ${String(dt.getHours()).padStart(2,"0")}:${String(dt.getMinutes()).padStart(2,"0")}`;
}
function formatShortDate(d) {
  const dt = typeof d === "string" ? new Date(d) : d;
  return `${String(dt.getDate()).padStart(2,"0")}/${String(dt.getMonth()+1).padStart(2,"0")}`;
}
function formatNumber(n) { return (n || 0).toLocaleString("th-TH"); }
function formatCurrency(n) { return "฿" + Math.round(n || 0).toLocaleString("th-TH"); }

Object.assign(window, {
  loadState, saveState, resetState,
  getStockBySKU, getStockByLocation, getLocationsForSKU,
  formatThaiDate, formatShortDate, formatNumber, formatCurrency,
});
