// flow.jsx — Quy trình mua/bán: thanh theo dõi workflow dùng chung cho Báo giá & Hợp đồng.
// Tự dò trạng thái thật (báo giá → HĐ → xuất/nhập kho → giao & nghiệm thu → thanh toán → kết thúc)
// và hiện NÚT "làm bước kế" cho bước đang tới (bán tự động). Host truyền `actions` = { key:{label,icon,run} }.

// Hợp đồng có mặt hàng nào đang quản lý tồn không (để biết có cần bước Xuất/Nhập kho).
function contractHasStock(c, products){
  if (!c || !products) return false;
  return (c.items || []).some(it => products.some(pr => pr.stockTracked && (
    (window.sdeburr && sdeburr(pr.name) === sdeburr(it.name)) ||
    (window.productMatches && productMatches(pr, it.name)) ||
    String(pr.name).toLowerCase() === String(it.name).toLowerCase())));
}

/* ----- Luồng BÁN: báo giá → xác nhận → HĐ → xuất kho → giao & nghiệm thu → thanh toán → kết thúc -----
   "Chốt không HĐ" KHÔNG kết thúc luồng: các bước sau chạy tiếp trên chính BÁO GIÁ
   (fulfil = HĐ nếu có, không thì báo giá won — schedule/acceptedDate/phiếu kho gắn theo mã báo giá). */
function sellFlowSteps(q, c, issues, hasStock){
  const total = q ? quoteTotals(q).total : (c ? contractTotals(c).total : 0);
  const needContract = total > QUOTE_CONTRACT_THRESHOLD;
  const qst = q ? quoteStatus(q) : (c ? 'converted' : null);
  const dead = qst === 'rejected' || qst === 'expired';
  const cst = c ? contractStatus(c) : null;
  const fulfil = c || (qst === 'won' ? q : null);          // vật mang schedule/acceptedDate sau khi chốt
  const sch = fulfil ? (fulfil.schedule || []) : [];
  const paid = sch.filter(s => s.paid).length;
  const allPaid = sch.length > 0 && paid === sch.length;
  const issued = !!(fulfil && (issues || []).some(i => i.contract === fulfil.code && i.status === 'issued'));
  const accepted = !!(fulfil && fulfil.acceptedDate);
  const warrantyOn = cst === 'warranty';
  const completed = cst === 'completed';

  const steps = [];
  // 1 — gửi báo giá
  steps.push({ key:'send', icon:'bi-send',
    state: q ? ((q.sentDate || ['sent', 'accepted', 'rejected', 'expired', 'converted', 'won'].includes(qst)) ? 'done' : 'current') : 'done' });
  // 2 — xác nhận báo giá
  steps.push({ key:'confirm', icon:'bi-check2-circle',
    state: dead ? 'failed' : ((['accepted', 'converted', 'won'].includes(qst) || c) ? 'done' : (qst === 'sent' ? 'current' : 'todo')) });
  // 3 — lập hợp đồng (KHUYẾN NGHỊ khi > 10tr, không bắt buộc — chốt không HĐ thì bước này 'skipped')
  steps.push({ key:'contract', icon:'bi-file-earmark-text', subKey: c ? null : (needContract ? 'recommend' : 'le10'),
    state: c ? 'done' : (qst === 'won' ? 'skipped' : (qst === 'accepted' ? 'current' : 'todo')) });
  // 4 — xuất kho (bỏ qua nếu không có mặt hàng quản lý tồn)
  steps.push({ key:'issue', icon:'bi-box-arrow-up',
    state: !fulfil ? 'todo' : (!hasStock ? 'skipped' : (issued ? 'done' : 'current')) });
  // 5 — giao hàng & nghiệm thu (mốc acceptedDate)
  steps.push({ key:'deliver', icon:'bi-truck',
    state: !fulfil ? 'todo' : (accepted ? 'done' : ((issued || !hasStock) ? 'current' : 'todo')) });
  // 6 — thanh toán
  steps.push({ key:'pay', icon:'bi-cash-coin', subLabel: fulfil && sch.length ? (paid + '/' + sch.length) : null,
    state: !fulfil ? 'todo' : (allPaid ? 'done' : ((paid > 0 || accepted) ? 'current' : 'todo')) });
  // 7 — kết thúc & bảo hành (báo giá won: xong khi thu đủ tiền)
  steps.push({ key:'warranty', icon:'bi-shield-check',
    state: !c ? (qst === 'won' ? (allPaid ? 'done' : 'todo') : 'todo') : (warrantyOn ? 'current' : (completed ? 'done' : (allPaid ? 'current' : 'todo'))) });
  return steps;
}

/* ----- Luồng MUA: (báo giá NCC → duyệt mua →) hợp đồng mua → nhập kho → trả NCC → hoàn tất -----
   q = báo giá mua (có thể null khi mở từ HĐ mua tạo trực tiếp — giữ hành vi cũ, bắt đầu từ bước HĐ). */
function buyFlowSteps(q, c, receipts, hasStock){
  const qst = q ? quoteStatus(q) : null;
  const dead = qst === 'rejected';
  const approved = q ? (['accepted', 'converted', 'won'].includes(qst) || !!c) : true;
  const needContract = q ? quoteTotals(q).total > QUOTE_CONTRACT_THRESHOLD : false;
  const cst = c ? contractStatus(c) : null;
  const wonNoC = qst === 'won' && !c;                       // mua trực tiếp không lập HĐ
  const fulfil = c || (wonNoC ? q : null);                  // vật mang schedule/phiếu nhập sau khi chốt
  const sch = fulfil ? (fulfil.schedule || []) : [];
  const paid = sch.filter(s => s.paid).length;
  const allPaid = sch.length > 0 && paid === sch.length;
  const received = !!(fulfil && (receipts || []).some(r => r.buyContract === fulfil.code));
  const cancelled = cst === 'cancelled';

  const steps = [];
  if (q){
    // 1 — ghi nhận báo giá từ NCC (có bản ghi là done)
    steps.push({ key:'recordBuy', icon:'bi-inbox', state:'done' });
    // 2 — duyệt mua
    steps.push({ key:'approveBuy', icon:'bi-check2-circle',
      state: dead ? 'failed' : (approved ? 'done' : 'current') });
  }
  // 3 — hợp đồng mua (từ báo giá: khuyến nghị >10tr; chốt không HĐ → skipped, các bước sau chạy trên báo giá)
  steps.push({ key:'buyContract', icon:'bi-file-earmark-text', subKey: (q && !c) ? (needContract ? 'recommend' : 'le10') : null,
    state: cancelled ? 'failed' : (c ? 'done' : (wonNoC ? 'skipped' : (q ? (approved && !dead ? 'current' : 'todo') : 'done'))) });
  steps.push({ key:'receive', icon:'bi-box-arrow-in-down',
    state: !fulfil ? 'todo' : (!hasStock ? 'skipped' : (received ? 'done' : 'current')) });
  steps.push({ key:'payV', icon:'bi-cash-coin', subLabel: sch.length ? (paid + '/' + sch.length) : null,
    state: !fulfil ? 'todo' : (allPaid ? 'done' : ((paid > 0 || received || !hasStock) ? 'current' : 'todo')) });
  steps.push({ key:'done', icon:'bi-check-circle',
    state: (fulfil && allPaid && (received || !hasStock)) ? 'done' : 'todo' });
  return steps;
}

const FLOW_DOT = {
  done:     { bg:'var(--success)', fg:'#fff', bd:'var(--success)' },
  current:  { bg:'var(--primary)', fg:'#fff', bd:'var(--primary)' },
  todo:     { bg:'var(--bg)', fg:'var(--text-muted)', bd:'var(--border-strong)' },
  skipped:  { bg:'var(--bg)', fg:'var(--gray-400)', bd:'var(--border)' },
  failed:   { bg:'var(--error)', fg:'#fff', bd:'var(--error)' },
};

function PurchaseFlow({ quote, contract, actions }){
  const { t, lang } = useLang();
  const p = usePortal();
  const isBuy = (contract && window.contractDir && contractDir(contract) === 'buy') || (quote && window.quoteDir && quoteDir(quote) === 'buy');
  const hasStock = contractHasStock(contract || quote, p.products);
  const steps = isBuy ? buyFlowSteps(quote, contract, p.receipts, hasStock) : sellFlowSteps(quote, contract, p.issues, hasStock);
  // Bước đang tới đầu tiên có hành động → hiện CTA.
  const cur = steps.find(s => s.state === 'current');
  const act = cur && actions ? actions[cur.key] : null;
  return (
    <div className="card" style={{ marginBottom:14 }}>
      <div className="card-head"><h3><i className="bi bi-diagram-3" style={{ marginRight:6, color:'var(--primary)' }}></i>{isBuy ? (lang === 'vi' ? 'Quy trình mua hàng' : 'Purchase workflow') : (lang === 'vi' ? 'Quy trình bán hàng' : 'Sales workflow')}</h3>
        {act && <button className="btn btn-sm btn-primary" onClick={act.run}><i className={'bi ' + (act.icon || 'bi-play')}></i>{act.label}</button>}</div>
      <div className="card-body" style={{ paddingTop:14, paddingBottom:18 }}>
        <div className="pflow">
          {steps.map((s, i) => {
            const col = FLOW_DOT[s.state];
            const isCheck = s.state === 'done';
            const isFail = s.state === 'failed';
            return (
              <div key={s.key} className={'pflow-step is-' + s.state}>
                {i > 0 && <span className="pflow-line" style={{ background:steps[i].state === 'todo' || steps[i].state === 'skipped' ? 'var(--border)' : (steps[i].state === 'failed' ? 'var(--error)' : 'var(--success)') }}></span>}
                <span className="pflow-dot" style={{ background:col.bg, color:col.fg, borderColor:col.bd, borderStyle:s.state === 'skipped' ? 'dashed' : 'solid' }}>
                  {isCheck ? <i className="bi bi-check-lg"></i> : isFail ? <i className="bi bi-x-lg"></i> : <i className={'bi ' + s.icon}></i>}
                </span>
                <span className="pflow-num">{i + 1}</span>
                <span className="pflow-label" style={{ fontWeight:s.state === 'current' ? 700 : 500, color:s.state === 'skipped' ? 'var(--gray-400)' : (s.state === 'current' ? 'var(--primary)' : 'var(--text)') }}>{t('flow.' + s.key)}</span>
                {s.subKey && <span className="pflow-sub">{t('flow.' + s.subKey)}</span>}
                {s.subLabel && <span className="pflow-sub mono">{s.subLabel}</span>}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { sellFlowSteps, buyFlowSteps, contractHasStock, PurchaseFlow });
