// ddata.jsx — DEALS (Thương vụ) mock. Loaded after cdata.jsx (dùng contractDir/contractTotals).
// 1 thương vụ gom nhiều HĐ mua (giá vốn) + nhiều HĐ bán (doanh thu) → P&L tổng.
const DEAL_STATUS = {
  open:   { vi:'Đang chạy', en:'Open',   cls:'badge-info' },
  won:    { vi:'Thắng',     en:'Won',    cls:'badge-success' },
  lost:   { vi:'Thua',      en:'Lost',   cls:'badge-error' },
  closed: { vi:'Đã đóng',   en:'Closed', cls:'badge-neutral' },
};
function deal(code, name, endCustomer, status, note, contracts){ return { code, name, endCustomer, status, note, contracts:contracts || [] }; }
const DEALS = [
  deal('TV-2026-001', 'Cung cấp & triển khai nền tảng cho Kizuna', 'KIZUNA', 'open',
    'Mua license nền tảng từ Tiên Phong (NCC-001), bán lại kèm triển khai cho Kizuna.',
    ['HD-2026-101', 'HD-2026-103']),
];

function genDealCode(list){
  const yr = TODAY.slice(0, 4);
  const max = (list || []).reduce((m, d) => { const mm = (d.code || '').match(new RegExp('TV-' + yr + '-(\\d+)')); return mm ? Math.max(m, +mm[1]) : m; }, 0);
  return 'TV-' + yr + '-' + String(max + 1).padStart(3, '0');
}

// P&L thương vụ = Σ doanh thu (HĐ bán) − Σ giá vốn (HĐ mua) trong số HĐ thành viên.
function dealPnl(d, allContracts){
  const members = (d.contracts || []).map(code => (allContracts || []).find(c => c.code === code)).filter(Boolean);
  const sells = members.filter(c => contractDir(c) === 'sell');
  const buys = members.filter(c => contractDir(c) === 'buy');
  const revenue = sells.reduce((s, c) => s + contractTotals(c).total, 0);
  const cost = buys.reduce((s, c) => s + contractTotals(c).total, 0);
  const profit = revenue - cost;
  return { members, sells, buys, revenue, cost, profit, marginPct: revenue ? Math.round(profit / revenue * 100) : 0 };
}

Object.assign(window, { DEALS, DEAL_STATUS, genDealCode, dealPnl });
