// ===================================================================
// Follow-up & Pipeline — màn hình tổng hợp cả khách lẻ lẫn B2B
// ===================================================================

// ----- Lịch sử tổng hợp (follow-up done + pipeline done) -----
function PipeFollowHistory({ kind, role, refreshKey }) {
  const live = window.TVS_API && window.TVS_API.isAuthed();
  const [followDone, setFollowDone] = React.useState([]);
  const [pipeDone, setPipeDone] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [filterOwner, setFilterOwner] = React.useState('');
  const [owners, setOwners] = React.useState([]);

  React.useEffect(() => {
    if (!live) { setLoading(false); return; }
    setLoading(true);
    // kind rỗng = gộp cả khách lẻ + đối tác.
    const fqs = kind === 'partner' ? '?kind=partner' : kind === 'customer' ? '?kind=customer' : '';
    const pipeCalls = kind
      ? [window.TVS_API.api('/api/pipeline?kind=' + kind).catch(() => ({ entries: [] }))]
      : [
          window.TVS_API.api('/api/pipeline?kind=customer').catch(() => ({ entries: [] })),
          window.TVS_API.api('/api/pipeline?kind=partner').catch(() => ({ entries: [] })),
        ];
    Promise.all([
      window.TVS_API.api('/api/followups' + fqs).catch(() => ({ followUps: [] })),
      Promise.all(pipeCalls).then(rs => ({ entries: rs.flatMap(r => r.entries || []) })),
    ]).then(([fRes, pRes]) => {
      const fDone = (fRes.followUps || []).filter(f => f.status === 'done');
      const pDone = (pRes.entries || []).filter(e => e.stage === 'done');
      setFollowDone(fDone);
      setPipeDone(pDone);
      // Thu thập danh sách owner
      const ownerSet = new Set();
      fDone.forEach(f => f.assignedTo && ownerSet.add(f.assignedTo));
      pDone.forEach(p => p.owner && ownerSet.add(p.owner));
      setOwners([...ownerSet]);
      setLoading(false);
    });
  }, [kind, refreshKey]);

  if (loading) return <Card><div className="text-sm fg-muted">Đang tải lịch sử…</div></Card>;

  const fFiltered = filterOwner ? followDone.filter(f => f.assignedTo === filterOwner) : followDone;
  const pFiltered = filterOwner ? pipeDone.filter(p => p.owner === filterOwner) : pipeDone;

  return (
    <div className="col gap-4">
      {/* Bộ lọc owner */}
      {owners.length > 1 && (
        <div className="row gap-2" style={{alignItems:'center'}}>
          <span className="text-sm fg-muted">Lọc theo sales:</span>
          <select className="input" style={{width:'auto', padding:'4px 10px', fontSize:13}}
            value={filterOwner} onChange={e => setFilterOwner(e.target.value)}>
            <option value="">Tất cả</option>
            {owners.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>
      )}

      {/* Pipeline đã kết thúc */}
      <Card pad={false}>
        <CardHeader
          title={`📋 Lịch sử Pipeline (${pFiltered.length})`}
          sub="Các pipeline đã bấm Kết thúc · Lưu lịch sử"
        />
        {pFiltered.length === 0 ? (
          <div className="card-pad empty"><div className="text-sm">Chưa có pipeline nào kết thúc</div></div>
        ) : (
          <div className="card-pad">
            <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px,1fr))', gap:10}}>
              {pFiltered.map(e => (
                <div key={e.id} className="pipeline-card" style={{border:'1px solid rgba(0,150,255,0.2)', background:'rgba(0,150,255,0.04)'}}>
                  <div className="row gap-2">
                    <Avatar name={e.customer ? e.customer.name : '?'} size="sm"/>
                    <div style={{flex:1, minWidth:0}}>
                      <div className="name">{e.customer ? e.customer.name : '(đối tác)'}</div>
                      <div className="meta tnum">{e.customer ? e.customer.phone : ''}</div>
                    </div>
                    <Tag variant="info" dot>Kết thúc</Tag>
                  </div>
                  {e.owner && <div className="text-xs fg-muted mt-1">Sales: {e.owner}</div>}
                  {e.note && (
                    <div className="text-xs fg-muted mt-2" style={{
                      whiteSpace:'pre-line', background:'var(--bg-soft)', padding:'4px 8px',
                      borderRadius:4, borderLeft:'2px solid var(--vs-light-blue)',
                      maxHeight:80, overflow:'auto'
                    }}>{e.note}</div>
                  )}
                  {e.customer && e.customer.ltv > 0 && (
                    <div className="value mt-2" style={{fontSize:12, margin:0}}>{fmt.vndFull(e.customer.ltv)}</div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </Card>

      {/* Follow-up đã hoàn thành */}
      <Card pad={false}>
        <CardHeader
          title={`✅ Lịch sử Follow-up (${fFiltered.length})`}
          sub="Các follow-up đã đánh dấu Đã xong"
        />
        {fFiltered.length === 0 ? (
          <div className="card-pad empty"><div className="text-sm">Chưa có follow-up nào hoàn thành</div></div>
        ) : (
          <div className="card-pad">
            <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px,1fr))', gap:10}}>
              {fFiltered.map(f => (
                <div key={f.id} className="pipeline-card" style={{border:'1px solid rgba(0,200,80,0.2)', background:'rgba(0,200,80,0.03)', opacity:0.9}}>
                  <div className="row gap-2">
                    <Avatar name={f.customer ? f.customer.name : '?'} size="sm"/>
                    <div style={{flex:1, minWidth:0}}>
                      <div className="name">{f.customer ? f.customer.name : '—'}</div>
                      <div className="meta tnum">{f.customer ? f.customer.phone : ''}</div>
                    </div>
                    <Tag variant="success" dot>Xong</Tag>
                  </div>
                  {f.assignedTo && <div className="text-xs fg-muted mt-1">Sales: {f.assignedTo}</div>}
                  <div className="text-xs fg-2 mt-2" style={{display:'flex', alignItems:'center', gap:5}}>
                    <Icon name="flag" size={11} style={{color:'var(--vs-light-blue)', flexShrink:0}}/>
                    {f.reason}
                  </div>
                  {f.doneAt && (
                    <div className="text-xs fg-muted mt-1 tnum">
                      Hoàn thành: {new Date(f.doneAt).toLocaleDateString('vi-VN', {day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit'})}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </Card>
    </div>
  );
}

// ----- Main screen -----
// Gộp khách lẻ + đối tác: KHÔNG còn tab Khách lẻ / Khách B2B. Mỗi tab con thao tác
// trên toàn bộ khách trong phân quyền của người dùng.
function FollowPipeScreen({ role, onOpenCustomer, onGoToTelesale, refreshKey }) {
  const CustomerPipeline = window.CustomerPipeline;
  const UnifiedFollowUps = window.UnifiedFollowUps;
  const [subTab, setSubTab] = React.useState('followup'); // 'followup' | 'pipeline' | 'history'
  const isManager = role && role.role !== 'staff';
  const accent = 'var(--vs-dark-blue)';

  const subTabs = [
    { key: 'followup', label: 'Follow-up', icon: 'flag' },
    { key: 'pipeline', label: 'Pipeline',  icon: 'target' },
    { key: 'history',  label: 'Lịch sử',   icon: 'clock' },
  ];

  return (
    <div className="col gap-4">
      {/* Header */}
      <div>
        <h1 style={{margin:0, fontSize:22, fontWeight:800, color:'var(--fg-1)', fontFamily:'var(--font-display)'}}>
          Follow-up & Pipeline
        </h1>
        <div className="text-sm fg-muted mt-1">Quản lý lịch theo dõi và tiến trình bán hàng — khách lẻ và đối tác chung một chỗ</div>
      </div>

      {/* Sub-tab — Follow-up / Pipeline / Lịch sử */}
      <div className="row gap-1" style={{
        background: 'var(--bg-soft)', padding: 4, borderRadius: 8,
        border: '1px solid var(--border-1)', width: 'fit-content',
      }}>
        {subTabs.map(t => {
          const isActive = subTab === t.key;
          return (
            <button key={t.key} onClick={() => setSubTab(t.key)} style={{
              padding: '8px 18px', fontSize: 13, fontWeight: isActive ? 700 : 500,
              borderRadius: 6,
              background: isActive ? accent : 'transparent',
              color: isActive ? '#fff' : 'var(--fg-2)',
              border: 'none', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
              transition: 'all 0.15s ease',
              boxShadow: isActive ? '0 2px 8px rgba(0,0,0,0.15)' : 'none',
            }}>
              <Icon name={t.icon} size={12} style={{opacity: isActive ? 1 : 0.6}}/>
              {t.label}
            </button>
          );
        })}
      </div>

      {/* Content — gộp toàn bộ khách (không lọc theo kind) */}
      {subTab === 'followup' && (
        window.UnifiedFollowUps ? (
          <window.UnifiedFollowUps
            role={role}
            refreshKey={refreshKey}
            onOpen={(r) => onOpenCustomer && r && r.raw && onOpenCustomer(r.raw)}
            onGoToTelesale={onGoToTelesale}
          />
        ) : (
          <Card><div className="card-pad text-sm fg-muted">Đang tải Follow-up...</div></Card>
        )
      )}
      {subTab === 'pipeline' && (
        window.CustomerPipeline ? (
          <window.CustomerPipeline
            kind="customer" role={role}
            refreshKey={refreshKey}
            onOpenCustomer={onOpenCustomer}
            myName={isManager ? null : (role && role.person)}
          />
        ) : (
          <Card><div className="card-pad text-sm fg-muted">Đang tải Pipeline...</div></Card>
        )
      )}
      {subTab === 'history' && (
        <PipeFollowHistory role={role} refreshKey={refreshKey}/>
      )}
    </div>
  );
}

Object.assign(window, { FollowPipeScreen });
