// auth.jsx — RBAC config, roles, permissions, users, audit, integrations, tasks
// Roles
const ROLES = {
  super_admin: { key: "super_admin", label: "Super Admin", short: "Admin",   color: "#7c3aed", desc: "Full system access — users, integrations & config" },
  ops_manager: { key: "ops_manager", label: "Ops Manager", short: "Manager", color: "#0d9488", desc: "Manage exceptions, assign tasks, edit rules" },
  ops_staff:   { key: "ops_staff",   label: "Ops Staff",   short: "Staff",   color: "#2563eb", desc: "Work assigned exceptions & personal tasks" },
  viewer:      { key: "viewer",      label: "Viewer",      short: "Viewer",  color: "#71717a", desc: "Read-only dashboard access" },
};

// Full nav catalogue
const NAV_ALL = {
  dashboard:    { key: "dashboard",    label: "Dashboard",          icon: "grid" },
  queue:        { key: "queue",        label: "Exception Queue",    icon: "alert", badge: 47 },
  assigned:     { key: "assigned",     label: "Assigned Exceptions",icon: "alert", badge: 5 },
  tasks:        { key: "tasks",        label: "My Tasks",           icon: "check", badge: 4 },
  orders:       { key: "orders",       label: "Orders",             icon: "box" },
  import:       { key: "import",       label: "Import Orders",      icon: "download" },
  automations:  { key: "automations",  label: "Automations",        icon: "zap" },
  analytics:    { key: "analytics",    label: "Analytics",          icon: "barchart" },
  warranty:     { key: "warranty",     label: "Warranty Claims",    icon: "shield", badge: 12 },
  install:      { key: "install",      label: "Installations",      icon: "wrench" },
  users:        { key: "users",        label: "Users",              icon: "users" },
  integrations: { key: "integrations", label: "Integrations",       icon: "plug" },
  rules:        { key: "rules",        label: "Rules",              icon: "sliders" },
  audit:        { key: "audit",        label: "Audit Logs",         icon: "list" },
  deptperms:    { key: "deptperms",    label: "Dept Permissions",   icon: "shield" },
};

// Per-role sidebar
const ROLE_NAV = {
  super_admin: ["dashboard", "queue", "orders", "import", "automations", "analytics", "users", "integrations", "rules", "audit", "deptperms"],
  ops_manager: ["dashboard", "queue", "orders", "import", "automations", "analytics", "warranty", "install", "users", "rules", "audit"],
  ops_staff:   ["dashboard", "assigned", "tasks"],
  viewer:      ["dashboard", "analytics"],
};

// Permission matrix
const PERMS = {
  super_admin: { act: true,  assign: true,  editRules: true,  manageUsers: true,  manageIntegrations: true, viewAudit: true,  viewAllExceptions: true, importOrders: true,  manageAutomations: true },
  ops_manager: { act: true,  assign: true,  editRules: true,  manageUsers: true,  manageIntegrations: false,viewAudit: true,  viewAllExceptions: true, importOrders: true,  manageAutomations: true },
  ops_staff:   { act: true,  assign: false, editRules: false, manageUsers: false, manageIntegrations: false,viewAudit: false, viewAllExceptions: false, importOrders: false, manageAutomations: false },
  viewer:      { act: false, assign: false, editRules: false, manageUsers: false, manageIntegrations: false,viewAudit: false, viewAllExceptions: false, importOrders: false, manageAutomations: false },
};

// Representative signed-in user per role (drives topbar / sidebar identity)
const ROLE_USER = {
  super_admin: { name: "Ethan Lee",     initials: "EL", color: "#7c3aed", role: "Super Admin",          email: "ethan.lee@trapo.co" },
  ops_manager: { name: "Nadia Hassan",  initials: "NH", color: "#0d9488", role: "Operations Manager",   email: "nadia.h@trapo.co" },
  ops_staff:   { name: "Marcus Tan",    initials: "MT", color: "#2563eb", role: "Ops Staff · Fulfillment", email: "marcus.t@trapo.co", staffKey: "marcus" },
  viewer:      { name: "Rahul Menon",   initials: "RM", color: "#71717a", role: "Viewer · Finance",      email: "rahul.m@trapo.co" },
};

// Users-management roster
const USERS = [
  { id: "u1", name: "Ethan Lee",       email: "ethan.lee@trapo.co",   role: "super_admin", dept: "IT / Admin",            last: "5 min ago",  status: "active",   color: "#7c3aed", initials: "EL" },
  { id: "u2", name: "Nadia Hassan",    email: "nadia.h@trapo.co",     role: "ops_manager", dept: "Operations",            last: "2 min ago",  status: "active",   color: "#0d9488", initials: "NH" },
  { id: "u3", name: "Aisyah Rahman",   email: "aisyah.r@trapo.co",    role: "ops_staff",   dept: "Fulfillment",           last: "12 min ago", status: "active",   color: "#2563eb", initials: "AR" },
  { id: "u4", name: "Marcus Tan",      email: "marcus.t@trapo.co",    role: "ops_staff",   dept: "Fulfillment",           last: "1 hour ago", status: "active",   color: "#1d4ed8", initials: "MT" },
  { id: "u5", name: "Priya Nair",      email: "priya.n@trapo.co",     role: "ops_staff",   dept: "Warranty",              last: "23 min ago", status: "active",   color: "#9333ea", initials: "PN" },
  { id: "u6", name: "Daniel Wong",     email: "daniel.w@trapo.co",    role: "ops_staff",   dept: "Logistics",             last: "4 min ago",  status: "active",   color: "#d97706", initials: "DW" },
  { id: "u7", name: "Siti Kamarudin",  email: "siti.k@trapo.co",      role: "ops_staff",   dept: "Customer Experience",   last: "Just now",   status: "active",   color: "#db2777", initials: "SK" },
  { id: "u8", name: "Jason Lim",       email: "jason.l@trapo.co",     role: "ops_staff",   dept: "Installations",         last: "2 hours ago",status: "active",   color: "#16a34a", initials: "JL" },
  { id: "u9", name: "Faridah Yusof",   email: "faridah.y@trapo.co",   role: "ops_staff",   dept: "Customer Experience",   last: "38 min ago", status: "active",   color: "#ea580c", initials: "FY" },
  { id: "u10",name: "Rahul Menon",     email: "rahul.m@trapo.co",     role: "viewer",      dept: "Finance",               last: "3 days ago", status: "active",   color: "#71717a", initials: "RM" },
  { id: "u11",name: "Clara Voon",      email: "clara.v@trapo.co",     role: "ops_staff",   dept: "Logistics",             last: "Pending",    status: "invited",  color: "#0891b2", initials: "CV" },
  { id: "u12",name: "Hafiz Othman",    email: "hafiz.o@trapo.co",     role: "ops_manager", dept: "Operations",            last: "Pending",    status: "invited",  color: "#0d9488", initials: "HO" },
  { id: "u13",name: "Lim Chee Kong",   email: "cheekong.l@trapo.co",  role: "ops_staff",   dept: "Fulfillment",           last: "16 days ago",status: "disabled", color: "#a1a1aa", initials: "LK" },
];

// Audit log
const AUDIT = [
  { id: "a1",  actor: "u1",  type: "rule",        action: "changed SLA threshold on \u201cUnfulfilled paid orders\u201d", detail: "from 24h to 48h", time: "Today, 14:32", ip: "203.82.45.11" },
  { id: "a2",  actor: "u2",  type: "assignment",  action: "reassigned order TRP-48170", detail: "to Warehouse Team", time: "Today, 14:18", ip: "203.82.45.09" },
  { id: "a3",  actor: "ai",  type: "ai",          action: "generated a customer reply for TRP-48201", detail: "drafted via OpsPilot AI", time: "Today, 13:55", ip: "system" },
  { id: "a4",  actor: "u6",  type: "status",      action: "marked TRP-48197 as escalated", detail: "Missing Tracking \u2192 Logistics", time: "Today, 13:40", ip: "210.19.7.88" },
  { id: "a5",  actor: "u1",  type: "user",        action: "invited a new user", detail: "clara.v@trapo.co as Ops Staff", time: "Today, 12:10", ip: "203.82.45.11" },
  { id: "a6",  actor: "u2",  type: "rule",        action: "enabled rule", detail: "\u201cReturn request unactioned\u201d", time: "Today, 11:47", ip: "203.82.45.09" },
  { id: "a7",  actor: "u5",  type: "status",      action: "approved warranty claim TRP-48188", detail: "replacement dispatched", time: "Today, 11:20", ip: "118.99.41.2" },
  { id: "a8",  actor: "system", type: "integration", action: "J&T Express webhook failed", detail: "tracking write-back error, retried 3\u00d7", time: "Today, 10:58", ip: "system" },
  { id: "a9",  actor: "u1",  type: "user",        action: "changed role for Hafiz Othman", detail: "Ops Staff \u2192 Ops Manager", time: "Today, 10:33", ip: "203.82.45.11" },
  { id: "a10", actor: "ai",  type: "ai",          action: "auto-classified warranty claim TRP-47998", detail: "categorised as hardware defect", time: "Today, 09:51", ip: "system" },
  { id: "a11", actor: "u3",  type: "auth",        action: "signed in", detail: "from Shah Alam, MY", time: "Today, 09:02", ip: "175.140.12.6" },
  { id: "a12", actor: "u2",  type: "assignment",  action: "assigned TRP-48155 to Marcus Tan", detail: "Payment Mismatch", time: "Yesterday, 18:44", ip: "203.82.45.09" },
  { id: "a13", actor: "u1",  type: "integration", action: "reconnected FPX payment gateway", detail: "OAuth token refreshed", time: "Yesterday, 17:12", ip: "203.82.45.11" },
  { id: "a14", actor: "u13", type: "auth",        action: "account disabled", detail: "by Super Admin (offboarding)", time: "Yesterday, 16:05", ip: "system" },
  { id: "a15", actor: "u2",  type: "rule",        action: "lowered priority on \u201cMissing tracking\u201d rule", detail: "High \u2192 Medium", time: "Yesterday, 15:30", ip: "203.82.45.09" },
  { id: "a16", actor: "ai",  type: "ai",          action: "surfaced 8 new exceptions to the queue", detail: "morning batch evaluation", time: "Yesterday, 08:00", ip: "system" },
];
const AUDIT_TYPE = {
  rule:        { label: "Rule",        icon: "sliders", color: "#7c3aed", bg: "#f5f3ff" },
  assignment:  { label: "Assignment",  icon: "user",    color: "#0d9488", bg: "#f0fdfa" },
  ai:          { label: "AI",          icon: "sparkles",color: "#0891b2", bg: "#ecfeff" },
  status:      { label: "Status",      icon: "flag",    color: "#ea580c", bg: "#fff7ed" },
  user:        { label: "User",        icon: "users",   color: "#2563eb", bg: "#eff6ff" },
  integration: { label: "Integration", icon: "plug",    color: "#dc2626", bg: "#fef2f2" },
  auth:        { label: "Auth",        icon: "lock",    color: "#52525b", bg: "#f4f4f5" },
};

// Integrations
const INTEGRATIONS = [
  { id: "i1", name: "J&T Express",        cat: "Courier",       desc: "Shipping labels, pickups & tracking write-back.", status: "error",        sync: "Failed 1h ago", letter: "JT", color: "#dc2626" },
  { id: "i2", name: "FPX Payment Gateway",cat: "Payments",      desc: "Malaysian online banking payment capture.",        status: "connected",    sync: "Synced 2 min ago", letter: "FP", color: "#16a34a" },
  { id: "i3", name: "Shopify Storefront", cat: "E-commerce",    desc: "Order, customer & catalogue sync.",                status: "connected",    sync: "Synced 5 min ago", letter: "SH", color: "#16a34a" },
  { id: "i4", name: "Warehouse WMS",      cat: "Fulfillment",   desc: "Stock levels, pick lists & dispatch events.",      status: "connected",    sync: "Synced 1 min ago", letter: "WM", color: "#16a34a" },
  { id: "i5", name: "WhatsApp Business",  cat: "Messaging",     desc: "Outbound customer replies & notifications.",       status: "connected",    sync: "Synced 8 min ago", letter: "WA", color: "#16a34a" },
  { id: "i6", name: "Xero Accounting",    cat: "Finance",       desc: "Invoice & refund reconciliation.",                 status: "disconnected", sync: "Not connected", letter: "XE", color: "#71717a" },
];
const INTEG_STATUS = {
  connected:    { label: "Connected",    color: "#15803d", bg: "#f0fdf4", dot: "#22c55e" },
  error:        { label: "Action needed",color: "#b91c1c", bg: "#fef2f2", dot: "#ef4444" },
  disconnected: { label: "Disconnected", color: "#52525b", bg: "#f4f4f5", dot: "#a1a1aa" },
};

// My Tasks (for Ops Staff)
const TASKS = [
  { id: "t1", title: "Verify warehouse stock & dispatch TRP-48201", order: "TRP-48201", priority: "high",   due: "Due in 2h",   status: "in_progress", by: "u2", note: "Honda City HEX II — payment cleared, awaiting fulfillment" },
  { id: "t2", title: "Pull AWB and send tracking for TRP-48197",    order: "TRP-48197", priority: "high",   due: "Overdue 1h",  status: "todo",        by: "u2", note: "J&T webhook failed — manual tracking required" },
  { id: "t3", title: "Confirm courier pickup window — TRP-48054",   order: "TRP-48054", priority: "medium", due: "Due today",   status: "in_progress", by: "u6", note: "Tesla-fit set, public holiday backlog" },
  { id: "t4", title: "Reconcile payment mismatch on TRP-48155",     order: "TRP-48155", priority: "medium", due: "Due tomorrow",status: "todo",        by: "u2", note: "RM20 short after double discount" },
  { id: "t5", title: "Offer silver finish alternative — TRP-48142", order: "TRP-48142", priority: "low",    due: "Due in 2 days",status: "todo",       by: "u2", note: "Carbon out of stock, customer awaiting choice" },
  { id: "t6", title: "Resend tracking SMS for TRP-48098",           order: "TRP-48098", priority: "low",    due: "Done",        status: "done",        by: "u7", note: "SMS gateway failure — resolved" },
];
const TASK_STATUS = {
  todo:        { label: "To do",       color: "#52525b", bg: "#f4f4f5", dot: "#a1a1aa" },
  in_progress: { label: "In progress", color: "#0f766e", bg: "#f0fdfa", dot: "#14b8a6" },
  done:        { label: "Done",        color: "#15803d", bg: "#f0fdf4", dot: "#22c55e" },
};

function userById(id) {
  if (id === "ai") return { name: "OpsPilot AI", initials: "AI", color: "#0891b2", ai: true };
  if (id === "system") return { name: "System", initials: "SY", color: "#a1a1aa", system: true };
  return USERS.find(u => u.id === id) || { name: "Unknown", initials: "?", color: "#a1a1aa" };
}

Object.assign(window, { ROLES, NAV_ALL, ROLE_NAV, PERMS, ROLE_USER, USERS, AUDIT, AUDIT_TYPE, INTEGRATIONS, INTEG_STATUS, TASKS, TASK_STATUS, userById });
