// ═══════════════════════════════════════════
// USER INSIGHT DATA — Mock + Real API
// Loads from /api/user-insights/all first,
// falls back to MOCK_USERS if API unavailable
// ═══════════════════════════════════════════

let USERS = [];
let DATA_SOURCE = 'mock'; // 'api' or 'mock'

const MOCK_USERS = [
  {
    id:1, name:"Nguyễn Thị Lan", email:"lan.nguyen@gmail.com", phone:"+84 912 345 678",
    userId:"CNF-20240156", gender:"Nữ", age:35, dob:"1991-03-15", avatar_color:"#6366F1",
    location:"Quận Cầu Giấy, Hà Nội", membership:"VIP Gold", join_date:"2024-01-12",
    channels:["Zalo OA","Web","Email"],
    aov:485000, total_orders:12, total_spent:5820000,
    health_score:82,
    rfm:{recency:90, frequency:75, monetary:68},
    // Chatbot insight (6-layer từ AI)
    chatbot_insight:{
      USER:"Nữ, 35 tuổi, mẹ bỉm sữa. Gu: basic, thoải mái, ưu tiên cotton organic.",
      TARGET:"Con trai 5 tuổi, thích màu xanh navy và đỏ. Size 110-120cm.",
      GOAL:"Mua quần áo trẻ em cho con đi học + đi chơi. Dịp: đầu năm học mới.",
      CONSTRAINS:"Budget 300k-600k/bộ. Chỉ muốn cotton 100%. Tránh polyester. Size 5T-6T.",
      LATEST_PRODUCT_INTEREST:"Áo thun bé trai Basic Cotton [6TS24B005] - Xanh navy",
      LAST_ACTION:"Bot đã gợi ý 3 combo áo+quần bé trai dưới 500k, khách hỏi thêm về chính sách đổi size.",
      SUMMARY_HISTORY:"Khách hỏi về áo thun bé trai → bot gợi ý → khách compare giá → hỏi size chart → hỏi combo deal → hỏi đổi trả"
    },
    predictions:{next_purchase:"Quần jean bé trai",next_purchase_conf:78,churn_risk:12,clv_6m:2400000,next_visit_days:3,
      recommended_collab:[
        {name:"Quần Jean Slim Bé Trai",icon:"👖",reason:"Đã xem 3 lần combo với áo thun",conf:85},
        {name:"Set Áo + Quần Combo",icon:"👚",reason:"Hay hỏi combo giảm giá",conf:72},
        {name:"Balo trẻ em",icon:"🎒",reason:"Cross-sell phụ kiện trẻ em",conf:58}
      ],
      recommended_basket:[
        {name:"Áo khoác gió bé trai",icon:"🧥",reason:"75% mua quần áo cũng mua",conf:75},
        {name:"Tất cotton trẻ em x3",icon:"🧦",reason:"Add-on phổ biến đơn trẻ em",conf:52},
        {name:"Khẩu trang trẻ em",icon:"😷",reason:"Cross-sell tiện ích",conf:45}
      ],
      recommended_trending:[
        {name:"Váy midi hoa nhí",icon:"👗",reason:"#1 trending nữ 25-35",conf:80},
        {name:"Áo thun organic",icon:"👕",reason:"Hot item tháng này",conf:65},
        {name:"Sandal đế xuồng",icon:"👡",reason:"Rising demand +120%",conf:55}
      ]
    },
    email_metrics:{delivered:42,opens:24,open_rate:57,click_rate:14,conversion_rate:8.5},
    segments:{purchase_likelihood:"High",discount_affinity:"Medium",customer_value:"VIP",lifecycle:"Active Customer"},
    top_categories:[
      {name:"Trẻ em bé trai",pct:35,color:"#6366F1"},{name:"Áo thun nữ",pct:22,color:"#F59E0B"},
      {name:"Quần jean",pct:18,color:"#10B981"},{name:"Áo khoác",pct:15,color:"#EF4444"},
      {name:"Phụ kiện",pct:10,color:"#8B5CF6"}
    ],
    last_attrs:{"Last Seen":"canifa.com/tre-em/be-trai","Last Email Open":"Summer Sale 2026","Last Visited Category":"Áo thun bé trai","Last Abandoned Cart":"320,000đ","Last Visited Product":"Áo thun Basic Cotton Bé Trai"},
    products:{last_visited:{name:"Áo thun Basic Cotton Bé Trai",price:"249,000đ",icon:"👕"},last_purchased:{name:"Set quần áo bé trai",price:"459,000đ",icon:"👖"},last_abandoned:{name:"Combo 3 áo thun bé trai",price:"320,000đ",icon:"👕"}},
    mobile:{app_opened:8,push_opened:12,inapp_seen:5,inapp_from_push:3},
    journey:{entered:9,completed:6},
    purchase_timeline:[
      {date:"22/03/2026",name:"Áo thun bé trai x2",price:"498,000đ",icon:"👕",channel:"Web"},
      {date:"15/03/2026",name:"Set quần áo bé trai",price:"459,000đ",icon:"👖",channel:"Zalo"},
      {date:"28/02/2026",name:"Quần jean bé trai skinny",price:"359,000đ",icon:"👖",channel:"Web"},
      {date:"14/02/2026",name:"Áo khoác gió bé trai",price:"450,000đ",icon:"🧥",channel:"Web"},
      {date:"20/01/2026",name:"Áo len cổ lọ bé trai",price:"390,000đ",icon:"🧶",channel:"Zalo"}
    ],
    next_best_actions:[
      {icon:"📧",title:"Gửi email BST Back-to-School",desc:"Conf 85% — mua đồ cho con đi học, timing cuối tháng 8",urgency:"urgent"},
      {icon:"🎁",title:"Push combo 'Mua 2 giảm 15%' trẻ em",desc:"Phù hợp hành vi mua combo, tăng AOV",urgency:"medium"},
      {icon:"📱",title:"Nhắc cart bỏ quên (320k combo)",desc:"Abandoned 2 ngày trước, recovery rate 40%",urgency:"urgent"}
    ],
    engagement_heatmap:[[0,1,2,0,1,3,2],[1,2,3,1,2,4,3],[0,0,1,0,0,2,1],[0,1,0,1,0,1,0]],
    chatbot_history:[
      {role:"user",text:"Cho mình xem áo thun cotton cho bé trai 5 tuổi"},
      {role:"bot",text:"Dạ chị ơi, em có nhiều mẫu áo thun cotton bé trai size 5T (110cm). Giá từ 149k-249k. Chị muốn xem màu nào ạ?"},
      {role:"user",text:"Xanh navy hoặc đỏ, có combo nào giảm giá không?"},
      {role:"bot",text:"Dạ có Combo 3 áo thun Basic Cotton bé trai chỉ 320k (tiết kiệm 30%) ạ! Có xanh navy, đỏ và trắng. Chị muốn em check size 5T không?"}
    ]
  },
  {
    id:2, name:"Trần Văn Minh", email:"minh.tran@outlook.com", phone:"+84 903 456 789",
    userId:"CNF-20240089", gender:"Nam", age:42, dob:"1984-07-22", avatar_color:"#059669",
    location:"Quận 7, TP HCM", membership:"Regular", join_date:"2024-03-05",
    channels:["Zalo OA","Web"],
    aov:720000, total_orders:8, total_spent:5760000,
    health_score:61,
    rfm:{recency:55, frequency:50, monetary:72},
    chatbot_insight:{
      USER:"Nam, 42 tuổi, IT manager. Gu: smart casual, công sở, không quá formal.",
      TARGET:"Bản thân (đi làm) + Vợ (35 tuổi, mua quà).",
      GOAL:"Tìm áo sơ mi đi làm + quà sinh nhật cho vợ.",
      CONSTRAINS:"Budget sơ mi 400k-600k. Quà vợ 500k-1tr. Size M nam, size S nữ. Không thích hoa văn quá nhiều.",
      LATEST_PRODUCT_INTEREST:"Sơ mi Oxford Slim [8SM24S012] - Trắng/xanh nhạt",
      LAST_ACTION:"Bot đã gợi ý 2 sơ mi + set quà cho vợ (váy + khăn). Khách hỏi về gói quà tặng.",
      SUMMARY_HISTORY:"Hỏi sơ mi công sở → bot gợi ý Oxford → khách OK → chuyển sang hỏi quà vợ → bot gợi ý váy + phụ kiện"
    },
    predictions:{next_purchase:"Áo sơ mi",next_purchase_conf:62,churn_risk:25,clv_6m:1800000,next_visit_days:7,
      recommended_collab:[{name:"Sơ mi Oxford Slim",icon:"👔",reason:"Mua sơ mi mỗi quý",conf:70},{name:"Thắt lưng da",icon:"🪢",reason:"Cross-sell phụ kiện nam",conf:55},{name:"Polo Dry-fit",icon:"👕",reason:"Tương tự SP đã mua",conf:48}],
      recommended_basket:[{name:"Quần âu slim",icon:"👖",reason:"Kèm sơ mi 65% đơn",conf:68},{name:"Tất cổ thấp",icon:"🧦",reason:"Add-on phổ biến",conf:42},{name:"Nước hoa mini",icon:"🧴",reason:"Gift set combo",conf:35}],
      recommended_trending:[{name:"Polo cổ mao",icon:"👔",reason:"#2 trending nam Q1",conf:60},{name:"Quần jogger premium",icon:"👖",reason:"Rising +80%",conf:50},{name:"Áo gió nhẹ",icon:"🧥",reason:"Mùa mới hot item",conf:45}]
    },
    email_metrics:{delivered:28,opens:10,open_rate:36,click_rate:7,conversion_rate:3.2},
    segments:{purchase_likelihood:"Medium",discount_affinity:"Low",customer_value:"Regular",lifecycle:"Active Customer"},
    top_categories:[{name:"Sơ mi nam",pct:35,color:"#059669"},{name:"Quần âu",pct:25,color:"#6366F1"},{name:"Polo nam",pct:20,color:"#F59E0B"},{name:"Giày dép",pct:12,color:"#EF4444"},{name:"Quà tặng",pct:8,color:"#8B5CF6"}],
    last_attrs:{"Last Seen":"canifa.com/nam/so-mi","Last Email Open":"New Arrivals Men","Last Visited Category":"Sơ mi nam","Last Abandoned Cart":"—","Last Visited Product":"Sơ mi Oxford Slim"},
    products:{last_visited:{name:"Sơ mi Oxford Slim",price:"499,000đ",icon:"👔"},last_purchased:{name:"Quần kaki slim",price:"549,000đ",icon:"👖"},last_abandoned:{name:"—",price:"—",icon:"📦"}},
    mobile:{app_opened:3,push_opened:5,inapp_seen:2,inapp_from_push:1},
    journey:{entered:4,completed:3},
    purchase_timeline:[
      {date:"18/03/2026",name:"Sơ mi Oxford Slim x2",price:"998,000đ",icon:"👔",channel:"Web"},
      {date:"02/03/2026",name:"Quần kaki slim",price:"549,000đ",icon:"👖",channel:"Web"},
      {date:"15/01/2026",name:"Sơ mi Oxford trắng",price:"499,000đ",icon:"👔",channel:"Zalo"}
    ],
    next_best_actions:[
      {icon:"📧",title:"Email BST Polo mùa hè mới",desc:"Conf 70% — top category, thời điểm mua quý",urgency:"medium"},
      {icon:"🎁",title:"Gợi ý set quà cho vợ",desc:"Đã hỏi về quà sinh nhật, tạo combo voucher gift",urgency:"urgent"},
      {icon:"🎯",title:"Upsell sơ mi premium tier",desc:"AOV cao, có thể nâng phân khúc",urgency:"medium"}
    ],
    engagement_heatmap:[[0,0,1,0,0,1,0],[0,1,1,1,0,2,1],[0,0,0,0,0,1,0],[0,0,0,0,0,0,0]],
    chatbot_history:[{role:"user",text:"Sơ mi nam công sở, size M, budget 500k?"},{role:"bot",text:"Dạ anh, em gợi ý Sơ mi Oxford Slim (499k) và Sơ mi Linen (459k). Cả 2 đều có size M, phù hợp đi làm ạ!"}]
  },
  {
    id:3, name:"Lê Phương Anh", email:"phuonganh.le@yahoo.com", phone:"+84 987 654 321",
    userId:"CNF-20250012", gender:"Nữ", age:28, dob:"1998-12-01", avatar_color:"#EC4899",
    location:"Quận Hoàn Kiếm, Hà Nội", membership:"VIP Platinum", join_date:"2025-01-03",
    channels:["Zalo OA","Web","Email","SMS"],
    aov:380000, total_orders:22, total_spent:8360000,
    health_score:95,
    rfm:{recency:95, frequency:92, monetary:78},
    chatbot_insight:{
      USER:"Nữ, 28 tuổi, designer freelance. Gu: minimalist, neutral tones, oversized fit.",
      TARGET:"Bản thân. Thích loungewear & đồ mặc nhà cao cấp.",
      GOAL:"Mua set pyjama lụa + đồ WFH thoải mái. Dịp: tự thưởng cuối tháng.",
      CONSTRAINS:"Budget 300k-500k/set. Chỉ muốn neutral colors (beige, trắng, xám). Size S. Không thích họa tiết cartoon.",
      LATEST_PRODUCT_INTEREST:"Set Pyjama Lụa [7PJ24W003] - Beige",
      LAST_ACTION:"Bot gửi link 3 set pyjama lụa neutral. Khách add to cart set beige size S.",
      SUMMARY_HISTORY:"Hỏi đồ mặc nhà → bot gợi ý cotton → khách muốn lụa → bot show 3 options → khách chọn beige → add cart → hỏi free ship"
    },
    predictions:{next_purchase:"Đồ mặc nhà lụa",next_purchase_conf:91,churn_risk:5,clv_6m:3200000,next_visit_days:1,
      recommended_collab:[{name:"Set Pyjama Lụa Mới",icon:"👚",reason:"Loyal buyer, mua set mỗi tháng",conf:92},{name:"Áo len oversized",icon:"🧶",reason:"Top category #2",conf:78},{name:"Quần legging fleece",icon:"🩳",reason:"Mùa đông sắp tới",conf:65}],
      recommended_basket:[{name:"Dép lông trong nhà",icon:"🩴",reason:"Mua kèm pyjama 55%",conf:60},{name:"Bộ chăn ga cotton",icon:"🛏️",reason:"Bundle deal đồ nhà",conf:48},{name:"Nến thơm",icon:"🕯️",reason:"Lifestyle add-on",conf:38}],
      recommended_trending:[{name:"Set loungewear modal",icon:"👚",reason:"#1 trending đồ nhà",conf:88},{name:"Cardigan len mỏng",icon:"🧶",reason:"Rising +150% MoM",conf:70},{name:"Áo hoodie oversize",icon:"🧥",reason:"Hot item Gen Z",conf:55}]
    },
    email_metrics:{delivered:68,opens:45,open_rate:66,click_rate:22,conversion_rate:14.7},
    segments:{purchase_likelihood:"High",discount_affinity:"High",customer_value:"VIP",lifecycle:"Loyal Customer"},
    top_categories:[{name:"Đồ mặc nhà",pct:28,color:"#EC4899"},{name:"Áo len",pct:22,color:"#6366F1"},{name:"Quần legging",pct:20,color:"#10B981"},{name:"Áo thun",pct:18,color:"#F59E0B"},{name:"Khác",pct:12,color:"#8B5CF6"}],
    last_attrs:{"Last Seen":"canifa.com/nu/do-mac-nha","Last Email Open":"Flash Sale Weekend","Last Visited Category":"Đồ mặc nhà","Last Abandoned Cart":"450,000đ","Last Visited Product":"Set Pyjama Lụa Beige"},
    products:{last_visited:{name:"Set Pyjama Lụa Beige",price:"450,000đ",icon:"👚"},last_purchased:{name:"Áo len cổ lọ oversized",price:"399,000đ",icon:"🧶"},last_abandoned:{name:"Set Pyjama Lụa Beige",price:"450,000đ",icon:"👚"}},
    mobile:{app_opened:15,push_opened:22,inapp_seen:11,inapp_from_push:8},
    journey:{entered:14,completed:11},
    purchase_timeline:[
      {date:"23/03/2026",name:"Set Pyjama Cotton",price:"279,000đ",icon:"👚",channel:"Email"},
      {date:"20/03/2026",name:"Áo len cổ lọ oversized",price:"399,000đ",icon:"🧶",channel:"Web"},
      {date:"10/03/2026",name:"Quần legging x2",price:"370,000đ",icon:"🩳",channel:"SMS"},
      {date:"28/02/2026",name:"Set Pyjama Lụa",price:"450,000đ",icon:"👚",channel:"Zalo"},
      {date:"14/02/2026",name:"Áo thun oversize x3",price:"447,000đ",icon:"👕",channel:"Web"},
      {date:"01/02/2026",name:"Áo hoodie fleece",price:"550,000đ",icon:"🧥",channel:"Web"}
    ],
    next_best_actions:[
      {icon:"⭐",title:"Nâng hạng VIP Platinum",desc:"Chỉ còn 1.6M nữa — 22 đơn trong 3 tháng",urgency:"medium"},
      {icon:"📧",title:"Email early access BST mới",desc:"Loyal customer — cho xem trước 24h",urgency:"low"},
      {icon:"🛒",title:"Nhắc cart Pyjama Lụa Beige (450k)",desc:"Added to cart 1 ngày trước, chưa thanh toán",urgency:"urgent"}
    ],
    engagement_heatmap:[[2,3,4,2,3,5,4],[3,4,5,3,4,6,5],[1,2,3,1,2,4,3],[1,1,2,1,1,2,1]],
    chatbot_history:[{role:"user",text:"Có set đồ mặc nhà nào đang sale không?"},{role:"bot",text:"Dạ chị ơi! Set Pyjama Cotton giảm 30% còn 279,000đ và set Pyjama Lụa giảm 20% còn 360,000đ ạ."},{role:"user",text:"Lụa nhé, còn size S không?"},{role:"bot",text:"Dạ set Pyjama Lụa size S còn 3 bộ (Beige và Xám nhạt). Free ship cho đơn từ 300k chị nhé!"}]
  },
  {
    id:4, name:"Phạm Quốc Hùng", email:"hung.pham@company.vn", phone:"+84 911 222 333",
    userId:"CNF-20230445", gender:"Nam", age:38, dob:"1988-05-10", avatar_color:"#D97706",
    location:"Quận Bình Thạnh, TP HCM", membership:"Premium", join_date:"2023-04-15",
    channels:["Web"],
    aov:1200000, total_orders:5, total_spent:6000000,
    health_score:35,
    rfm:{recency:25, frequency:30, monetary:85},
    chatbot_insight:{
      USER:"Nam, 38 tuổi, giám đốc kinh doanh. Gu: premium, formal, thích brand cao cấp.",
      TARGET:"Bản thân (đi meeting, event).",
      GOAL:"Tìm blazer wool cho mùa đông, cần sang trọng.",
      CONSTRAINS:"Budget 1tr-2tr. Size L. Chỉ muốn màu tối (đen, navy, charcoal). Không muốn synthetic fabric.",
      LATEST_PRODUCT_INTEREST:"Áo Blazer Wool [8BL24W001] - Navy",
      LAST_ACTION:"Bot gợi ý Blazer Wool + quần âu matching. Khách abandoned cart 2 lần.",
      SUMMARY_HISTORY:"Hỏi blazer premium → bot gợi ý → khách add cart → abandoned → quay lại hỏi → abandoned lần 2"
    },
    predictions:{next_purchase:"Áo khoác blazer",next_purchase_conf:35,churn_risk:68,clv_6m:800000,next_visit_days:21,
      recommended_collab:[{name:"Áo Blazer Wool",icon:"🧥",reason:"Abandoned cart x2",conf:60},{name:"Sơ mi premium",icon:"👔",reason:"Phân khúc cao cấp",conf:45},{name:"Gift card Canifa",icon:"🎁",reason:"Win-back campaign",conf:40}],
      recommended_basket:[{name:"Quần âu wool blend",icon:"👖",reason:"Kèm blazer 70% đơn",conf:62},{name:"Cà vạt lụa",icon:"👔",reason:"Business set",conf:45},{name:"Giày leather",icon:"👞",reason:"Premium bundle",conf:38}],
      recommended_trending:[{name:"Áo khoác bomber",icon:"🧥",reason:"Trending nam 30+",conf:50},{name:"Polo premium pima",icon:"👔",reason:"Premium tier bestseller",conf:42},{name:"Belt da Ý",icon:"🪢",reason:"Rising luxury segment",conf:35}]
    },
    email_metrics:{delivered:15,opens:3,open_rate:20,click_rate:3,conversion_rate:1.5},
    segments:{purchase_likelihood:"Low",discount_affinity:"Low",customer_value:"Premium",lifecycle:"At-Risk"},
    top_categories:[{name:"Áo khoác nam",pct:40,color:"#D97706"},{name:"Sơ mi",pct:30,color:"#6366F1"},{name:"Quần âu",pct:20,color:"#10B981"},{name:"Khác",pct:10,color:"#EF4444"}],
    last_attrs:{"Last Seen":"canifa.com/nam/ao-khoac","Last Email Open":"—","Last Visited Category":"Áo khoác nam","Last Abandoned Cart":"1,290,000đ","Last Visited Product":"Áo Blazer Wool Navy"},
    products:{last_visited:{name:"Áo Blazer Wool Navy",price:"1,290,000đ",icon:"🧥"},last_purchased:{name:"Sơ mi Oxford",price:"499,000đ",icon:"👔"},last_abandoned:{name:"Áo Blazer Wool Navy",price:"1,290,000đ",icon:"🧥"}},
    mobile:{app_opened:1,push_opened:0,inapp_seen:0,inapp_from_push:0},
    journey:{entered:2,completed:1},
    purchase_timeline:[
      {date:"05/01/2026",name:"Sơ mi Oxford",price:"499,000đ",icon:"👔",channel:"Web"},
      {date:"20/11/2025",name:"Áo khoác dạ dài",price:"1,490,000đ",icon:"🧥",channel:"Web"}
    ],
    next_best_actions:[
      {icon:"🚨",title:"Win-back campaign URGENT",desc:"68% churn risk — không mua 82 ngày, cần retarget ngay",urgency:"urgent"},
      {icon:"💸",title:"Gửi voucher 200k cho blazer",desc:"Abandoned cart 1.29M x2 lần — giảm giá có thể convert",urgency:"urgent"},
      {icon:"📞",title:"Gọi điện chăm sóc VIP",desc:"Premium tier — personal touch có thể giữ chân",urgency:"medium"}
    ],
    engagement_heatmap:[[0,0,0,0,0,0,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]],
    chatbot_history:[{role:"user",text:"Blazer wool nam, size L, navy?"},{role:"bot",text:"Dạ anh, em có Blazer Wool Slim Fit (1,290,000đ) màu Navy, size L còn hàng. Chất wool blend 70%, lót viscose. Phù hợp đi meeting ạ!"}]
  },
  {
    id:5, name:"Đỗ Thanh Hà", email:"ha.do@gmail.com", phone:"+84 978 111 222",
    userId:"CNF-20260034", gender:"Nữ", age:20, dob:"2006-06-18", avatar_color:"#7C3AED",
    location:"Quận Đống Đa, Hà Nội", membership:"New Member", join_date:"2026-03-01",
    channels:["Zalo OA","Web","TikTok"],
    aov:295000, total_orders:3, total_spent:885000,
    health_score:72,
    rfm:{recency:80, frequency:35, monetary:30},
    chatbot_insight:{
      USER:"Nữ, 20 tuổi, sinh viên ĐH Kinh tế. Gu: trendy, GenZ, thích crop top & Y2K.",
      TARGET:"Bản thân, mua đi chơi + đi học.",
      GOAL:"Tìm áo crop top trendy, giá rẻ. Hay mua theo trend TikTok.",
      CONSTRAINS:"Budget dưới 300k. Size XS/S. Thích pastel & màu neon. Ghét basic boring.",
      LATEST_PRODUCT_INTEREST:"Crop Top Ribbed [7CT24S005] - Hồng pastel",
      LAST_ACTION:"Bot show 3 crop top dưới 200k. Khách thích Ribbed nhưng chưa mua vì hết pastel size XS.",
      SUMMARY_HISTORY:"Hỏi crop top trendy → bot list 3 options → khách thích ribbed → hết size → bot gợi ý size S → khách cân nhắc"
    },
    predictions:{next_purchase:"Áo crop top",next_purchase_conf:82,churn_risk:18,clv_6m:1500000,next_visit_days:2,
      recommended_collab:[{name:"Crop Top Ribbed",icon:"👕",reason:"Abandoned cart, giá rẻ",conf:88},{name:"Quần short denim",icon:"🩳",reason:"Combo mùa hè",conf:72},{name:"Kính mát",icon:"🕶️",reason:"Phụ kiện Gen Z",conf:50}],
      recommended_basket:[{name:"Sandal quai chéo",icon:"👡",reason:"Combo mùa hè 60%",conf:65},{name:"Túi đeo chéo mini",icon:"👜",reason:"Cross-sell Gen Z",conf:55},{name:"Nón bucket",icon:"🧢",reason:"Add-on trending",conf:45}],
      recommended_trending:[{name:"Áo babydoll",icon:"👚",reason:"#1 Gen Z nữ",conf:78},{name:"Quần culottes",icon:"👖",reason:"Rising +200%",conf:60},{name:"Set bikini",icon:"👙",reason:"Mùa hè sắp tới",conf:48}]
    },
    email_metrics:{delivered:8,opens:6,open_rate:75,click_rate:25,conversion_rate:12.0},
    segments:{purchase_likelihood:"High",discount_affinity:"High",customer_value:"New",lifecycle:"New Customer"},
    top_categories:[{name:"Áo crop top",pct:40,color:"#7C3AED"},{name:"Quần short",pct:30,color:"#F59E0B"},{name:"Phụ kiện",pct:18,color:"#10B981"},{name:"Khác",pct:12,color:"#EF4444"}],
    last_attrs:{"Last Seen":"canifa.com/nu/ao-croptop","Last Email Open":"Welcome Series #2","Last Visited Category":"Áo crop top","Last Abandoned Cart":"195,000đ","Last Visited Product":"Crop Top Ribbed Hồng"},
    products:{last_visited:{name:"Crop Top Ribbed Hồng",price:"195,000đ",icon:"👕"},last_purchased:{name:"Quần short kaki",price:"299,000đ",icon:"🩳"},last_abandoned:{name:"Crop Top Ribbed Hồng",price:"195,000đ",icon:"👕"}},
    mobile:{app_opened:12,push_opened:8,inapp_seen:6,inapp_from_push:4},
    journey:{entered:3,completed:2},
    purchase_timeline:[
      {date:"21/03/2026",name:"Quần short kaki",price:"299,000đ",icon:"🩳",channel:"Web"},
      {date:"15/03/2026",name:"Áo crop top basic x2",price:"298,000đ",icon:"👕",channel:"TikTok Shop"},
      {date:"10/03/2026",name:"Nón bucket cotton",price:"149,000đ",icon:"🧢",channel:"Web"}
    ],
    next_best_actions:[
      {icon:"🛒",title:"Nhắc cart Crop Top Ribbed 195k",desc:"Viewed 5x, abandoned 1x — very hot lead",urgency:"urgent"},
      {icon:"📱",title:"Push TikTok sale notification",desc:"High TikTok engagement — push > email cho GenZ",urgency:"medium"},
      {icon:"🎉",title:"Gửi Welcome voucher 10%",desc:"New customer — nurture với content mùa hè",urgency:"low"}
    ],
    engagement_heatmap:[[1,2,3,1,2,4,3],[2,3,4,2,3,5,4],[0,1,2,0,1,3,2],[0,0,1,0,0,1,0]],
    chatbot_history:[{role:"user",text:"có áo croptop nào dưới 200k k 💀"},{role:"bot",text:"Dạ chị, em có 3 mẫu Crop Top dưới 200k: Basic (149k), Ribbed (195k), và Henley (189k). Ribbed đang hot nhất ạ! 🔥"}]
  },
  {
    id:6, name:"Bùi Đức Thịnh", email:"thinh.bui@company.com", phone:"+84 966 333 444",
    userId:"CNF-20240201", gender:"Nam", age:30, dob:"1996-09-14", avatar_color:"#2563EB",
    location:"Quận Thanh Xuân, Hà Nội", membership:"VIP Silver", join_date:"2024-02-01",
    channels:["Zalo OA","Web","Email"],
    aov:520000, total_orders:15, total_spent:7800000,
    health_score:88,
    rfm:{recency:85, frequency:82, monetary:75},
    chatbot_insight:{
      USER:"Nam, 30 tuổi, nhân viên gym. Gu: sporty, athleisure, thích Dryfit.",
      TARGET:"Bản thân (gym + chạy bộ).",
      GOAL:"Mua đồ thể thao, quần jogger mới + áo tập gym.",
      CONSTRAINS:"Budget 300k-600k/item. Size M. Chỉ muốn Dryfit/tech fabric. Không thích cotton (thấm mồ hôi).",
      LATEST_PRODUCT_INTEREST:"Quần Jogger Tech v2 [8JG24S008] - Đen",
      LAST_ACTION:"Bot gợi ý set gym (áo tank + jogger). Khách mua áo Dryfit, jogger cân nhắc.",
      SUMMARY_HISTORY:"Hỏi đồ gym → bot gợi ý Dryfit → khách mua ngay áo → hỏi thêm jogger → cân nhắc v1 vs v2"
    },
    predictions:{next_purchase:"Quần jogger",next_purchase_conf:75,churn_risk:8,clv_6m:2800000,next_visit_days:4,
      recommended_collab:[{name:"Quần Jogger Tech v2",icon:"👖",reason:"Bản nâng cấp SP cũ",conf:80},{name:"Áo gió thể thao",icon:"🧥",reason:"Bổ sung set",conf:68},{name:"Giày sneaker",icon:"👟",reason:"Category #4, chưa mua",conf:52}],
      recommended_basket:[{name:"Bình nước thể thao",icon:"🧴",reason:"Add-on 45% đơn sportswear",conf:50},{name:"Tất thể thao x3",icon:"🧦",reason:"Bundle deal phổ biến",conf:42},{name:"Túi gym",icon:"🎒",reason:"Cross-sell lifestyle",conf:38}],
      recommended_trending:[{name:"Áo tank top dry-fit",icon:"👕",reason:"#1 sportswear nam",conf:72},{name:"Quần short chạy bộ",icon:"🩳",reason:"Rising +90%",conf:60},{name:"Áo compression",icon:"👕",reason:"New category hot",conf:48}]
    },
    email_metrics:{delivered:55,opens:32,open_rate:58,click_rate:18,conversion_rate:9.1},
    segments:{purchase_likelihood:"High",discount_affinity:"Medium",customer_value:"VIP",lifecycle:"Loyal Customer"},
    top_categories:[{name:"Đồ thể thao",pct:35,color:"#2563EB"},{name:"Quần jogger",pct:24,color:"#10B981"},{name:"Áo thun nam",pct:21,color:"#F59E0B"},{name:"Giày sneaker",pct:12,color:"#EF4444"},{name:"Phụ kiện",pct:8,color:"#8B5CF6"}],
    last_attrs:{"Last Seen":"canifa.com/nam/the-thao","Last Email Open":"Member Day Sale","Last Visited Category":"Đồ thể thao","Last Abandoned Cart":"—","Last Visited Product":"Quần Jogger Tech v2"},
    products:{last_visited:{name:"Quần Jogger Tech v2",price:"429,000đ",icon:"👖"},last_purchased:{name:"Áo thun Dryfit x2",price:"698,000đ",icon:"👕"},last_abandoned:{name:"—",price:"—",icon:"📦"}},
    mobile:{app_opened:20,push_opened:18,inapp_seen:9,inapp_from_push:7},
    journey:{entered:11,completed:9},
    purchase_timeline:[
      {date:"22/03/2026",name:"Áo thun Dryfit x2",price:"698,000đ",icon:"👕",channel:"Web"},
      {date:"18/03/2026",name:"Quần Jogger Tech v1",price:"399,000đ",icon:"👖",channel:"Zalo"},
      {date:"05/03/2026",name:"Set đồ thể thao (áo+quần)",price:"650,000đ",icon:"🏃",channel:"Web"},
      {date:"20/02/2026",name:"Giày sneaker trắng",price:"890,000đ",icon:"👟",channel:"Web"}
    ],
    next_best_actions:[
      {icon:"🏋️",title:"Push Jogger Tech v2 upgrade",desc:"Đã mua v1, giờ v2 ra → conf 80% upgrade",urgency:"urgent"},
      {icon:"⭐",title:"Mời referral program",desc:"Loyal + high engagement → ambassador potential",urgency:"medium"},
      {icon:"📱",title:"Push deal bundle 'Gym Set'",desc:"Áo + Quần + Giày combo giảm 25%",urgency:"medium"}
    ],
    engagement_heatmap:[[1,2,3,2,2,4,3],[2,3,4,3,3,5,4],[1,1,2,1,1,3,2],[0,1,1,1,0,1,1]],
    chatbot_history:[{role:"user",text:"Quần jogger tech v2 khác v1 gì anh?"},{role:"bot",text:"Dạ anh, v2 nâng cấp: vải 4-way stretch, túi zip chống rơi, thêm lưới thoáng khí ở đùi. Giá 429k (v1 là 399k). Đáng upgrade ạ!"}]
  }
];

// ═══ TRY LOAD FROM API, FALLBACK TO MOCK ═══
async function loadInsightData() {
  try {
    const resp = await fetch('/api/user-insights/all');
    const data = await resp.json();
    if (data.status === 'success' && data.insights && data.insights.length > 0) {
      // Merge API insights into mock users by identity_key or append as new
      data.insights.forEach((apiUser, idx) => {
        const existing = MOCK_USERS.find(u => u.userId === apiUser.identity_key);
        if (existing && apiUser.insight) {
          existing.chatbot_insight = apiUser.insight;
          existing._source = 'api';
        } else if (apiUser.insight) {
          // Create a new user entry from API data
          const insight = apiUser.insight;
          MOCK_USERS.push({
            id: 100 + idx, name: apiUser.identity_key,
            email: "—", phone: "—", userId: apiUser.identity_key,
            gender: insight.USER?.includes("Nữ") ? "Nữ" : insight.USER?.includes("Nam") ? "Nam" : "—",
            age: 0, dob: "—", avatar_color: ["#6366F1","#059669","#EC4899","#D97706","#7C3AED","#2563EB"][idx%6],
            location: "—", membership: "—", join_date: "—", channels: ["Chatbot"],
            aov: 0, total_orders: apiUser.message_count || 0, total_spent: 0,
            health_score: 50, rfm: {recency:50,frequency:50,monetary:50},
            chatbot_insight: insight,
            predictions: {next_purchase:"—",next_purchase_conf:0,churn_risk:50,clv_6m:0,next_visit_days:0,
              recommended_collab:[],recommended_basket:[],recommended_trending:[]},
            email_metrics: {delivered:0,opens:0,open_rate:0,click_rate:0,conversion_rate:0},
            segments: {purchase_likelihood:"Unknown",discount_affinity:"Unknown",customer_value:"Unknown",lifecycle:"Unknown"},
            top_categories: [], last_attrs: {},
            products: {last_visited:{name:"—",price:"—",icon:"📦"},last_purchased:{name:"—",price:"—",icon:"📦"},last_abandoned:{name:"—",price:"—",icon:"📦"}},
            mobile: {app_opened:0,push_opened:0,inapp_seen:0,inapp_from_push:0},
            journey: {entered:0,completed:0}, purchase_timeline: [],
            next_best_actions: [], engagement_heatmap: [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]],
            chatbot_history: [], _source: 'api'
          });
        }
      });
      DATA_SOURCE = 'api+mock';
      console.log(`✅ Loaded ${data.insights.length} insights from API + ${MOCK_USERS.length} total users`);
    }
  } catch (e) {
    console.log('ℹ️ API not available, using mock data only');
  }
  USERS = MOCK_USERS;
  if (typeof renderUserList === 'function') renderUserList();
}

// Auto-load on page init
USERS = MOCK_USERS;
loadInsightData();
