/* AAU CRM — Customer Profile 360 — playbook-aware (script, qualify gate, signals, MAKE THE MOVE) */

function StatCard({ icon, label, value, tone }) {
  return (
    <div className="card pad row aic g12">
      <span className="center" style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0, background: 'var(--p-bg-surface-tertiary)', color: tone || '#4a4a4a' }}><Icon name={icon} size={20} /></span>
      <div><div className="t12 muted">{label}</div><div className="t17 fw7" style={{ color: tone || undefined }}>{value}</div></div>
    </div>
  );
}

function CustomerProfile360({ id }) {
  const leads = useLeads();
  const viewer = useViewer();
  const lead = LeadStore.byId(id);
  const [tab, setTab] = useState('overview');
  const [move, setMove] = useState(false);
  const [assign, setAssign] = useState(false);
  const [edit, setEdit] = useState(false);
  if (!lead) return <div className="page"><EmptyState title="Không tìm thấy lead" action={<Button variant="primary" onClick={() => navigate('/leads')}>Về danh sách</Button>} /></div>;
  if (!SalesAccess.canSee(lead, viewer)) return <div className="page"><EmptyState icon="lock" title="Ngoài phạm vi truy cập" desc={'Lead này thuộc khóa ' + ((AAU.courseById(lead.courseInterest) || {}).code || '') + ' — ngoài danh sách khóa ' + viewer.name + ' phụ trách. Liên hệ Sales Leader để được phân công.'} action={<Button variant="primary" onClick={() => navigate('/leads')}>Về Pipeline</Button>} /></div>;
  const canEdit = SalesAccess.canEdit(viewer);

  const st = AAU.stageById(lead.stage);
  const g = pbGuide(st.code) || {};
  const meta = (window.PLAYBOOK && PLAYBOOK.scriptTypeMeta[g.type]) || {};
  const qCount = Object.values(lead.qualify).filter(Boolean).length;

  const seedTimeline = [
    { type: 'chat', icon: 'message', color: '#0084ff', at: '8 phút trước', title: 'Tin nhắn ' + (AAU.channels[lead.channel]?.label || ''), sub: lead.signal ? '"' + lead.signal.text + '"' : 'Khách tương tác' },
    { type: 'asset', icon: 'paperclip', color: '#573b8a', at: '2 giờ trước', title: 'Đã gửi tài liệu', sub: (g.send && g.send[0]) || 'Brochure' },
    { type: 'create', icon: 'plus', color: '#8a8a8a', at: AAU.fmtDate(lead.createdAt), title: 'Lead được tạo', sub: 'Nguồn: ' + (AAU.sourceMeta[lead.source]?.label) + ' · Nhánh ' + (lead.branch || '—') },
  ];
  const moveHist = (lead.history || []).map(h => ({ type: 'stage', icon: 'kanban', color: '#f59e0b', at: h.at, title: 'Chuyển ' + h.from + ' → ' + h.to, sub: 'Lý do: ' + h.reason + ' · trigger: ' + h.trigger }));
  const timeline = [...moveHist, ...seedTimeline];

  const qLabels = { bizModel: ['Mô hình kinh doanh rõ', lead.bizModel + ' · ' + lead.chainSize], painpoint: ['Có painpoint cụ thể', lead.painpoints[0] || '—'], courseMap: ['Map đúng khóa học', AAU.courseById(lead.courseInterest)?.name || '—'], budget: ['Đủ khả năng tài chính', 'Doanh thu ~' + AAU.fmtVNDm(lead.revenue) + '/th'] };

  return (
    <div className="page wide">
      <PageHead breadcrumb={[{ label: 'Sales CRM' }, { label: 'Bảng Pipeline', href: 1, onClick: () => navigate('/leads') }, { label: lead.company }]}
        title={<span className="row aic g10">{lead.company} <GradeBadge grade={lead.grade} /> {lead.hot && <HotIcon />}</span>}
        subtitle={lead.name + ' · ' + lead.role + ' · ' + lead.bizModel + ' · ' + lead.region}
        actions={<><Button icon="message" onClick={() => navigate('/inbox')}>Hội thoại</Button>{canEdit && <Button icon="edit" onClick={() => setEdit(true)}>Sửa hồ sơ</Button>}{canEdit ? <Button variant="primary" icon="bolt" onClick={() => setMove(true)}>MAKE THE MOVE</Button> : <Button icon="lock" disabled>Chỉ xem</Button>}</>} />

      <div className="row aic g10 mb16 wrap">
        <StageChip stageId={lead.stage} />
        {st.branch && <BranchTag branch={st.branch} />}
        {st.lane && <LaneTag lane={st.lane} />}
        {lead.signal && <SignalBadge signal={lead.signal} />}
        {lead.dealValue > 0 && <span className="badge neutral">Deal {AAU.fmtVND(lead.dealValue)}</span>}
        <span className="badge neutral">Khóa: {(AAU.courseById(lead.courseInterest) || {}).code || '—'}</span>
        <span className="muted t13 mla row aic g6">Phụ trách: {AAU.users.find(u => u.id === lead.assignedTo)?.name || 'Chưa gán'}{canEdit && <span className="linkish t12" onClick={() => setAssign(true)}>{lead.assignedTo ? 'Đổi' : 'Phân công'}</span>}</span>
      </div>

      <div className="grid gc4 mb16">
        <StatCard icon="clock" label="SLA hiện tại" value={lead.slaLeft} tone={lead.sla === 'bad' ? '#c4320a' : lead.sla === 'warn' ? '#b06f00' : '#0e7c4a'} />
        <StatCard icon="fire" label="Hot signal" value={lead.signal ? lead.signal.level : 'Không'} tone={lead.signal ? '#c4320a' : undefined} />
        <StatCard icon="target" label="Qualify score" value={qCount + '/4'} tone={qCount >= 4 ? '#0e7c4a' : '#b06f00'} />
        <StatCard icon="layers" label="Ngày ở stage" value={(lead.daysInStage || 0) + ' ngày'} />
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1fr 340px', alignItems: 'start' }}>
        <Card pad={false}>
          <div style={{ padding: '4px 8px' }}><Tabs value={tab} onChange={setTab} tabs={[{ value: 'overview', label: 'Tổng quan' }, { value: 'qualify', label: 'Qualify' }, { value: 'timeline', label: 'Timeline' }, { value: 'history', label: 'Stage History' }]} /></div>
          <div className="card-body">
            {tab === 'overview' && (
              <div className="grid gc2 g24">
                <div><div className="t12 fw7 subtle mb8">ĐỊNH DANH</div><div className="col g4"><Row360 k="SĐT" v={lead.phone} /><Row360 k="Facebook" v={<a className="linkish">{lead.fb}</a>} /><Row360 k="Email" v={lead.email} /><Row360 k="Khu vực" v={lead.region} /></div></div>
                <div><div className="t12 fw7 subtle mb8">KINH DOANH (B2B)</div><div className="col g4"><Row360 k="Mô hình" v={lead.bizModel} /><Row360 k="Ngành" v={lead.industry} /><Row360 k="Quy mô" v={lead.chainSize} /><Row360 k="Doanh thu/th" v={AAU.fmtVNDm(lead.revenue)} /></div></div>
                <div><div className="t12 fw7 subtle mb8">NHU CẦU</div><div className="col g6">{lead.painpoints.map((p, i) => <span key={i} className="tag">{p}</span>)}<span className="badge info mt4">{AAU.courseById(lead.courseInterest)?.name}</span></div></div>
                <div><div className="t12 fw7 subtle mb8">ATTRIBUTION & DEAL</div><div className="col g4"><Row360 k="Nguồn" v={AAU.sourceMeta[lead.source]?.label} /><Row360 k="Nhánh" v={'Nhánh ' + (lead.branch || '—')} /><Row360 k="Ngày tạo" v={AAU.fmtDate(lead.createdAt)} /><Row360 k="Deal value" v={lead.dealValue ? AAU.fmtVND(lead.dealValue) : '—'} /></div></div>
                {lead.objection && <div style={{ gridColumn: '1/-1' }}><div className="t12 fw7 subtle mb8">OBJECTION / BLOCKER</div><div className="row aic g8" style={{ padding: 12, borderRadius: 10, background: 'var(--p-warning-bg)' }}><Icon name="alert" size={16} color="#b06f00" /><span className="t13">{lead.objection}</span></div></div>}
              </div>
            )}
            {tab === 'qualify' && (
              <div className="col g12">
                <div className="t12 muted">Lead phải đủ <b>4 điều kiện</b> mới được move sang 3.1 Qualify. Click để cập nhật.</div>
                {Object.keys(qLabels).map(k => {
                  const on = !!lead.qualify[k];
                  return (
                    <div key={k} className="row aic g12" style={{ padding: 12, borderRadius: 10, border: '1px solid var(--p-border)', background: on ? 'var(--p-success-bg)' : '#fff', cursor: canEdit ? 'pointer' : 'default' }} onClick={canEdit ? () => LeadStore.toggleQualify(lead.id, k) : undefined}>
                      <span className="center" style={{ width: 26, height: 26, borderRadius: '50%', background: on ? '#0e7c4a' : '#e3e3e3', color: '#fff' }}><Icon name={on ? 'check' : 'x'} size={15} /></span>
                      <div className="f1"><div className="t13 fw6">{qLabels[k][0]}</div><div className="t12 muted">{qLabels[k][1]}</div></div>
                    </div>
                  );
                })}
                <div className="t13 mt8">Qualify score: <b>{qCount}/4</b> — {qCount >= 4 ? <span className="sla-ok">Đủ điều kiện → 3.1 Qualify</span> : <span className="sla-warn">Thiếu {4 - qCount} điều kiện → nurture 3.0 (SOFT)</span>}</div>
              </div>
            )}
            {tab === 'timeline' && (
              <div style={{ position: 'relative', paddingLeft: 8 }}>
                {timeline.map((t, i) => (
                  <div key={i} className="row g12" style={{ paddingBottom: 18, position: 'relative' }}>
                    {i < timeline.length - 1 && <div style={{ position: 'absolute', left: 17, top: 32, bottom: -4, width: 2, background: 'var(--p-border)' }} />}
                    <span className="center" style={{ width: 36, height: 36, borderRadius: '50%', flexShrink: 0, background: t.color + '18', color: t.color, zIndex: 1 }}><Icon name={t.icon} size={17} /></span>
                    <div className="f1" style={{ paddingTop: 2 }}>
                      <div className="row jcsb aic"><span className="t13 fw6">{t.title}</span><span className="t11 subtle">{t.at}</span></div>
                      <div className="t12 muted mt4">{t.sub}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
            {tab === 'history' && (
              (lead.history && lead.history.length) ? (
                <table className="tbl"><thead><tr><th>Từ</th><th>Đến</th><th>Lý do</th><th>Trigger</th></tr></thead>
                  <tbody>{lead.history.map((h, i) => <tr key={i}><td>{h.from}</td><td className="fw6">{h.to}</td><td className="muted">{h.reason}</td><td><Badge tone={h.trigger === 'hot_signal' ? 'critical' : 'neutral'}>{h.trigger}</Badge></td></tr>)}</tbody></table>
              ) : <EmptyState icon="kanban" title="Chưa có lịch sử chuyển stage" desc="Dùng MAKE THE MOVE để chuyển stage — mỗi lần move sẽ ghi lại lý do & trigger ở đây." />
            )}
          </div>
        </Card>

        <div className="col g12">
          {/* MAKE THE MOVE script card */}
          <Card>
            <div className="row aic g8 mb8"><ScriptTag type={g.type} /><span className="t13 fw7">{st.code} · {g.title || st.name}</span></div>
            <div className="t12 muted mb10">{g.objective}</div>
            {g.openings && g.openings.length > 0 && (
              <div className="col g6 mb10">
                <div className="t11 fw7 subtle">KỊCH BẢN — {meta.label}</div>
                {g.openings.map((o, i) => <div key={i} className="mtm-line">{o}</div>)}
              </div>
            )}
            {g.send && g.send.length > 0 && (
              <div className="mb10"><div className="t11 fw7 subtle mb4"><Icon name="paperclip" size={11} /> Tài liệu gửi</div><div className="row g6 wrap">{g.send.map((s, i) => <span key={i} className="tag">{s}</span>)}</div></div>
            )}
            {g.cadence && <div className="t11 subtle mb10"><Icon name="clock" size={11} /> {g.cadence}</div>}
            {canEdit ? <Button variant="primary" icon="bolt" style={{ width: '100%' }} onClick={() => setMove(true)}>Chuyển stage</Button> : <div className="pb-note"><Icon name="lock" size={13} /><span>Vai trò chỉ-xem — không thể chuyển stage.</span></div>}
          </Card>

          {/* next action */}
          <Card title="Next action">
            <div style={{ padding: 12, borderRadius: 10, background: 'var(--p-magic-bg)' }}>
              <div className="row aic g8 t13 fw6"><Icon name="sparkles" size={15} color="#573b8a" />Hành động kế tiếp</div>
              <div className="t12 mt4" style={{ color: '#573b8a' }}>{lead.nextAction}</div>
            </div>
            <div className="row g8 mt10">
              <Button variant="secondary" icon="phone" style={{ flex: 1 }}>Tạo task gọi</Button>
              <Button variant="secondary" icon="paperclip" style={{ flex: 1 }} onClick={() => navigate('/enablement/assets')}>Gửi TL</Button>
            </div>
          </Card>

          <Card title="Metadata">
            <div className="col g4"><Row360 k="Lead ID" v={lead.id} /><Row360 k="KPI stage" v={g.kpi || '—'} /><Row360 k="PIC vai trò" v={g.pic || st.role} /><Row360 k="Tenant" v="AAU HCM" /></div>
          </Card>
        </div>
      </div>

      {move && <MakeTheMoveDrawer lead={lead} onClose={() => setMove(false)} onMove={(lid, to, r, t) => { LeadStore.move(lid, to, r, t); setMove(false); }} onToggleQualify={(lid, k) => LeadStore.toggleQualify(lid, k)} readOnly={!canEdit} />}
      {assign && <AssignDrawer lead={lead} onClose={() => setAssign(false)} />}
      {edit && <LeadEditDrawer lead={lead} onClose={() => setEdit(false)} />}
    </div>
  );
}

function LeadEditDrawer({ lead, onClose }) {
  const [f, setF] = useState({
    phone: lead.phone, email: lead.email, fb: lead.fb, region: lead.region,
    bizModel: lead.bizModel, industry: lead.industry, chainSize: lead.chainSize,
    revenue: lead.revenue, dealValue: lead.dealValue || 0,
    painpoints: (lead.painpoints || []).join(', '), objection: lead.objection || '',
  });
  const set = (k, v) => setF(p => ({ ...p, [k]: v }));
  const num = v => Number(String(v).replace(/\D/g, '')) || 0;
  function save() {
    LeadStore.update(lead.id, {
      phone: f.phone, email: f.email, fb: f.fb, region: f.region,
      bizModel: f.bizModel, industry: f.industry, chainSize: f.chainSize,
      revenue: num(f.revenue), dealValue: num(f.dealValue),
      painpoints: f.painpoints.split(',').map(s => s.trim()).filter(Boolean),
      objection: f.objection.trim(),
    });
    onClose();
  }
  return (
    <Drawer width={520} title={'Chỉnh sửa hồ sơ · ' + lead.company} onClose={onClose}
      footer={<><Button onClick={onClose}>Hủy</Button><Button variant="primary" icon="save" onClick={save}>Lưu hồ sơ</Button></>}>
      <div className="callout-soft mb16"><Icon name="user" size={14} /><span className="t12">Thông tin định danh & B2B do sales nhập tay (chat tự động chỉ gợi ý). Qualify chỉnh ở tab Qualify.</span></div>
      <div className="t12 fw7 subtle mb8">ĐỊNH DANH</div>
      <div className="grid gc2 g12 mb16">
        <Field label="SĐT"><Input value={f.phone} onChange={v => set('phone', v)} /></Field>
        <Field label="Email"><Input value={f.email} onChange={v => set('email', v)} /></Field>
        <Field label="Facebook"><Input value={f.fb} onChange={v => set('fb', v)} /></Field>
        <Field label="Khu vực"><Input value={f.region} onChange={v => set('region', v)} /></Field>
      </div>
      <div className="t12 fw7 subtle mb8">KINH DOANH (B2B)</div>
      <div className="grid gc2 g12 mb16">
        <Field label="Mô hình"><Input value={f.bizModel} onChange={v => set('bizModel', v)} /></Field>
        <Field label="Ngành"><Input value={f.industry} onChange={v => set('industry', v)} /></Field>
        <Field label="Quy mô"><Input value={f.chainSize} onChange={v => set('chainSize', v)} /></Field>
        <Field label="Doanh thu/tháng (₫)"><Input value={f.revenue} onChange={v => set('revenue', v)} /></Field>
      </div>
      <div className="t12 fw7 subtle mb8">NHU CẦU & DEAL</div>
      <div className="col g12">
        <Field label="Painpoints (phân tách bởi dấu phẩy)"><Input value={f.painpoints} onChange={v => set('painpoints', v)} placeholder="Chi phí cao, Chưa chuẩn SOP" /></Field>
        <div className="grid gc2 g12">
          <Field label="Deal value (₫)"><Input value={f.dealValue} onChange={v => set('dealValue', v)} /></Field>
          <Field label="Objection / blocker"><Input value={f.objection} onChange={v => set('objection', v)} placeholder="vd Cần thuyết phục đồng sáng lập" /></Field>
        </div>
      </div>
    </Drawer>
  );
}

Object.assign(window, { CustomerProfile360, StatCard });