// Mock data for the multi-tenant SaaS prototype.
// Thai UI labels, English code/db fields.

const TENANTS = [
  {
    id: "t_abc",
    tenant_code: "ABC",
    company_name: "ABC Manufacturing Co., Ltd.",
    company_short: "ABC Manufacturing",
    contact_person: "คุณสมชาย ใจดี",
    contact_email: "somchai@abc-mfg.co.th",
    contact_phone: "+66 2 555 1200",
    service_start_date: "2025-04-01",
    service_expiry_date: "2026-03-31",
    service_status: "active",
    database_type: "separate_schema",
    database_name: "raci_saas_main",
    schema_name: "tenant_abc",
    plan: "Business",
    seats: 80,
    created_at: "2025-04-01",
    last_login_at: "2026-05-22 09:14",
    industry: "การผลิต",
    accent: "indigo",
    usage: { users:54, active_users:48, divisions:5, departments:14, positions:32, processes:24, tasks:312, storage_gb: 6.4 },
  },
  {
    id: "t_grg",
    tenant_code: "GRG",
    company_name: "Green Retail Group Co., Ltd.",
    company_short: "Green Retail Group",
    contact_person: "คุณวรรณา รักษ์โลก",
    contact_email: "wanna@greenretail.co.th",
    contact_phone: "+66 2 555 2233",
    service_start_date: "2025-07-15",
    service_expiry_date: "2026-07-14",
    service_status: "active",
    database_type: "separate_database",
    database_name: "raci_grg_prod",
    schema_name: "public",
    plan: "Enterprise",
    seats: 200,
    created_at: "2025-07-15",
    last_login_at: "2026-05-22 11:38",
    industry: "ค้าปลีก",
    accent: "emerald",
    usage: { users:142, active_users:128, divisions:7, departments:22, positions:55, processes:38, tasks:614, storage_gb: 14.8 },
  },
  {
    id: "t_dsc",
    tenant_code: "DSC",
    company_name: "Demo Suspended Company Co., Ltd.",
    company_short: "Demo Suspended Co.",
    contact_person: "คุณภาคิน ทดสอบ",
    contact_email: "pakin@demo-susp.co.th",
    contact_phone: "+66 2 555 9090",
    service_start_date: "2024-12-01",
    service_expiry_date: "2025-11-30",
    service_status: "suspended",
    database_type: "logical_partition",
    database_name: "raci_saas_main",
    schema_name: "public",
    plan: "Starter",
    seats: 20,
    created_at: "2024-12-01",
    last_login_at: "2025-11-25 16:01",
    industry: "บริการ",
    accent: "amber",
    usage: { users:12, active_users:0, divisions:3, departments:6, positions:14, processes:9, tasks:88, storage_gb: 1.1 },
    suspend_reason: "ค้างชำระค่าบริการเกิน 30 วัน",
  },
  {
    id: "t_nva",
    tenant_code: "NVA",
    company_name: "Northwave Logistics Public Co., Ltd.",
    company_short: "Northwave Logistics",
    contact_person: "คุณนภัส คลื่นเหนือ",
    contact_email: "napas@northwave.co.th",
    contact_phone: "+66 2 555 7474",
    service_start_date: "2025-09-01",
    service_expiry_date: "2026-08-31",
    service_status: "active",
    database_type: "separate_schema",
    database_name: "raci_saas_main",
    schema_name: "tenant_nva",
    plan: "Business",
    seats: 120,
    created_at: "2025-09-01",
    last_login_at: "2026-05-21 18:22",
    industry: "ขนส่ง",
    accent: "sky",
    usage: { users:86, active_users:74, divisions:6, departments:18, positions:41, processes:31, tasks:402, storage_gb: 9.2 },
  },
  {
    id: "t_pbc",
    tenant_code: "PBC",
    company_name: "Pacific Bank Consulting Co., Ltd.",
    company_short: "Pacific Bank Consulting",
    contact_person: "คุณกาญจน์ ภัทรพงศ์",
    contact_email: "kan@pbc.co.th",
    contact_phone: "+66 2 555 1122",
    service_start_date: "2024-10-01",
    service_expiry_date: "2025-09-30",
    service_status: "inactive",
    database_type: "logical_partition",
    database_name: "raci_saas_main",
    schema_name: "public",
    plan: "Starter",
    seats: 25,
    created_at: "2024-10-01",
    last_login_at: "2025-09-12 10:11",
    industry: "ที่ปรึกษา",
    accent: "rose",
    usage: { users:8, active_users:0, divisions:2, departments:4, positions:9, processes:6, tasks:32, storage_gb: 0.4 },
  },
];

const TENANT_ADMIN_USERS = {
  t_abc: { full_name:"ธนพร อัศวิน", email:"thanaporn@abc-mfg.co.th", employee_code:"ABC-0001", last_login_at:"2026-05-22 09:14" },
  t_grg: { full_name:"ปริญญา เกียรติศักดิ์", email:"prinya@greenretail.co.th", employee_code:"GRG-0001", last_login_at:"2026-05-22 11:38" },
  t_dsc: { full_name:"ภาคิน ทดสอบ", email:"pakin@demo-susp.co.th", employee_code:"DSC-0001", last_login_at:"2025-11-25 16:01" },
  t_nva: { full_name:"นภัส คลื่นเหนือ", email:"napas@northwave.co.th", employee_code:"NVA-0001", last_login_at:"2026-05-21 18:22" },
  t_pbc: { full_name:"กาญจน์ ภัทรพงศ์", email:"kan@pbc.co.th", employee_code:"PBC-0001", last_login_at:"2025-09-12 10:11" },
};

// ---------- Tenant ABC's client-company data (this is the "active" data we render in workspace) ----------

const DIVISIONS = [
  { id:"d1", name:"Finance & Accounting", short:"FIN" },
  { id:"d2", name:"Sales & Marketing", short:"S&M" },
  { id:"d3", name:"Operations", short:"OPS" },
  { id:"d4", name:"Human Resources", short:"HR" },
  { id:"d5", name:"Information Technology", short:"IT" },
];

const DEPARTMENTS = [
  { id:"dp1", division_id:"d1", name:"Accounting", short:"AC" },
  { id:"dp2", division_id:"d1", name:"Tax", short:"TX" },
  { id:"dp3", division_id:"d1", name:"Treasury", short:"TR" },
  { id:"dp4", division_id:"d2", name:"Sales", short:"SL" },
  { id:"dp5", division_id:"d2", name:"Marketing", short:"MK" },
  { id:"dp6", division_id:"d3", name:"Procurement", short:"PC" },
  { id:"dp7", division_id:"d3", name:"Warehouse", short:"WH" },
  { id:"dp8", division_id:"d4", name:"HR Admin", short:"HA" },
  { id:"dp9", division_id:"d4", name:"Recruiting", short:"RC" },
  { id:"dp10", division_id:"d5", name:"IT Support", short:"IS" },
  { id:"dp11", division_id:"d5", name:"IT Security", short:"SC" },
];

// position_level: officer / senior / manager / director
const POSITIONS = [
  // Accounting
  { id:"p1", division_id:"d1", department_id:"dp1", name:"Accounting Officer", level:"officer" },
  { id:"p2", division_id:"d1", department_id:"dp1", name:"Senior Accountant", level:"senior" },
  { id:"p3", division_id:"d1", department_id:"dp1", name:"Accounting Manager", level:"manager" },
  // Tax
  { id:"p4", division_id:"d1", department_id:"dp2", name:"Tax Officer", level:"officer" },
  { id:"p5", division_id:"d1", department_id:"dp2", name:"Tax Manager", level:"manager" },
  // Treasury
  { id:"p6", division_id:"d1", department_id:"dp3", name:"Treasury Officer", level:"officer" },
  { id:"p7", division_id:"d1", department_id:"dp3", name:"Treasury Manager", level:"manager" },
  // Sales
  { id:"p8", division_id:"d2", department_id:"dp4", name:"Sales Executive", level:"officer" },
  { id:"p9", division_id:"d2", department_id:"dp4", name:"Sales Manager", level:"manager" },
  // Marketing
  { id:"p10", division_id:"d2", department_id:"dp5", name:"Marketing Officer", level:"officer" },
  { id:"p11", division_id:"d2", department_id:"dp5", name:"Marketing Manager", level:"manager" },
  // Procurement
  { id:"p12", division_id:"d3", department_id:"dp6", name:"Procurement Officer", level:"officer" },
  { id:"p13", division_id:"d3", department_id:"dp6", name:"Procurement Manager", level:"manager" },
  // Warehouse
  { id:"p14", division_id:"d3", department_id:"dp7", name:"Warehouse Officer", level:"officer" },
  // HR Admin
  { id:"p15", division_id:"d4", department_id:"dp8", name:"HR Officer", level:"officer" },
  { id:"p16", division_id:"d4", department_id:"dp8", name:"HR Manager", level:"manager" },
  // Recruiting
  { id:"p17", division_id:"d4", department_id:"dp9", name:"Recruiter", level:"officer" },
  // IT Support
  { id:"p18", division_id:"d5", department_id:"dp10", name:"IT Support Officer", level:"officer" },
  { id:"p19", division_id:"d5", department_id:"dp10", name:"IT Manager", level:"manager" },
  // IT Security
  { id:"p20", division_id:"d5", department_id:"dp11", name:"Security Officer", level:"officer" },
];

const USERS = [
  { id:"u1", employee_code:"ABC-0010", full_name:"กัญญา วัฒนากร", email:"kanya.w@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p1"] },
  { id:"u2", employee_code:"ABC-0011", full_name:"เอกชัย พิบูลสุข", email:"ekkachai.p@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p2"] },
  { id:"u3", employee_code:"ABC-0012", full_name:"สุชาดา ศรีอัมพร", email:"suchada.s@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p3"] },
  { id:"u4", employee_code:"ABC-0013", full_name:"ภาณุพงศ์ ตรีรัตน์", email:"panupong.t@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p4"] },
  { id:"u5", employee_code:"ABC-0014", full_name:"จิรัฏฐ์ ชยานนท์", email:"jirat.c@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p5"] },
  { id:"u6", employee_code:"ABC-0015", full_name:"ธิดารัตน์ มงคล", email:"thida.m@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p6"] },
  { id:"u7", employee_code:"ABC-0016", full_name:"พรเทพ พิทักษ์", email:"pornthep.p@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p7"] },
  { id:"u8", employee_code:"ABC-0017", full_name:"นิตยา รุ่งเรือง", email:"nittaya.r@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p8"] },
  { id:"u9", employee_code:"ABC-0018", full_name:"พงศกร สิริชัย", email:"pongsakorn.s@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p9"] },
  { id:"u10", employee_code:"ABC-0019", full_name:"ปวีณา ธาราเงิน", email:"paweena.t@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p10"] },
  { id:"u11", employee_code:"ABC-0020", full_name:"วรพจน์ จิตตเกษม", email:"woraphot.j@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p11"] },
  { id:"u12", employee_code:"ABC-0021", full_name:"อรทัย วงศ์สถิตย์", email:"orathai.w@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p12"] },
  { id:"u13", employee_code:"ABC-0022", full_name:"ชัยภพ เลิศวานิช", email:"chaiyaphop.l@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p13"] },
  { id:"u14", employee_code:"ABC-0023", full_name:"สิรินดา ปิยะวรรณ", email:"sirinda.p@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p14"] },
  { id:"u15", employee_code:"ABC-0024", full_name:"ภัทรพล สมบูรณ์", email:"phattaraphon.s@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p15"] },
  { id:"u16", employee_code:"ABC-0025", full_name:"พิมพ์ชนก ธีรพร", email:"pimchanok.t@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p16"] },
  { id:"u17", employee_code:"ABC-0026", full_name:"กิตติพงษ์ อภิวัฒน์", email:"kittipong.a@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p17"] },
  { id:"u18", employee_code:"ABC-0027", full_name:"ณัฐกานต์ จันทรา", email:"natthakarn.j@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p18"] },
  { id:"u19", employee_code:"ABC-0028", full_name:"ดวงใจ สุริยา", email:"duangjai.s@abc-mfg.co.th", system_role:"manager", status:"active", positions:["p19"] },
  { id:"u20", employee_code:"ABC-0029", full_name:"ธนวัฒน์ พัฒนา", email:"thanawat.p@abc-mfg.co.th", system_role:"employee", status:"active", positions:["p20"] },
  // unassigned employees
  { id:"u21", employee_code:"ABC-0030", full_name:"ศิรินภา ภักดี", email:"sirinapha.p@abc-mfg.co.th", system_role:"employee", status:"active", positions:[] },
  { id:"u22", employee_code:"ABC-0031", full_name:"กฤษฎา รัตนกูล", email:"krisada.r@abc-mfg.co.th", system_role:"employee", status:"inactive", positions:[] },
];

// Processes ----------------------------------------------------------------
const MAIN_PROCESSES = [
  { id:"mp1", name:"Finance & Accounting Closing", division_id:"d1", order:1, status:"active" },
  { id:"mp2", name:"Procurement", division_id:"d3", order:2, status:"active" },
  { id:"mp3", name:"Human Resources", division_id:"d4", order:3, status:"active" },
  { id:"mp4", name:"IT Support", division_id:"d5", order:4, status:"active" },
  { id:"mp5", name:"Sales & Customer", division_id:"d2", order:5, status:"active" },
];

const PROCESSES = [
  // mp1
  { id:"pr1", main_process_id:"mp1", name:"Accounts Payable", order:1 },
  { id:"pr2", main_process_id:"mp1", name:"Tax Compliance", order:2 },
  { id:"pr3", main_process_id:"mp1", name:"Bank Reconciliation", order:3 },
  // mp2
  { id:"pr4", main_process_id:"mp2", name:"Purchase Request", order:1 },
  { id:"pr5", main_process_id:"mp2", name:"Supplier Management", order:2 },
  // mp3
  { id:"pr6", main_process_id:"mp3", name:"Payroll", order:1 },
  { id:"pr7", main_process_id:"mp3", name:"Recruitment", order:2 },
  // mp4
  { id:"pr8", main_process_id:"mp4", name:"User Access Management", order:1 },
  { id:"pr9", main_process_id:"mp4", name:"Incident Management", order:2 },
  // mp5
  { id:"pr10", main_process_id:"mp5", name:"Customer Onboarding", order:1 },
];

// Sub-processes with RACI assignments embedded
// status codes: blank, P, A, C, S
const SUBPROCESSES = [
  // Accounts Payable
  { id:"sp1", main_process_id:"mp1", process_id:"pr1", name:"Review supplier invoices", frequency:"daily", due_day:"ทุกวันทำการ", R:"p1", A:"p3", C:["p12"], I:["p7"] },
  { id:"sp2", main_process_id:"mp1", process_id:"pr1", name:"Record AP voucher", frequency:"daily", due_day:"ภายในวันถัดไป", R:"p2", A:"p3", C:["p1"], I:["p7"] },
  { id:"sp3", main_process_id:"mp1", process_id:"pr1", name:"Prepare payment batch", frequency:"weekly", due_day:"ทุกวันศุกร์", R:"p6", A:"p7", C:["p3"], I:["p3","p13"] },
  // Tax
  { id:"sp4", main_process_id:"mp1", process_id:"pr2", name:"Prepare monthly VAT return (ภ.พ.30)", frequency:"monthly", due_day:"วันที่ 15", R:"p4", A:"p5", C:["p2"], I:["p3"] },
  { id:"sp5", main_process_id:"mp1", process_id:"pr2", name:"Prepare withholding tax return (ภ.ง.ด.3,53)", frequency:"monthly", due_day:"วันที่ 7", R:"p4", A:"p5", C:["p2","p6"], I:["p3"] },
  { id:"sp6", main_process_id:"mp1", process_id:"pr2", name:"Reconcile input VAT", frequency:"monthly", due_day:"วันที่ 20", R:"p4", A:"p5", C:["p1","p2"], I:["p3"] },
  // Bank Recon
  { id:"sp7", main_process_id:"mp1", process_id:"pr3", name:"Daily bank reconciliation", frequency:"daily", due_day:"ทุกวันทำการ", R:"p6", A:"p7", C:["p2"], I:["p3"] },
  { id:"sp8", main_process_id:"mp1", process_id:"pr3", name:"Monthly cash position report", frequency:"monthly", due_day:"วันที่ 5", R:"p6", A:"p7", C:["p3"], I:["p3"] },
  // Procurement
  { id:"sp9", main_process_id:"mp2", process_id:"pr4", name:"Review purchase request", frequency:"daily", due_day:"ทุกวันทำการ", R:"p12", A:"p13", C:["p1"], I:["p14"] },
  { id:"sp10", main_process_id:"mp2", process_id:"pr4", name:"Approve purchase order", frequency:"daily", due_day:"ทุกวันทำการ", R:"p12", A:"p13", C:["p3"], I:["p14","p1"] },
  { id:"sp11", main_process_id:"mp2", process_id:"pr4", name:"Receive goods documentation", frequency:"daily", due_day:"วันรับสินค้า", R:"p14", A:"p13", C:[], I:["p1"] },
  { id:"sp12", main_process_id:"mp2", process_id:"pr5", name:"Supplier evaluation review", frequency:"quarterly", due_day:"สิ้นไตรมาส", R:"p12", A:"p13", C:["p3"], I:["p11"], track_status:false },
  // HR
  { id:"sp13", main_process_id:"mp3", process_id:"pr6", name:"Prepare monthly payroll", frequency:"monthly", due_day:"วันที่ 23", R:"p15", A:"p16", C:["p2"], I:["p3","p19"] },
  { id:"sp14", main_process_id:"mp3", process_id:"pr6", name:"Review employee attendance", frequency:"monthly", due_day:"วันที่ 20", R:"p15", A:"p16", C:[], I:["p3"] },
  { id:"sp15", main_process_id:"mp3", process_id:"pr6", name:"Approve payroll summary", frequency:"monthly", due_day:"วันที่ 25", R:"p16", A:"p3", C:["p2"], I:["p7"] },
  { id:"sp16", main_process_id:"mp3", process_id:"pr7", name:"Open new requisition", frequency:"ad-hoc", due_day:"ตามคำขอ", R:"p17", A:"p16", C:["p11"], I:["p3"], track_status:false },
  // IT
  { id:"sp17", main_process_id:"mp4", process_id:"pr8", name:"Create new user access", frequency:"ad-hoc", due_day:"ภายใน 1 วันทำการ", R:"p18", A:"p19", C:["p20"], I:["p15"] },
  { id:"sp18", main_process_id:"mp4", process_id:"pr8", name:"Quarterly access rights review", frequency:"quarterly", due_day:"สิ้นไตรมาส", R:"p20", A:"p19", C:["p3"], I:["p16"] },
  { id:"sp19", main_process_id:"mp4", process_id:"pr8", name:"Disable resigned employee access", frequency:"ad-hoc", due_day:"วันสุดท้ายการทำงาน", R:"p18", A:"p19", C:["p15"], I:["p3","p16"] },
  { id:"sp20", main_process_id:"mp4", process_id:"pr9", name:"Incident triage & resolution", frequency:"daily", due_day:"ภายใน 4 ชม.", R:"p18", A:"p19", C:["p20"], I:["p3"] },
  // Sales
  { id:"sp21", main_process_id:"mp5", process_id:"pr10", name:"New customer KYC review", frequency:"daily", due_day:"ภายใน 2 วัน", R:"p8", A:"p9", C:["p3","p4"], I:["p10"] },
];

// task_instances: keyed by sub_process_id for the current period
const STATUS_NAMES = {
  blank: "ยังไม่ถึงกำหนด",
  P: "รอจัดทำ",
  A: "รอตรวจสอบ",
  C: "มี Comment ให้แก้ไข",
  S: "สำเร็จ",
};

const today = "2026-05-22";
// Build current-month task instances for each sub-process
const TASKS_INIT = [
  { sub_process_id:"sp1",  status:"S",     due_date:"2026-05-22", updated:"2026-05-22 08:30", note:"จัดทำและอนุมัติเรียบร้อย" },
  { sub_process_id:"sp2",  status:"A",     due_date:"2026-05-22", updated:"2026-05-22 09:12" },
  { sub_process_id:"sp3",  status:"P",     due_date:"2026-05-22", updated:"2026-05-21 17:40" },
  { sub_process_id:"sp4",  status:"C",     due_date:"2026-05-15", updated:"2026-05-15 13:20" },
  { sub_process_id:"sp5",  status:"S",     due_date:"2026-05-07", updated:"2026-05-07 11:00" },
  { sub_process_id:"sp6",  status:"P",     due_date:"2026-05-20", updated:"2026-05-19 16:50", overdue:true },
  { sub_process_id:"sp7",  status:"S",     due_date:"2026-05-22", updated:"2026-05-22 09:50" },
  { sub_process_id:"sp8",  status:"S",     due_date:"2026-05-05", updated:"2026-05-05 10:11" },
  { sub_process_id:"sp9",  status:"A",     due_date:"2026-05-22", updated:"2026-05-22 10:31" },
  { sub_process_id:"sp10", status:"P",     due_date:"2026-05-22", updated:"2026-05-22 08:00" },
  { sub_process_id:"sp11", status:"S",     due_date:"2026-05-21", updated:"2026-05-21 15:22" },
  { sub_process_id:"sp12", status:"blank", due_date:"2026-06-30", updated:"" },
  { sub_process_id:"sp13", status:"P",     due_date:"2026-05-23", updated:"" },
  { sub_process_id:"sp14", status:"A",     due_date:"2026-05-20", updated:"2026-05-20 17:00", overdue:true },
  { sub_process_id:"sp15", status:"blank", due_date:"2026-05-25", updated:"" },
  { sub_process_id:"sp16", status:"S",     due_date:"2026-05-12", updated:"2026-05-12 14:00" },
  { sub_process_id:"sp17", status:"S",     due_date:"2026-05-19", updated:"2026-05-19 09:30" },
  { sub_process_id:"sp18", status:"blank", due_date:"2026-06-30", updated:"" },
  { sub_process_id:"sp19", status:"C",     due_date:"2026-05-22", updated:"2026-05-22 09:00" },
  { sub_process_id:"sp20", status:"A",     due_date:"2026-05-22", updated:"2026-05-22 11:14" },
  { sub_process_id:"sp21", status:"P",     due_date:"2026-05-22", updated:"" },
];

// Initial comment history per task
const COMMENTS_INIT = {
  sp4: [
    { id:"c1", type:"correction", author_pos:"p5", author_name:"จิรัฏฐ์ ชยานนท์", text:"กรุณาแนบเอกสารใบกำกับภาษีฉบับสมบูรณ์ของเดือนนี้ และตรวจสอบรายการ Output VAT ลำดับที่ 14 อีกครั้ง", at:"2026-05-15 13:20", task_date:"2026-05-15" },
  ],
  sp19: [
    { id:"c2", type:"correction", author_pos:"p19", author_name:"ดวงใจ สุริยา", text:"กรุณาตรวจสอบบัญชีที่ปิดในระบบ AD ว่าครบถ้วนหรือไม่ มี 2 บัญชียังเข้าระบบได้", at:"2026-05-22 09:00", task_date:"2026-05-22" },
  ],
  sp1: [
    { id:"c3", type:"system_note", author_name:"System", text:"เปลี่ยนสถานะ blank → P", at:"2026-05-22 08:00", task_date:"2026-05-22" },
    { id:"c4", type:"system_note", author_name:"System", text:"เปลี่ยนสถานะ P → A โดย กัญญา วัฒนากร", at:"2026-05-22 08:15", task_date:"2026-05-22" },
    { id:"c5", type:"system_note", author_name:"System", text:"เปลี่ยนสถานะ A → S โดย สุชาดา ศรีอัมพร", at:"2026-05-22 08:30", task_date:"2026-05-22" },
  ],
};

// Audit log (super admin level + tenant level)
const AUDIT_LOG_INIT = [
  { id:"a1", scope:"super",  tenant_id:"t_dsc", action:"suspend",      reason:"ค้างชำระค่าบริการเกิน 30 วัน", performed_by:"SaaS Admin", at:"2025-11-26 09:14" },
  { id:"a2", scope:"super",  tenant_id:"t_grg", action:"activate",     reason:"เปิดใช้งานหลังต่อสัญญา",       performed_by:"SaaS Admin", at:"2025-07-15 10:02" },
  { id:"a3", scope:"super",  tenant_id:"t_nva", action:"create",       reason:"เปิดบริการลูกค้าใหม่",         performed_by:"SaaS Admin", at:"2025-09-01 08:30" },
  { id:"a4", scope:"super",  tenant_id:"t_pbc", action:"deactivate",   reason:"ลูกค้ายกเลิกสัญญา",            performed_by:"SaaS Admin", at:"2025-09-13 11:40" },
  { id:"a5", scope:"super",  tenant_id:"t_abc", action:"support_access",reason:"ช่วย reset master data",     performed_by:"SaaS Admin", at:"2026-04-12 16:22" },
  // tenant ABC level
  { id:"a6", scope:"tenant", tenant_id:"t_abc", action:"status_change", reason:"P → A (sp2 Record AP voucher)", performed_by:"กัญญา วัฒนากร", at:"2026-05-22 09:12" },
  { id:"a7", scope:"tenant", tenant_id:"t_abc", action:"status_change", reason:"A → C (sp4 VAT return) มี comment ให้แก้ไข", performed_by:"จิรัฏฐ์ ชยานนท์", at:"2026-05-15 13:20" },
  { id:"a8", scope:"tenant", tenant_id:"t_abc", action:"delete",        reason:"ลบ Sub-process ที่ไม่ใช้แล้ว", performed_by:"ธนพร อัศวิน", at:"2026-04-10 11:08" },
  { id:"a9", scope:"tenant", tenant_id:"t_abc", action:"create",        reason:"สร้าง Sub-process ใหม่ - บันทึก KYC", performed_by:"ธนพร อัศวิน", at:"2026-04-15 14:00" },
];

// Demo accounts shown in login screen
const DEMO_ACCOUNTS = [
  { label:"Super Admin (SaaS Owner)", tenant_code:"", email:"superadmin@raciworks.io", role:"super_admin", color:"bg-indigo-950" },
  { label:"ABC · Company Admin",      tenant_code:"ABC", email:"thanaporn@abc-mfg.co.th", role:"admin", color:"bg-indigo-600" },
  { label:"ABC · Manager (สุชาดา)",   tenant_code:"ABC", email:"suchada.s@abc-mfg.co.th", role:"manager", user_id:"u3", color:"bg-violet-600" },
  { label:"ABC · Employee (กัญญา)",   tenant_code:"ABC", email:"kanya.w@abc-mfg.co.th", role:"employee", user_id:"u1", color:"bg-blue-600" },
  { label:"ABC · Viewer (ผู้บริหาร)",  tenant_code:"ABC", email:"executive@abc-mfg.co.th", role:"viewer", color:"bg-slate-600" },
  { label:"DSC · ทดสอบ Suspend",      tenant_code:"DSC", email:"pakin@demo-susp.co.th", role:"admin", color:"bg-amber-600" },
];

// Generate task history per sub-process — many instances by date based on frequency.
// "Today" is 2026-05-22 for the demo.
const TODAY = new Date("2026-05-22T00:00:00");
const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;
const isWorkday = (d) => d.getDay() !== 0 && d.getDay() !== 6;

// Seeded RNG for deterministic mock data
let _seed = 7;
const rand = () => { _seed = (_seed * 9301 + 49297) % 233280; return _seed / 233280; };
const pickStatus = (isPast, isToday, recent=false) => {
  if (!isPast && !isToday) return "blank";
  if (isToday) {
    const r = rand();
    if (r < 0.18) return "S";
    if (r < 0.40) return "A";
    if (r < 0.60) return "P";
    if (r < 0.72) return "C";
    return "S";
  }
  // past days — mostly S
  const r = rand();
  if (recent && r < 0.08) return "C"; // some recent rework
  if (r < 0.92) return "S";
  if (r < 0.97) return "C";
  return "A";
};

// Build history per sub-process — array of { date, status, prepared_by, approved_by, updated, has_comment }
const buildTaskHistory = () => {
  const out = {};
  const monthsBack = 4; // generate ~4 months for monthly tasks
  SUBPROCESSES.forEach(sp => {
    const rUser = USERS.find(u => u.positions.includes(sp.R));
    const aUser = USERS.find(u => u.positions.includes(sp.A));
    const arr = [];
    if (sp.frequency === "daily") {
      // 30 calendar days back; only workdays
      for (let i = 30; i >= 0; i--) {
        const d = new Date(TODAY); d.setDate(d.getDate() - i);
        if (!isWorkday(d)) continue;
        const isToday = i === 0;
        const isPast = i > 0;
        const recent = i <= 5;
        const status = pickStatus(isPast, isToday, recent);
        const updated = status === "blank" ? "" : `${fmt(d)} ${String(8+Math.floor(rand()*8)).padStart(2,"0")}:${String(Math.floor(rand()*60)).padStart(2,"0")}`;
        arr.push({
          date: fmt(d),
          status,
          updated,
          prepared_by: rUser?.full_name,
          approved_by: status === "S" ? aUser?.full_name : null,
          has_comment: status === "C" || (status === "S" && rand() < 0.1),
        });
      }
    } else if (sp.frequency === "weekly") {
      // last ~10 weeks; due Fridays
      for (let i = 10; i >= 0; i--) {
        const d = new Date(TODAY); d.setDate(d.getDate() - i*7);
        while (d.getDay() !== 5) d.setDate(d.getDate() - 1);
        const isToday = i === 0;
        const status = pickStatus(i > 0, isToday, i<=2);
        arr.push({
          date: fmt(d), status,
          updated: status === "blank" ? "" : `${fmt(d)} 16:${String(Math.floor(rand()*60)).padStart(2,"0")}`,
          prepared_by: rUser?.full_name, approved_by: status === "S" ? aUser?.full_name : null,
          has_comment: status === "C",
        });
      }
    } else if (sp.frequency === "monthly") {
      // last ~6 months
      for (let i = 6; i >= 0; i--) {
        const d = new Date(TODAY); d.setMonth(d.getMonth() - i);
        // pick due day based on the original due_day string roughly = 15
        const m = d.getMonth(), y = d.getFullYear();
        // parse due_day like "วันที่ 15" → 15
        const match = (sp.due_day||"").match(/\d+/); const day = match ? +match[0] : 15;
        const dueDate = new Date(y, m, day);
        const past = dueDate < TODAY;
        const status = past ? (rand() < 0.85 ? "S" : (rand() < 0.5 ? "C" : "A")) : (i===0 ? pickStatus(false, true) : "blank");
        arr.push({
          date: fmt(dueDate), status,
          updated: status === "blank" ? "" : `${fmt(dueDate)} 13:${String(Math.floor(rand()*60)).padStart(2,"0")}`,
          prepared_by: rUser?.full_name, approved_by: status === "S" ? aUser?.full_name : null,
          has_comment: status === "C",
        });
      }
    } else if (sp.frequency === "quarterly") {
      // last 4 quarters
      for (let i = 4; i >= 0; i--) {
        const d = new Date(TODAY); d.setMonth(d.getMonth() - i*3);
        const status = i > 0 ? "S" : "blank";
        arr.push({
          date: fmt(d), status,
          updated: status==="blank" ? "" : `${fmt(d)} 17:00`,
          prepared_by: rUser?.full_name, approved_by: status === "S" ? aUser?.full_name : null,
          has_comment: false,
        });
      }
    } else if (sp.frequency === "ad-hoc") {
      // a handful of past ad-hoc instances
      const cnt = 3 + Math.floor(rand()*4);
      for (let i = cnt; i >= 0; i--) {
        const d = new Date(TODAY); d.setDate(d.getDate() - i*4 - Math.floor(rand()*3));
        const status = i === 0 ? pickStatus(false, true) : "S";
        arr.push({
          date: fmt(d), status,
          updated: status==="blank" ? "" : `${fmt(d)} ${String(9+Math.floor(rand()*7)).padStart(2,"0")}:00`,
          prepared_by: rUser?.full_name, approved_by: status === "S" ? aUser?.full_name : null,
          has_comment: status === "C",
        });
      }
    }
    out[sp.id] = arr;
  });
  return out;
};
const TASK_HISTORY = buildTaskHistory();

// Useful helpers
const byId = (arr, id) => arr.find(x => x.id === id);
const positionDisplay = (id) => {
  const p = byId(POSITIONS, id); if (!p) return "—";
  const dept = byId(DEPARTMENTS, p.department_id);
  return { name: p.name, dept: dept?.name || "", div: byId(DIVISIONS, p.division_id)?.short || "" };
};
const userByPosition = (positionId) => USERS.find(u => u.positions.includes(positionId));

// Status meta
const STATUS_META = {
  blank: { label:"ยังไม่ถึงกำหนด", short:"-",  bg:"bg-slate-100",   text:"text-slate-500",   border:"border-slate-200",   dot:"#94a3b8" },
  P:     { label:"รอจัดทำ",       short:"P",  bg:"bg-blue-50",     text:"text-blue-700",    border:"border-blue-200",    dot:"#2563eb" },
  A:     { label:"รอตรวจสอบ",     short:"A",  bg:"bg-violet-50",   text:"text-violet-700",  border:"border-violet-200",  dot:"#7c3aed" },
  C:     { label:"แก้ไข",         short:"C",  bg:"bg-amber-50",    text:"text-amber-700",   border:"border-amber-200",   dot:"#d97706" },
  S:     { label:"สำเร็จ",        short:"S",  bg:"bg-emerald-50",  text:"text-emerald-700", border:"border-emerald-200", dot:"#059669" },
};

const RACI_META = {
  R: { label:"Responsible · ผู้จัดทำ",      short:"R", bg:"bg-blue-100",    text:"text-blue-700",    ring:"ring-blue-200" },
  A: { label:"Accountable · ผู้ตรวจสอบ",    short:"A", bg:"bg-violet-100",  text:"text-violet-700",  ring:"ring-violet-200" },
  C: { label:"Consulted · ผู้ให้ข้อมูล",     short:"C", bg:"bg-amber-100",   text:"text-amber-700",   ring:"ring-amber-200" },
  I: { label:"Informed · ผู้รับแจ้งข้อมูล",   short:"I", bg:"bg-emerald-100", text:"text-emerald-700", ring:"ring-emerald-200" },
};

Object.assign(window, {
  TENANTS, TENANT_ADMIN_USERS, DIVISIONS, DEPARTMENTS, POSITIONS, USERS,
  MAIN_PROCESSES, PROCESSES, SUBPROCESSES, TASKS_INIT, COMMENTS_INIT, AUDIT_LOG_INIT,
  STATUS_NAMES, STATUS_META, RACI_META, DEMO_ACCOUNTS, byId, positionDisplay, userByPosition,
  TASK_HISTORY, TODAY,
});
