/* AAU CRM — Pipeline Kanban: 3 funnel rows (Lead / Deal / Won),
   branch & lane labels, drag-drop + MAKE THE MOVE drawer. */

function LeadCard({ lead, onDragStart, onOpen }) {
  const tier = priorityTier(lead);
  return (
    <div draggable onDragStart={onDragStart} onClick={onOpen} className="kb-card">
      <span className="kb-card-rail" style={{ background: tier.color }} />
      <div className="row jcsb aic">
        <span className="t13 fw6 ellip">{lead.company}</span>
        <div className="row aic g4">{lead.hot && <HotIcon />}<GradeBadge grade={lead.grade} /></div>
      </div>
      <div className="t11 muted mt2 ellip">{lead.name} · {lead.role}</div>
      {lead.signal && <div className="mt6"><SignalBadge signal={lead.signal} compact /></div>}
      <div className="row jcsb aic mt8">
        {lead.dealValue > 0 ? <span className="t12 fw7 tnum">{AAU.fmtVNDm(lead.dealValue)}</span> : <span className="t11 subtle">—</span>}
        <SLATag sla={lead.sla} left={lead.slaLeft} />
      </div>
    </div>
  );
}

function KanbanColumn({ stage, leads, onDrop, onDragStart, onOpen, onAdd, canEdit }) {
  const [over, setOver] = useState(false);
  const dropRef = useRef(null);
  const CAP = 10;
  const total = leads.reduce((s, l) => s + (l.dealValue || 0), 0);
  const overflow = Math.max(0, leads.length - CAP);

  // Cap the visible height to exactly CAP cards; the rest scroll.
  useEffect(() => {
    const el = dropRef.current; if (!el) return;
    const cards = el.querySelectorAll('.kb-card');
    if (cards.length > CAP) {
      const last = cards[CAP - 1];
      el.style.maxHeight = (last.offsetTop + last.offsetHeight + 8) + 'px';
    } else {
      el.style.maxHeight = '';
    }
  }, [leads.length, leads.map(l => l.id).join(',')]);

  return (
    <div className="kb-col"
      onDragOver={e => { e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)}
      onDrop={() => { setOver(false); onDrop(stage.id); }}>
      <div className="kb-col-head">
        <span className="t12 fw7 tnum" style={{ color: stage.color }}>{stage.code}</span>
        <span className="t12 fw6 ellip">{stage.name}</span>
        <span className="mla badge neutral" style={{ fontSize: 10 }}>{leads.length}</span>
      </div>
      <div className="row aic g6 kb-col-sub">
        {stage.branch && <BranchTag branch={stage.branch} />}
        {stage.lane && <LaneTag lane={stage.lane} />}
        {stage.slaText && stage.slaText !== '—' && <span className="t11 subtle"><Icon name="clock" size={10} /> {stage.slaText}</span>}
        {total > 0 && <span className="t11 fw6 tnum mla">{AAU.fmtVNDm(total)}</span>}
      </div>
      <div ref={dropRef} className={'kb-drop' + (over ? ' over' : '')}>
        {leads.map(l => <LeadCard key={l.id} lead={l} onDragStart={e => onDragStart(l.id, stage.id)} onOpen={() => onOpen(l.id)} />)}
        {leads.length === 0 && <div className="center t11 subtle" style={{ height: 56 }}>—</div>}
      </div>
      {overflow > 0 && <div className="kb-morehint">↑ cuộn để xem {overflow} khách còn lại</div>}
      {canEdit && (
        <div className="kb-col-foot">
          <button className="kb-addbtn" onClick={() => onAdd(stage.id)} title={'Thêm khách vào ' + stage.code + ' ' + stage.name}>
            <Icon name="plus" size={13} /> Thêm khách
          </button>
        </div>
      )}
    </div>
  );
}

function FunnelRow({ index, title, hint, stages, leadsByStage, ...handlers }) {
  const total = stages.reduce((s, st) => s + (leadsByStage[st.id] || []).length, 0);
  const val = stages.reduce((sum, st) => sum + (leadsByStage[st.id] || []).reduce((a, l) => a + (l.dealValue || 0), 0), 0);
  return (
    <div className="mb18">
      <div className="row aic g8 mb10">
        <span className="kb-fnum">{index}</span>
        <span className="t15 fw7">{title}</span>
        <span className="t12 subtle">{hint}</span>
        <span className="mla t12 subtle">{total} lead{val > 0 ? ' · ' + AAU.fmtVNDm(val) : ''}</span>
      </div>
      <div className="kb-scroll">
        {stages.map(s => <KanbanColumn key={s.id} stage={s} leads={leadsByStage[s.id] || []} {...handlers} />)}
      </div>
    </div>
  );
}

function NewLeadDrawer({ defaultStage, viewer, onClose, onCreated }) {
  const leadStages = AAU.stages.filter(s => s.funnel === 'lead' || s.funnel === 'leadb').sort((a, b) => a.pos - b.pos);
  const courseOpts = [{ value: '', label: '— Chưa rõ —' }].concat(AAU.courses.map(c => ({ value: c.id, label: c.code + ' · ' + c.name })));
  const sourceOpts = Object.keys(AAU.sourceMeta).map(k => ({ value: k, label: AAU.sourceMeta[k].label }));
  const canAssignSelf = viewer && (viewer.salesRole === 'member' || viewer.salesRole === 'leader');

  const [f, setF] = useState({
    company: '', name: '', role: 'Chủ', phone: '', email: '', region: 'TP.HCM',
    bizModel: '', chainSize: '', courseInterest: '', source: 'direct',
    stage: defaultStage || 's_raw', grade: 'C', dealValue: '',
    painpoints: '', nextAction: '', assignSelf: !!canAssignSelf,
  });
  const set = (k, v) => setF(p => ({ ...p, [k]: v }));
  const num = v => Number(String(v).replace(/\D/g, '')) || 0;
  const valid = f.company.trim() && f.name.trim();

  function save() {
    if (!valid) return;
    const id = LeadStore.add({
      company: f.company.trim(), name: f.name.trim(), role: f.role.trim() || 'Chủ',
      phone: f.phone.trim(), email: f.email.trim(), region: f.region.trim(),
      bizModel: f.bizModel.trim(), industry: f.bizModel.trim() || 'F&B', chainSize: f.chainSize.trim(),
      courseInterest: f.courseInterest, source: f.source,
      stage: f.stage, grade: f.grade, dealValue: num(f.dealValue),
      painpoints: f.painpoints.split(',').map(s => s.trim()).filter(Boolean),
      nextAction: f.nextAction.trim(),
      assignedTo: f.assignSelf && canAssignSelf ? viewer.id : '',
    });
    onCreated && onCreated(id);
  }

  const st = AAU.stageById(f.stage);
  return (
    <Drawer width={520} title="Thêm data — lead mới (nhập tay)" onClose={onClose}
      footer={<><Button onClick={onClose}>Hủy</Button><Button variant="primary" icon="plus" disabled={!valid} onClick={save}>Tạo lead</Button></>}>
      <div className="callout-soft mb16"><Icon name="phone" size={14} /><span className="t12">Dùng khi khách gọi hotline / giới thiệu mà chưa có sẵn trên hệ thống. Tối thiểu cần Tên doanh nghiệp + Người liên hệ.</span></div>

      <div className="t12 fw7 subtle mb8">ĐỊNH DANH</div>
      <div className="grid gc2 g12 mb16">
        <Field label="Tên doanh nghiệp *"><Input value={f.company} onChange={v => set('company', v)} placeholder="VD: Sơn Seafood" autoFocus /></Field>
        <Field label="Người liên hệ *"><Input value={f.name} onChange={v => set('name', v)} placeholder="VD: Anh Sơn" /></Field>
        <Field label="Vai trò"><Input value={f.role} onChange={v => set('role', v)} placeholder="Founder / Chủ / CEO" /></Field>
        <Field label="Khu vực"><Input value={f.region} onChange={v => set('region', v)} /></Field>
        <Field label="SĐT"><Input value={f.phone} onChange={v => set('phone', v)} placeholder="09xx xxx xxx" /></Field>
        <Field label="Email"><Input value={f.email} onChange={v => set('email', v)} /></Field>
      </div>

      <div className="t12 fw7 subtle mb8">KINH DOANH & NHU CẦU</div>
      <div className="grid gc2 g12 mb16">
        <Field label="Mô hình KD"><Input value={f.bizModel} onChange={v => set('bizModel', v)} placeholder="Hải sản / Cà phê…" /></Field>
        <Field label="Quy mô"><Input value={f.chainSize} onChange={v => set('chainSize', v)} placeholder="3 chi nhánh" /></Field>
        <Field label="Khóa quan tâm"><Select value={f.courseInterest} onChange={v => set('courseInterest', v)} options={courseOpts} /></Field>
        <Field label="Nguồn"><Select value={f.source} onChange={v => set('source', v)} options={sourceOpts} /></Field>
        <Field label="Painpoints (phân tách dấu phẩy)"><Input value={f.painpoints} onChange={v => set('painpoints', v)} placeholder="Chi phí cao, Chưa chuẩn SOP" /></Field>
        <Field label="Deal value dự kiến (₫)"><Input value={f.dealValue} onChange={v => set('dealValue', v)} placeholder="0" /></Field>
      </div>

      <div className="t12 fw7 subtle mb8">XẾP VÀO PIPELINE</div>
      <div className="grid gc2 g12 mb16">
        <Field label="Stage"><Select value={f.stage} onChange={v => set('stage', v)} options={leadStages.map(s => ({ value: s.id, label: s.code + ' · ' + s.name }))} /></Field>
        <Field label="Grade"><Seg value={f.grade} onChange={v => set('grade', v)} options={[{ value: 'A', label: 'A' }, { value: 'B', label: 'B' }, { value: 'C', label: 'C' }, { value: 'D', label: 'D' }]} /></Field>
      </div>
      {st && st.slaText && st.slaText !== '—' && <div className="t11 subtle mb16"><Icon name="clock" size={11} /> SLA stage {st.code}: {st.slaText}</div>}

      <Field label="Hành động kế tiếp"><Input value={f.nextAction} onChange={v => set('nextAction', v)} placeholder="VD: Gọi lại qualify 4 điều kiện trong 24h" /></Field>
      {canAssignSelf && (
        <label className="row aic g8 mt12" style={{ cursor: 'pointer' }}>
          <input type="checkbox" checked={f.assignSelf} onChange={e => set('assignSelf', e.target.checked)} />
          <span className="t12">Phân công cho tôi ({viewer.name})</span>
        </label>
      )}
    </Drawer>
  );
}

function PipelineKanban() {
  const allLeads = useLeads();
  const viewer = useViewer();
  const canEdit = SalesAccess.canEdit(viewer);
  const leads = SalesAccess.scoped(allLeads, viewer);
  const dragRef = useRef(null);
  const [pending, setPending] = useState(null); // {leadId, from, to}
  const [reason, setReason] = useState('');
  const [trigger, setTrigger] = useState('manual');
  const [open, setOpen] = useState(null);
  const [adding, setAdding] = useState(null); // stageId for new-lead drawer

  const byStage = {}; leads.forEach(l => { (byStage[l.stage] = byStage[l.stage] || []).push(l); });
  Object.values(byStage).forEach(arr => arr.sort((a, b) => leadPriority(b) - leadPriority(a)));

  const onDragStart = (leadId, from) => { if (!canEdit) return; dragRef.current = { leadId, from }; };
  const onDrop = (to) => { if (!canEdit) return; const d = dragRef.current; if (!d || d.from === to) return; setPending({ ...d, to }); setReason(''); setTrigger('manual'); };
  const confirmMove = () => {
    if (!reason.trim()) return;
    const toStage = AAU.stageById(pending.to);
    LeadStore.move(pending.leadId, toStage.code, reason, trigger);
    setPending(null);
  };

  const ord = (arr) => arr.slice().sort((a, b) => a.pos - b.pos);
  const leadStages = ord(AAU.stages.filter(s => s.funnel === 'lead'));
  const leadbStages = ord(AAU.stages.filter(s => s.funnel === 'leadb'));
  const dealStages = ord(AAU.stages.filter(s => s.funnel === 'deal'));
  const tnStages = ord(AAU.stages.filter(s => s.funnel === 'potential'));
  const wonStages = ord(AAU.stages.filter(s => s.funnel === 'won'));
  const alumniStages = ord(AAU.stages.filter(s => s.funnel === 'alumni'));
  const handlers = { onDrop, onDragStart, onOpen: (id) => setOpen(id), onAdd: (stageId) => setAdding(stageId), canEdit };
  const current = open ? leads.find(l => l.id === open) : null;

  return (
    <div className="page wide">
      <PageHead title="Pipeline Kanban" subtitle="6 funnel: Lead Social · Lead Nhánh B · Deal · Tiềm năng (TN) · Won · Alumni. Mỗi funnel có điểm loại cuối phễu. Kéo-thả hoặc click thẻ để MAKE THE MOVE."
        actions={<>{canEdit && <Button icon="plus" variant="primary" onClick={() => setAdding('s_raw')}>Thêm data</Button>}<Button icon="bolt" onClick={() => navigate('/sales/today')}>Hôm nay</Button><Button icon="table" onClick={() => navigate('/leads')}>Dạng bảng</Button><Button icon="settings" onClick={() => navigate('/leads/pipeline-config')}>Playbook</Button></>} />
      <div className="mb16"><AccessNote viewer={viewer} /></div>

      <FunnelRow index="①" title="LEAD · Social/Inbound" hint="Inbound social · phân loại · cuối phễu: Lead Social Rác" stages={leadStages} leadsByStage={byStage} {...handlers} />
      <div className="divider mb18" />
      <FunnelRow index="②" title="LEAD · Nhánh B (Event/Outbound)" hint="Event / sales tự kiếm / call · cuối phễu: Lead Others Rác" stages={leadbStages} leadsByStage={byStage} {...handlers} />
      <div className="divider mb18" />
      <FunnelRow index="③" title="DEAL · Nurture" hint="MAKE THE MOVE · nurture 3.0–3.4 · cuối phễu: Deal Lost" stages={dealStages} leadsByStage={byStage} {...handlers} />
      <div className="divider mb18" />
      <FunnelRow index="④" title="TIỀM NĂNG (TN)" hint="Deal nóng cần close · 3.5–3.7 · cuối phễu: TN Lost" stages={tnStages} leadsByStage={byStage} {...handlers} />
      <div className="divider mb18" />
      <FunnelRow index="⑤" title="WON · đang học" hint="Onboard · 30–90 ngày · gồm Bảo lưu (4.3) & Dự án B2B (4.6)" stages={wonStages} leadsByStage={byStage} {...handlers} />
      <div className="divider mb18" />
      <FunnelRow index="⑥" title="ALUMNI & TÁI BÁN" hint="Kho tái bán phân tầng · 5.0 mới → 5.1 active → 5.2 nurture → 5.3 dormant · có tín hiệu → đẩy 3.5" stages={alumniStages} leadsByStage={byStage} {...handlers} />

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

      {adding && <NewLeadDrawer defaultStage={adding} viewer={viewer} onClose={() => setAdding(null)} onCreated={(id) => { setAdding(null); setOpen(id); }} />}

      {pending && (
        <Modal title="MAKE THE MOVE — lý do chuyển" onClose={() => setPending(null)}
          footer={<><Button onClick={() => setPending(null)}>Hủy</Button><Button variant="primary" onClick={confirmMove} disabled={!reason.trim()}>Xác nhận chuyển</Button></>}>
          <div className="col g16">
            <div className="row aic g8 t13" style={{ padding: 12, borderRadius: 10, background: 'var(--p-bg-surface-tertiary)' }}>
              <StageChip stageId={pending.from} /><Icon name="arrowRight" size={16} /><StageChip stageId={pending.to} />
            </div>
            <Field label="Lý do chuyển (bắt buộc — PRE-MOVE CHECKLIST)">
              <textarea className="input" rows={3} placeholder="VD: Khách xác nhận ngân sách, hẹn ký hợp đồng tuần này…" value={reason} onChange={e => setReason(e.target.value)} autoFocus />
            </Field>
            <Field label="Nguồn trigger">
              <Seg value={trigger} onChange={setTrigger} options={[{ value: 'manual', label: 'Thủ công' }, { value: 'hot_signal', label: 'Hot signal' }, { value: 'sla_breach', label: 'SLA breach' }]} />
            </Field>
            {!reason.trim() && <div className="t12 sla-warn row aic g6"><Icon name="alert" size={13} />Phải nhập lý do thì mới được thả.</div>}
          </div>
        </Modal>
      )}
    </div>
  );
}

Object.assign(window, { PipelineKanban });
