/* ============================================================
   VKTR TCO -- Lead Time module (v1.7.6, added 2026-07-11)
   ============================================================
   Informational-only estimate of order-to-delivery lead time, entirely
   separate from computeTCO() -- does not affect any cost/financing math.
   Source data: data/lead_time.xlsx (finance/PM-editable, same loader
   pattern as data/vehicles.xlsx -- see loadVehiclesReference() in
   vehicles.jsx). Falls back to the hardcoded defaults below if the fetch
   fails or the file is missing, same reasoning as vehicles.jsx.

   Two calculation paths:
     1. Real VKTR data (vehId present in LEAD_TIME_VKTR) -- per-phase
        breakdown, threshold-based unit-count scaling (>30 units), a
        zero-guard (a phase with baseline 0 never scales, e.g. Body
        Builder for cabin-chassis trucks), and an optional Payload Build
        add-on for the toggle-eligible LDT/HDT cabin-chassis SKUs.
     2. Modeled estimate (everything else -- competitors, and any VKTR
        vehicle without a real PMO row yet, e.g. an MDT placeholder or a
        future custom vehicle) -- Import Type x Segment Tier x Powertrain
        heuristic, flagged `estimated: true` so the UI never presents a
        guess as measured data.

   "Total Lead Time" is deliberately conservative: it assumes the full
   order is delivered together, not staggered in real-world batches (see
   PMO Data.xlsx's Chaca-meeting sourcing notes) -- real deliveries may be
   faster once negotiated in batches.
   ============================================================ */

/* ---- Hardcoded defaults (mirrors data/lead_time.xlsx "VKTR Lead Time" sheet) ---- */
const LEAD_TIME_VKTR = {
  P124: { internalProcess: 14, principalProduction: 70, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: true,  payloadBuildFixedIncluded: false },
  P125: { internalProcess: 14, principalProduction: 70, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: true,  payloadBuildFixedIncluded: false },
  P126: { internalProcess: 14, principalProduction: 70, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: false, payloadBuildFixedIncluded: false },
  P127: { internalProcess: 14, principalProduction: 70, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: true,  payloadBuildFixedIncluded: false },
  P129: { internalProcess: 14, principalProduction: 60, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: true,  payloadBuildFixedIncluded: false },
  P130: { internalProcess: 14, principalProduction: 60, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: true,  payloadBuildFixedIncluded: false },
  P131: { internalProcess: 14, principalProduction: 60, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: true,  payloadBuildFixedIncluded: false },
  P132: { internalProcess: 14, principalProduction: 60, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: true,  payloadBuildFixedIncluded: false },
  P133: { internalProcess: 14, principalProduction: 84, shipping: 15, customs: 3, chassisAssembly: 6, bodyBuilder: 42, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: false, payloadBuildFixedIncluded: false },
  P134: { internalProcess: 14, principalProduction: 84, shipping: 15, customs: 3, chassisAssembly: 0, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: false, payloadBuildFixedIncluded: false },
  P135: { internalProcess: 14, principalProduction: 126, shipping: 15, customs: 3, chassisAssembly: 6, bodyBuilder: 56, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: false, payloadBuildFixedIncluded: false },
  P173: { internalProcess: 14, principalProduction: 70, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: false, payloadBuildFixedIncluded: false },
  P174: { internalProcess: 14, principalProduction: 70, shipping: 15, customs: 3, chassisAssembly: 8, bodyBuilder: 0, finalPdi: 3, delivery: 7, vehicleRegistration: 14, payloadBuildEligible: false, payloadBuildFixedIncluded: true },
};

/* ---- Phase scaling rules (threshold=30 units, rate = extra days/unit beyond it) ---- */
const LEAD_TIME_RULES = {
  chassisAssembly: { affected: true,  threshold: 30, rate: 0.5 },
  bodyBuilder:      { affected: true,  threshold: 30, rate: 0.5 },
  delivery:         { affected: true,  threshold: 30, rate: 0.5 },
  payloadBuild:     { affected: true,  threshold: 30, rate: 0.2 },
};
const PAYLOAD_BUILD_BASE_DAYS = 60;

/* ---- Competitor / no-real-data fallback: Import Type x Segment Tier base days ---- */
const SEGMENT_TIER = {
  LDT: "Tier1", Pickup: "Tier1", "Double Cabin": "Tier1", VAN: "Tier1",
  MDT: "Tier2", HDT: "Tier2", TH: "Tier2",
  BUS: "Tier3",
};
const TIER_BASE_DAYS = {
  Tier1: { CBU: 90,  IKD: 75,  CKD: 130 },
  Tier2: { CBU: 105, IKD: 110, CKD: 165 },
  Tier3: { CBU: 120, IKD: 150, CKD: 215 },
};
const EV_MULTIPLIER = 1.15;
const ICE_MULTIPLIER = 1.0;

/* ---- Brand -> assumed import type (see PMO Data.xlsx "Competitor Lead Time (Est.)" sheet for sourcing) ---- */
const BRAND_IMPORT_TYPE = {
  Hino: "IKD", Isuzu: "IKD", Fuso: "IKD", Toyota: "IKD",
  Foton: "CKD", JAC: "CKD", MABI: "CKD", BEIBEN: "CBU",
};

/* Scale a phase's baseline days by unit count past the threshold. Zero-guard:
   a phase with baseline 0 (e.g. Body Builder on a cabin-chassis truck) never
   scales -- it was never in scope for that vehicle, regardless of volume. */
function scalePhase(baseline, fleetSize, rule) {
  if (!baseline || baseline === 0) return 0;
  if (!rule || !rule.affected) return baseline;
  const units = fleetSize || 1;
  if (units <= rule.threshold) return baseline;
  return baseline + (units - rule.threshold) * rule.rate;
}

/* Real VKTR data path. `payloadBuildEnabled` is ignored for
   payloadBuildFixedIncluded vehicles (P174) -- always on. */
function computeVktrLeadTime(row, fleetSize, payloadBuildEnabled) {
  const phases = {
    internalProcess: row.internalProcess,
    principalProduction: row.principalProduction,
    shipping: row.shipping,
    customs: row.customs,
    chassisAssembly: scalePhase(row.chassisAssembly, fleetSize, LEAD_TIME_RULES.chassisAssembly),
    bodyBuilder: scalePhase(row.bodyBuilder, fleetSize, LEAD_TIME_RULES.bodyBuilder),
    finalPdi: row.finalPdi,
    delivery: scalePhase(row.delivery, fleetSize, LEAD_TIME_RULES.delivery),
    vehicleRegistration: row.vehicleRegistration,
  };
  const chassisOnlyTotal = Object.values(phases).reduce((a, b) => a + b, 0);

  const payloadBuildApplied = row.payloadBuildFixedIncluded || (row.payloadBuildEligible && !!payloadBuildEnabled);
  const payloadBuildDays = payloadBuildApplied
    ? scalePhase(PAYLOAD_BUILD_BASE_DAYS, fleetSize, LEAD_TIME_RULES.payloadBuild)
    : 0;

  return {
    estimated: false,
    phases,
    payloadBuildEligible: row.payloadBuildEligible,
    payloadBuildFixedIncluded: row.payloadBuildFixedIncluded,
    payloadBuildApplied,
    payloadBuildDays,
    chassisOnlyTotal,
    total: chassisOnlyTotal + payloadBuildDays,
  };
}

/* Modeled-estimate path for anything without a real PMO row -- competitors,
   and any VKTR vehicle (present or future) not yet in LEAD_TIME_VKTR. */
function computeEstimatedLeadTime(veh) {
  const tier = SEGMENT_TIER[veh.segment] || "Tier2";
  const importType = veh.vktr ? "CKD" : (BRAND_IMPORT_TYPE[veh.brand] || "CKD");
  const base = (TIER_BASE_DAYS[tier] && TIER_BASE_DAYS[tier][importType]) || TIER_BASE_DAYS.Tier2.CKD;
  const mult = veh.powertrain === "EV" ? EV_MULTIPLIER : ICE_MULTIPLIER;
  return {
    estimated: true,
    importType,
    tier,
    total: Math.round(base * mult),
  };
}

/* Public entry point. fleetSize/payloadBuildEnabled are ignored on the
   estimated path (no real per-phase/unit-count model exists for it). */
function computeLeadTime(vehId, fleetSize, payloadBuildEnabled) {
  const veh = window.findVeh ? window.findVeh(vehId) : null;
  const row = LEAD_TIME_VKTR[vehId];
  if (row) return { vehId, ...computeVktrLeadTime(row, fleetSize, payloadBuildEnabled) };
  if (!veh) return { vehId, estimated: true, total: null, unknown: true };
  return { vehId, ...computeEstimatedLeadTime(veh) };
}

/* True only for the SKUs that get a user-facing toggle on Screen 2
   (real data + eligible + not fixed-included, e.g. not P174). */
function isPayloadBuildToggleable(vehId) {
  const row = LEAD_TIME_VKTR[vehId];
  return !!(row && row.payloadBuildEligible && !row.payloadBuildFixedIncluded);
}

Object.assign(window, {
  LEAD_TIME_VKTR, LEAD_TIME_RULES, PAYLOAD_BUILD_BASE_DAYS,
  SEGMENT_TIER, TIER_BASE_DAYS, BRAND_IMPORT_TYPE,
  computeLeadTime, isPayloadBuildToggleable,
});

/* Loads data/lead_time.xlsx and overwrites the hardcoded defaults above in
   place, same pattern/reasoning as loadVehiclesReference() in vehicles.jsx
   (res.ok guard before XLSX.read, silent fallback on any failure, skipped
   entirely in the standalone-build path). */
async function loadLeadTimeReference() {
  if (window.__VKTR_XLSX_BAKED__) return;
  try {
    const res = await fetch('data/lead_time.xlsx?v=' + Date.now());
    if (!res.ok) return;
    const buf = await res.arrayBuffer();
    const wb = XLSX.read(buf, { type: 'array' });
    const readSheet = (name) => XLSX.utils.sheet_to_json(wb.Sheets[name]);

    readSheet('VKTR Lead Time').forEach(r => {
      try {
        if (!r.id) return;
        LEAD_TIME_VKTR[r.id] = {
          internalProcess: r.internal_process,
          principalProduction: r.principal_production,
          shipping: r.shipping,
          customs: r.customs,
          chassisAssembly: r.chassis_assembly,
          bodyBuilder: r.body_builder,
          finalPdi: r.final_pdi,
          delivery: r.delivery,
          vehicleRegistration: r.vehicle_registration,
          payloadBuildEligible: !!r.payload_build_eligible,
          payloadBuildFixedIncluded: !!r.payload_build_fixed_included,
        };
      } catch (rowErr) { /* skip this row, continue with the rest of the sheet */ }
    });

    readSheet('Rules').forEach(r => {
      try {
        const keyMap = {
          chassis_assembly: 'chassisAssembly', body_builder: 'bodyBuilder',
          delivery: 'delivery', payload_build: 'payloadBuild',
        };
        const key = keyMap[r.phase];
        if (key && LEAD_TIME_RULES[key]) {
          LEAD_TIME_RULES[key] = { affected: !!r.affected_by_unit_count, threshold: r.threshold, rate: r.rate_per_unit };
        }
      } catch (rowErr) { /* skip this row, continue with the rest of the sheet */ }
    });

    readSheet('Competitor Tiers').forEach(r => {
      try {
        if (!r.segment) return;
        SEGMENT_TIER[r.segment] = r.tier === 'Tier 1' ? 'Tier1' : r.tier === 'Tier 2' ? 'Tier2' : 'Tier3';
        const tierKey = SEGMENT_TIER[r.segment];
        TIER_BASE_DAYS[tierKey] = { CBU: r.cbu_days, IKD: r.ikd_days, CKD: r.ckd_days };
      } catch (rowErr) { /* skip this row, continue with the rest of the sheet */ }
    });

    readSheet('Brand Import Type').forEach(r => {
      try {
        if (!r.brand) return;
        BRAND_IMPORT_TYPE[r.brand] = r.import_type;
      } catch (rowErr) { /* skip this row, continue with the rest of the sheet */ }
    });
  } catch (e) {
    // Keep the hardcoded defaults -- nothing to do.
  }
}
window.loadLeadTimeReference = loadLeadTimeReference;
