/* SER-OS — Mock data (cases, packages, caskets, add-ons) */

/* Anchor "now" for the demo so seed timestamps stay realistic relative
   to the prototype's notion of today. All date filtering / relative-time
   strings reference MOCK_NOW rather than the wall clock — this keeps the
   demo deterministic and makes the date-range presets behave predictably. */
const MOCK_NOW = new Date("2026-05-18T16:00:00+08:00").getTime();
const _hoursAgo = (h) => new Date(MOCK_NOW - h * 3600 * 1000).toISOString();
const _daysAgo  = (d) => new Date(MOCK_NOW - d * 86400 * 1000).toISOString();

const SEED_CASES = [
  {
    caseNumber: "QT-240518-014",
    deceased: "Tan Ah Kow", contactId: "c001",
    contact: "Sarah Tan", phone: "+65 91234567",
    primaryRelationship: "Daughter",
    religion: "Buddhist", brand: "Fountains Funerals",
    updatedAt: _hoursAgo(4), fd: "John Lim", status: "Working",
    wakeDate: "19 May 2026", wakeEndDate: "20 May 2026", wakeDuration: 2,
    funeralDate: "20 May 2026",
    package: "Blessing Package (HDB)", casket: "Not selected",
    floral: "Not selected", serviceType: "Cremation",
    archived: false,
  },
  {
    /* Second case for Sarah Tan — earlier case for her late mother.
       Provides realistic multi-case prototype data so the Linked Cases
       section in the Contact Details modal can showcase >1 row. */
    caseNumber: "QT-230812-002",
    deceased: "Tan Bee Lian", contactId: "c001",
    contact: "Sarah Tan", phone: "+65 91234567",
    primaryRelationship: "Daughter",
    religion: "Buddhist", brand: "Fountains Funerals",
    updatedAt: _daysAgo(285), fd: "John Lim", status: "Confirmed",
    wakeDate: "10 Aug 2023", wakeEndDate: "12 Aug 2023", wakeDuration: 3,
    funeralDate: "14 Aug 2023",
    package: "Serenity Package (HDB)", casket: "Heritage Oak",
    floral: "Standard Arrangement", serviceType: "Cremation", addons: "2 items",
    archived: false,
  },
  {
    caseNumber: "QT-240517-013",
    deceased: "Mary Lim Siew Hwa", contactId: "c002",
    contact: "David Lim", phone: "+65 82345678",
    religion: "Christian", brand: "Serenity Casket & Funerals",
    updatedAt: _hoursAgo(23), fd: "John Lim", status: "Working",
    wakeDate: "16 May 2026", wakeEndDate: "18 May 2026", wakeDuration: 3,
    funeralDate: "23 May 2026",
    package: "Serenity Package (HDB)", casket: "Safe with Angels (White)",
    floral: "Premium Arrangement", serviceType: "Cremation", addons: "8 items",
    archived: false,
  },
  {
    caseNumber: "QT-240517-011",
    deceased: "Wong Mei Ling", contactId: "c003",
    contact: "Peter Wong", phone: "+65 98765432",
    religion: "Free Thinker", brand: "Serenity Casket & Funerals",
    updatedAt: _daysAgo(1), fd: "John Lim", status: "Working",
    wakeDate: "17 May 2026", wakeEndDate: "18 May 2026", wakeDuration: 2,
    funeralDate: "18 May 2026",
    package: "Straight Cremation", casket: "Safe with Angels (Brown)",
    floral: "Basic Arrangement", serviceType: "Cremation", addons: "1 item",
    archived: true, // archived from active workspace
  },
  {
    caseNumber: "QT-240516-009",
    deceased: "Lim Boon Huat", contactId: "c004",
    contact: "Grace Lim", phone: "+65 87654321",
    religion: "Buddhist", brand: "Fountains Funerals",
    updatedAt: _daysAgo(2), fd: ["John Lim", "Sarah Ong"], status: "Working",
    wakeDate: "18 May 2026", wakeEndDate: "19 May 2026", wakeDuration: 2,
    funeralDate: "19 May 2026",
    package: "Orchid Package (Others)", casket: "Peaceful Symphony (Brown)",
    floral: "Selected", serviceType: "Cremation", addons: "2 items",
    archived: false,
  },
  {
    caseNumber: "QT-240514-007",
    deceased: "Chen Wei Ming", contactId: "c005",
    contact: "Lisa Chen", phone: "+65 92348765",
    religion: "Catholic", brand: "Serenity Casket & Funerals",
    updatedAt: _daysAgo(4), fd: "John Lim", status: "Working",
    wakeDate: null, wakeEndDate: null, wakeDuration: null,
    funeralDate: null,
    package: "Not selected", casket: "Not selected",
    floral: "Not selected", serviceType: "Not decided",
    archived: false,
  },
  {
    caseNumber: "QT-240512-005",
    deceased: "Goh Hock Seng", contactId: "c006",
    contact: "Janet Goh", phone: "+65 94451122",
    religion: "Christian", brand: "Serenity Casket & Funerals",
    updatedAt: _daysAgo(6), fd: "John Lim", status: "Working",
    wakeDate: "14 May 2026", wakeEndDate: "15 May 2026", wakeDuration: 2,
    funeralDate: "15 May 2026",
    package: "Serenity Package (Others)", casket: "Safe with Angels (Brown)",
    floral: "Selected", serviceType: "Cremation", addons: "1 item",
    archived: false,
  },
  {
    caseNumber: "QT-240505-004",
    deceased: "Ng Choon Hwee", contactId: "c007",
    contact: "Patrick Ng", phone: "+65 97786543",
    religion: "Buddhist", brand: "Fountains Funerals",
    updatedAt: _daysAgo(13), fd: "John Lim", status: "Working",
    wakeDate: "6 May 2026", wakeEndDate: "7 May 2026", wakeDuration: 2,
    funeralDate: "7 May 2026",
    package: "Lily Package (HDB)", casket: "Not selected",
    floral: "Not selected", serviceType: "Cremation",
    archived: false,
  },
  {
    caseNumber: "QT-240428-002",
    deceased: "Koh Lai Hua", contactId: "c008",
    contact: "Michelle Koh", phone: "+65 81129988",
    religion: "Christian", brand: "Serenity Casket & Funerals",
    updatedAt: _daysAgo(20), fd: "John Lim", status: "Working",
    wakeDate: "29 Apr 2026", wakeEndDate: "30 Apr 2026", wakeDuration: 2,
    funeralDate: "30 Apr 2026",
    package: "Serenity Package (HDB)", casket: "Solemn Tribute (White)",
    floral: "Premium Arrangement", serviceType: "Cremation", addons: "4 items",
    archived: true,
  },
  {
    caseNumber: "QT-240412-008",
    deceased: "Soh Ah Lian", contactId: "c012",
    contact: "Mei Soh", phone: "+65 90013344",
    religion: "Buddhist", brand: "Fountains Funerals",
    updatedAt: _daysAgo(36), fd: "John Lim", status: "Working",
    wakeDate: "13 Apr 2026", wakeEndDate: "14 Apr 2026", wakeDuration: 2,
    funeralDate: "14 Apr 2026",
    package: "Orchid Package (HDB)", casket: "Peaceful Symphony (Brown)",
    floral: "Basic Arrangement", serviceType: "Cremation", addons: "2 items",
    archived: true,
  },
  {
    caseNumber: "QT-240320-001",
    deceased: "Yeo Boon Keng", contactId: "c013",
    contact: "Yeo Hui Min", phone: "+65 96674422",
    religion: "Catholic", brand: "Serenity Casket & Funerals",
    updatedAt: _daysAgo(59), fd: "John Lim", status: "Cancelled",
    wakeDate: "21 Mar 2026", wakeEndDate: "22 Mar 2026", wakeDuration: 2,
    funeralDate: "22 Mar 2026",
    package: "Serenity Package (HDB)", casket: "Not selected",
    floral: "Not selected", serviceType: "Cremation",
    archived: true,
  },
  {
    caseNumber: "QT-240218-006",
    deceased: "Tay Beng Hock", contactId: "c009",
    contact: "Andrew Tay", phone: "+65 80025566",
    religion: "Buddhist", brand: "Fountains Funerals",
    updatedAt: _daysAgo(89), fd: "John Lim", status: "Working",
    wakeDate: "19 Feb 2026", wakeEndDate: "20 Feb 2026", wakeDuration: 2,
    funeralDate: "20 Feb 2026",
    package: "Lotus Package (HDB)", casket: "Comforting Solace (Brown)",
    floral: "Premium Arrangement", serviceType: "Cremation", addons: "5 items",
    archived: true,
  },

  /* ── Awaiting Signature sample cases ─────────────────────────── */
  {
    caseNumber: "QT-260518-019",
    deceased: "Tan Swee Kiat", contactId: "c014",
    contact: "Jessica Tan", phone: "+65 91123344",
    religion: "Christian", brand: "Serenity Casket & Funerals",
    updatedAt: _hoursAgo(3), fd: ["John Lim", "Michael Tan"], status: "Working",
    wakeDate: "16 May 2026", wakeEndDate: "18 May 2026", wakeDuration: 3,
    funeralDate: "19 May 2026",
    package: "Serenity Package (HDB)", casket: "Solemn Tribute (White)",
    floral: "Classic Arrangement", serviceType: "Cremation", addons: "2 items",
    archived: false,
  },
  {
    caseNumber: "QT-260517-020",
    deceased: "Chua Ah Mooi", contactId: "c015",
    contact: "Bernard Chua", phone: "+65 82349910",
    religion: "Catholic", brand: "Serenity Casket & Funerals",
    updatedAt: _hoursAgo(28), fd: "John Lim", status: "Working",
    wakeDate: "15 May 2026", wakeEndDate: "17 May 2026", wakeDuration: 3,
    funeralDate: "18 May 2026",
    package: "Serenity Package (Others)", casket: "Safe with Angels (White)",
    floral: "Premium Arrangement", serviceType: "Burial", addons: "3 items",
    archived: false,
  },

  /* ── Confirmed sample cases ───────────────────────────────────── */
  {
    caseNumber: "QT-260515-021",
    deceased: "Lee Siew Eng", contactId: "c016",
    contact: "Raymond Lee", phone: "+65 95567788",
    religion: "Free Thinker", brand: "Serenity Casket & Funerals",
    updatedAt: _daysAgo(3), fd: "John Lim", status: "Working",
    wakeDate: "13 May 2026", wakeEndDate: "15 May 2026", wakeDuration: 3,
    funeralDate: "16 May 2026",
    package: "Serenity Package (HDB)", casket: "Peaceful Symphony (White)",
    floral: "Classic Arrangement", serviceType: "Cremation", addons: "1 item",
    archived: false,
  },
  {
    caseNumber: "QT-260512-022",
    deceased: "Yap Boon Teik", contactId: "c017",
    contact: "Helen Yap", phone: "+65 80014433",
    religion: "Christian", brand: "Serenity Casket & Funerals",
    updatedAt: _daysAgo(6), fd: "John Lim", status: "Working",
    wakeDate: "10 May 2026", wakeEndDate: "12 May 2026", wakeDuration: 3,
    funeralDate: "13 May 2026",
    package: "Serenity Package (Others)", casket: "Solemn Tribute (White)",
    floral: "Premium Arrangement", serviceType: "Cremation", addons: "5 items",
    archived: false,
  },

  /* ── Pre-Need sample case ─────────────────────────────────────── */
  {
    caseNumber: "PN-260520-001",
    deceased: "Lim Ah Seng", contactId: "c019",
    contact: "Lim Ah Seng", phone: "+65 91002233",
    religion: "Buddhist", brand: "Serenity Casket & Funerals",
    updatedAt: _hoursAgo(6), fd: "John Lim", status: "Working",
    wakeDate: null, wakeEndDate: null, wakeDuration: null,
    funeralDate: null,
    package: "Not selected", casket: "Not selected",
    floral: "Not selected", serviceType: "Not decided",
    needType: "pre_need",
    archived: false,
  },
];

const SEED_CONTACTS = [
  // ── Family / customer contacts (linked to existing cases) ───────────────
  {
    id: "c001", type: "individual", category: "family",
    name: "Sarah Tan", phone: "+65 61234567", mobile: "+65 91234567",
    email: "sarah.tan@email.com",
    address: "Blk 234 Ang Mo Kio Ave 3, #08-12, Singapore 560234",
    relationship: "Daughter of late Tan Ah Kow",
    tags: ["Buddhist", "HDB"],
    notes: "Family of late Tan Ah Kow. Prefers calls in the evening.",
    updatedAt: _hoursAgo(4),
  },
  {
    id: "c002", type: "individual", category: "family",
    name: "David Lim", phone: "+65 68245678", mobile: "+65 82345678",
    email: "david.lim@email.com",
    address: "Blk 88 Bishan Street 13, #14-203, Singapore 570088",
    relationship: "Son of late Mary Lim Siew Hwa",
    tags: ["Christian"],
    notes: "Lead family contact. Wife Karen handles arrangement payments.",
    updatedAt: _hoursAgo(23),
  },
  {
    id: "c003", type: "individual", category: "family",
    name: "Peter Wong", phone: "+65 68765432", mobile: "+65 98765432",
    email: "p.wong@email.com",
    address: "12 Coronation Road, Singapore 269410",
    relationship: "Husband of late Wong Mei Ling",
    tags: ["Free Thinker"],
    notes: "",
    updatedAt: _daysAgo(1),
  },
  {
    id: "c004", type: "individual", category: "family",
    name: "Grace Lim", phone: "+65 67654321", mobile: "+65 87654321",
    email: "grace.lim@email.com",
    address: "Blk 412 Bedok North Ave 2, #05-118, Singapore 460412",
    relationship: "Wife of late Lim Boon Huat",
    tags: ["Buddhist", "HDB"],
    notes: "",
    updatedAt: _daysAgo(2),
  },
  {
    id: "c005", type: "individual", category: "family",
    name: "Lisa Chen", phone: "+65 62348765", mobile: "+65 92348765",
    email: "lisa.chen@email.com",
    address: "8 Marina Boulevard, #28-04, Singapore 018981",
    relationship: "Daughter of late Chen Wei Ming",
    tags: ["Catholic"],
    notes: "Prefers email correspondence.",
    updatedAt: _daysAgo(4),
  },
  {
    id: "c006", type: "individual", category: "family",
    name: "Janet Goh", phone: "+65 64451122", mobile: "+65 94451122",
    email: "janet.goh@email.com",
    address: "Blk 173 Toa Payoh Lor 1, #12-43, Singapore 310173",
    relationship: "Wife of late Goh Hock Seng",
    tags: ["Christian"],
    notes: "",
    updatedAt: _daysAgo(6),
  },
  {
    id: "c007", type: "individual", category: "family",
    name: "Patrick Ng", phone: "+65 67786543", mobile: "+65 97786543",
    email: "patrick.ng@email.com",
    address: "44 Joo Chiat Place, Singapore 427778",
    relationship: "Son of late Ng Choon Hwee",
    tags: ["Buddhist"],
    notes: "",
    updatedAt: _daysAgo(13),
  },
  {
    id: "c008", type: "individual", category: "family",
    name: "Michelle Koh", phone: "+65 61129988", mobile: "+65 81129988",
    email: "m.koh@email.com",
    address: "Blk 519 Hougang Ave 6, #07-251, Singapore 530519",
    relationship: "Daughter of late Koh Lai Hua",
    tags: ["Christian", "HDB"],
    notes: "",
    updatedAt: _daysAgo(20),
  },
  {
    id: "c009", type: "individual", category: "family",
    name: "Andrew Tay", phone: "+65 60025566", mobile: "+65 80025566",
    email: "andrew.tay@email.com",
    address: "Blk 268 Tampines St 21, #09-415, Singapore 520268",
    relationship: "Son of late Tay Beng Hock",
    tags: ["Buddhist"],
    notes: "",
    updatedAt: _daysAgo(89),
  },
  // ── Additional family contacts (no active cases yet) ───────────────────
  {
    id: "c010", type: "individual", category: "family",
    name: "Lee Hui Ling", phone: "+65 63457788", mobile: "+65 93457788",
    email: "huiling.lee@email.com",
    address: "Blk 901 Jurong West St 91, #10-302, Singapore 640901",
    relationship: "",
    tags: ["Christian"],
    notes: "Prospective enquiry on 12 May 2026. Awaiting follow-up.",
    updatedAt: _daysAgo(7),
  },
  {
    id: "c011", type: "individual", category: "family",
    name: "Lim Boon Heng", phone: "+65 64567890", mobile: "+65 84567890",
    email: "boonheng.lim@email.com",
    address: "Blk 65 Telok Blangah Hts, #03-65, Singapore 100065",
    relationship: "",
    tags: ["Buddhist"],
    notes: "Walk-in enquiry, considering pre-arrangement.",
    updatedAt: _daysAgo(11),
  },
  {
    id: "c012", type: "individual", category: "family",
    name: "Mei Soh", phone: "+65 60013344", mobile: "+65 90013344",
    email: "mei.soh@email.com",
    address: "Blk 357 Clementi Ave 2, #11-08, Singapore 120357",
    relationship: "Daughter of late Soh Ah Lian",
    tags: ["Buddhist", "HDB"],
    notes: "",
    updatedAt: _daysAgo(36),
  },
  {
    id: "c013", type: "individual", category: "family",
    name: "Yeo Hui Min", phone: "+65 66674422", mobile: "+65 96674422",
    email: "huimin.yeo@email.com",
    address: "32 Greenwood Avenue, Singapore 289221",
    relationship: "Daughter of late Yeo Boon Keng",
    tags: ["Catholic"],
    notes: "Case was cancelled. Family decided on private service.",
    updatedAt: _daysAgo(59),
  },
  {
    id: "c014", type: "individual", category: "family",
    name: "Jessica Tan", phone: "+65 61123344", mobile: "+65 91123344",
    email: "jessica.tan@gmail.com",
    address: "42 Bishan Street 22, #08-120, Singapore 570042",
    relationship: "Daughter of late Tan Swee Kiat",
    tags: ["Christian"],
    notes: "",
    updatedAt: _hoursAgo(3),
  },
  {
    id: "c015", type: "individual", category: "family",
    name: "Bernard Chua", phone: "+65 62349910", mobile: "+65 82349910",
    email: "bernard.chua@yahoo.com.sg",
    address: "8 Toh Yi Drive, #03-55, Singapore 596468",
    relationship: "Son of late Chua Ah Mooi",
    tags: ["Catholic"],
    notes: "",
    updatedAt: _hoursAgo(28),
  },
  {
    id: "c016", type: "individual", category: "family",
    name: "Raymond Lee", phone: "+65 65567788", mobile: "+65 95567788",
    email: "raymondlee88@hotmail.com",
    address: "23 Lorong Chuan, #12-08, Singapore 556791",
    relationship: "Son of late Lee Siew Eng",
    tags: ["Free Thinker"],
    notes: "",
    updatedAt: _daysAgo(3),
  },
  {
    id: "c017", type: "individual", category: "family",
    name: "Helen Yap", phone: "+65 60014433", mobile: "+65 80014433",
    email: "helen.yap@outlook.com",
    address: "67 Sunset Way, Singapore 597070",
    relationship: "Daughter of late Yap Boon Teik",
    tags: ["Christian"],
    notes: "",
    updatedAt: _daysAgo(6),
  },
  {
    id: "c018", type: "individual", category: "family",
    name: "Karen Lim", phone: "", mobile: "+65 92341122",
    email: "",
    address: "Blk 88 Bishan Street 13, #14-203, Singapore 570088",
    relationship: "Daughter-in-law of late Mary Lim Siew Hwa",
    tags: ["Christian"],
    notes: "Wife of David Lim. Handles arrangement payments.",
    updatedAt: _hoursAgo(23),
  },
  {
    id: "c019", type: "individual", category: "family",
    name: "Lim Ah Seng", phone: "+65 61002233", mobile: "+65 91002233",
    email: "lim.ahseng@email.com",
    address: "Blk 45 Toa Payoh Lorong 6, #09-120, Singapore 310045",
    relationship: "Planee (self)",
    tags: ["Buddhist"],
    notes: "Pre-need arrangement. Plans arranged by Mr Lim himself. Daughter Tracy Lim is secondary contact.",
    updatedAt: _hoursAgo(6),
  },
  // ── Vendors / suppliers ────────────────────────────────────────────────
  {
    id: "v001", type: "company", category: "vendor",
    name: "Lotus Florists Pte Ltd", phone: "+65 63342200", mobile: "",
    email: "orders@lotusflorists.com.sg",
    address: "16 Jalan Kilang Barat, #02-08, Singapore 159355",
    relationship: "Floral arrangement supplier",
    tags: ["Floral", "Preferred"],
    notes: "Net-30 terms. Direct delivery to wake venues.",
    updatedAt: _daysAgo(3),
  },
  {
    id: "v002", type: "company", category: "vendor",
    name: "Mandai Crematorium Services", phone: "+65 65524800", mobile: "",
    email: "bookings@mandaiservices.sg",
    address: "300 Mandai Road, Singapore 779393",
    relationship: "Crematorium booking partner",
    tags: ["Cremation"],
    notes: "Direct booking system. Confirm slot 48 hrs in advance.",
    updatedAt: _daysAgo(15),
  },
  {
    id: "v003", type: "individual", category: "vendor",
    name: "Reverend James Tan", phone: "+65 91124477", mobile: "+65 91124477",
    email: "rev.jamestan@parishstm.org",
    address: "Church of St Mary, 5 Mount Vernon Road",
    relationship: "Officiating clergy (Christian / Catholic)",
    tags: ["Clergy", "Christian", "Catholic"],
    notes: "Available Mon–Sat, advance booking required.",
    updatedAt: _daysAgo(22),
  },
  {
    id: "v004", type: "company", category: "vendor",
    name: "Eternal Memorials Pte Ltd", phone: "+65 68901122", mobile: "",
    email: "info@eternalmemorials.sg",
    address: "120 Lower Delta Road, #07-15, Singapore 169208",
    relationship: "Niche & memorial plaque supplier",
    tags: ["Memorial"],
    notes: "",
    updatedAt: _daysAgo(45),
  },
];

const PACKAGES = [
  {
    id: 1, name: "Straight Cremation", category: "Essential", venue: "all",
    venueLabel: null, religion: "all", price: 1980,
    image: "./assets/safe-with-angels.png",
    blurb: "Simple, direct cremation service without wake.",
    sections: [
      { name: "Professional Services", items: [
        "Safe With Angels Cremation Casket", "Transfer Services",
        "Cremation arrangement", "Transport to crematorium",
      ]},
    ],
  },
  {
    id: 10, name: "Serenity Package (HDB)", category: "Christian", venue: "hdb",
    venueLabel: "HDB Void Deck", religion: "christian", price: 6277,
    image: "./assets/pkg-serenity-hdb.png",
    blurb: "Christian funeral at HDB void deck with 3-day tentage.",
    sections: [
      { name: "Professional Services", items: [
        "Safe With Angels Quality Cremation Casket",
        "Transfer Services",
        "Female Clinical Care by our Female Embalmers",
        "Team of Pallbearers for Funeral Procession",
      ]},
      { name: "Complimentary Services", items: [
        "Wi-Fi Network", "Spotify Music Player", "TV Display for Montage",
        "Full PA System (Speakers, Podium, Mics)",
        "Ash Collection Services",
      ]},
      { name: "Memorial Service Hall", items: [
        "Tentage Services (Void Deck / Multi-Purpose Hall)",
        "Serenity Memorial Set-Up with LED Screen, Lighting, Carpet",
        "Fresh Floral Photo Wreath & Casket Top Arrangement",
        "10\" × 12\" Photo with Frame & 6 Passport Photos",
        "Mobile Toilet with Basin", "Chiller",
      ]},
      { name: "Funeral Procession", items: [
        "Fully Air-Conditioned Bus Transportation (2-way)",
        "Mercedes-Benz Limo Hearse / Maserati Limo Hearse",
      ]},
    ],
  },
  {
    id: 11, name: "Serenity Package (Others)", category: "Christian", venue: "others",
    venueLabel: "Church / Parlour", religion: "christian", price: 4277,
    image: "./assets/pkg-serenity-others.jpg",
    blurb: "Christian funeral at church, parlour, or private venue.",
    sections: [
      { name: "Professional Services", items: [
        "Safe With Angels Quality Cremation Casket",
        "Transfer Services",
        "Female Clinical Care by our Female Embalmers",
        "Team of Pallbearers for Funeral Procession",
      ]},
      { name: "Memorial Service Hall", items: [
        "Serenity Memorial Set-Up with LED Screen, Lighting, Carpet",
        "Fresh Floral Photo Wreath & Casket Top Arrangement",
        "10\" × 12\" Photo with Frame & 6 Passport Photos",
      ]},
      { name: "Funeral Procession", items: [
        "Fully Air-Conditioned Bus Transportation (2-way)",
        "Mercedes-Benz Limo Hearse / Maserati Limo Hearse",
      ]},
    ],
  },
  {
    id: 20, name: "Blessing Package (HDB)", category: "Buddhist", venue: "hdb",
    venueLabel: "HDB Void Deck", religion: "buddhist", price: 6588,
    image: null,
    blurb: "Traditional Buddhist wake at HDB void deck.",
    sections: [
      { name: "Professional Services", items: [
        "Casket with upgrade options",
        "Buddhist ceremony arrangements",
        "Embalming & preparation",
      ]},
      { name: "Memorial Service Hall", items: [
        "3-day tentage & furnishings",
        "Floral tributes & ancestral altar",
      ]},
    ],
  },
  {
    id: 30, name: "Orchid Package (HDB)", category: "Buddhist", venue: "hdb",
    venueLabel: "HDB Void Deck", religion: "buddhist", price: 6188,
    image: null,
    blurb: "Traditional Buddhist wake at HDB void deck.",
    sections: [
      { name: "Professional Services", items: [
        "Casket with upgrade options",
        "Buddhist ceremony arrangements",
        "Embalming & preparation",
      ]},
    ],
  },
  {
    id: 31, name: "Orchid Package (Others)", category: "Buddhist", venue: "others",
    venueLabel: "Parlour / Private", religion: "buddhist", price: 5488,
    image: null,
    blurb: "Traditional Buddhist wake at temple or private venue.",
    sections: [
      { name: "Professional Services", items: [
        "Casket with upgrade options",
        "Buddhist ceremony arrangements",
        "Venue coordination",
      ]},
    ],
  },
  {
    id: 40, name: "Lily Package (HDB)", category: "Buddhist", venue: "hdb",
    venueLabel: "HDB Void Deck", religion: "buddhist", price: 8988,
    image: null,
    blurb: "Enhanced Buddhist arrangements at HDB void deck.",
    sections: [
      { name: "Professional Services", items: [
        "Premium casket selection",
        "Full Buddhist ceremony arrangements",
      ]},
    ],
  },
  {
    id: 60, name: "Lotus Package (HDB)", category: "Buddhist", venue: "hdb",
    venueLabel: "HDB Void Deck", religion: "buddhist", price: 13088,
    image: null,
    blurb: "Deluxe Buddhist arrangements at HDB void deck.",
    sections: [
      { name: "Professional Services", items: [
        "Deluxe casket selection",
        "Traditional Buddhist ceremony",
      ]},
    ],
  },
];

const CASKETS = [
  { id: "swa-brown", name: "Safe with Angels", finish: "Brown",
    tier: "6 Sided", material: "Premium Wood", interior: "Soft fabric lining",
    designHighlights: "Classic six-panel design with refined craftsmanship",
    upgrade: 0, included: true,
    image:  "./assets/casket-safewithangels-brown.jpg",
    images: [
      "./assets/casket-safewithangels-brown.jpg",
      "./assets/safe-with-angels.png",
      "./assets/casket-safewithangels-white.jpg",
    ],
  },
  { id: "swa-white", name: "Safe with Angels", finish: "White",
    tier: "6 Sided", material: "Premium Wood", interior: "Soft fabric lining",
    designHighlights: "Classic six-panel design with refined craftsmanship",
    upgrade: 150, included: false,
    image:  "./assets/casket-safewithangels-white.jpg",
    images: [
      "./assets/casket-safewithangels-white.jpg",
      "./assets/casket-safewithangels-brown.jpg",
      "./assets/safe-with-angels.png",
    ],
  },
  { id: "ps-brown", name: "Peaceful Symphony", finish: "Brown",
    tier: "4 Sided", material: "Solid hardwood", interior: "Premium velvet lining",
    designHighlights: "Four-panel contemporary design with smooth contours",
    upgrade: 700, included: false, image: null, images: [] },
  { id: "ps-white", name: "Peaceful Symphony", finish: "White",
    tier: "4 Sided", material: "Solid hardwood", interior: "Premium velvet lining",
    designHighlights: "Four-panel contemporary design with smooth contours",
    upgrade: 900, included: false, image: null, images: [] },
  { id: "st-brown", name: "Solemn Tribute", finish: "Brown",
    tier: "8 Sided", material: "Premium hardwood", interior: "Plush satin interior",
    designHighlights: "Eight-panel traditional design with ornate details",
    upgrade: 1100, included: false, image: null, images: [] },
  { id: "st-white", name: "Solemn Tribute", finish: "White",
    tier: "8 Sided", material: "Premium hardwood", interior: "Plush satin interior",
    designHighlights: "Eight-panel traditional design with ornate details",
    upgrade: 1300, included: false, image: null, images: [] },
  { id: "cs-brown", name: "Comforting Solace", finish: "Brown",
    tier: "Full Glass", material: "Premium wood with full glass panel",
    interior: "Luxury satin lining",
    designHighlights: "Full glass viewing panel for complete visibility",
    upgrade: 2500, included: false, image: null, images: [] },
  { id: "cs-white", name: "Comforting Solace", finish: "White",
    tier: "Full Glass", material: "Premium wood with full glass panel",
    interior: "Luxury satin lining",
    designHighlights: "Full glass viewing panel for complete visibility",
    upgrade: 2900, included: false, image: null, images: [] },
  { id: "ch", name: "Comforting Haven", finish: "Premium Finish",
    tier: "Serenity Signature", material: "Premium hardwood",
    interior: "Designer fabric lining",
    designHighlights: "Signature series with elegant craftsmanship",
    upgrade: 3100, included: false, image: null, images: [] },
  { id: "co", name: "Calvary Oak", finish: "Premium Oak",
    tier: "Serenity Signature", material: "Premium oak",
    interior: "Plush velvet interior",
    designHighlights: "Rich oak wood with traditional styling",
    upgrade: 4200, included: false, image: null, images: [] },
  { id: "7ft", name: "7 ft Casket", finish: "Standard",
    tier: "7ft", material: "Standard wood", interior: "Standard lining",
    designHighlights: "Extended length for taller individuals",
    upgrade: 1300, included: false, image: null, images: [] },
];

const ADDON_ITEMS = [
  { id: "1",  name: "Coffee Beans",                  category: "Catering",  unitPrice: 0,   chargeType: "complimentary",
    icon: "coffeeBeans", suggested: true, keywords: ["beverage", "drink", "coffee"] },
  { id: "2",  name: "Nespresso Capsule Coffee Machine", category: "Equipment", unitPrice: 0, chargeType: "complimentary",
    icon: "coffeeMachine", suggested: true, keywords: ["coffee", "machine", "nespresso"] },
  { id: "3",  name: "Coffee Machine (SFP)",          category: "Equipment", unitPrice: 450, chargeType: "one-time",
    icon: "coffeeMachine", keywords: ["coffee", "espresso", "sfp"] },
  { id: "4",  name: "Mobile Toilet",                 category: "Logistics", unitPrice: 110, chargeType: "per day", rentable: true,
    icon: "toilet", suggested: true, keywords: ["toilet", "washroom", "wc"] },
  { id: "5",  name: "Mobile Toilet (Chemical)",      category: "Logistics", unitPrice: 120, chargeType: "per day", rentable: true,
    icon: "toilet", keywords: ["toilet", "chemical", "washroom"] },
  { id: "6",  name: "Chiller",                       category: "Equipment", unitPrice: 60,  chargeType: "per day", rentable: true,
    icon: "chiller", suggested: true, keywords: ["fridge", "cooler", "refrigerator"] },
  { id: "7",  name: "Cooler",                        category: "Equipment", unitPrice: 110, chargeType: "per day", rentable: true,
    icon: "chiller", keywords: ["fridge", "cooler"] },
  { id: "8",  name: "Lighting (1 Phase)",            category: "Equipment", unitPrice: 150, chargeType: "one-time",
    icon: "bulb", keywords: ["light", "lamp", "electrical"] },
  { id: "9",  name: "Standing Fan",                  category: "Equipment", unitPrice: 25,  chargeType: "per day", rentable: true,
    icon: "fan", suggested: true, keywords: ["fan", "cooling", "ventilation"] },
  { id: "10", name: "Canvas",                        category: "Equipment", unitPrice: 60,  chargeType: "per day", rentable: true,
    icon: "canvas", keywords: ["sheet", "covering", "fabric"] },
  { id: "12", name: "Square Table",                  category: "Equipment", unitPrice: 7,   chargeType: "per day", rentable: true,
    icon: "table", keywords: ["furniture", "table"] },
  { id: "13", name: "Round Table",                   category: "Equipment", unitPrice: 10,  chargeType: "per day", rentable: true,
    icon: "tableRound", suggested: true, keywords: ["furniture", "table"] },
  { id: "15", name: "Chairs (PVC)",                  category: "Equipment", unitPrice: 1.5, chargeType: "per day", rentable: true,
    icon: "chair", suggested: true, keywords: ["furniture", "seating"] },
  { id: "16", name: "Chairs (Tiffany)",              category: "Equipment", unitPrice: 2,   chargeType: "per day", rentable: true,
    icon: "chair", keywords: ["furniture", "seating", "tiffany"] },
  { id: "18", name: "White T-Shirts",                category: "Apparel",   unitPrice: 8,   chargeType: "one-time",
    icon: "shirt", keywords: ["apparel", "uniform", "shirt"] },
  { id: "19", name: "Dri Fit T-Shirt",               category: "Apparel",   unitPrice: 11,  chargeType: "one-time",
    icon: "shirt", keywords: ["apparel", "uniform", "drifit"] },
  { id: "20", name: "Polo Shirt",                    category: "Apparel",   unitPrice: 15,  chargeType: "one-time",
    icon: "polo", keywords: ["apparel", "uniform", "polo"] },
  { id: "22", name: "Photo Montage",                 category: "Services",  unitPrice: 0,   chargeType: "one-time",
    icon: "photo", suggested: true, keywords: ["photos", "montage", "slideshow", "memory"] },
  { id: "23", name: "Live Streaming",                category: "Services",  unitPrice: 0,   chargeType: "one-time",
    icon: "stream", suggested: true, keywords: ["broadcast", "stream", "remote", "online"] },
  { id: "26", name: "Night Service",                 category: "Services",  unitPrice: 25,  chargeType: "per hour", minQuantity: 3,
    icon: "moon", keywords: ["overnight", "wake"] },
  { id: "27", name: "Night Vigil",                   category: "Services",  unitPrice: 180, chargeType: "one-time",
    icon: "moon", keywords: ["overnight", "vigil", "wake"] },
  { id: "28", name: "Additional Bus",                category: "Logistics", unitPrice: 230, chargeType: "one-time",
    icon: "bus", keywords: ["transport", "transportation"] },
  { id: "29", name: "Inland Scattering",             category: "Services",  unitPrice: 450, chargeType: "one-time",
    icon: "wave", keywords: ["scattering", "ashes", "garden"] },
  { id: "30", name: "Sea Burial",                    category: "Services",  unitPrice: 280, chargeType: "one-time",
    icon: "wave", keywords: ["sea", "burial", "scattering"] },
  { id: "31", name: "Sea Burial (Premium)",          category: "Services",  unitPrice: 400, chargeType: "one-time",
    icon: "wave", keywords: ["sea", "burial", "premium"] },
  { id: "25", name: "Buffet Catering",               category: "Catering",  unitPrice: 18,  chargeType: "per pax",
    icon: "plate", suggested: true, keywords: ["food", "meal", "catering"] },
];

const ADDON_CATEGORIES = ["All", "Equipment", "Logistics", "Apparel", "Services", "Catering"];

function brandForReligion(religion) {
  const r = (religion || "").toLowerCase();
  if (r === "christian" || r === "catholic") return "serenity";
  if (r === "buddhist" || r === "taoist")    return "fountains";
  return "all";
}

/* ---- Workspace (brand context) helpers ---- */

const RELIGIONS_BY_WORKSPACE = {
  serenity:  ["Catholic", "Christian", "Free Thinker"],
  fountains: ["Buddhist", "Taoist",   "Free Thinker"],
};

function workspaceFromCase(c) {
  if (c && c.brand === "Fountains Funerals")         return "fountains";
  if (c && c.brand === "Serenity Casket & Funerals") return "serenity";
  const r = (c && c.religion || "").toLowerCase();
  if (r === "buddhist" || r === "taoist") return "fountains";
  if (r === "christian" || r === "catholic") return "serenity";
  return "serenity";
}

function workspaceBrandLabel(w) {
  return w === "fountains" ? "Fountains Funerals" : "Serenity Casket & Funerals";
}

function brandLabel(brand) {
  if (brand === "serenity") return "Serenity Casket & Funerals";
  if (brand === "fountains") return "Fountains Funerals";
  return "All Brands";
}

function formatPrice(n) {
  return "$" + Number(n).toLocaleString("en-SG", { maximumFractionDigits: 2 });
}

function titleCase(s) {
  return (s || "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

/* ---- Date / range helpers ---- */

function relativeTime(iso) {
  if (!iso) return "";
  const then = new Date(iso).getTime();
  const diffMs = MOCK_NOW - then;
  if (diffMs < 0)             return "Just now";
  const mins  = Math.floor(diffMs / 60000);
  if (mins < 60)              return mins <= 1 ? "Just now" : `${mins} minutes ago`;
  const hours = Math.floor(diffMs / 3600000);
  if (hours < 24)             return `${hours} hour${hours === 1 ? "" : "s"} ago`;
  const days = Math.floor(diffMs / 86400000);
  if (days < 7)               return `${days} day${days === 1 ? "" : "s"} ago`;
  const weeks = Math.floor(days / 7);
  if (days < 30)              return `${weeks} week${weeks === 1 ? "" : "s"} ago`;
  const months = Math.floor(days / 30);
  if (months < 12)            return `${months} month${months === 1 ? "" : "s"} ago`;
  const years = Math.floor(days / 365);
  return `${years} year${years === 1 ? "" : "s"} ago`;
}

/* Returns {from, to} as millisecond timestamps for a preset id.
   `from` inclusive, `to` exclusive. null = unbounded. */
function rangeForPreset(preset, customFrom, customTo) {
  const now = MOCK_NOW;
  const startOfDay = (ts) => {
    const d = new Date(ts);
    d.setHours(0, 0, 0, 0);
    return d.getTime();
  };
  const endOfDay = (ts) => startOfDay(ts) + 86400000;

  switch (preset) {
    case "today":
      return { from: startOfDay(now), to: endOfDay(now) };
    case "7d":
      return { from: startOfDay(now - 6 * 86400000), to: endOfDay(now) };
    case "30d":
      return { from: startOfDay(now - 29 * 86400000), to: endOfDay(now) };
    case "month": {
      const d = new Date(now);
      const first = new Date(d.getFullYear(), d.getMonth(), 1).getTime();
      return { from: first, to: endOfDay(now) };
    }
    case "custom": {
      const f = customFrom ? new Date(customFrom + "T00:00:00").getTime() : null;
      const t = customTo   ? new Date(customTo   + "T00:00:00").getTime() + 86400000 : null;
      return { from: f, to: t };
    }
    case "all":
    default:
      return { from: null, to: null };
  }
}

function labelForPreset(preset, customFrom, customTo) {
  switch (preset) {
    case "today": return "Today";
    case "7d":    return "Last 7 Days";
    case "30d":   return "Last 30 Days";
    case "month": return "This Month";
    case "custom":
      if (customFrom && customTo) return `${customFrom} → ${customTo}`;
      if (customFrom)             return `From ${customFrom}`;
      if (customTo)               return `Until ${customTo}`;
      return "Custom Range";
    case "all":
    default:      return "All Time";
  }
}

/* ---- Contact helpers ----
   `getLinkedCasesForContact(contactOrName, cases)` — accepts either
   a contact object (preferred — matches via FK `contactId`) or a
   bare name string (legacy fallback). Used in both directions:
   - From My Contacts: pass the contact object
   - From a case (legacy data): pass the name as string */
function getLinkedCasesForContact(contactOrName, cases = SEED_CASES) {
  if (!contactOrName) return [];

  if (typeof contactOrName === "string") {
    // Legacy: match by name only.
    const target = contactOrName.trim().toLowerCase();
    return cases.filter((c) => (c.contact || "").trim().toLowerCase() === target);
  }

  // Preferred: match by contactId FK; fall back to name compare so cases
  // created before the FK existed still resolve.
  const id   = contactOrName.id;
  const name = (contactOrName.name || "").trim().toLowerCase();
  return cases.filter((c) =>
    (id && c.contactId === id) ||
    (!c.contactId && (c.contact || "").trim().toLowerCase() === name)
  );
}

function contactInitials(name) {
  if (!name) return "?";
  const parts = name.trim().split(/\s+/);
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function contactCategoryLabel(c) {
  if (!c) return "";
  if (c.category === "vendor")  return c.type === "company" ? "Vendor / Supplier" : "Vendor Contact";
  if (c.category === "family")  return c.type === "company" ? "Customer Company"  : "Family Contact";
  if (c.category === "company") return "Company";
  return "Contact";
}

/* ---- Mocked Odoo sync stubs (these would call res.partner endpoints) ----
   Each helper returns a Promise that resolves with the saved record. The
   demo just resolves synchronously after a short delay; in production the
   request body shape mirrors Odoo's `res.partner` model fields. */

function odooCreateContact(payload) {
  // Odoo: POST /web/dataset/call_kw/res.partner/create
  //   args: [{ name, phone, mobile, email, street, is_company, category_id, comment, ... }]
  return new Promise((resolve) => {
    const id = "c" + Math.floor(Math.random() * 1e6).toString(36);
    setTimeout(() => resolve({ ...payload, id, updatedAt: new Date().toISOString() }), 250);
  });
}

function odooUpdateContact(id, patch) {
  // Odoo: POST /web/dataset/call_kw/res.partner/write
  //   args: [[id], { ...patch }]
  return new Promise((resolve) => {
    setTimeout(() => resolve({ id, ...patch, updatedAt: new Date().toISOString() }), 200);
  });
}

function odooDeleteContact(id) {
  // Odoo: POST /web/dataset/call_kw/res.partner/unlink
  //   args: [[id]]
  return new Promise((resolve) => setTimeout(() => resolve({ id, deleted: true }), 150));
}

function odooSearchContacts(query) {
  // Odoo: POST /web/dataset/call_kw/res.partner/search_read
  //   kwargs: { domain: [['name','ilike', query]], fields: [...] }
  // Demo: return an empty stub; consumers filter locally.
  return Promise.resolve([]);
}

/* ── Coupon Codes ──────────────────────────────────────────────────────────
   Two types:
     Type A (discount)  — pre-GST deduction applied to the arrangement total.
                          GST is recalculated on the reduced subtotal.
     Type B (freeitem)  — adds a complimentary line item to the arrangement;
                          has no direct monetary effect on pricing rows.
   ────────────────────────────────────────────────────────────────────────── */
const COUPON_CODES = {
  // Type A — pre-GST discount coupons ($50–$300)
  "DISC50":      { type: "discount", amount: 50,  label: "$50 off (pre-GST)"  },
  "DISC100":     { type: "discount", amount: 100, label: "$100 off (pre-GST)" },
  "DISC150":     { type: "discount", amount: 150, label: "$150 off (pre-GST)" },
  "DISC200":     { type: "discount", amount: 200, label: "$200 off (pre-GST)" },
  "DISC250":     { type: "discount", amount: 250, label: "$250 off (pre-GST)" },
  "DISC300":     { type: "discount", amount: 300, label: "$300 off (pre-GST)" },
  // Type B — complimentary item coupons
  "COMP-FLORAL": { type: "freeitem", itemName: "Complimentary Floral Arrangement",   label: "Complimentary Floral Arrangement"   },
  "COMP-CANDLE": { type: "freeitem", itemName: "Complimentary Memorial Candles",     label: "Complimentary Memorial Candles"     },
  "COMP-FRAME":  { type: "freeitem", itemName: "Complimentary Memorial Photo Frame", label: "Complimentary Memorial Photo Frame" },
};

Object.assign(window, {
  SEED_CASES, SEED_CONTACTS, PACKAGES, CASKETS, ADDON_ITEMS, ADDON_CATEGORIES,
  RELIGIONS_BY_WORKSPACE, MOCK_NOW, COUPON_CODES,
  brandForReligion, brandLabel, formatPrice, titleCase,
  workspaceFromCase, workspaceBrandLabel,
  relativeTime, rangeForPreset, labelForPreset,
  getLinkedCasesForContact, contactInitials, contactCategoryLabel,
  odooCreateContact, odooUpdateContact, odooDeleteContact, odooSearchContacts,
});
