/* lib-landed-cost — pure helpers for landed cost / ROI / break-even.
 * Exposed as window.calcLandedCost (single function) + window.LANDED_DEFAULTS.
 * Reusable from landed-cost.jsx, opportunity.jsx, profit-calc.jsx, restock checks.
 */

window.LANDED_DEFAULTS = {
  currency: "USD",
  fx: 1.36,           // USD → CAD
  unitCost: 4.20,     // supplier price per unit (in `currency`)
  qty: 100,
  inboundTotal: 180,  // total inbound freight CAD across the qty
  dutyPct: 0,         // customs duty % on landed value
  prepPerUnit: 0.50,  // KCC prep cost CAD
  inspectionFlat: 0,  // optional one-time inspection
  damagePct: 2,       // % units written off in transit
  sellPrice: 24.99,
  referralPct: 15,
  fbaFee: 5.20,
  storagePerUnit: 0.85,
  returnPct: 3,
};

window.calcLandedCost = function calcLandedCost(input) {
  const v = { ...window.LANDED_DEFAULTS, ...input };

  // -- upstream cost: cost to land 1 unit at Amazon FBA warehouse
  const unitCostCAD = v.currency === "CAD" ? v.unitCost : v.unitCost * v.fx;
  const goodsCAD    = unitCostCAD * v.qty;
  const dutyCAD     = goodsCAD * (v.dutyPct / 100);
  const inboundUnit = v.qty > 0 ? v.inboundTotal / v.qty : 0;
  const inspecUnit  = v.qty > 0 ? v.inspectionFlat / v.qty : 0;
  const dutyUnit    = unitCostCAD * (v.dutyPct / 100);
  const damageBuffer= unitCostCAD * (v.damagePct / 100);

  const landedPerUnit =
    unitCostCAD + inboundUnit + dutyUnit + v.prepPerUnit + inspecUnit + damageBuffer;
  const landedTotal = landedPerUnit * v.qty;

  // -- downstream: profit at sellPrice
  const referralFee = v.sellPrice * (v.referralPct / 100);
  const returnsCost = v.sellPrice * (v.returnPct / 100);
  const amazonOut   = referralFee + v.fbaFee + v.storagePerUnit + returnsCost;
  const profitUnit  = v.sellPrice - landedPerUnit - amazonOut;
  const profitTotal = profitUnit * v.qty;

  const marginPct = v.sellPrice > 0 ? (profitUnit / v.sellPrice) * 100 : 0;
  const roiPct    = landedPerUnit > 0 ? (profitUnit / landedPerUnit) * 100 : 0;
  const breakEven = landedPerUnit + amazonOut;

  const verdict =
    marginPct >= 28 && roiPct >= 50 ? "buy"
    : marginPct >= 20 && roiPct >= 30 ? "marginal"
    : "pass";

  return {
    inputs: v,
    // upstream breakdown (per-unit, CAD)
    unitCostCAD,
    inboundUnit,
    dutyUnit,
    prepPerUnit: v.prepPerUnit,
    inspecUnit,
    damageBuffer,
    landedPerUnit,
    // totals
    goodsCAD,
    dutyCAD,
    landedTotal,
    // downstream
    referralFee,
    fbaFee: v.fbaFee,
    storagePerUnit: v.storagePerUnit,
    returnsCost,
    amazonOut,
    profitUnit,
    profitTotal,
    // scoring
    marginPct,
    roiPct,
    breakEven,
    verdict,
  };
};
