/* AAU CRM — Pipeline Table · Sales Activity (Working Process) · Pipeline Config (Playbook) */

function PipelineTable() {
  const leads = useLeads();
  const viewer = useViewer();
  const canEdit = SalesAccess.canEdit(viewer);
  const isLeader = viewer.buScope === 'all';
  const [adv, setAdv] = useState(false);
  const [fStage, setFStage] = useState('all');
  const [fFunnel, setFFunnel] = useState('all');
  const [fSource, setFSource] = useState('all');
  const [fGrade, setFGrade] = useState('all');
  const [fBranch, setFBranch] = useState('all');
  const [fGroup, setFGroup] = useState('all');
  const [fAssignee, setFAssignee] = useState('all');
  const [fHot, setFHot] = useState(false);
  const [assign, setAssign] = useState(null);
  let rows = SalesAccess.scoped(leads, viewer);
  if (fFunnel !== 'all') rows = rows.filter(l => (AAU.stageById(l.stage) || {}).funnel === fFunnel);
  if (fStage !== 'all') rows = rows.filter(l => l.stage === fStage);
  if (fSource !== 'all') rows = rows.filter(l => l.source === fSource);
  if (fGrade !== 'all') rows = rows.filter(l => l.grade === fGrade);
  if (fBranch !== 'all') rows = rows.filter(l => l.branch === fBranch);
  if (fGroup !== 'all') rows = rows.filter(l => l.courseInterest === fGroup);
  if (fAssignee !== 'all') rows = rows.filter(l => fAssignee === 'none' ? !l.assignedTo : l.assignedTo === fAssignee);
  if (fHot) rows = rows.filter(l => l.hot);

  const cols = [
    { key: 'company', label: 'Khách hàng', render: l => <div><div className="fw6 row aic g6">{l.company} {l.hot && <span className="hot">🔥</span>}</div><div className="t11 subtle">{l.name} · {l.role}</div></div>, csv: l => l.company },
    { key: 'stage', label: 'Stage', render: l => <StageChip stageId={l.stage} />, csv: l => AAU.stageById(l.stage)?.code + ' ' + AAU.stageById(l.stage)?.name },
    { key: 'branch', label: 'Nhánh', render: l => l.branch ? <BranchTag branch={l.branch} /> : <span className="subtle">—</span>, csv: l => l.branch || '' },
    { key: 'signal', label: 'Hot signal', render: l => l.signal ? <SignalBadge signal={l.signal} compact /> : <span className="subtle t12">—</span>, csv: l => l.signal ? l.signal.level : '' },
    { key: 'grade', label: 'Grade', render: l => <GradeBadge grade={l.grade} /> },
    { key: 'source', label: 'Nguồn', render: l => <span className="badge neutral">{AAU.sourceMeta[l.source]?.label}</span>, csv: l => AAU.sourceMeta[l.source]?.label },
    { key: 'industry', label: 'Ngành F&B' },
    { key: 'bu', label: 'Khóa quan tâm', render: l => { const c = AAU.courseById(l.courseInterest); return <span className="badge neutral">{c ? c.code : '—'}</span>; }, csv: l => (AAU.courseById(l.courseInterest) || {}).name || '' },
    { key: 'dealValue', label: 'Deal value', num: true, render: l => l.dealValue ? AAU.fmtVND(l.dealValue) : '—' },
    { key: 'sla', label: 'SLA', render: l => <SLATag sla={l.sla} left={l.slaLeft} /> },
    { key: 'assignedTo', label: 'Phụ trách', render: l => { const u = AAU.users.find(x => x.id === l.assignedTo); return (
      <div className="row aic g6">
        {u ? <span className="row aic g6"><Avatar name={u.name} color={u.color} size={20} /><span className="t12">{u.name}</span></span> : <span className="subtle">Chưa gán</span>}
        {canEdit && <span className="linkish t11" onClick={e => { e.stopPropagation(); setAssign(l); }}>{u ? 'Đổi' : 'Phân công'}</span>}
      </div>
    ); }, csv: l => AAU.users.find(u => u.id === l.assignedTo)?.name || '' },
  ];
  const bulk = [
    { icon: 'user', label: 'Gán sales', onClick: () => {} },
    { icon: 'kanban', label: 'Chuyển stage', onClick: () => {} },
    { icon: 'tag', label: 'Thêm tag', onClick: () => {} },
  ];
  const toolbar = (
    <>
      <Select value={fFunnel} onChange={v => { setFFunnel(v); setFStage('all'); }} options={[{ value: 'all', label: 'Mọi funnel' }, { value: 'lead', label: '① Lead Social' }, { value: 'leadb', label: '② Lead Nhánh B' }, { value: 'deal', label: '③ Deal' }, { value: 'potential', label: '④ Tiềm năng' }, { value: 'won', label: '⑤ Won' }, { value: 'alumni', label: '⑥ Alumni' }]} style={{ width: 150 }} />
      <Select value={fStage} onChange={setFStage} options={[{ value: 'all', label: 'Mọi stage' }, ...AAU.stages.filter(s => fFunnel === 'all' || s.funnel === fFunnel).map(s => ({ value: s.id, label: s.code + ' ' + s.name }))]} style={{ width: 180 }} />
      <Button size="sm" icon="filter" onClick={() => setAdv(!adv)}>Lọc nâng cao</Button>
    </>
  );
  return (
    <div className="page wide">
      <PageHead title="Bảng Pipeline" subtitle={rows.length + '/' + leads.length + ' lead trong phạm vi của bạn · lọc theo funnel / khóa / người phụ trách · xuất CSV'}
        actions={<><Button icon="bolt" onClick={() => navigate('/sales/today')}>Hôm nay</Button><Button icon="kanban" onClick={() => navigate('/leads/kanban')}>Dạng Kanban</Button><Button variant="primary" icon="plus">Thêm lead</Button></>} />
      <div className="mb16"><AccessNote viewer={viewer} /></div>
      {adv && (
        <Card pad className="mb16">
          <div className="row g16 wrap aic">
            <Field label="Khóa quan tâm"><Select value={fGroup} onChange={setFGroup} options={[{ value: 'all', label: 'Mọi khóa' }, ...AAU.courses.filter(c => c.status === 'active').map(c => ({ value: c.id, label: c.code + ' · ' + c.name }))]} style={{ width: 200 }} /></Field>
            <Field label="Người phụ trách"><Select value={fAssignee} onChange={setFAssignee} options={[{ value: 'all', label: 'Tất cả' }, ...SalesAccess.members().map(u => ({ value: u.id, label: u.name })), { value: 'none', label: 'Chưa gán' }]} style={{ width: 150 }} /></Field>
            <Field label="Nhánh acquisition"><Seg value={fBranch} onChange={setFBranch} options={[{ value: 'all', label: 'Tất cả' }, { value: 'A', label: 'Nhánh A' }, { value: 'B', label: 'Nhánh B' }]} /></Field>
            <Field label="Grade"><Select value={fGrade} onChange={setFGrade} options={[{ value: 'all', label: 'Tất cả' }, 'A', 'B', 'C', 'D'].map(o => typeof o === 'string' ? { value: o, label: o } : o)} style={{ width: 110 }} /></Field>
            <div className="row aic g8" style={{ alignSelf: 'flex-end', paddingBottom: 6 }}><Switch on={fHot} onChange={setFHot} /><span className="t13">Chỉ hot signal</span></div>
          </div>
        </Card>
      )}
      <DataTable columns={cols} rows={rows} getId={l => l.id} searchKeys={['name', 'company', 'email', 'phone']} selectable bulkActions={bulk} onRowClick={l => navigate('/leads/' + l.id)} toolbar={toolbar} exportName="pipeline-leads" pageSize={12} />
      {assign && <AssignDrawer lead={assign} onClose={() => setAssign(null)} />}
    </div>
  );
}

/* ───────────────── Sales Activity + Working Process ───────────────── */
function SalesActivity() {
  const [tab, setTab] = useState('activity');
  return (
    <div className="page wide">
      <PageHead title="Sales Activity & Working Process" subtitle="Hoạt động · KPI theo nhân viên · quy trình vận hành hằng ngày/tuần"
        actions={<Button icon="bolt" onClick={() => navigate('/sales/today')}>Hôm nay</Button>} />
      <div className="mb16"><Tabs value={tab} onChange={setTab} tabs={[{ value: 'activity', label: 'Activity & KPI' }, { value: 'daily', label: 'Daily Flow' }, { value: 'weekly', label: 'Weekly Cadence' }, { value: 'report', label: 'Báo cáo' }]} /></div>
      {tab === 'activity' && <ActivityKPI />}
      {tab === 'daily' && <DailyFlowView />}
      {tab === 'weekly' && <WeeklyView />}
      {tab === 'report' && <ReportView />}
    </div>
  );
}

function ActivityKPI() {
  const [sale, setSale] = useState('u4');
  const sales = SalesAccess.members();
  const kpis = { u4: { calls: 42, mins: 318, chats: 86, msgs: 540, leads: 14, moves: 22, tasks: 18, meetings: 5 }, u5: { calls: 31, mins: 240, chats: 64, msgs: 410, leads: 11, moves: 18, tasks: 14, meetings: 4 }, u9: { calls: 18, mins: 120, chats: 38, msgs: 220, leads: 7, moves: 9, tasks: 8, meetings: 2 } }[sale];
  const targets = { calls: 50, chats: 80, leads: 15, tasks: 20, meetings: 6 };
  const items = [
    { k: 'calls', l: 'Cuộc gọi', v: kpis.calls, t: targets.calls, sub: kpis.mins + ' phút' },
    { k: 'chats', l: 'Phiên chat', v: kpis.chats, t: targets.chats, sub: kpis.msgs + ' tin gửi' },
    { k: 'leads', l: 'Lead mới', v: kpis.leads, t: targets.leads, sub: kpis.moves + ' lượt move stage' },
    { k: 'tasks', l: 'Task xong', v: kpis.tasks, t: targets.tasks, sub: '' },
    { k: 'meetings', l: 'Meeting/TVCS', v: kpis.meetings, t: targets.meetings, sub: '' },
  ];
  const rows = sales.map(s => { const d = { u4: { calls: 42, chats: 86, leads: 14, won: 3, rev: 44700000 }, u5: { calls: 31, chats: 64, leads: 11, won: 2, rev: 33800000 }, u9: { calls: 18, chats: 38, leads: 7, won: 1, rev: 11900000 } }[s.id]; return { id: s.id, name: s.name, ...d }; });
  return (
    <>
      <div className="row jcsb aic mb12"><span className="t13 fw7">KPI tuần · {AAU.users.find(u => u.id === sale)?.name}</span><div className="row g8"><Select value={sale} onChange={setSale} options={sales.map(s => ({ value: s.id, label: s.name }))} style={{ width: 160 }} /><Seg value="w" onChange={() => {}} options={[{ value: 'd', label: 'Ngày' }, { value: 'w', label: 'Tuần' }, { value: 'm', label: 'Tháng' }]} /></div></div>
      <div className="grid gc5 mb16">
        {items.map(it => (
          <div key={it.k} className="kpi">
            <div className="kl">{it.l}</div>
            <div className="row aie g6"><div className="kv tnum">{it.v}</div><div className="t12 subtle" style={{ paddingBottom: 6 }}>/ {it.t}</div></div>
            <div className="mt8"><Progress value={it.v} max={it.t} color={it.v >= it.t ? '#0e7c4a' : '#303030'} /></div>
            {it.sub && <div className="ksub mt4">{it.sub}</div>}
          </div>
        ))}
      </div>
      <Card title="Breakdown theo nhân viên">
        <table className="tbl"><thead><tr><th>Nhân viên</th><th className="num">Cuộc gọi</th><th className="num">Phiên chat</th><th className="num">Lead mới</th><th className="num">Deal won</th><th className="num">Doanh thu</th></tr></thead>
          <tbody>{rows.map(r => <tr key={r.id} className="clickable" onClick={() => setSale(r.id)}><td><div className="row aic g8"><Avatar name={r.name} size={26} color={AAU.users.find(u => u.id === r.id)?.color} />{r.name}</div></td><td className="num">{r.calls}</td><td className="num">{r.chats}</td><td className="num">{r.leads}</td><td className="num fw6">{r.won}</td><td className="num fw6">{AAU.fmtVND(r.rev)}</td></tr>)}</tbody></table>
      </Card>
    </>
  );
}

function DailyFlowView() {
  const flow = PLAYBOOK.dailyFlowBU;
  const Block = ({ b, active }) => (
    <div className={'flow-block' + (active ? ' active' : '')}>
      <div className="flow-time"><span className="t13 fw7 tnum">{b.time}</span><span className="badge neutral" style={{ fontSize: 10 }}>{b.dur}</span></div>
      <div className="flow-body"><div className="t13 fw7 mb6">{b.title}</div><ul className="flow-items">{b.items.map((it, i) => <li key={i}>{it}</li>)}</ul></div>
    </div>
  );
  return (
    <>
      <div className="pb-note mb16"><Icon name="bolt" size={15} color="#1a4fa3" /><span>Nguyên tắc: luôn từ <b>hot nhất → nguội</b>. Sáng là khung giờ năng lượng cao — ưu tiên việc khó (close, proposal). Dòng dò ngược: 3.5 → 3.6 → 3.7 → 3.1 → 3.2–3.4 → 3.0 → 2.3 → 2.1/2.2.</span></div>
      <div className="grid gc2 g20">
        <Card title="Sáng · 8:30–12:00" subtitle="Năng lượng cao — close & proposal"><div className="col g10">{flow.am.map((b, i) => <Block key={i} b={b} active={i === 2} />)}</div></Card>
        <Card title="Chiều · 13:00–18:00" subtitle="Lead mới · self-source · admin"><div className="col g10">{flow.pm.map((b, i) => <Block key={i} b={b} />)}</div></Card>
      </div>
    </>
  );
}

function WeeklyView() {
  return (
    <div className="col g14">
      <div className="pb-note mb4"><Icon name="calendar" size={15} color="#1a4fa3" /><span>Sales Leader chạy nhịp tuần với team: 60% coaching · 30% own deals · 10% admin. Imlặng là kẻ thù — escalate sớm.</span></div>
      <div className="grid gc3 g14">
        {PLAYBOOK.weekly.map((w, i) => (
          <Card key={i}>
            <div className="row jcsb aic mb8"><span className="t13 fw7">{w.title}</span><span className="badge info">{w.owner}</span></div>
            <div className="t12 subtle mb10">{w.day}</div>
            <ul className="flow-items">{w.items.map((it, j) => <li key={j}>{it}</li>)}</ul>
          </Card>
        ))}
      </div>
    </div>
  );
}

function ReportView() {
  return (
    <div className="grid gc2 g16">
      <Card title="Daily Report — Sales BU" subtitle="Submit trước 18:00 · Larksuite chat group">
        <div className="col g8">
          {PLAYBOOK.dailyReport.map((r, i) => (
            <div key={i} className="report-row"><span className="report-k">{i + 1}. {r.k}</span><span className="t12 muted">{r.v}</span></div>
          ))}
          <Button variant="primary" icon="send" style={{ marginTop: 6 }}>Gửi báo cáo hôm nay</Button>
        </div>
      </Card>
      <Card title="Cadence báo cáo" subtitle="Actionable · không spam · tự động hóa khi có thể">
        <table className="tbl"><thead><tr><th>Báo cáo</th><th>Cadence</th><th>Owner → Audience</th></tr></thead>
          <tbody>
            {[['Daily Report', 'Daily 18:00', 'Sales BU → Leader'], ['Weekly Plan', 'Thứ 2 9:00', 'Leader → Team'], ['Weekly Report', 'Thứ 6 18:00', 'Leader → CEO'], ['QC Weekly', 'Thứ 6 17:00', 'QC → Leader/L&D'], ['Pipeline Dashboard', 'Real-time', 'BA → Cả team'], ['Monthly Revenue', 'Ngày 3', 'Finance → CEO/BOD']].map((r, i) => (
              <tr key={i}><td className="fw6">{r[0]}</td><td className="muted">{r[1]}</td><td className="muted">{r[2]}</td></tr>
            ))}
          </tbody></table>
      </Card>
    </div>
  );
}

/* ───────────────── Pipeline Config & Playbook reference ───────────────── */
function PipelineConfig() {
  const [tab, setTab] = useState('access');
  return (
    <div className="page wide">
      <PageHead breadcrumb={[{ label: 'Sales CRM' }, { label: 'Cấu hình & Playbook' }]} title="Cấu hình Pipeline & Playbook" subtitle={AAU.stages.length + ' stage · 4 funnel · quy tắc chuyển stage · hot signal · MAKE THE MOVE'}
        actions={<Button icon="kanban" onClick={() => navigate('/leads/kanban')}>Xem Kanban</Button>} />
      <div className="mb16"><Tabs value={tab} onChange={setTab} tabs={[{ value: 'access', label: 'Phân quyền Lead' }, { value: 'stages', label: 'Stages (' + AAU.stages.length + ')' }, { value: 'transitions', label: 'Transition Rules' }, { value: 'signals', label: 'Hot Signals' }, { value: 'move', label: 'MAKE THE MOVE' }, { value: 'priority', label: 'Data Priority' }]} /></div>
      {tab === 'access' && <ConfigAccess />}
      {tab === 'stages' && <ConfigStages />}
      {tab === 'transitions' && <ConfigTransitions />}
      {tab === 'signals' && <ConfigSignals />}
      {tab === 'move' && <ConfigMove />}
      {tab === 'priority' && <ConfigPriority />}
    </div>
  );
}

function ConfigAccess() {
  const leads = useLeads();
  const SCOPE_KEY = 'aau.salesScope.v1';
  const team = AAU.users.filter(u => u.salesRole && u.salesRole !== 'admin');
  const members = team.filter(u => u.salesRole === 'member');
  const [edit, setEdit] = useState(false);
  const [, bump] = useState(0);
  const [scopes, setScopes] = useState(() => { const o = {}; team.forEach(u => o[u.id] = u.buScope === 'all' ? 'all' : [...(u.buScope || [])]); return o; });

  const persist = (next) => {
    setScopes(next);
    team.forEach(u => { if (next[u.id] !== undefined) u.buScope = next[u.id]; });
    try { localStorage.setItem(SCOPE_KEY, JSON.stringify(next)); } catch (e) {}
    bump(x => x + 1);
  };
  const addCourse = (uid, cid) => { const cur = scopes[uid]; if (cur === 'all' || !cid || cur.includes(cid)) return; persist({ ...scopes, [uid]: [...cur, cid] }); };
  const removeCourse = (uid, cid) => { const cur = scopes[uid]; if (cur === 'all') return; persist({ ...scopes, [uid]: cur.filter(x => x !== cid) }); };

  const visCount = (u) => SalesAccess.scoped(leads, { ...u, buScope: scopes[u.id] }).length;
  const allCourses = AAU.courses;
  const courseChip = (cid, uid) => { const c = AAU.courseById(cid); if (!c) return null; return (
    <span key={cid} className="tag" style={{ paddingRight: edit ? 4 : 9 }}>{c.code}{edit && <button className="chip-x" onClick={() => removeCourse(uid, cid)} title={'Bỏ ' + c.code}><Icon name="x" size={11} /></button>}</span>
  ); };

  return (
    <>
      <div className="pb-note mb16"><Icon name="shield" size={15} color="#1a4fa3" /><span>Phân quyền lead <b>theo từng khóa</b>: mỗi Sales BU được gán danh sách khóa cụ thể và chỉ thấy lead của các khóa đó. Khóa có thể thêm/bớt tùy hiệu quả kinh doanh. Sales Leader/Manager thấy toàn bộ. Dùng "Xem với" trên thanh trên cùng để thử từng vai trò.</span></div>
      <Card title="Team & phạm vi truy cập" subtitle="Vai trò · khóa phụ trách · cấp quyền · số lead nhìn thấy" className="mb16"
        actions={<Button size="sm" icon={edit ? 'check' : 'edit'} variant={edit ? 'primary' : 'secondary'} onClick={() => setEdit(!edit)}>{edit ? 'Xong' : 'Chỉnh sửa khóa'}</Button>}>
        <table className="tbl"><thead><tr><th>Thành viên</th><th>Vai trò</th><th style={{ minWidth: 280 }}>Khóa phụ trách</th><th>Cấp quyền</th><th className="num">Lead thấy</th></tr></thead>
          <tbody>{team.map(u => { const m = SalesAccess.accessMeta[u.access] || {}; const sc = scopes[u.id]; const avail = allCourses.filter(c => sc !== 'all' && !sc.includes(c.id)); return (
            <tr key={u.id}>
              <td><div className="row aic g8"><Avatar name={u.name} color={u.color} size={26} /><div><div className="t13 fw6">{u.name}</div><div className="t11 subtle">{u.title}</div></div></div></td>
              <td>{u.salesRole === 'leader' ? <Badge tone="magic">Leader</Badge> : u.salesRole === 'member' ? <Badge tone="info">Member</Badge> : <Badge tone="neutral">{u.salesRole}</Badge>}</td>
              <td>{sc === 'all' ? <span className="badge neutral">Toàn bộ khóa</span> : (
                <div className="row g4 wrap aic">
                  {sc.length ? sc.map(cid => courseChip(cid, u.id)) : <span className="t12 subtle">— chưa gán khóa —</span>}
                  {edit && avail.length > 0 && <Select value="" onChange={cid => addCourse(u.id, cid)} options={[{ value: '', label: '+ khóa' }, ...avail.map(c => ({ value: c.id, label: c.code + ' · ' + c.name }))]} style={{ width: 120 }} />}
                </div>
              )}</td>
              <td><span className={'badge ' + (m.tone || 'neutral')}><Icon name={m.icon} size={12} />{m.label}</span></td>
              <td className="num fw6">{visCount(u)}</td>
            </tr>
          ); })}</tbody></table>
      </Card>
      <div className="grid gc2 g16">
        <Card title="Khóa học → Sales phụ trách" subtitle="Ai thấy lead của khóa nào (theo phân quyền hiện tại)">
          <table className="tbl"><thead><tr><th>Khóa học</th><th>Sales BU phụ trách</th></tr></thead>
            <tbody>{allCourses.filter(c => c.status === 'active').map(c => { const owners = members.filter(u => scopes[u.id] !== 'all' && (scopes[u.id] || []).includes(c.id)); return (
              <tr key={c.id}>
                <td><div className="t13 fw6">{c.code}</div><div className="t11 subtle">{c.name}</div></td>
                <td>{owners.length ? <div className="row g6 wrap">{owners.map(o => <span key={o.id} className="row aic g4"><Avatar name={o.name} color={o.color} size={20} /><span className="t12">{o.name}</span></span>)}</div> : <span className="badge warning">Chưa ai phụ trách</span>}</td>
              </tr>
            ); })}</tbody></table>
        </Card>
        <Card title="Cấp quyền" subtitle="Quyền thao tác theo cấp độ trong team">
          <div className="col g10">
            {[['view', 'Xem pipeline, hồ sơ lead trong phạm vi. KHÔNG move/sửa/assign.'], ['edit', 'Xem + MAKE THE MOVE + sửa qualify + tự nhận lead trong khóa phụ trách.'], ['manage', 'Toàn quyền: assign/đổi người phụ trách, cấu hình, xem mọi khóa.']].map(([k, d]) => { const m = SalesAccess.accessMeta[k]; return (
              <div key={k} className="row g10" style={{ padding: 12, borderRadius: 10, background: 'var(--p-bg-surface-tertiary)' }}>
                <span className={'badge ' + m.tone}><Icon name={m.icon} size={12} />{m.label}</span>
                <span className="t12 muted f1">{d}</span>
              </div>
            ); })}
          </div>
        </Card>
      </div>
    </>
  );
}

function ConfigStages() {
  const leads = useLeads();
  const STAGE_KEY = 'aau.stages.v1';
  const leadCount = {}; leads.forEach(l => leadCount[l.stage] = (leadCount[l.stage] || 0) + 1);
  const [edit, setEdit] = useState(false);
  const [, bump] = useState(0);
  const [draft, setDraft] = useState({}); // { catId: { code, name } }

  const loadDiff = () => { try { return JSON.parse(localStorage.getItem(STAGE_KEY) || '{}'); } catch (e) { return {}; } };
  const saveDiff = (d) => { try { localStorage.setItem(STAGE_KEY, JSON.stringify(d)); } catch (e) {} };

  const addStage = (cat) => {
    const d = draft[cat.id] || {}; const name = (d.name || '').trim(); if (!name) return;
    const sameFunnel = AAU.stages.filter(s => s.funnel === cat.funnel);
    const maxPos = sameFunnel.reduce((m, s) => Math.max(m, s.pos), 0);
    const stage = { id: 'sx_' + Math.random().toString(36).slice(2, 8), code: (d.code || '·').trim(), name,
      category: cat.id, funnel: cat.funnel, branch: null, lane: null, pos: maxPos + 1,
      slaHours: 0, slaText: (d.sla || '—').trim() || '—', role: 'sales', color: '#64748b', flags: [] };
    AAU.stages.push(stage);
    const diff = loadDiff(); diff.added = [...(diff.added || []), stage]; saveDiff(diff);
    setDraft(p => ({ ...p, [cat.id]: {} })); bump(x => x + 1);
  };
  const removeStage = (s) => {
    if (leadCount[s.id] > 0) return;
    const i = AAU.stages.findIndex(x => x.id === s.id); if (i >= 0) AAU.stages.splice(i, 1);
    const diff = loadDiff();
    diff.added = (diff.added || []).filter(x => x.id !== s.id);
    if (!String(s.id).startsWith('sx_')) diff.removed = [...(diff.removed || []), s.id];
    saveDiff(diff); bump(x => x + 1);
  };
  const resetStages = () => { localStorage.removeItem(STAGE_KEY); location.reload(); };

  return (
    <>
      <div className="pb-note mb16"><Icon name="bolt" size={15} color="#1a4fa3" /><span>Bật <b>Chỉnh sửa</b> để thêm/bớt stage cho từng nhóm funnel. Stage còn lead sẽ <b>không cho xóa</b> (phải chuyển lead đi trước). Thay đổi áp dụng cho cả Kanban & bảng pipeline.</span>
        <span className="row aic g8 mla">{edit && <Button size="sm" icon="refresh" onClick={resetStages}>Khôi phục mặc định</Button>}<Button size="sm" icon={edit ? 'check' : 'edit'} variant={edit ? 'primary' : 'secondary'} onClick={() => setEdit(!edit)}>{edit ? 'Xong' : 'Chỉnh sửa stage'}</Button></span>
      </div>
      {AAU.stageCategories.map(cat => {
        const ss = AAU.stages.filter(s => s.category === cat.id).sort((a, b) => a.pos - b.pos);
        if (!ss.length && !edit) return null;
        const d = draft[cat.id] || {};
        return (
          <Card key={cat.id} title={cat.label} subtitle={'Funnel: ' + cat.funnel} className="mb16">
            <table className="tbl"><thead><tr><th>Code</th><th>Tên stage</th><th>Nhánh / Lane</th><th>SLA</th><th>PIC</th><th>Script</th><th className="num">Lead</th><th>Cờ</th>{edit && <th></th>}</tr></thead>
              <tbody>{ss.map(s => { const g = pbGuide(s.code); const locked = leadCount[s.id] > 0; return (
                <tr key={s.id}>
                  <td><span className="badge" style={{ background: s.color + '22', color: s.color }}>{s.code}</span></td>
                  <td className="fw6">{s.name}</td>
                  <td>{s.branch ? <BranchTag branch={s.branch} /> : ''} {s.lane ? <LaneTag lane={s.lane} /> : (!s.branch ? <span className="subtle">—</span> : '')}</td>
                  <td>{s.slaText}</td>
                  <td className="muted t12">{g ? g.pic : s.role}</td>
                  <td>{g && g.type ? <ScriptTag type={g.type} /> : '—'}</td>
                  <td className="num">{leadCount[s.id] || 0}</td>
                  <td>{s.flags.length ? s.flags.map(f => <span key={f} className={'badge ' + (f === 'won' ? 'success' : f === 'lost' || f === 'junk' ? 'neutral' : f === 'hotlane' ? 'warning' : 'info')} style={{ marginRight: 4 }}>{f}</span>) : '—'}</td>
                  {edit && <td className="num"><button className="plan-step" disabled={locked} title={locked ? 'Còn lead, không thể xóa' : 'Xóa stage'} style={{ opacity: locked ? .4 : 1, cursor: locked ? 'not-allowed' : 'pointer' }} onClick={() => removeStage(s)}><Icon name="x" size={12} /></button></td>}
                </tr>
              ); })}</tbody></table>
            {edit && (
              <div className="row aic g8 mt12" style={{ flexWrap: 'wrap' }}>
                <input className="num-input" style={{ width: 70, textAlign: 'left' }} placeholder="Code" value={d.code || ''} onChange={e => setDraft(p => ({ ...p, [cat.id]: { ...d, code: e.target.value } }))} />
                <input className="txt-input" style={{ border: '1px solid var(--p-border)', minWidth: 200 }} placeholder="Tên stage mới" value={d.name || ''} onChange={e => setDraft(p => ({ ...p, [cat.id]: { ...d, name: e.target.value } }))} />
                <input className="num-input" style={{ width: 90, textAlign: 'left' }} placeholder="SLA" value={d.sla || ''} onChange={e => setDraft(p => ({ ...p, [cat.id]: { ...d, sla: e.target.value } }))} />
                <Button size="sm" icon="plus" variant="primary" disabled={!(d.name || '').trim()} onClick={() => addStage(cat)}>Thêm stage</Button>
              </div>
            )}
          </Card>
        );
      })}
    </>
  );
}

function ConfigTransitions() {
  const rows = PLAYBOOK.transitions;
  return (
    <Card title="Stage Transition Rules — Deal Management" subtitle="Reference nhanh khi Sales/Leader review deal">
      <table className="tbl"><thead><tr><th>Current</th><th>Trigger</th><th>Next Stage</th></tr></thead>
        <tbody>{rows.map((r, i) => { const f = AAU.stageByCode(r.from), t = AAU.stageByCode(r.to); return (
          <tr key={i}>
            <td>{f && <StageChip stageId={f.id} />}</td>
            <td className="muted">{r.trigger}</td>
            <td>{t && <StageChip stageId={t.id} />}</td>
          </tr>
        ); })}</tbody></table>
    </Card>
  );
}

function ConfigSignals() {
  const map = { HIGH: 'critical', MED: 'warning', LOW: 'neutral' };
  return (
    <>
      <div className="pb-note mb16"><Icon name="fire" size={15} color="#c4320a" /><span>Rule: detect signal → <b>MOVE NGAY lên Hot lane (3.5)</b>, không chờ timer. Sai quy trình nhất là giữ khách hot ở nurture lane.</span></div>
      <Card title="Hot Signal Rules">
        <table className="tbl"><thead><tr><th>Signal</th><th style={{ width: 90 }}>Level</th><th>Example phrase / behavior</th></tr></thead>
          <tbody>{PLAYBOOK.hotSignals.map((s, i) => (
            <tr key={i}><td className="fw6">{s.name}</td><td><Badge tone={map[s.level]}>{s.level}</Badge></td><td className="muted">{s.example}</td></tr>
          ))}</tbody></table>
      </Card>
    </>
  );
}

function ConfigMove() {
  return (
    <>
      <div className="pb-note mb16"><Icon name="bolt" size={15} color="#1a4fa3" /><span>Triết lý: <b>Stage không phải trạng thái chờ — là điểm can thiệp có kịch bản cụ thể</b> để push khách sang stage mới. Nếu không MAKE THE MOVE được, stage đó vô nghĩa.</span></div>
      <div className="grid gc3 g14 mb16">
        {PLAYBOOK.makeTheMove.map(p => (
          <Card key={p.n}>
            <div className="row aic g8 mb8"><span className="mtm-num">{p.n}</span><Icon name={p.icon} size={18} color="#1a4fa3" /></div>
            <div className="t14 fw7">{p.title}</div>
            <div className="t11 subtle mb10" style={{ letterSpacing: '0.05em' }}>{p.en}</div>
            <ul className="flow-items">{p.items.map((it, i) => <li key={i}>{it}</li>)}</ul>
          </Card>
        ))}
      </div>
      <Card title="4 nguyên tắc cốt lõi">
        <div className="grid gc2 g12">
          {PLAYBOOK.principles.map(p => (
            <div key={p.n} className="row g10" style={{ padding: 12, borderRadius: 10, background: 'var(--p-bg-surface-tertiary)' }}>
              <span className="mtm-num">{p.n}</span>
              <div><div className="t13 fw7">{p.t}</div><div className="t12 muted mt2">{p.d}</div></div>
            </div>
          ))}
        </div>
      </Card>
    </>
  );
}

function ConfigPriority() {
  const Col = ({ title, hint, list }) => (
    <Card title={title} subtitle={hint}>
      <div className="col g6">
        {list.map((r, i) => { const s = AAU.stageByCode(r.code); return (
          <div key={i} className="prio-row">
            <span className="prio-n">{String(i + 1).padStart(2, '0')}</span>
            {s && <StageChip stageId={s.id} />}
            <span className="t12 muted f1">{r.note}</span>
          </div>
        ); })}
      </div>
    </Card>
  );
  return (
    <>
      <div className="pb-note mb16"><Icon name="layers" size={15} color="#1a4fa3" /><span>Data Priority Flow: thứ tự dò khi Sales cần kiếm số — luôn từ <b>nóng xuống nguội</b> để tối đa số Won/ngày. Đây cũng là logic xếp hạng của màn "Hôm nay".</span></div>
      <div className="grid gc2 g16">
        <Col title="Lead side" hint="Khi cần kiếm số ở Lead pipeline" list={PLAYBOOK.dataPriorityLead} />
        <Col title="Deal side" hint="Vận hành daily — tối đa Won deal" list={PLAYBOOK.dataPriorityDeal} />
      </div>
    </>
  );
}

Object.assign(window, { PipelineTable, SalesActivity, PipelineConfig });
