// ops-data.jsx — data for Shopify import, automations, auto-resolution agent, analytics, Lark
function pcust(name, color) {
  const initials = name.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase();
  return { name, initials, color };
}

/* ---------- Shopify import anomaly detection ---------- */
const ANOMALY_TYPES = {
  missing_tracking:   { label: "Missing tracking number", icon: "truck",  color: "#b91c1c", bg: "#fef2f2" },
  delayed_fulfillment:{ label: "Delayed fulfillment",     icon: "clock",  color: "#c2410c", bg: "#fff7ed" },
  car_model_mapping:  { label: "Incorrect car model mapping", icon: "box", color: "#7c3aed", bg: "#f5f3ff" },
  duplicate_warranty: { label: "Duplicate warranty claim", icon: "shield", color: "#0e7490", bg: "#ecfeff" },
};
const IMPORT_ANOMALIES = [
  { id: "an1", type: "missing_tracking",    order: "SHP-90412", customer: pcust("Lim Wei Sheng", "#2563eb"), car: "Honda City 2023",      detail: "Fulfilled 18h ago, no AWB written back from J&T.", severity: "high" },
  { id: "an2", type: "delayed_fulfillment", order: "SHP-90388", customer: pcust("Aishah Borhan", "#db2777"), car: "Perodua Myvi 2024",    detail: "Paid 52h ago, still in 'unfulfilled' state past SLA.", severity: "high" },
  { id: "an3", type: "car_model_mapping",   order: "SHP-90377", customer: pcust("Ganesan Rao", "#7c3aed"),  car: "Toyota Vios 2024",     detail: "SKU mapped to 'Vios 2019' cut — fitment mismatch.", severity: "medium" },
  { id: "an4", type: "duplicate_warranty",  order: "SHP-90341", customer: pcust("Chong Li Wei", "#0d9488"),  car: "Mazda CX-5 2023",      detail: "2 warranty claims opened for same defect within 1h.", severity: "medium" },
  { id: "an5", type: "delayed_fulfillment", order: "SHP-90319", customer: pcust("Nor Hidayah", "#ea580c"),   car: "Proton X50 2023",      detail: "Packed 61h ago, no courier pickup scan.", severity: "high" },
  { id: "an6", type: "missing_tracking",    order: "SHP-90302", customer: pcust("Daniel Yeoh", "#16a34a"),   car: "Honda HR-V 2024",      detail: "Tracking field empty after dispatch webhook.", severity: "low" },
  { id: "an7", type: "car_model_mapping",   order: "SHP-90288", customer: pcust("Farah Nadia", "#9333ea"),   car: "Nissan Almera 2023",   detail: "Generic SKU — no vehicle-specific cut assigned.", severity: "low" },
  { id: "an8", type: "duplicate_warranty",  order: "SHP-90274", customer: pcust("Siva Kumar", "#0891b2"),    car: "Toyota Corolla 2022",  detail: "Claim matches resolved claim TRP-47120 (90% similar).", severity: "low" },
];
const IMPORT_STEPS = [
  { key: "connect",  label: "Connecting to Shopify",     icon: "plug" },
  { key: "fetch",    label: "Fetching orders",            icon: "download" },
  { key: "validate", label: "Validating against catalogue", icon: "check" },
  { key: "detect",   label: "Detecting operational anomalies", icon: "sparkles" },
  { key: "done",     label: "Import complete",            icon: "resolve" },
];

/* ---------- Lark channels ---------- */
const LARK_ACTIONS = [
  { key: "warehouse", label: "Send to Warehouse Channel", icon: "truck",     channel: "#warehouse-ops", toast: "Message sent to Lark channel #warehouse-ops" },
  { key: "support",   label: "Notify Customer Support",   icon: "headset",   channel: "#cx-support",    toast: "Customer Support notified in Lark #cx-support" },
  { key: "task",      label: "Create Ops Task",           icon: "check",     channel: "Lark Tasks",     toast: "Ops task created in Lark" },
];

/* ---------- Automation workflows (node-based builder) ---------- */
const AUTOMATIONS = [
  {
    id: "wf1", name: "Delayed order escalation", enabled: true, runsToday: 14,
    desc: "When an order breaches the 48h dispatch SLA, route it to the warehouse manager, draft a customer update and raise priority.",
    trigger: { icon: "clock", title: "Order delayed > 48h", detail: "Dispatch SLA breach" },
    conditions: [{ icon: "card", title: "Order value ≥ RM 200", detail: "Standard & premium tiers" }],
    actions: [
      { icon: "user",     title: "Assign to Warehouse Manager", detail: "Daniel Wong" },
      { icon: "sparkles", title: "Generate customer update",    detail: "Apologetic · email" },
      { icon: "flag",     title: "Escalate priority to High",   detail: "From current level" },
    ],
  },
  {
    id: "wf2", name: "Missing tracking auto-chase", enabled: true, runsToday: 6,
    desc: "If a dispatched order has no tracking after 6h, pull the AWB from the courier and notify the customer automatically.",
    trigger: { icon: "truck", title: "No tracking 6h after dispatch", detail: "Courier write-back failed" },
    conditions: [],
    actions: [
      { icon: "download", title: "Pull AWB from courier API", detail: "J&T / Pos Laju" },
      { icon: "chat",     title: "Send tracking via WhatsApp", detail: "Customer's preferred channel" },
    ],
  },
  {
    id: "wf3", name: "Duplicate warranty dedupe", enabled: true, runsToday: 3,
    desc: "Detect warranty claims that match an existing claim and merge them to prevent double replacements.",
    trigger: { icon: "shield", title: "Warranty claim opened", detail: "Any channel" },
    conditions: [{ icon: "copy", title: "≥ 85% similar to open claim", detail: "Same customer & defect" }],
    actions: [
      { icon: "layers", title: "Merge into original claim", detail: "Keep earliest" },
      { icon: "users",  title: "Flag to Warranty Lead",     detail: "Priya Nair" },
    ],
  },
  {
    id: "wf4", name: "VIP fast-track", enabled: false, runsToday: 0,
    desc: "Any exception on a VIP account jumps the queue and pings the on-call manager in Lark.",
    trigger: { icon: "shieldcheck", title: "Exception on VIP account", detail: "Loyalty tier ≥ Gold" },
    conditions: [],
    actions: [
      { icon: "flag",      title: "Set priority to High", detail: "Override scoring" },
      { icon: "megaphone", title: "Ping on-call manager", detail: "Lark #ops-oncall" },
    ],
  },
];

/* ---------- Auto-Resolution Agent runs ---------- */
// references real exception ids; per-step + overall confidence
function agentRuns() {
  const pick = (id) => EXCEPTIONS.find(e => e.id === id);
  const mk = (id, conf, steps, decision, target) => ({ id, row: pick(id), conf, steps, decision, target });
  return [
    mk("TRP-48098", 94, { detect: 97, recommend: 95, draft: 93, escalate: 91 }, "auto", "Logistics"),
    mk("TRP-48039", 91, { detect: 95, recommend: 92, draft: 90, escalate: 88 }, "auto", "Branch Manager"),
    mk("TRP-48142", 86, { detect: 93, recommend: 88, draft: 85, escalate: 80 }, "auto", "Inventory Team"),
    mk("TRP-48201", 78, { detect: 90, recommend: 82, draft: 76, escalate: 70 }, "review", "Warehouse Team"),
    mk("TRP-48197", 64, { detect: 84, recommend: 70, draft: 60, escalate: 55 }, "review", "Logistics"),
    mk("TRP-48077", 41, { detect: 72, recommend: 48, draft: 38, escalate: 30 }, "human", "Warranty Lead"),
  ];
}
const AGENT_STEPS = [
  { key: "detect",   label: "Detect issue",            icon: "search" },
  { key: "recommend",label: "Generate recommendation", icon: "sparkles" },
  { key: "draft",    label: "Draft customer reply",    icon: "chat" },
  { key: "escalate", label: "Suggest escalation target", icon: "escalate" },
];
const AGENT_DECISION = {
  auto:   { label: "Auto-resolve eligible", color: "#15803d", bg: "#f0fdf4", dot: "#22c55e" },
  review: { label: "Quick review advised",  color: "#a16207", bg: "#fefce8", dot: "#eab308" },
  human:  { label: "Needs human handling",  color: "#b91c1c", bg: "#fef2f2", dot: "#ef4444" },
};
function confColor(c) { return c >= 85 ? "#16a34a" : c >= 65 ? "#d97706" : "#dc2626"; }

/* ---------- Analytics datasets ---------- */
const ANALYTICS = {
  // avg resolution time (hours) over 14 days — trending down
  resolution: [6.4, 6.1, 6.3, 5.8, 5.9, 5.4, 5.2, 5.5, 4.9, 4.7, 4.8, 4.4, 4.3, 4.2],
  resolutionDays: 14,
  // issue category distribution
  distribution: [
    { label: "Delayed shipment",      value: 31, color: "#0d9488" },
    { label: "Warranty claim",        value: 22, color: "#2563eb" },
    { label: "Missing tracking",      value: 17, color: "#7c3aed" },
    { label: "Installation booking",  value: 12, color: "#ea580c" },
    { label: "Payment mismatch",      value: 9,  color: "#db2777" },
    { label: "Stock / returns",       value: 9,  color: "#a1a1aa" },
  ],
  // warehouse performance
  warehouses: [
    { name: "Shah Alam DC", dispatchH: 32, slaPct: 96, volume: 612 },
    { name: "Klang DC",     dispatchH: 61, slaPct: 71, volume: 388 },
    { name: "Penang DC",    dispatchH: 41, slaPct: 88, volume: 214 },
    { name: "Johor DC",     dispatchH: 37, slaPct: 91, volume: 170 },
  ],
  // SLA compliance
  slaOverall: 87,
  slaTrend: [79, 81, 80, 83, 84, 86, 87],
  slaByCategory: [
    { label: "Fulfillment",   pct: 92 },
    { label: "Tracking",      pct: 84 },
    { label: "Warranty",      pct: 78 },
    { label: "Installation",  pct: 81 },
  ],
  kpis: [
    { label: "Avg resolution time", value: "4.2h", delta: "−0.6h", good: true,  sub: "vs last week" },
    { label: "SLA compliance",      value: "87%",  delta: "+3pts", good: true,  sub: "rolling 7-day" },
    { label: "Exceptions resolved", value: "342",  delta: "+28",   good: true,  sub: "this week" },
    { label: "Auto-resolution rate",value: "38%",  delta: "+9pts", good: true,  sub: "by OpsPilot agent" },
  ],
};

Object.assign(window, {
  ANOMALY_TYPES, IMPORT_ANOMALIES, IMPORT_STEPS, LARK_ACTIONS,
  AUTOMATIONS, agentRuns, AGENT_STEPS, AGENT_DECISION, confColor, ANALYTICS,
});
