/* AAU CRM — Work Queue "Hôm nay": rep's daily home.
   Data Priority Flow worklist · 3 switchable layouts · daily routine rail. */

function WQLeadRow({ lead, onOpen, dense }) {
  const st = AAU.stageById(lead.stage);
  const tier = priorityTier(lead);
  return (
    <div className="wq-row" onClick={onOpen}>
      <span className="wq-rail" style={{ background: tier.color }} />
      <div className="wq-main">
        <div className="row aic g8" style={{ minWidth: 0 }}>
          <span className="t13 fw7 ellip">{lead.company}</span>
          <BranchTag branch={lead.branch} />
          {lead.hot && <HotIcon />}
          <GradeBadge grade={lead.grade} />
        </div>
        <div className="row aic g8 mt4 wrap">
          <StageChip stageId={lead.stage} />
          {lead.signal && <SignalBadge signal={lead.signal} compact />}
          <SLATag sla={lead.sla} left={lead.slaLeft} />
        </div>
        {!dense && <div className="wq-action"><Icon name="bolt" size={12} /> {lead.nextAction}</div>}
      </div>
      <div className="wq-side">
        {lead.dealValue > 0 && <span className="t12 fw7 tnum">{AAU.fmtVNDm(lead.dealValue)}</span>}
        <span className="wq-prio" title="Điểm ưu tiên (Data Priority)">{leadPriority(lead)}</span>
        <Button size="sm" variant="primary" icon="arrowRight">Xử lý</Button>
      </div>
    </div>
  );
}

function WorkQueue() {
  const leads = useLeads();
  const viewer = useViewer();
  const isLeader = viewer.buScope === 'all';
  const canEdit = SalesAccess.canEdit(viewer);
  const [fMember, setFMember] = useState('all');
  const [fGroup, setFGroup] = useState('all');
  const [layout, setLayout] = useState(() => localStorage.getItem('wq_layout') || 'priority');
  const [open, setOpen] = useState(null);
  useEffect(() => localStorage.setItem('wq_layout', layout), [layout]);

  const groupOpts = isLeader ? [...new Set(leads.map(l => l.courseInterest).filter(Boolean))] : (viewer.buScope || []);

  // actionable queue scoped to viewer (exclude junk + lost)
  let queue = SalesAccess.scoped(leads, viewer)
    .filter(l => { const st = AAU.stageById(l.stage); return st && !st.flags.includes('junk') && !st.flags.includes('lost'); });
  if (isLeader && fMember !== 'all') queue = queue.filter(l => (fMember === 'none' ? !l.assignedTo : l.assignedTo === fMember));
  if (fGroup !== 'all') queue = queue.filter(l => l.courseInterest === fGroup);
  queue = queue.sort((a, b) => leadPriority(b) - leadPriority(a));

  const toggleQ = (id, k) => LeadStore.toggleQualify(id, k);

  // KPI strip
  const cnt = (fn) => queue.filter(fn).length;
  const toClose = cnt(l => { const s = AAU.stageById(l.stage); return s && s.flags.includes('hotlane'); });
  const critical = cnt(l => { const s = AAU.stageById(l.stage); return s && ['1.6', '3.1', '1.4'].includes(s.code); });
  const overdue = cnt(l => l.sla === 'bad');
  const hotSig = cnt(l => l.signal && l.signal.level === 'HIGH');

  const openLead = (l) => setOpen(l.id);
  const current = open ? leads.find(l => l.id === open) : null;

  // grouping for layouts
  const tiers = { now: [], next: [], later: [] };
  queue.forEach(l => tiers[priorityTier(l).key].push(l));

  const laneGroups = [
    { id: 'hot', label: '🔥 Hot lane — Close mode', hint: '3.5 / 3.6 / 3.7 · respond < 1h', test: s => s.flags.includes('hotlane') },
    { id: 'qual', label: 'Critical window', hint: '1.6 / 3.1 / 1.4 · không để nguội', test: s => ['1.6', '3.1', '1.4'].includes(s.code) },
    { id: 'newlead', label: 'Lead cần qualify', hint: '1.0 / 1.2 / 2.1 / 2.2 / 2.3 / 1.5', test: s => (s.funnel === 'lead' || s.funnel === 'leadb') && !['1.6', '1.4'].includes(s.code) },
    { id: 'nurture', label: 'Nurture queue', hint: '3.0 / 3.2 / 3.3 / 3.4', test: s => ['3.0', '3.2', '3.3', '3.4'].includes(s.code) },
    { id: 'won', label: 'Won & Alumni', hint: 'Onboard · cross-sell · alumni tái bán', test: s => s.funnel === 'won' || s.funnel === 'alumni' },
  ];

  return (
    <div className="page wide">
      <PageHead title={<span className="row aic g10">Hôm nay <span className="t13 subtle fw5">· {AAU.fmtDate('2026-06-02')}</span></span>}
        subtitle="Work queue theo Data Priority — luôn từ nóng xuống nguội, không skip stage. Click để MAKE THE MOVE."
        actions={<>
          {isLeader && <Select value={fMember} onChange={setFMember} options={[{ value: 'all', label: 'Cả team' }, ...SalesAccess.members().map(s => ({ value: s.id, label: s.name })), { value: 'none', label: 'Chưa gán' }]} style={{ width: 150 }} />}
          {groupOpts.length > 1 && <Select value={fGroup} onChange={setFGroup} options={[{ value: 'all', label: 'Mọi khóa' }, ...groupOpts.map(g => ({ value: g, label: (AAU.courseById(g) || {}).code || g }))]} style={{ width: 150 }} />}
        </>} />

      <div className="mb16"><AccessNote viewer={viewer} /></div>

      <div className="grid gc4 mb16">
        <div className="kpi"><div className="kl"><Icon name="fire" size={14} />Cần CHỐT hôm nay</div><div className="kv tnum" style={{ color: '#ea580c' }}>{toClose}</div><div className="ksub">Hot lane · close mode</div></div>
        <div className="kpi"><div className="kl"><Icon name="clock" size={14} />Critical window</div><div className="kv tnum" style={{ color: '#9a6700' }}>{critical}</div><div className="ksub">Qualify 48h · không để nguội</div></div>
        <div className="kpi"><div className="kl"><Icon name="alert" size={14} />Quá hạn SLA</div><div className="kv tnum" style={{ color: '#c4320a' }}>{overdue}</div><div className="ksub">Xử lý trước tiên</div></div>
        <div className="kpi"><div className="kl"><Icon name="bolt" size={14} />Hot signal HIGH</div><div className="kv tnum" style={{ color: '#1a4fa3' }}>{hotSig}</div><div className="ksub">Đẩy lên 3.5 ngay</div></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1fr 300px', alignItems: 'start' }}>
        <div className="col g12" style={{ minWidth: 0 }}>
          <div className="row jcsb aic">
            <div className="row aic g8"><span className="t13 fw7">{queue.length} việc cần xử lý</span><span className="t11 subtle">xếp theo điểm ưu tiên</span></div>
            <Seg value={layout} onChange={setLayout} options={[{ value: 'priority', label: 'Ưu tiên' }, { value: 'nnl', label: 'Now · Next · Later' }, { value: 'lane', label: 'Theo lane' }]} />
          </div>

          {/* LAYOUT A — single ranked list */}
          {layout === 'priority' && (
            <Card pad={false}><div className="wq-list">
              {queue.map(l => <WQLeadRow key={l.id} lead={l} onOpen={() => openLead(l)} />)}
              {queue.length === 0 && <EmptyState icon="checkCircle" title="Hết việc nóng" desc="Queue trống — chuyển sang self-source / new lead pick-up." />}
            </div></Card>
          )}

          {/* LAYOUT B — Now / Next / Later buckets */}
          {layout === 'nnl' && (
            <div className="grid gc3" style={{ alignItems: 'start' }}>
              {[{ k: 'now', t: 'NOW', d: 'Xử lý ngay', c: '#c4320a' }, { k: 'next', t: 'NEXT', d: 'Trong hôm nay', c: '#9a6700' }, { k: 'later', t: 'LATER', d: 'Nurture / theo dõi', c: '#5a6472' }].map(col => (
                <div key={col.k} className="wq-col">
                  <div className="wq-col-head" style={{ borderColor: col.c }}><span className="t12 fw7" style={{ color: col.c }}>{col.t}</span><span className="t11 subtle">{col.d}</span><span className="mla badge neutral">{tiers[col.k].length}</span></div>
                  <div className="col g8">{tiers[col.k].map(l => <WQLeadRow key={l.id} lead={l} onOpen={() => openLead(l)} dense />)}
                    {tiers[col.k].length === 0 && <div className="t11 subtle center" style={{ padding: 16 }}>—</div>}</div>
                </div>
              ))}
            </div>
          )}

          {/* LAYOUT C — by lane sections */}
          {layout === 'lane' && (
            <div className="col g14">
              {laneGroups.map(grp => {
                const items = queue.filter(l => grp.test(AAU.stageById(l.stage)));
                if (!items.length) return null;
                const val = items.reduce((s, l) => s + (l.dealValue || 0), 0);
                return (
                  <Card key={grp.id} pad={false}>
                    <div className="wq-sec-head"><div><span className="t13 fw7">{grp.label}</span> <span className="t11 subtle">· {grp.hint}</span></div><div className="row aic g8"><span className="badge neutral">{items.length}</span>{val > 0 && <span className="t12 fw7 tnum">{AAU.fmtVNDm(val)}</span>}</div></div>
                    <div className="wq-list">{items.map(l => <WQLeadRow key={l.id} lead={l} onOpen={() => openLead(l)} />)}</div>
                  </Card>
                );
              })}
            </div>
          )}
        </div>

        {/* daily routine rail */}
        <DailyRoutineRail />
      </div>

      {current && <MakeTheMoveDrawer lead={current} onClose={() => setOpen(null)} onMove={(id, to, r, t) => { LeadStore.move(id, to, r, t); setOpen(null); }} onToggleQualify={toggleQ} readOnly={!canEdit} />}
    </div>
  );
}

function DailyRoutineRail() {
  const flow = (window.PLAYBOOK && PLAYBOOK.dailyFlowBU) || { am: [], pm: [] };
  const all = [...flow.am, ...flow.pm];
  // mock "current" block — 9:00–10:30 Hot calls
  const activeIdx = 2;
  return (
    <div className="col g12" style={{ position: 'sticky', top: 0 }}>
      <Card title="Lịch trình hôm nay" subtitle="Sales BU · từ nóng → nguội">
        <div className="dr-list">
          {all.map((b, i) => (
            <div key={i} className={'dr-block' + (i === activeIdx ? ' active' : '')}>
              <div className="dr-time">{b.time}<span className="dr-dur">{b.dur}</span></div>
              <div className="dr-body">
                <div className="t12 fw7">{b.title}</div>
                {i === activeIdx && <ul className="dr-items">{b.items.map((it, j) => <li key={j}>{it}</li>)}</ul>}
              </div>
            </div>
          ))}
        </div>
      </Card>
      <Card>
        <div className="row aic g8 mb6"><Icon name="send" size={15} color="#1a4fa3" /><span className="t13 fw7">Báo cáo cuối ngày</span></div>
        <div className="t12 muted mb10">Submit trước 18:00 cho Sales Leader (Larksuite).</div>
        <Button variant="secondary" icon="checkCircle" style={{ width: '100%' }} onClick={() => navigate('/sales/activity')}>Mở mẫu Daily Report</Button>
      </Card>
    </div>
  );
}

Object.assign(window, { WorkQueue });
