/* AAU CRM — Unified Inbox (3 columns, interactive) */

const INBOX_LABELS = [
  { id: 'hot', label: 'Hot', color: '#ef4444' },
  { id: 'proposal', label: 'Chờ proposal', color: '#f59e0b' },
  { id: 'callback', label: 'Hẹn gọi lại', color: '#3b82f6' },
  { id: 'franchise', label: 'Nhượng quyền', color: '#8b5cf6' },
  { id: 'care', label: 'Cần CSKH', color: '#0a9e6e' },
  { id: 'spam', label: 'Rác / Spam', color: '#9ca3af' },
];
const labelById = (id) => INBOX_LABELS.find(l => l.id === id);
const SENTIMENT = { cv1: 'pos', cv2: 'neu', cv3: 'neg', cv4: 'pos', cv5: 'neu', cv6: 'neg', cv7: 'neu', cv8: 'pos' };
const SENT_META = { pos: { l: 'Thiện chí', c: '#0a9e6e' }, neu: { l: 'Trung lập', c: '#8a8a8a' }, neg: { l: 'Do dự', c: '#c4320a' } };
const DUPES = { L1: 'Khoa BBQ — hồ sơ cũ (T9/2025)' };
const ME_ID = 'u5'; // người đang trực inbox (demo)

function ChannelAvatar({ ch, name, color, size = 40 }) {
  const c = (AAU.channels && AAU.channels[ch]) || { color: '#8a8f98', short: (ch || '?').toUpperCase() };
  return (
    <div style={{ position: 'relative', flexShrink: 0 }}>
      <Avatar name={name} color={color} size={size} />
      <span className="center" style={{ position: 'absolute', right: -2, bottom: -2, width: 17, height: 17, borderRadius: '50%', background: c.color, color: '#fff', fontSize: 9, fontWeight: 800, border: '2px solid #fff' }}>{c.short[0]}</span>
    </div>
  );
}

function LabelChip({ id, small, onRemove }) {
  const l = labelById(id); if (!l) return null;
  return (
    <span className="row aic g4" style={{ fontSize: small ? 9.5 : 11, fontWeight: 600, padding: small ? '0 5px' : '1px 7px', borderRadius: 5, background: l.color + '1f', color: l.color, lineHeight: 1.5, whiteSpace: 'nowrap' }}>
      <span style={{ width: 5, height: 5, borderRadius: '50%', background: l.color }} />{l.label}
      {onRemove && <span style={{ cursor: 'pointer', opacity: 0.6 }} onClick={e => { e.stopPropagation(); onRemove(); }}><Icon name="x" size={10} /></span>}
    </span>
  );
}

function SentimentChip({ s }) {
  const m = SENT_META[s] || SENT_META.neu;
  return <span className="badge" style={{ background: m.c + '1c', color: m.c, fontSize: 10.5 }}><span className="dot" style={{ background: m.c }} />{m.l}</span>;
}

/* ── Call modal (click-to-call → log + disposition) ── */
function CallModal({ lead, onClose, onLog }) {
  const [phase, setPhase] = useState('calling');
  const [sec, setSec] = useState(0);
  const [disp, setDisp] = useState('consulted');
  const [note, setNote] = useState('');
  useEffect(() => { if (phase !== 'calling') return; const t = setInterval(() => setSec(s => s + 1), 1000); return () => clearInterval(t); }, [phase]);
  const mmss = `${String(Math.floor(sec / 60)).padStart(2, '0')}:${String(sec % 60).padStart(2, '0')}`;
  const dispo = [
    { v: 'consulted', l: 'Đã tư vấn xong', tone: 'success' },
    { v: 'callback', l: 'Hẹn gọi lại', tone: 'info' },
    { v: 'noanswer', l: 'Không nghe máy', tone: 'warning' },
    { v: 'wrong', l: 'Sai số', tone: 'critical' },
    { v: 'refused', l: 'Từ chối', tone: 'critical' },
  ];
  return (
    <Modal title="Cuộc gọi đi" width={440} onClose={onClose}
      footer={phase === 'calling'
        ? <Button variant="critical" icon="phone" onClick={() => setPhase('ended')} style={{ margin: '0 auto' }}>Kết thúc cuộc gọi</Button>
        : <div className="row g8"><Button variant="plain" onClick={onClose}>Hủy</Button><Button variant="primary" icon="check" onClick={() => onLog({ duration: mmss, disp, note })}>Lưu vào nhật ký</Button></div>}>
      <div className="center col g10" style={{ padding: '14px 0 18px' }}>
        <Avatar name={lead.name} size={68} color={lead.grade === 'A' ? '#0a9e6e' : '#5b6cff'} />
        <div className="t17 fw7">{lead.name}</div>
        <div className="t13 muted tnum">{lead.phone}</div>
        {phase === 'calling'
          ? <span className="badge success" style={{ marginTop: 4 }}><span className="dot" style={{ animation: 'none' }} />Đang kết nối · {mmss}</span>
          : <span className="badge neutral" style={{ marginTop: 4 }}>Đã kết thúc · {mmss}</span>}
      </div>
      {phase === 'ended' && (
        <div className="col g12">
          <div>
            <div className="t12 fw7 subtle mb6">KẾT QUẢ CUỘC GỌI</div>
            <div className="row g8 wrap">
              {dispo.map(d => (
                <button key={d.v} className={'pill-tab'} style={{ border: 'none', padding: 0 }} onClick={() => setDisp(d.v)}>
                  <span className="pill-tab"><button className={disp === d.v ? 'on' : ''}>{d.l}</button></span>
                </button>
              ))}
            </div>
          </div>
          <div>
            <div className="t12 fw7 subtle mb6">GHI CHÚ</div>
            <textarea className="input" rows={3} value={note} onChange={e => setNote(e.target.value)} placeholder="Tóm tắt nội dung trao đổi, cam kết tiếp theo…" style={{ resize: 'none' }} />
          </div>
          <div className="row aic g8 t12 subtle"><Icon name="checkCircle" size={14} color="#0e7c4a" />Tự động ghi vào hội thoại + Timeline hồ sơ 360°. Chọn "Hẹn gọi lại" sẽ snooze hội thoại.</div>
        </div>
      )}
    </Modal>
  );
}

function InboxEmptyState() {
  return (
    <div className="page wide">
      <PageHead title="Hội thoại" subtitle="Hộp thư hợp nhất các kênh chat" />
      <EmptyState icon="inbox" title="Chưa có hội thoại nào"
        desc="Đã xoá sạch dữ liệu chat. Vào 'Nguồn kết nối' → thêm kênh thật + nối CQA (CQA_DB_DSN) + Đồng bộ để kéo tin nhắn Zalo thật về đây." />
    </div>
  );
}

// Wrapper: chặn crash khi chưa có hội thoại nào (sau khi wipe / trước khi nối real data).
function UnifiedInbox() {
  if (!AAU.conversations || Object.keys(AAU.conversations).length === 0) return <InboxEmptyState />;
  return <UnifiedInboxBody />;
}

function UnifiedInboxBody() {
  const convList = Object.values(AAU.conversations);
  // Hội thoại thật từ CQA có thể CHƯA gắn lead (leadId rỗng) → trả lead mặc định an
  // toàn để màn không crash. Khi lead được tạo/nối, lookup thật sẽ thay thế.
  const leadOf = c => AAU.leadById(c.leadId) || {
    id: '', name: c.name || 'Khách', company: '', role: '', phone: '', email: '',
    bizModel: '', industry: '', courseInterest: '', source: c.channel || 'zalo', channel: c.channel || 'zalo',
    stage: 's4', branch: '', grade: '', dealValue: 0, sla: 'ok', slaLeft: '', hot: false,
    signal: { level: '', text: '' }, painpoints: [], region: '', assignedTo: '', qualify: {},
  };
  const [chFilter, setChFilter] = useState('all');
  const [triage, setTriage] = useState('all');
  const [q, setQ] = useState('');
  const [selId, setSelId] = useState(() => {
    const ni = window.NavIntent;
    if (ni && ni.inboxConv && AAU.conversations[ni.inboxConv]) { window.NavIntent = null; return ni.inboxConv; }
    return convList[0].id;
  });
  const [store, setStore] = useState(() => JSON.parse(JSON.stringify(AAU.conversations)));
  const [meta, setMeta] = useState(() => {
    const m = {};
    convList.forEach(c => {
      const l = leadOf(c);
      const labels = [];
      if (l.hot) labels.push('hot');
      if (l.courseInterest === 'c10') labels.push('franchise');
      if (['s6', 's7'].includes(l.stage)) labels.push('proposal');
      m[c.id] = { owner: l.assignedTo || '', labels, status: 'open', snoozeLabel: '', notes: [] };
    });
    if (m.cv1) m.cv1.notes = [{ id: 'n0', by: ME_ID, at: new Date(Date.now() - 36e5).toISOString(), text: '@Lê Vy khách quyết nhanh, ưu tiên gọi xác nhận lịch trước 5h chiều nay nhé.' }];
    return m;
  });
  const [draft, setDraft] = useState('');
  const [composerTab, setComposerTab] = useState('reply');
  const [aiMode, setAiMode] = useState(store[selId].aiMode);
  const [copilot, setCopilot] = useState('');
  const [playbook, setPlaybook] = useState(true);
  const [slash, setSlash] = useState(false);
  const [panel, setPanel] = useState(true);
  const [botOff, setBotOff] = useState({});
  const [labelMenu, setLabelMenu] = useState(false);
  const [assignMenu, setAssignMenu] = useState(false);
  const [attachMenu, setAttachMenu] = useState(false);
  const [callOpen, setCallOpen] = useState(false);
  const bodyRef = useRef(null);

  const conv = store[selId];
  const lead = leadOf(conv);
  const cm = meta[selId];
  const sales = AAU.users.filter(u => u.role === 'sales');

  const playbookSteps = {
    s7: { step: 'Bước: Chốt đàm phán', tip: 'Khách đã hỏi proposal & muốn chốt sớm → đưa ưu đãi early-bird có thời hạn, xác nhận lịch khai giảng.', asset: 'Brochure Nhượng quyền + Bảng giá Q2', reply: 'Dạ em xác nhận ưu đãi early-bird giảm 20% nếu anh đăng ký trước 15/06. Lớp Nhượng quyền F&B khai giảng 22/06, em giữ slot giúp anh nhé?' },
    s6: { step: 'Bước: Theo dõi proposal', tip: 'Đã gửi proposal → hỏi phản hồi, xử lý phản đối về ngân sách.', asset: 'Case study + So sánh đối thủ', reply: 'Dạ chị xem proposal em gửi chưa ạ? Nếu cần em gửi thêm case study của chuỗi tương tự để chị tham khảo phần ROI nhé.' },
    s5: { step: 'Bước: Tư vấn chuyên sâu', tip: 'Đào sâu painpoint, map đúng khóa, đặt lịch tư vấn 1-1.', asset: 'Pitch deck khóa quan tâm', reply: 'Dạ để tư vấn sát nhất, em xin phép đặt lịch gọi 15 phút trao đổi về tình hình quán mình hiện tại được không ạ?' },
    s4: { step: 'Bước: Qualify SQL', tip: 'Xác nhận mô hình KD, ngân sách, nhu cầu → chấm điểm qualify.', asset: 'Brochure khóa + Bảng giá', reply: 'Dạ để em tư vấn đúng khóa, cho em hỏi hiện quán mình đang vận hành mấy điểm và anh/chị muốn cải thiện nhất điều gì ạ?' },
  };
  const pb = playbookSteps[lead.stage] || playbookSteps.s4;
  const detectedMap = {
    s7: { label: '"Đòi chốt nhanh / hỏi thanh toán"', cat: 'Tín hiệu mua', color: '#0e7c4a', win: 88 },
    s6: { label: '"Im lặng > 3 ngày sau báo giá"', cat: 'Rủi ro mất deal', color: '#b42318', win: 33 },
    s5: { label: '"So sánh AAU vs đối thủ X"', cat: 'So sánh đối thủ', color: '#6d28d9', win: 59 },
    s4: { label: '"Hỏi lịch khai giảng"', cat: 'Câu hỏi lặp lại', color: '#1a4fa3', win: 72 },
  };
  const detected = detectedMap[lead.stage] || detectedMap.s4;

  useEffect(() => { setAiMode(store[selId].aiMode); setComposerTab('reply'); }, [selId]);
  useEffect(() => { setCopilot(aiMode === 'copilot' ? pb.reply : ''); }, [selId, aiMode]);
  useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [selId, conv.messages.length, cm.notes.length]);

  function patchMeta(id, p) { setMeta(m => ({ ...m, [id]: { ...m[id], ...p } })); }

  const triageTabs = [
    { v: 'all', l: 'Tất cả', f: c => meta[c.id].status !== 'done' },
    { v: 'unread', l: 'Chưa đọc', f: c => c.unread > 0 && meta[c.id].status !== 'done' },
    { v: 'mine', l: 'Của tôi', f: c => meta[c.id].owner === ME_ID && meta[c.id].status !== 'done' },
    { v: 'unassigned', l: 'Chưa gán', f: c => !meta[c.id].owner && meta[c.id].status !== 'done' },
    { v: 'overdue', l: 'Quá hạn SLA', f: c => leadOf(c).sla === 'bad' && meta[c.id].status !== 'done' },
    { v: 'snoozed', l: 'Snooze', f: c => meta[c.id].status === 'snoozed' },
    { v: 'done', l: 'Xong', f: c => meta[c.id].status === 'done' },
  ];
  const triF = triageTabs.find(t => t.v === triage).f;

  const filtered = convList
    .filter(triF)
    .filter(c => (chFilter === 'all' || c.channel === chFilter) && (!q || leadOf(c).name.toLowerCase().includes(q.toLowerCase())))
    .sort((a, b) => new Date(b.lastAt) - new Date(a.lastAt));

  // keyboard shortcuts: J/K navigate, E mark done
  useEffect(() => {
    function onKeyG(e) {
      if (/input|textarea|select/i.test(e.target.tagName)) return;
      const ids = filtered.map(c => c.id); const i = ids.indexOf(selId);
      if (e.key === 'j' && i < ids.length - 1) { setSelId(ids[i + 1]); }
      else if (e.key === 'k' && i > 0) { setSelId(ids[i - 1]); }
      else if (e.key === 'e') { patchMeta(selId, { status: 'done' }); }
    }
    window.addEventListener('keydown', onKeyG);
    return () => window.removeEventListener('keydown', onKeyG);
  }, [filtered, selId]);

  // A — auto-refresh: định kỳ kéo /conversations, gộp tin mới (theo id) vào store +
  // cập nhật danh sách trái. Không clobber tin optimistic/note đang có.
  useEffect(() => {
    if (!(window.API && window.API.enabled && window.API.get)) return;
    let alive = true;
    const pull = () => window.API.get('/conversations').then(server => {
      if (!alive || !server) return;
      const list = Array.isArray(server) ? server : Object.values(server);
      list.forEach(sc => { AAU.conversations[sc.id] = { ...(AAU.conversations[sc.id] || {}), ...sc }; });
      // lead mới (auto-tạo từ chat) chưa có trong AAU.leads → refresh để panel + kanban điền
      const haveLead = new Set((AAU.leads || []).map(l => l.id));
      if (list.some(sc => sc.leadId && !haveLead.has(sc.leadId)) && window.API.refreshLeads) window.API.refreshLeads().catch(() => { });
      setMeta(m => { let ch = false; const nm = { ...m }; list.forEach(sc => { if (!nm[sc.id]) { const l = leadOf(sc); nm[sc.id] = { owner: l.assignedTo || '', labels: [], status: 'open', snoozeLabel: '', notes: [] }; ch = true; } }); return ch ? nm : m; });
      setStore(prev => {
        const next = { ...prev }; let ch = false;
        list.forEach(sc => {
          const loc = prev[sc.id];
          if (!loc) { next[sc.id] = sc; ch = true; return; }
          const have = new Set((loc.messages || []).map(m => m.id));
          const add = (sc.messages || []).filter(m => !have.has(m.id));
          if (add.length || sc.unread !== loc.unread || sc.lastAt !== loc.lastAt || sc.leadId !== loc.leadId) {
            next[sc.id] = { ...loc, leadId: sc.leadId || loc.leadId, linked: !!(sc.leadId || loc.leadId), name: sc.name || loc.name, messages: [...(loc.messages || []), ...add].sort((a, b) => new Date(a.at) - new Date(b.at)), lastAt: sc.lastAt || loc.lastAt, unread: sc.unread };
            ch = true;
          }
        });
        return ch ? next : prev;
      });
    }).catch(() => { });
    const iv = setInterval(pull, 30000);
    return () => { alive = false; clearInterval(iv); };
  }, []);

  // Tạo Lead từ chat hiện tại → gắn vào pipeline + điền panel.
  function createLeadFromChat() {
    if (!(window.API && window.API.enabled)) { window.alert('Cần chế độ LIVE để tạo lead.'); return; }
    const cid = selId;
    window.API.createLeadFromConv(cid).then(lead => {
      if (!lead || !lead.id) return;
      if (Array.isArray(AAU.leads) && !AAU.leads.some(l => l.id === lead.id)) AAU.leads.unshift(lead);
      if (typeof LeadStore !== 'undefined' && LeadStore.reload) LeadStore.reload();
      AAU.conversations[cid] = { ...(AAU.conversations[cid] || {}), leadId: lead.id, linked: true };
      setStore(s => { const c = s[cid]; if (!c) return s; return { ...s, [cid]: { ...c, leadId: lead.id, linked: true } }; });
    }).catch(e => window.alert('Tạo lead lỗi: ' + (e && e.message || e)));
  }

  const lastOutId = [...conv.messages].reverse().find(m => m.dir === 'out')?.id;

  // B — gửi ra khách: optimistic 'sending' → patch theo kết quả thật (delivered/failed).
  function send(text) {
    const t = (text ?? draft).trim(); if (!t) return;
    const mid = 'x' + Date.now();
    const liveSend = !!(window.API && window.API.enabled);
    setStore(s => { const n = { ...s }; n[selId] = { ...n[selId], messages: [...n[selId].messages, { id: mid, dir: 'out', at: new Date().toISOString(), by: ME_ID, text: t, ai: aiMode === 'autopilot', status: liveSend ? 'sending' : 'sent' }], unread: 0 }; return n; });
    setDraft(''); setSlash(false); setCopilot('');
    if (liveSend) {
      const cid = selId;
      window.API.sendMessage(cid, t, ME_ID)
        .then(r => setStore(s => { const c = s[cid]; if (!c) return s; return { ...s, [cid]: { ...c, messages: c.messages.map(m => m.id === mid ? { ...m, id: (r && r.id) || mid, status: (r && r.delivered) ? 'delivered' : 'sent', note: r && r.note } : m) } }; }))
        .catch(e => { setStore(s => { const c = s[cid]; if (!c) return s; return { ...s, [cid]: { ...c, messages: c.messages.map(m => m.id === mid ? { ...m, status: 'failed' } : m) } }; }); window.alert('Gửi tới khách thất bại: ' + (e && e.message || e)); });
    }
  }
  function attach(name) {
    setStore(s => { const n = { ...s }; n[selId] = { ...n[selId], messages: [...n[selId].messages, { id: 'x' + Date.now(), dir: 'out', at: new Date().toISOString(), by: ME_ID, attachment: name, status: 'sent' }] }; return n; });
    setAttachMenu(false);
  }
  function saveNote() {
    const t = draft.trim(); if (!t) return;
    patchMeta(selId, { notes: [...cm.notes, { id: 'n' + Date.now(), by: ME_ID, at: new Date().toISOString(), text: t }] });
    setDraft('');
  }
  function onKey(e) { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); composerTab === 'note' ? saveNote() : send(); } }
  function onDraft(v) { setDraft(v); setSlash(composerTab === 'reply' && v.startsWith('/')); }
  function logCall({ duration, disp, note }) {
    const dispMap = { consulted: 'Đã tư vấn xong', callback: 'Hẹn gọi lại', noanswer: 'Không nghe máy', wrong: 'Sai số', refused: 'Từ chối' };
    setStore(s => { const n = { ...s }; n[selId] = { ...n[selId], messages: [...n[selId].messages, { id: 'c' + Date.now(), type: 'call', dir: 'out', at: new Date().toISOString(), by: ME_ID, duration, disp: dispMap[disp], note }] }; return n; });
    if (window.API && window.API.enabled) { const lid = (store[selId] || {}).leadId; if (lid) window.API.logCall({ leadId: lid, duration, agent: ME_ID, verdict: disp }).catch(() => {}); }
    if (disp === 'callback') patchMeta(selId, { status: 'snoozed', snoozeLabel: 'Hẹn gọi lại 3h', labels: [...new Set([...cm.labels, 'callback'])] });
    setCallOpen(false);
  }

  // merged thread (messages + internal notes), sorted
  const thread = [
    ...conv.messages.map(m => ({ ...m, _t: m.type === 'call' ? 'call' : 'msg' })),
    ...cm.notes.map(n => ({ ...n, _t: 'note', at: n.at })),
  ].sort((a, b) => new Date(a.at) - new Date(b.at));

  const assets = ['Brochure Nhượng quyền F&B', 'Bảng giá Q2/2026', 'Case study chuỗi 6 chi nhánh', 'Lịch khai giảng tháng 6'];
  const aiOpts = [{ value: 'off', label: 'Tắt' }, { value: 'copilot', label: 'Copilot' }, { value: 'autopilot', label: 'Autopilot' }];

  return (
    <div style={{ height: '100%', display: 'grid', gridTemplateColumns: panel ? '340px minmax(440px,1fr) 322px' : '340px minmax(460px,1fr)', minWidth: panel ? 1102 : 800 }}>
      {/* LEFT */}
      <div className="col" style={{ borderRight: '1px solid var(--p-border)', height: '100%', gap: 0, minWidth: 0, overflow: 'hidden' }}>
        <div style={{ padding: '14px 14px 8px' }}>
          <div className="row jcsb aic mb10"><span className="t17 fw7">Hộp thư</span><Badge tone="critical">{convList.reduce((s, c) => s + c.unread, 0)} chưa đọc</Badge></div>
          <div className="row g8 aic">
            <div className="f1"><Input icon="search" placeholder="Tìm khách hàng…" value={q} onChange={setQ} /></div>
            <Select value={chFilter} onChange={setChFilter} options={[{ value: 'all', label: 'Mọi kênh' }, { value: 'fb', label: 'FB' }, { value: 'zalo', label: 'Zalo' }, { value: 'instagram', label: 'IG' }, { value: 'tiktok', label: 'TikTok' }]} style={{ width: 96 }} />
          </div>
          <div className="row g6 mt10" style={{ overflowX: 'auto', paddingBottom: 4 }}>
            {triageTabs.map(t => { const n = convList.filter(t.f).length; return (
              <button key={t.v} onClick={() => setTriage(t.v)} className="row aic g4" style={{ flexShrink: 0, fontSize: 11.5, fontWeight: 600, padding: '4px 9px', borderRadius: 7, cursor: 'pointer', border: '1px solid ' + (triage === t.v ? '#1a4fa3' : 'var(--p-border)'), background: triage === t.v ? '#1a4fa3' : '#fff', color: triage === t.v ? '#fff' : 'var(--p-text)' }}>
                {t.l}<span style={{ fontSize: 10, opacity: triage === t.v ? 0.85 : 0.5 }}>{n}</span>
              </button>
            ); })}
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', borderTop: '1px solid var(--p-border-secondary)' }}>
          {filtered.length === 0 && <div className="t12 muted center" style={{ padding: 30 }}>Không có hội thoại nào.</div>}
          {filtered.map(c => { const l = leadOf(c); const m2 = meta[c.id]; const last = c.messages[c.messages.length - 1]; const sel = c.id === selId; return (
            <div key={c.id} onClick={() => setSelId(c.id)} style={{ display: 'flex', gap: 10, padding: '11px 14px', cursor: 'pointer', background: sel ? 'var(--p-bg-surface-selected)' : 'transparent', borderBottom: '1px solid var(--p-border-secondary)', borderLeft: sel ? '3px solid #1a4fa3' : '3px solid transparent', opacity: m2.status === 'done' ? 0.6 : 1 }}>
              <ChannelAvatar ch={c.channel} name={l.name} color={l.grade === 'A' ? '#0a9e6e' : '#5b6cff'} size={42} />
              <div className="f1" style={{ minWidth: 0 }}>
                <div className="row jcsb aic g6"><span className="t13 fw6 row aic g4" style={{ minWidth: 0, flex: 1 }}><span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.name}</span>{l.hot && <HotIcon />}</span><span className="t11 subtle" style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>{relTime(c.lastAt)}</span></div>
                <div className="t12 muted" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{!last ? '—' : last.type === 'call' ? '📞 Cuộc gọi' : (last.dir === 'out' ? 'Bạn: ' : '') + (last.attachment ? '📎 ' + last.attachment : (last.text || ''))}</div>
                <div className="row aic g6 mt4" style={{ flexWrap: 'nowrap', minWidth: 0 }}>
                  <div className="row aic g4" style={{ minWidth: 0, flex: 1, overflow: 'hidden' }}>
                    {m2.status === 'snoozed' && <span className="badge info" style={{ fontSize: 9.5, padding: '0 5px', flexShrink: 0 }}><Icon name="clock" size={10} />{m2.snoozeLabel || 'Snooze'}</span>}
                    {m2.status === 'done' && <span className="badge success" style={{ fontSize: 9.5, padding: '0 5px', flexShrink: 0 }}><Icon name="check" size={10} />Xong</span>}
                    {m2.labels.slice(0, 2).map(id => <LabelChip key={id} id={id} small />)}
                  </div>
                  <span style={{ flexShrink: 0 }}><SLATag sla={l.sla} left={l.slaLeft} /></span>
                  {c.unread > 0 && <span className="ni-badge" style={{ flexShrink: 0 }}>{c.unread}</span>}
                </div>
              </div>
            </div>
          ); })}
        </div>
      </div>

      {/* MIDDLE */}
      <div className="col" style={{ height: '100%', minHeight: 0, gap: 0, minWidth: 0 }}>
        <div className="row aic g10" style={{ padding: '11px 18px 9px', borderBottom: '1px solid var(--p-border-secondary)' }}>
          <ChannelAvatar ch={conv.channel} name={lead.name} color={lead.grade === 'A' ? '#0a9e6e' : '#5b6cff'} size={38} />
          <div className="f1" style={{ minWidth: 0 }}><div className="row aic g8"><span className="t15 fw7">{lead.name}</span>{lead.hot && <HotIcon />}<GradeBadge grade={lead.grade} /><SentimentChip s={SENTIMENT[conv.id]} /></div><div className="t12 muted">{lead.company} · {AAU.channels[conv.channel].label}</div></div>
          <span className={'badge ' + (conv.windowLeft === 'Hết hạn' ? 'critical' : 'info')}><Icon name="clock" size={12} />Cửa sổ {conv.windowLeft}</span>
          <IconButton name="phone" title="Gọi điện" onClick={() => setCallOpen(true)} />
          <IconButton name="user" title="Mở hồ sơ 360°" onClick={() => navigate('/leads/' + lead.id)} />
          <IconButton name="columns" title={panel ? 'Ẩn hồ sơ' : 'Hiện hồ sơ'} onClick={() => setPanel(!panel)} />
        </div>

        {/* Toolbar: owner · labels · snooze/done */}
        <div className="row aic g8" style={{ padding: '7px 18px', borderBottom: '1px solid var(--p-border)', position: 'relative', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative' }}>
            <button className="row aic g6" onClick={() => { setAssignMenu(!assignMenu); setLabelMenu(false); }} style={{ cursor: 'pointer', border: '1px solid var(--p-border)', borderRadius: 7, padding: '3px 8px 3px 4px', background: '#fff' }}>
              {cm.owner ? <><Avatar name={AAU.users.find(u => u.id === cm.owner)?.name} color={AAU.users.find(u => u.id === cm.owner)?.color} size={20} /><span className="t12 fw5">{AAU.users.find(u => u.id === cm.owner)?.name}</span></> : <span className="t12 fw6" style={{ padding: '0 4px', color: '#c4320a' }}><Icon name="user" size={13} /> Chưa gán</span>}
              <Icon name="chevronDown" size={13} />
            </button>
            {assignMenu && (
              <div style={{ position: 'absolute', top: '100%', left: 0, zIndex: 30, marginTop: 4, width: 200, background: '#fff', border: '1px solid var(--p-border)', borderRadius: 10, boxShadow: 'var(--p-shadow-popover)', overflow: 'hidden' }}>
                <div className="t11 subtle" style={{ padding: '8px 12px 4px', fontWeight: 700 }}>GÁN PHỤ TRÁCH</div>
                {sales.map(u => (
                  <div key={u.id} className="row aic g8" onClick={() => { patchMeta(selId, { owner: u.id }); setAssignMenu(false); }} style={{ padding: '8px 12px', cursor: 'pointer', background: cm.owner === u.id ? 'var(--p-bg-surface-selected)' : '' }} onMouseEnter={e => { if (cm.owner !== u.id) e.currentTarget.style.background = 'var(--p-bg-surface-hover)'; }} onMouseLeave={e => { if (cm.owner !== u.id) e.currentTarget.style.background = ''; }}>
                    <Avatar name={u.name} color={u.color} size={24} /><span className="t12 fw5 f1">{u.name}</span>{cm.owner === u.id && <Icon name="check" size={14} color="#0e7c4a" />}
                  </div>
                ))}
              </div>
            )}
          </div>
          {cm.labels.map(id => <LabelChip key={id} id={id} onRemove={() => patchMeta(selId, { labels: cm.labels.filter(x => x !== id) })} />)}
          <div style={{ position: 'relative' }}>
            <button className="iconbtn" title="Gắn nhãn" onClick={() => { setLabelMenu(!labelMenu); setAssignMenu(false); }} style={{ width: 26, height: 26 }}><Icon name="tag" size={14} /></button>
            {labelMenu && (
              <div style={{ position: 'absolute', top: '100%', left: 0, zIndex: 30, marginTop: 4, width: 190, background: '#fff', border: '1px solid var(--p-border)', borderRadius: 10, boxShadow: 'var(--p-shadow-popover)', overflow: 'hidden', padding: 6 }}>
                {INBOX_LABELS.map(l => { const on = cm.labels.includes(l.id); return (
                  <div key={l.id} className="row aic g8" onClick={() => patchMeta(selId, { labels: on ? cm.labels.filter(x => x !== l.id) : [...cm.labels, l.id] })} style={{ padding: '7px 8px', cursor: 'pointer', borderRadius: 7 }} onMouseEnter={e => e.currentTarget.style.background = 'var(--p-bg-surface-hover)'} onMouseLeave={e => e.currentTarget.style.background = ''}>
                    <Checkbox on={on} onChange={() => {}} /><LabelChip id={l.id} />
                  </div>
                ); })}
              </div>
            )}
          </div>
          <div className="mla row aic g6">
            {cm.status === 'snoozed'
              ? <Button size="sm" variant="plain" icon="clock" onClick={() => patchMeta(selId, { status: 'open', snoozeLabel: '' })}>Bỏ snooze</Button>
              : <Button size="sm" variant="plain" icon="clock" onClick={() => patchMeta(selId, { status: 'snoozed', snoozeLabel: 'Snooze 3h' })}>Snooze</Button>}
            {cm.status === 'done'
              ? <Button size="sm" variant="secondary" icon="refresh" onClick={() => patchMeta(selId, { status: 'open' })}>Mở lại</Button>
              : <Button size="sm" variant="success" icon="check" onClick={() => patchMeta(selId, { status: 'done' })}>Đánh dấu xong</Button>}
          </div>
        </div>

        {['fb', 'instagram', 'zalo'].includes(conv.channel) && (
          botOff[selId] ? (
            <div className="row aic g8" style={{ padding: '8px 18px', background: 'var(--p-success-bg)', borderBottom: '1px solid var(--p-border-secondary)' }}>
              <Icon name="checkCircle" size={15} color="#0e7c4a" />
              <span className="t12" style={{ color: '#0e7c4a' }}>Đã tắt bot tự động {AAU.channels[conv.channel].label} — hội thoại do CRM điều khiển, sales trả lời trực tiếp.</span>
              <button className="linkish mla t12 fw6" onClick={() => setBotOff(s => ({ ...s, [selId]: false }))}>Bật lại bot</button>
            </div>
          ) : (
            <div className="row aic g10" style={{ padding: '9px 18px', background: 'var(--p-warning-bg)', borderBottom: '1px solid var(--p-border-secondary)' }}>
              <Icon name="robot" size={16} color="#b06f00" />
              <div className="f1 t12" style={{ color: '#7a4d00' }}><b>Bot tự động {AAU.channels[conv.channel].label} đang trả lời.</b> Tắt để chuyển hội thoại về hệ thống chat & sales tiếp quản.</div>
              <Button size="sm" variant="secondary" icon="robot" onClick={() => { setBotOff(s => ({ ...s, [selId]: true })); if (window.API && window.API.enabled) window.API.setAIMode(selId, 'off').catch(() => {}); }}>Tắt bot & nhận hội thoại</Button>
            </div>
          )
        )}

        <div ref={bodyRef} style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '18px 18px 8px', background: 'var(--p-bg-surface-secondary)' }}>
          {thread.map(m => {
            if (m._t === 'note') return (
              <div key={m.id} style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
                <div style={{ maxWidth: '82%', width: '100%', background: '#fff7e0', border: '1px solid #f0d27a', borderRadius: 10, padding: '8px 12px' }}>
                  <div className="row aic g6 mb2"><Icon name="lock" size={12} color="#a06a00" /><span className="t11 fw7" style={{ color: '#8a5a00' }}>NỘI BỘ · {AAU.users.find(u => u.id === m.by)?.name}</span><span className="t11 subtle mla">{relTime(m.at)} trước</span></div>
                  <div className="t13" style={{ lineHeight: 1.45 }}>{m.text.split(/(@[^\s]+(?:\s[A-ZÀ-Ỹ][^\s]*)?)/).map((p, i) => p.startsWith('@') ? <b key={i} style={{ color: '#1a4fa3' }}>{p}</b> : p)}</div>
                </div>
              </div>
            );
            if (m._t === 'call') return (
              <div key={m.id} style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
                <div className="row aic g8" style={{ background: '#fff', border: '1px solid var(--p-border)', borderRadius: 10, padding: '7px 12px' }}>
                  <span className="center" style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--p-success-bg)', color: '#0e7c4a' }}><Icon name="phone" size={13} /></span>
                  <div className="t12"><b>Cuộc gọi đi · {m.duration || '—'}</b> · {m.disp}{m.note ? <span className="subtle"> — {m.note}</span> : ''}<div className="t11 subtle">{relTime(m.at)} trước · đã ghi vào hồ sơ 360°</div></div>
                </div>
              </div>
            );
            return (
              <div key={m.id} style={{ display: 'flex', justifyContent: m.dir === 'out' ? 'flex-end' : 'flex-start', marginBottom: 10 }}>
                <div style={{ maxWidth: '70%' }}>
                  {m.image ? (
                    <div className="col g4" style={{ alignItems: m.dir === 'out' ? 'flex-end' : 'flex-start' }}>
                      <a href={m.image} target="_blank" rel="noopener noreferrer" style={{ display: 'block' }}>
                        <img src={m.image} alt="📷 Hình ảnh" loading="lazy" style={{ maxWidth: 230, maxHeight: 280, borderRadius: 12, display: 'block', border: '1px solid var(--p-border)', background: '#f0f0f0', objectFit: 'cover' }} />
                      </a>
                      {m.text ? <div style={{ padding: '7px 11px', borderRadius: 12, fontSize: 13, background: m.dir === 'out' ? '#303030' : '#fff', color: m.dir === 'out' ? '#fff' : '#303030', border: m.dir === 'in' ? '1px solid var(--p-border)' : 'none' }}>{m.text}</div> : null}
                    </div>
                  ) : m.attachment ? (
                    <div className="row aic g8" style={{ padding: '10px 13px', borderRadius: 14, borderBottomRightRadius: 4, background: '#303030', color: '#fff' }}>
                      <span className="center" style={{ width: 34, height: 34, borderRadius: 8, background: 'rgba(255,255,255,.15)' }}><Icon name="paperclip" size={16} /></span>
                      <div><div className="t13 fw6">{m.attachment}</div><div className="t11" style={{ opacity: 0.7 }}>PDF · đã gửi</div></div>
                    </div>
                  ) : (
                    <div style={{ padding: '9px 13px', borderRadius: 14, fontSize: 13.5, lineHeight: 1.45, background: m.dir === 'out' ? (m.ai ? '#ece4ff' : '#303030') : '#fff', color: m.dir === 'out' && !m.ai ? '#fff' : '#303030', border: m.dir === 'in' ? '1px solid var(--p-border)' : 'none', borderBottomRightRadius: m.dir === 'out' ? 4 : 14, borderBottomLeftRadius: m.dir === 'in' ? 4 : 14 }}>{m.text}</div>
                  )}
                  <div className="t11 subtle mt4" style={{ textAlign: m.dir === 'out' ? 'right' : 'left' }}>
                    {m.ai && <span className="badge magic" style={{ fontSize: 9, padding: '0 5px', marginRight: 4 }}>AI</span>}
                    {relTime(m.at)} trước
                    {m.dir === 'out' && m.status === 'sending' && <span style={{ marginLeft: 5 }}>· Đang gửi…</span>}
                    {m.dir === 'out' && m.status === 'failed' && <span style={{ marginLeft: 5, color: '#c4320a' }}>· ⚠ Gửi lỗi</span>}
                    {m.dir === 'out' && m.status === 'delivered' && <span style={{ marginLeft: 5, color: '#0a7d4f' }}>· ✓ Đã gửi tới khách</span>}
                    {m.dir === 'out' && m.id === lastOutId && !['sending', 'failed', 'delivered'].includes(m.status) && <span style={{ marginLeft: 5 }}>· {String(m.id).startsWith('x') || String(m.id).startsWith('c') ? 'Đã gửi' : (conv.linked ? '✓✓ Đã xem' : 'Đã gửi')}</span>}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Playbook */}
        <div style={{ borderTop: '1px solid var(--p-border)', background: '#fff' }}>
          <div className="row aic g8" style={{ padding: '8px 18px', cursor: 'pointer' }} onClick={() => setPlaybook(!playbook)}>
            <Icon name="sparkles" size={15} color="#573b8a" /><span className="t12 fw6">Playbook Assistant</span>
            <span className="badge magic" style={{ fontSize: 10 }}>{pb.step}</span>
            <span className="mla"><Icon name={playbook ? 'chevronDown' : 'chevronRight'} size={15} /></span>
          </div>
          {playbook && (
            <div style={{ padding: '0 18px 12px' }}>
              <div className="row aic g8" style={{ padding: '8px 10px', borderRadius: 9, background: detected.color + '12', marginBottom: 10 }}>
                <span className="center" style={{ width: 22, height: 22, borderRadius: 6, background: detected.color + '22', color: detected.color, flexShrink: 0 }}><Icon name="target" size={13} /></span>
                <div className="f1" style={{ minWidth: 0 }}>
                  <div className="t11 fw7" style={{ color: detected.color }}>AI PHÁT HIỆN PATTERN · {detected.cat}</div>
                  <div className="t12" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{detected.label} · win-rate {detected.win}%</div>
                </div>
                <button className="t11 fw6 row aic g2" style={{ flexShrink: 0, color: detected.color, cursor: 'pointer' }} onClick={() => navigate('/enablement/intelligence')}>Xem<Icon name="chevronRight" size={12} /></button>
              </div>
              <div className="t12 muted mb8">{pb.tip}</div>
              <div className="row aic g8 wrap">
                <Button size="sm" variant="secondary" icon="plus" onClick={() => onDraft((draft ? draft + ' ' : '') + pb.reply)}>Chèn script</Button>
                <button className="tag" style={{ cursor: 'pointer' }} onClick={() => attach(pb.asset.split(' + ')[0])}><Icon name="paperclip" size={13} />{pb.asset}</button>
                <Button size="sm" variant="plain" onClick={() => navigate('/enablement/assets')}>Mở Asset Library</Button>
              </div>
            </div>
          )}
        </div>

        {/* Composer */}
        <div style={{ borderTop: '1px solid var(--p-border)', padding: '10px 18px 14px', background: '#fff', position: 'relative' }}>
          {/* Copilot draft */}
          {composerTab === 'reply' && aiMode === 'copilot' && copilot && (
            <div style={{ background: 'var(--p-magic-bg)', border: '1px solid var(--p-magic-border)', borderRadius: 12, padding: '10px 12px', marginBottom: 8 }}>
              <div className="row aic g6 mb4"><Icon name="sparkles" size={13} color="#573b8a" /><span className="t11 fw7" style={{ color: '#573b8a' }}>AI GỢI Ý TRẢ LỜI</span><span className="t11 subtle mla">Copilot — bạn duyệt trước khi gửi</span></div>
              <div className="t13" style={{ color: '#3d2a63', lineHeight: 1.45 }}>{copilot}</div>
              <div className="row g8 mt8">
                <Button size="sm" variant="primary" icon="send" onClick={() => send(copilot)}>Gửi ngay</Button>
                <Button size="sm" variant="secondary" icon="edit" onClick={() => { setDraft(copilot); setCopilot(''); }}>Dùng & sửa</Button>
                <Button size="sm" variant="plain" onClick={() => setCopilot('')}>Bỏ</Button>
              </div>
            </div>
          )}
          {slash && (
            <div style={{ position: 'absolute', bottom: '100%', left: 18, right: 18, background: '#fff', borderRadius: 12, boxShadow: 'var(--p-shadow-popover)', overflow: 'hidden', marginBottom: 6 }}>
              <div className="t11 subtle" style={{ padding: '8px 12px 4px', fontWeight: 600 }}>QUICK REPLY · gõ để lọc</div>
              {AAU.replyTemplates.filter(t => t.key.includes(draft.slice(1).toLowerCase()) || t.label.toLowerCase().includes(draft.slice(1).toLowerCase())).map(t => (
                <div key={t.key} onClick={() => send(t.text)} style={{ padding: '9px 12px', cursor: 'pointer', borderTop: '1px solid var(--p-border-secondary)' }} onMouseEnter={e => e.currentTarget.style.background = 'var(--p-bg-surface-hover)'} onMouseLeave={e => e.currentTarget.style.background = ''}>
                  <div className="t12 fw6">/{t.key} · {t.label}</div><div className="t11 muted" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.text}</div>
                </div>
              ))}
            </div>
          )}
          {attachMenu && (
            <div style={{ position: 'absolute', bottom: '100%', left: 18, width: 280, background: '#fff', borderRadius: 12, boxShadow: 'var(--p-shadow-popover)', border: '1px solid var(--p-border)', overflow: 'hidden', marginBottom: 6 }}>
              <div className="t11 subtle" style={{ padding: '8px 12px 4px', fontWeight: 700 }}>GỬI TÀI LIỆU</div>
              {assets.map(a => (
                <div key={a} className="row aic g8" onClick={() => attach(a)} style={{ padding: '9px 12px', cursor: 'pointer', borderTop: '1px solid var(--p-border-secondary)' }} onMouseEnter={e => e.currentTarget.style.background = 'var(--p-bg-surface-hover)'} onMouseLeave={e => e.currentTarget.style.background = ''}>
                  <Icon name="paperclip" size={14} color="#573b8a" /><span className="t12 fw5">{a}</span>
                </div>
              ))}
            </div>
          )}
          <div className="row aic g10 mb8">
            <Seg value={composerTab} onChange={setComposerTab} options={[{ value: 'reply', label: 'Trả lời khách' }, { value: 'note', label: 'Note nội bộ' }]} />
            {composerTab === 'reply' && <>
              <span className="t12 muted">AI:</span>
              <Seg value={aiMode} onChange={v => { setAiMode(v); setStore(s => ({ ...s, [selId]: { ...s[selId], aiMode: v } })); if (window.API && window.API.enabled) window.API.setAIMode(selId, v).catch(() => {}); }} options={aiOpts} />
              {aiMode === 'autopilot' && <Badge tone="magic" dot>AI tự trả lời</Badge>}
            </>}
            {composerTab === 'note' && <span className="t12" style={{ color: '#a06a00' }}><Icon name="lock" size={12} /> Chỉ nội bộ thấy · gõ @ để nhắc đồng đội</span>}
          </div>
          <div className="row g8 aie">
            {composerTab === 'reply' && <IconButton name="paperclip" title="Gửi tài liệu" onClick={() => setAttachMenu(!attachMenu)} />}
            <textarea className="input" rows={2} placeholder={composerTab === 'note' ? 'Ghi chú nội bộ, @ để nhắc đồng đội…  (⌘/Ctrl+Enter để lưu)' : 'Nhập tin nhắn…  (gõ / để chèn mẫu · ⌘/Ctrl+Enter để gửi)'} value={draft} onChange={e => onDraft(e.target.value)} onKeyDown={onKey} style={{ resize: 'none', background: composerTab === 'note' ? '#fffdf3' : '#fff', borderColor: composerTab === 'note' ? '#f0d27a' : undefined }} />
            {composerTab === 'note'
              ? <Button variant="secondary" icon="check" onClick={saveNote} style={{ height: 38 }}>Lưu</Button>
              : <Button variant="primary" icon="send" onClick={() => send()} style={{ height: 38 }} />}
          </div>
          <div className="t11 subtle mt6">Phím tắt: <b>J/K</b> chuyển hội thoại · <b>E</b> đánh dấu xong</div>
        </div>
      </div>

      {/* RIGHT — Customer 360 */}
      {panel && <Customer360Panel key={lead.id} lead={lead} conv={conv} onCreateLead={createLeadFromChat} />}
      {callOpen && <CallModal lead={lead} onClose={() => setCallOpen(false)} onLog={logCall} />}
    </div>
  );
}

function Section360({ title, children, action }) {
  const [open, setOpen] = useState(true);
  return (
    <div style={{ borderBottom: '1px solid var(--p-border-secondary)' }}>
      <div className="row aic g8" style={{ padding: '11px 16px', cursor: 'pointer' }} onClick={() => setOpen(!open)}>
        <span className="t12 fw7" style={{ letterSpacing: '0.02em' }}>{title}</span>
        {action}
        <span className="mla"><Icon name={open ? 'chevronDown' : 'chevronRight'} size={15} /></span>
      </div>
      {open && <div style={{ padding: '0 16px 14px' }}>{children}</div>}
    </div>
  );
}
function Row360({ k, v, auto }) {
  return (
    <div className="row jcsb aic" style={{ padding: '3px 0' }}>
      <span className="t12 subtle row aic g6">{k}{auto && <span className="badge neutral" style={{ fontSize: 9, padding: '0 5px' }}>auto</span>}</span>
      <span className="t12 fw5" style={{ textAlign: 'right' }}>{v}</span>
    </div>
  );
}

/* Inline-editable key/value row */
function EditRow({ k, value, onChange, editing, type = 'text', suffix }) {
  if (!editing) return <Row360 k={k} v={(value || '—') + (suffix && value ? ' ' + suffix : '')} />;
  return (
    <div className="row jcsb aic g8" style={{ padding: '3px 0' }}>
      <span className="t12 subtle" style={{ flexShrink: 0 }}>{k}</span>
      <input className="input" value={value} type={type} onChange={e => onChange(e.target.value)} style={{ height: 28, fontSize: 12.5, textAlign: 'right', padding: '2px 8px' }} />
    </div>
  );
}

const LEARNER_ROLES = ['Chủ / Founder', 'CEO / Tổng GĐ', 'Quản lý vận hành', 'Quản lý cửa hàng', 'Bếp trưởng', 'Phụ trách Marketing', 'Phụ trách Nhân sự', 'Nhân viên cử đi học'];

/* Multi-value contact list (phone / email) */
function ContactList({ items, onChange, editing, type = 'text', icon }) {
  const [val, setVal] = useState('');
  function add() { const t = val.trim(); if (!t) return; onChange([...items, t]); setVal(''); }
  return (
    <div className="col g4">
      {items.map((it, i) => (
        <div key={i} className="row jcsb aic" style={{ padding: '2px 0' }}>
          <span className="t12 fw5 row aic g6">{i === 0 && <span className="badge neutral" style={{ fontSize: 8.5, padding: '0 4px' }}>chính</span>}{it}</span>
          {editing && items.length > 1 && <span style={{ cursor: 'pointer', opacity: 0.5 }} onClick={() => onChange(items.filter((_, j) => j !== i))}><Icon name="x" size={12} /></span>}
        </div>
      ))}
      {editing && (
        <div className="row g6 mt2">
          <input className="input" type={type} value={val} placeholder={'Thêm ' + (type === 'tel' ? 'SĐT' : 'email') + '…'} onChange={e => setVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') add(); }} style={{ height: 28, fontSize: 12.5 }} />
          <Button size="sm" icon="plus" onClick={add} />
        </div>
      )}
    </div>
  );
}

/* Multi-select scrollable course picker */
function CourseMultiSelect({ value, onChange }) {
  const [open, setOpen] = useState(false);
  const courses = AAU.courses.filter(c => c.status === 'active');
  function toggle(id) { onChange(value.includes(id) ? value.filter(x => x !== id) : [...value, id]); }
  return (
    <div style={{ position: 'relative' }}>
      <div className="col g6">
        {value.length === 0 && <span className="t12 muted">Chưa chọn khóa</span>}
        <div className="row g6 wrap">
          {value.map(id => { const c = AAU.courseById(id); if (!c) return null; return (
            <span key={id} className="tag" style={{ background: 'var(--p-info-bg)', color: 'var(--p-info-text)' }}>{c.name}<span className="x" onClick={() => toggle(id)}><Icon name="x" size={11} /></span></span>
          ); })}
        </div>
      </div>
      <button className="btn btn-secondary btn-sm mt6" onClick={() => setOpen(!open)} style={{ width: '100%', justifyContent: 'space-between' }}>
        <span className="row aic g6"><Icon name="plus" size={13} />Thêm khóa quan tâm</span><Icon name={open ? 'chevronDown' : 'chevronRight'} size={13} />
      </button>
      {open && (
        <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 20, marginTop: 4, background: '#fff', border: '1px solid var(--p-border)', borderRadius: 10, boxShadow: 'var(--p-shadow-popover)', maxHeight: 230, overflowY: 'auto' }}>
          {AAU.courseGroups.map(g => {
            const list = courses.filter(c => c.group === g.id); if (!list.length) return null;
            return (
              <div key={g.id}>
                <div className="t11 subtle" style={{ padding: '7px 12px 3px', fontWeight: 700, position: 'sticky', top: 0, background: '#fff' }}>{g.label.toUpperCase()}</div>
                {list.map(c => { const on = value.includes(c.id); return (
                  <div key={c.id} onClick={() => toggle(c.id)} className="row aic g8" style={{ padding: '7px 12px', cursor: 'pointer', background: on ? 'var(--p-bg-surface-selected)' : '' }} onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--p-bg-surface-hover)'; }} onMouseLeave={e => { if (!on) e.currentTarget.style.background = ''; }}>
                    <Checkbox on={on} onChange={() => toggle(c.id)} />
                    <div className="f1"><div className="t12 fw5">{c.name}</div><div className="t11 subtle">{c.code} · {AAU.fmtVNDm(c.price)}</div></div>
                  </div>
                ); })}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function Customer360Panel({ lead, conv, onCreateLead }) {
  const [editId, setEditId] = useState(false);
  const [editBiz, setEditBiz] = useState(false);
  const [editNeed, setEditNeed] = useState(false);
  const [phones, setPhones] = useState([lead.phone]);
  const [emails, setEmails] = useState([lead.email]);
  const [biz, setBiz] = useState({ bizModel: lead.bizModel, industry: lead.industry, chainSize: lead.chainSize, revenue: AAU.fmtVNDm(lead.revenue) });
  const [pains, setPains] = useState(lead.painpoints);
  const [newPain, setNewPain] = useState('');
  const [courses, setCourses] = useState(lead.courseInterest ? [lead.courseInterest] : []);
  const [learner, setLearner] = useState('');
  const [applied, setApplied] = useState({});
  const [dupeDismissed, setDupeDismissed] = useState(false);
  const aiSug = [{ id: 'budget', f: 'Ngân sách', v: '~20tr/khóa' }, { id: 'role', f: 'Vai trò', v: 'Người quyết định' }];

  function addPain() { const t = newPain.trim(); if (!t) return; setPains([...pains, t]); setNewPain(''); }

  return (
    <div className="col" style={{ width: 322, flexShrink: 0, borderLeft: '1px solid var(--p-border)', height: '100%', gap: 0, overflowY: 'auto' }}>
      <div style={{ padding: '16px 16px 12px', textAlign: 'center', borderBottom: '1px solid var(--p-border-secondary)' }}>
        <Avatar name={lead.name} color={lead.grade === 'A' ? '#0a9e6e' : '#5b6cff'} size={56} />
        <div className="t15 fw7 mt8">{lead.name}</div>
        <div className="t12 muted">{lead.role} · {lead.company}</div>
        <div className="row jcc g6 mt8"><StageChip stageId={lead.stage} /></div>
        <div className="col jcc g6 mt8" style={{ alignItems: 'center' }}>
          {lead.id
            ? <><span className="badge success" style={{ fontSize: 10 }}><Icon name="checkCircle" size={11} /> Đã link CRM</span><Button size="sm" variant="secondary" icon="user" onClick={() => navigate('/leads/' + lead.id)}>Xem dữ liệu 360°</Button></>
            : <Button size="sm" variant="success" icon="plus" onClick={onCreateLead}>Tạo Lead từ chat</Button>}
        </div>
      </div>

      {DUPES[lead.id] && !dupeDismissed && (
        <div style={{ margin: 12, padding: 10, borderRadius: 10, background: 'var(--p-warning-bg)', border: '1px solid var(--p-warning-border)' }}>
          <div className="row aic g6 mb4"><Icon name="users" size={14} color="#7a4d00" /><span className="t12 fw7" style={{ color: '#7a4d00' }}>Nghi ngờ trùng lặp</span></div>
          <div className="t12" style={{ color: '#7a4d00' }}>Trùng SĐT với <b>{DUPES[lead.id]}</b>.</div>
          <div className="row g8 mt8"><Button size="sm" variant="secondary" icon="users">Xem & gộp</Button><Button size="sm" variant="plain" onClick={() => setDupeDismissed(true)}>Bỏ qua</Button></div>
        </div>
      )}

      <Section360 title="ĐỊNH DANH" action={<IconButton name={editId ? 'check' : 'edit'} size={14} onClick={e => { e.stopPropagation(); setEditId(!editId); }} />}>
        <div className="t12 subtle mb2 row aic g6">SĐT {!editId && <span className="badge neutral" style={{ fontSize: 9, padding: '0 5px' }}>auto</span>}</div>
        <ContactList items={phones} onChange={setPhones} editing={editId} type="tel" />
        <div className="t12 subtle mb2 mt8">Email</div>
        <ContactList items={emails} onChange={setEmails} editing={editId} type="email" />
        <div className="mt8"><Row360 k="Facebook" v={<a className="linkish">{lead.fb}</a>} auto /><Row360 k="Khu vực" v={lead.region} auto /></div>
      </Section360>
      <Section360 title="KINH DOANH (B2B)" action={<IconButton name={editBiz ? 'check' : 'edit'} size={14} onClick={e => { e.stopPropagation(); setEditBiz(!editBiz); }} />}>
        <EditRow k="Mô hình" value={biz.bizModel} editing={editBiz} onChange={v => setBiz({ ...biz, bizModel: v })} />
        <EditRow k="Ngành" value={biz.industry} editing={editBiz} onChange={v => setBiz({ ...biz, industry: v })} />
        <EditRow k="Quy mô" value={biz.chainSize} editing={editBiz} onChange={v => setBiz({ ...biz, chainSize: v })} />
        <EditRow k="Doanh thu/th" value={biz.revenue} editing={editBiz} onChange={v => setBiz({ ...biz, revenue: v })} />
        {editBiz && <div className="t11 subtle mt6">Lưu vào hồ sơ 360° của khách.</div>}
      </Section360>
      <Section360 title="NHU CẦU" action={<IconButton name={editNeed ? 'check' : 'edit'} size={14} onClick={e => { e.stopPropagation(); setEditNeed(!editNeed); }} />}>
        <div className="t12 subtle mb4">Painpoints</div>
        <div className="col g6">
          {pains.map((p, i) => (
            <span key={i} className="tag">{p}{editNeed && <span className="x" onClick={() => setPains(pains.filter((_, j) => j !== i))}><Icon name="x" size={11} /></span>}</span>
          ))}
          {editNeed && (
            <div className="row g6 mt2">
              <input className="input" value={newPain} placeholder="Thêm painpoint…" onChange={e => setNewPain(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addPain(); }} style={{ height: 30, fontSize: 12.5 }} />
              <Button size="sm" icon="plus" onClick={addPain} />
            </div>
          )}
        </div>
        <div className="t12 subtle mt12 mb4">Khóa quan tâm <span className="subtle">(chọn 1 hoặc nhiều)</span></div>
        {editNeed
          ? <CourseMultiSelect value={courses} onChange={setCourses} />
          : <div className="row g6 wrap">{courses.length ? courses.map(id => <span key={id} className="badge info">{AAU.courseById(id)?.name}</span>) : <span className="t12 muted">—</span>}</div>}
        <div className="t12 subtle mt12 mb4">Người học</div>
        {editNeed
          ? <Select value={learner} onChange={setLearner} options={[{ value: '', label: '— Chọn người học —' }, ...LEARNER_ROLES.map(r => ({ value: r, label: r }))]} style={{ width: '100%' }} />
          : <span className="t12 fw5">{learner || '—'}</span>}
      </Section360>
      <Section360 title="GỢI Ý TỪ AI (chờ duyệt)">
        <div className="col g8">
          {aiSug.map(s => (
            <div key={s.id} className="row aic g8" style={{ padding: 8, borderRadius: 8, background: applied[s.id] ? 'var(--p-success-bg)' : 'var(--p-magic-bg)' }}>
              <Icon name={applied[s.id] ? 'check' : 'sparkles'} size={14} color={applied[s.id] ? '#0e7c4a' : '#573b8a'} />
              <div className="f1 t12"><b>{s.f}:</b> {s.v}</div>
              {applied[s.id]
                ? <span className="t11 fw6" style={{ color: '#0e7c4a' }}>Đã áp dụng</span>
                : <IconButton name="check" size={14} title="Áp vào hồ sơ" onClick={() => { setApplied({ ...applied, [s.id]: true }); if (s.id === 'role') setLearner('Chủ / Founder'); }} />}
            </div>
          ))}
        </div>
      </Section360>
      <Section360 title="TRẠNG THÁI CRM">
        <Row360 k="SLA" v={<SLATag sla={lead.sla} left={lead.slaLeft} />} />
        <Row360 k="Hot signal" v={lead.hot ? <span className="hot row aic g4"><Icon name="fire" size={13} />Có</span> : 'Không'} />
        <Row360 k="Grade" v={<GradeBadge grade={lead.grade} />} />
        <Row360 k="Deal value" v={AAU.fmtVND(lead.dealValue)} />
        <Row360 k="Qualify" v={Object.values(lead.qualify).filter(Boolean).length + '/4'} />
      </Section360>
    </div>
  );
}

Object.assign(window, { UnifiedInbox, Customer360Panel, ChannelAvatar, CallModal });
