// ═══════════════════════════════════════════
// USER INSIGHT — RENDER ENGINE
// ═══════════════════════════════════════════
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.email}</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){
  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){
  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){
  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>`;
}

// ═══ 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>=50?'pred-red':p.churn_risk>=20?'pred-amber':'pred-green';
  const coC=p.next_purchase_conf>=70?'pred-green':p.next_purchase_conf>=40?'pred-amber':'pred-red';

  el.innerHTML=`
    <div class="profile-tabs">
      <button class="tab-btn active" onclick="switchTab(this, 'tab-actual')">Tổng quan & Thực tế</button>
      <button class="tab-btn" onclick="switchTab(this, 'tab-ai')">
        <span style="color:#6366F1">✨</span> AI Phân tích & Đề xuất
      </button>
    </div>

    <!-- TAB 1: THỰC TẾ (ACTUAL) -->
    <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">Name</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">Channels</div><div>${u.channels.map(c=>`<span class="channel-tag">${c}</span>`).join('')}</div></div>
            <div><div class="overview-field-label">Phone</div><div class="overview-field-value">${u.phone}</div></div>
            <div><div class="overview-field-label">Tổng chi tiêu</div><div class="overview-field-value">${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)}
          <div class="health-factors">
            ${factorBar('Recency',u.rfm.recency)}
            ${factorBar('Frequency',u.rfm.frequency)}
            ${factorBar('Monetary',u.rfm.monetary)}
          </div>
        </div>
      </div>

      <!-- EMAIL METRICS -->
      <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 -->
      <div class="product-cards">
        ${['last_visited','last_purchased','last_abandoned'].map(k=>{const pr=u.products[k];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 -->
      <div class="section">
        <div class="section-label">Lịch sử mua hàng (Purchase Timeline)</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/JOURNEY -->
      <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}</div></div>
            <div class="mini-cell"><div class="m-label">Push</div><div class="m-value">${u.mobile.push_opened}</div></div>
            <div class="mini-cell"><div class="m-label">InApp</div><div class="m-value">${u.mobile.inapp_seen}</div></div>
            <div class="mini-cell"><div class="m-label">Push→InApp</div><div class="m-value">${u.mobile.inapp_from_push}</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}</div></div>
            <div class="mini-cell"><div class="m-label">Completed</div><div class="m-value">${u.journey.completed}</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 PHÂN TÍCH (AI ANALYSIS) -->
    <div id="tab-ai" class="tab-pane">
      <!-- AI PREDICTIONS -->
      <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">${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>
          ${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>
        <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">Predicted Last Attributes</div>
          ${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>
      </div>

      <!-- RECOMMENDATION ENGINE -->
      <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 -->
      <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();
