// ═══════════════════════════════════════════
// USER INSIGHT — RENDER ENGINE v2
// Renders full user profile + 6-layer chatbot insight
// ═══════════════════════════════════════════
let selectedUserId = null;
const fmt = n => new Intl.NumberFormat('vi-VN').format(n) + 'đ';
const segK = k => k.replace(/_/g,' ').replace(/\b\w/g,c=>c.toUpperCase());
const segC = v => {
  if(v==='High')return'seg-high';if(v==='Medium')return'seg-medium';if(v==='Low')return'seg-low';
  if(v==='VIP'||v==='Premium')return'seg-vip';if(v.includes('Active')||v.includes('Loyal'))return'seg-active';
  if(v==='New'||v.includes('New'))return'seg-high';if(v.includes('At-Risk'))return'seg-low';return'';
};

// ═══ USER LIST ═══
function renderUserList(filter=''){
  const el=document.getElementById('userItems');
  const f=USERS.filter(u=>!filter||u.name.toLowerCase().includes(filter.toLowerCase())||(u.email||'').toLowerCase().includes(filter.toLowerCase())||(u.phone||'').includes(filter));
  el.innerHTML=f.map(u=>`
    <div class="user-item ${selectedUserId===u.id?'active':''}" onclick="selectUser(${u.id})">
      <div class="user-avatar" style="background:${u.avatar_color}">${u.name.charAt(0)}</div>
      <div class="user-item-info">
        <div class="user-item-name">${u.name}</div>
        <div class="user-item-meta">${u.age?u.age+'t, ':''}${u.gender||''} ${u.location?'· '+u.location.split(',')[0]:''}</div>
      </div>
      <div class="user-item-right">
        <div class="val" style="color:${u.health_score>=70?'#059669':u.health_score>=40?'#D97706':'#DC2626'}">${u.health_score}</div>
        <div class="lbl">Health</div>
      </div>
    </div>
  `).join('');
}
function filterUsers(){renderUserList(document.getElementById('searchBox').value)}
function selectUser(id){selectedUserId=id;renderUserList(document.getElementById('searchBox').value);renderProfile(USERS.find(u=>u.id===id))}

// ═══ HEALTH RING SVG ═══
function healthRing(score){
  const r=52,c=2*Math.PI*r,pct=score/100,dash=c*pct,gap=c-dash;
  const col=score>=70?'#059669':score>=40?'#D97706':'#DC2626';
  return `<div class="health-ring"><svg viewBox="0 0 120 120">
    <circle cx="60" cy="60" r="${r}" fill="none" stroke="#E5E7EB" stroke-width="12"/>
    <circle cx="60" cy="60" r="${r}" fill="none" stroke="${col}" stroke-width="12"
      stroke-dasharray="${dash} ${gap}" stroke-dashoffset="${c*0.25}" stroke-linecap="round"
      transform="rotate(-90 60 60)" style="transition:stroke-dasharray .8s ease"/>
  </svg><div class="score-text"><div class="score-num" style="color:${col}">${score}</div><div class="score-lbl">Health</div></div></div>`;
}

// ═══ DONUT CHART ═══
function buildDonut(cats){
  if(!cats||!cats.length) return '<div style="text-align:center;color:#9CA3AF;padding:20px">Chưa có dữ liệu</div>';
  const s=140,cx=70,cy=70,r=50,sw=20,ci=2*Math.PI*r;let off=0;
  const segs=cats.map(c=>{const l=(c.pct/100)*ci;const s2=`<circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${c.color}" stroke-width="${sw}" stroke-dasharray="${l} ${ci-l}" stroke-dashoffset="${-off}" transform="rotate(-90 ${cx} ${cy})"/>`;off+=l;return s2});
  return `<svg class="donut-svg" viewBox="0 0 ${s} ${s}">${segs.join('')}</svg>`;
}

// ═══ FACTOR BAR ═══
function factorBar(label,score){
  const col=score>=70?'#059669':score>=40?'#D97706':'#DC2626';
  return `<div class="factor-card"><div class="f-head"><span class="f-name">${label}</span><span class="f-score" style="color:${col}">${score}</span></div><div class="factor-bar"><div class="factor-bar-fill" style="width:${score}%;background:${col}"></div></div></div>`;
}

// ═══ HEATMAP ═══
function buildHeatmap(data){
  if(!data||!data.length) return '<div style="text-align:center;color:#9CA3AF;padding:20px">Chưa có dữ liệu</div>';
  const days=['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const slots=['Sáng','Trưa','Chiều','Tối'];
  const maxV=Math.max(...data.flat(),1);
  const color=(v)=>{if(!v)return'#F3F4F6';const t=v/maxV;if(t>.7)return'#6366F1';if(t>.4)return'#A5B4FC';return'#C7D2FE'};
  let html=`<div class="heatmap-grid"><div class="h-label"></div>`;
  days.forEach(d=>{html+=`<div class="h-day">${d}</div>`});
  data.forEach((row,i)=>{html+=`<div class="h-label">${slots[i]}</div>`;row.forEach(v=>{html+=`<div class="h-cell" style="background:${color(v)}">${v||''}</div>`})});
  return html+'</div>';
}

// ═══ RECO SECTION ═══
function recoBlock(label,emoji,items){
  if(!items||!items.length) return '';
  return `<div class="reco-section"><div class="reco-strat-label">${emoji} ${label}</div><div class="reco-grid">${items.map(r=>`
    <div class="reco-item"><span class="reco-icon">${r.icon}</span><div><div class="reco-name">${r.name}</div><div class="reco-reason">${r.reason}</div></div><span class="reco-conf" style="color:${r.conf>=70?'#059669':r.conf>=50?'#D97706':'#9CA3AF'}">${r.conf}%</span></div>
  `).join('')}</div></div>`;
}

// ═══ CHATBOT INSIGHT RENDER (6-layer) ═══
function renderChatbotInsight(insight) {
  if (!insight) return '<div style="text-align:center;color:#9CA3AF;padding:30px">Chatbot chưa phân tích user này</div>';

  const layers = [
    { key:'USER', icon:'👤', label:'Người chat', color:'#6366F1', bgColor:'#EEF2FF' },
    { key:'TARGET', icon:'🎯', label:'Đối tượng thụ hưởng', color:'#059669', bgColor:'#F0FDF4' },
    { key:'GOAL', icon:'🛒', label:'Mục tiêu mua sắm', color:'#D97706', bgColor:'#FFFBEB' },
    { key:'CONSTRAINS', icon:'🔒', label:'Ràng buộc cứng', color:'#DC2626', bgColor:'#FEF2F2' },
    { key:'LATEST_PRODUCT_INTEREST', icon:'💎', label:'Sản phẩm quan tâm gần nhất', color:'#7C3AED', bgColor:'#F5F3FF' },
    { key:'LAST_ACTION', icon:'⚡', label:'Hành động bot vừa thực hiện', color:'#2563EB', bgColor:'#EFF6FF' },
    { key:'SUMMARY_HISTORY', icon:'📝', label:'Tóm tắt lịch sử chat', color:'#64748B', bgColor:'#F8FAFC' },
  ];

  return `<div class="insight-layers">${layers.map(l => {
    const val = insight[l.key];
    if (!val || val === 'Chưa rõ.' || val === 'Chưa có.' || val === 'Chưa có' || val === '') return '';
    return `<div class="insight-layer" style="border-left:3px solid ${l.color};background:${l.bgColor}">
      <div class="insight-layer-header">
        <span class="insight-layer-icon">${l.icon}</span>
        <span class="insight-layer-label" style="color:${l.color}">${l.label}</span>
      </div>
      <div class="insight-layer-value">${val}</div>
    </div>`;
  }).join('')}</div>`;
}

// ═══ MAIN RENDER ═══
function renderProfile(u){
  if(!u)return;
  document.getElementById('profileEmpty').style.display='none';
  const el=document.getElementById('profileContent');
  el.style.display='block';
  const p=u.predictions||{};
  const chC=(p.churn_risk||0)>=50?'pred-red':(p.churn_risk||0)>=20?'pred-amber':'pred-green';
  const coC=(p.next_purchase_conf||0)>=70?'pred-green':(p.next_purchase_conf||0)>=40?'pred-amber':'pred-red';

  el.innerHTML=`
    <div class="profile-tabs">
      <button class="tab-btn active" onclick="switchTab(this, 'tab-actual')">Tổng quan</button>
      <button class="tab-btn" onclick="switchTab(this, 'tab-insight')">
        <span style="color:#6366F1">🧠</span> AI Chatbot Insight
      </button>
      <button class="tab-btn" onclick="switchTab(this, 'tab-ai')">
        <span style="color:#6366F1">✨</span> AI Phân tích
      </button>
    </div>

    <!-- TAB 1: TỔNG QUAN -->
    <div id="tab-actual" class="tab-pane active">
      <!-- OVERVIEW -->
      <div class="section">
        <div class="section-label">User Overview</div>
        <div class="overview-grid">
          <div class="overview-avatar" style="background:${u.avatar_color}">${u.name.charAt(0)}</div>
          <div class="overview-details">
            <div><div class="overview-field-label">Tên</div><div class="overview-field-value">${u.name}</div></div>
            <div><div class="overview-field-label">Email</div><div class="overview-field-value">${u.email||'—'}</div></div>
            <div><div class="overview-field-label">User ID</div><div class="overview-field-value">${u.userId}</div></div>
            <div><div class="overview-field-label">Tuổi / Giới tính</div><div class="overview-field-value">${u.age||'—'} tuổi, ${u.gender||'—'}</div></div>
            <div><div class="overview-field-label">Ngày sinh</div><div class="overview-field-value">${u.dob||'—'}</div></div>
            <div><div class="overview-field-label">Membership</div><div class="overview-field-value"><span class="channel-tag" style="${u.membership?.includes('VIP')?'background:#FEF3C7;color:#92400E':u.membership?.includes('Premium')?'background:#EDE9FE;color:#5B21B6':''}">${u.membership||'—'}</span></div></div>
            <div><div class="overview-field-label">Địa chỉ</div><div class="overview-field-value">${u.location||'—'}</div></div>
            <div><div class="overview-field-label">SĐT</div><div class="overview-field-value">${u.phone||'—'}</div></div>
            <div><div class="overview-field-label">Channels</div><div>${(u.channels||[]).map(c=>`<span class="channel-tag">${c}</span>`).join('')}</div></div>
            <div><div class="overview-field-label">Ngày gia nhập</div><div class="overview-field-value">${u.join_date||'—'}</div></div>
            <div><div class="overview-field-label">Tổng đơn</div><div class="overview-field-value">${u.total_orders||0} đơn</div></div>
            <div><div class="overview-field-label">Tổng chi tiêu</div><div class="overview-field-value">${u.total_spent?fmt(u.total_spent):'—'}</div></div>
          </div>
        </div>
      </div>

      <!-- HEALTH SCORE + RFM -->
      <div class="section">
        <div class="section-label">Customer Health Score & RFM Analysis</div>
        <div class="health-row">
          ${healthRing(u.health_score||0)}
          <div class="health-factors">
            ${factorBar('Recency',u.rfm?.recency||0)}
            ${factorBar('Frequency',u.rfm?.frequency||0)}
            ${factorBar('Monetary',u.rfm?.monetary||0)}
          </div>
        </div>
      </div>

      <!-- EMAIL METRICS -->
      ${u.email_metrics?.delivered ? `<div class="section">
        <div class="section-label">Email Metrics (3 tháng)</div>
        <div class="metrics-row">
          <div class="metric-cell"><div class="m-label">Delivered</div><div class="m-value">${u.email_metrics.delivered}</div></div>
          <div class="metric-cell"><div class="m-label">Opens</div><div class="m-value">${u.email_metrics.opens}</div></div>
          <div class="metric-cell"><div class="m-label">Open Rate</div><div class="m-value">${u.email_metrics.open_rate}<span class="m-unit">%</span></div></div>
          <div class="metric-cell"><div class="m-label">Click Rate</div><div class="m-value">${u.email_metrics.click_rate}<span class="m-unit">%</span></div></div>
          <div class="metric-cell"><div class="m-label">Conversion</div><div class="m-value">${u.email_metrics.conversion_rate}<span class="m-unit">%</span></div></div>
        </div>
      </div>` : ''}

      <!-- PRODUCT CARDS -->
      ${u.products?.last_visited?.name!=='—' ? `<div class="product-cards">
        ${['last_visited','last_purchased','last_abandoned'].map(k=>{const pr=u.products[k];if(!pr||pr.name==='—')return'';const lbl=k==='last_visited'?'Last Visited':k==='last_purchased'?'Last Purchased':'Last Abandoned';return `<div class="product-card"><div class="product-card-icon">${pr.icon}</div><div class="product-card-info"><div class="product-card-label">${lbl}</div><div class="product-card-name">${pr.name}</div><div class="product-card-price">${pr.price}</div></div></div>`}).join('')}
      </div><div style="height:16px"></div>` : ''}

      <!-- PURCHASE TIMELINE -->
      ${u.purchase_timeline?.length ? `<div class="section">
        <div class="section-label">Lịch sử mua hàng</div>
        <div class="timeline">
          ${u.purchase_timeline.map(t=>`<div class="tl-item"><div class="tl-date">${t.date} · ${t.channel}</div><div class="tl-content"><span class="tl-icon">${t.icon}</span><div class="tl-detail"><div class="tl-name">${t.name}</div></div><span class="tl-price">${t.price}</span></div></div>`).join('')}
        </div>
      </div>` : ''}

      <!-- ENGAGEMENT HEATMAP + MOBILE -->
      <div class="two-col">
        <div class="section">
          <div class="section-label">Engagement Heatmap (tuần gần nhất)</div>
          ${buildHeatmap(u.engagement_heatmap)}
        </div>
        <div class="section">
          <div class="section-label">Mobile & Journey</div>
          <div class="mini-metrics" style="margin-bottom:12px">
            <div class="mini-cell"><div class="m-label">App</div><div class="m-value">${u.mobile?.app_opened||0}</div></div>
            <div class="mini-cell"><div class="m-label">Push</div><div class="m-value">${u.mobile?.push_opened||0}</div></div>
            <div class="mini-cell"><div class="m-label">InApp</div><div class="m-value">${u.mobile?.inapp_seen||0}</div></div>
            <div class="mini-cell"><div class="m-label">Push→InApp</div><div class="m-value">${u.mobile?.inapp_from_push||0}</div></div>
          </div>
          <div class="mini-metrics cols-2">
            <div class="mini-cell"><div class="m-label">Journeys Entered</div><div class="m-value">${u.journey?.entered||0}</div></div>
            <div class="mini-cell"><div class="m-label">Completed</div><div class="m-value">${u.journey?.completed||0}</div></div>
          </div>
        </div>
      </div>

      <!-- CHAT HISTORY -->
      ${u.chatbot_history?.length?`<div class="section"><div class="section-label">Lịch sử Chat gần nhất</div><div class="chat-history">${u.chatbot_history.map(m=>`<div class="chat-msg ${m.role}">${m.text}</div>`).join('')}</div></div>`:''}
    </div>

    <!-- TAB 2: AI CHATBOT INSIGHT (6-layer) -->
    <div id="tab-insight" class="tab-pane">
      <div class="section">
        <div class="section-label">🧠 Chatbot AI đã phân tích ${u.name}</div>
        <p style="font-size:12px;color:#6B7280;margin-bottom:16px">Insight 6 tầng được chatbot tự động tạo trong quá trình chat. Dữ liệu cập nhật real-time.</p>
        ${renderChatbotInsight(u.chatbot_insight)}
      </div>

      <!-- CHAT HISTORY in insight tab too -->
      ${u.chatbot_history?.length?`<div class="section"><div class="section-label">💬 Cuộc chat đã phân tích</div><div class="chat-history" style="max-height:400px">${u.chatbot_history.map(m=>`<div class="chat-msg ${m.role}">${m.text}</div>`).join('')}</div></div>`:''}
    </div>

    <!-- TAB 3: AI PHÂN TÍCH -->
    <div id="tab-ai" class="tab-pane">
      <!-- AI PREDICTIONS -->
      ${p.next_purchase ? `<div class="section">
        <div class="section-label">⚡ AI Core Predictions</div>
        <div class="pred-grid">
          <div class="pred-card ${coC}"><div class="pred-icon">🛒</div><div class="pred-val">${p.next_purchase}</div><div class="pred-lbl">Mua tiếp (${p.next_purchase_conf}%)</div></div>
          <div class="pred-card ${chC}"><div class="pred-icon">⚠️</div><div class="pred-val">${p.churn_risk}%</div><div class="pred-lbl">Churn Risk</div></div>
          <div class="pred-card pred-blue"><div class="pred-icon">💰</div><div class="pred-val">${p.clv_6m?fmt(p.clv_6m):'—'}</div><div class="pred-lbl">CLV 6 tháng</div></div>
          <div class="pred-card pred-blue"><div class="pred-icon">📅</div><div class="pred-val">${p.next_visit_days||'—'}d</div><div class="pred-lbl">Quay lại sau</div></div>
        </div>
      </div>` : ''}

      <!-- SEGMENTS + CATEGORIES + ATTRS -->
      <div class="three-col">
        <div class="section">
          <div class="section-label">Predictive Segments</div>
          ${u.segments?Object.entries(u.segments).map(([k,v])=>`<div class="segment-row"><span class="seg-label">${segK(k)}</span><span class="seg-value ${segC(v)}">${v}</span></div>`).join(''):'<div style="color:#9CA3AF">Chưa có</div>'}
        </div>
        <div class="section">
          <div class="section-label">Danh mục quan tâm</div>
          <div class="donut-wrap">${buildDonut(u.top_categories)}<div class="donut-legend">${(u.top_categories||[]).map(c=>`<div class="legend-row"><span class="legend-dot" style="background:${c.color}"></span><span>${c.name}</span><span class="legend-pct">${c.pct}%</span></div>`).join('')}</div></div>
        </div>
        <div class="section">
          <div class="section-label">Last Attributes</div>
          ${u.last_attrs?Object.entries(u.last_attrs).map(([k,v])=>`<div class="attr-row"><span class="attr-label">${k}</span><span class="attr-value">${v}</span></div>`).join(''):'<div style="color:#9CA3AF">Chưa có</div>'}
        </div>
      </div>

      <!-- RECOMMENDATION ENGINE -->
      ${p.recommended_collab?.length ? `<div class="section">
        <div class="section-label">🎯 Product Recommendation Engine</div>
        ${recoBlock('Vì bạn đã mua (Collaborative Filtering)','🧠',p.recommended_collab)}
        ${recoBlock('Thường mua cùng (Market Basket Analysis)','🛒',p.recommended_basket)}
        ${recoBlock('Trending trong phân khúc','🔥',p.recommended_trending)}
      </div>` : ''}

      <!-- NEXT BEST ACTIONS -->
      ${u.next_best_actions?.length ? `<div class="section">
        <div class="section-label">🚀 Next Best Actions (AI Suggested)</div>
        <div class="nba-grid">
          ${u.next_best_actions.map(a=>`<div class="nba-card nba-${a.urgency}"><div class="nba-icon">${a.icon}</div><div class="nba-title">${a.title}</div><div class="nba-desc">${a.desc}</div><span class="nba-tag">${a.urgency==='urgent'?'URGENT':a.urgency==='medium'?'MEDIUM':'LOW'}</span></div>`).join('')}
        </div>
      </div>` : ''}
    </div>
  `;
  document.getElementById('profilePane').scrollTop=0;
}

// ═══ TAB SWITCHING ═══
function switchTab(btn, tabId) {
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
  btn.classList.add('active');
  document.getElementById(tabId).classList.add('active');
}

// ═══ INIT ═══
renderUserList();
