/* ============================================================
   Carzello — data layer
   Sayarah-owned + consignment inventory, AutoGrade (0.0–5.0),
   structured condition reports, announcements, run-list metadata.
   ============================================================ */

const PHOTO_CATS = ["Front 3/4", "Rear 3/4", "Driver side", "Passenger side", "Dash", "Front seats", "Rear seats", "Odometer", "Engine bay", "Trunk", "Undercarriage", "Wheels"];

/* AutoGrade → color + label */
function gradeColor(g) {
  if (g >= 4.0) return "var(--g-hi)";
  if (g >= 3.0) return "var(--g-mid)";
  if (g >= 2.0) return "var(--g-lo)";
  return "var(--g-bad)";
}
function gradeLabel(g) {
  if (g >= 4.5) return "Excellent";
  if (g >= 3.5) return "Above average";
  if (g >= 2.5) return "Average";
  if (g >= 1.5) return "Rough";
  return "Poor / Inoperable"; // a grade is a condition, not a title brand
}

/* Recent sold comparables (closed Sayarah auctions) — the basis for the
   market-value estimate. Replaces the old guessed number with real comps. */
const SOLD_HISTORY = []; // superseded by real comps recorded from completed Carzello auctions


function median(nums) {
  if (!nums.length) return 0;
  const s = [...nums].sort((a, b) => a - b);
  const m = Math.floor(s.length / 2);
  return s.length % 2 ? s[m] : Math.round((s[m - 1] + s[m]) / 2);
}
/* comps for a lot: same make+model, weighted toward similar grade/year */
function compsFor(lot) {
  // real comps: completed Carzello auctions (recorded by the engine from the auction server)
  const solds = (typeof Engine !== "undefined" && Engine.getState().soldComps) || [];
  const rows = solds
    .filter(c => c.make === lot.make && c.model === lot.model)
    .map(c => ({ ...c, dest: c.dest || "Carzello", daysAgo: Math.max(0, Math.round((Date.now() - (c.ts || Date.now())) / 86400000)) }));
  rows.sort((a, b) => Math.abs(a.grade - lot.autograde) - Math.abs(b.grade - lot.autograde));
  return rows;
}
function estimateFromComps(lot) {
  const rows = compsFor(lot);
  if (rows.length < 2) return null;
  // grade-adjust each comp toward this lot's grade (~6% of value per grade point)
  const adj = rows.map(c => Math.round(c.final * (1 + (lot.autograde - c.grade) * 0.06)));
  return { value: median(adj), low: Math.min(...adj), high: Math.max(...adj), n: rows.length, comps: rows };
}

/* NAAA-style sale light: red = as-is (≤$3k or salvage), yellow = announcements /
   branded title (limited guarantee), green = ride & drive. Blue (title attached)
   unused in this model — titles are always in hand. */
function saleLight(lot) {
  if (lot.startPrice <= 3000 || lot.title === "Salvage") return { light: "red", label: "As-is", desc: "Sold as-is. Arbitration limited to title, odometer & VIN issues." };
  if (lot.title !== "Clean" || (lot.announcements || []).some(a => !a.ok)) return { light: "yellow", label: "Announced", desc: "Sold with announcements — guarantee limited to what is disclosed." };
  return { light: "green", label: "Ride & drive", desc: "Guaranteed free of undisclosed major defects per the condition report." };
}

/* Destination eligibility — per-country import rules (simplified but real-shaped) */
const DEST_RULES = {
  UAE: { maxAge: 10, banned: ["Salvage", "Flood", "Fire"], restricted: ["Rebuilt", "Hail", "Lemon buyback", "Odometer brand"], note: "Rebuilt/branded require RTA pass test before registration" },
  KSA: { maxAge: 5, banned: ["Salvage", "Rebuilt", "Flood", "Fire", "Hail", "Lemon buyback", "Odometer brand"], restricted: [], note: "SABER/SASO conformity; used imports ≤5 model years; no branded titles" },
  OMN: { maxAge: 7, banned: ["Salvage", "Flood", "Fire"], restricted: ["Rebuilt"], note: "GSO conformity required" },
  QAT: { maxAge: 5, banned: ["Salvage", "Rebuilt", "Flood", "Fire"], restricted: [], note: "GSO conformity; ≤5 model years" },
  UZB: { maxAge: 99, banned: ["Salvage"], restricted: ["Rebuilt", "Flood", "Fire"], note: "Age-tiered customs duty; certification on arrival" },
};
function eligibleFor(lot, code) {
  const r = DEST_RULES[code]; if (!r) return { ok: true };
  const age = new Date().getFullYear() - lot.year;
  if (age > r.maxAge) return { ok: false, reason: `over ${r.maxAge}-year age limit` };
  if (r.banned.includes(lot.title)) return { ok: false, reason: `${lot.title} title prohibited` };
  if (r.restricted.includes(lot.title)) return { ok: true, warn: `${lot.title} title restricted — ${r.note}` };
  return { ok: true };
}

/* Market value ("MMR") signal — compares current price to est. market value */
function marketSignal(highBid, mv) {
  if (!mv) return null;
  const save = mv - highBid;
  const pct = save / mv;
  let label, kind;
  if (pct >= 0.10) { label = "Great buy"; kind = "green"; }
  else if (pct >= 0.02) { label = "Below market"; kind = "green"; }
  else if (pct >= -0.03) { label = "At market"; kind = "amber"; }
  else { label = "Above market"; kind = "red"; }
  return { label, kind, save, pct, mv };
}

/* Relative end times are turned into absolute ms timestamps at boot (engine.jsx). */
const RAW_LISTINGS = []; // real inventory only — added by the team via Admin → Add car (shared to all visitors)


/* Seeded purchase history. Day-offset fields (wonDaysAgo / paidDaysAgo /
   pickedDaysAgo) become absolute timestamps at boot so the payment-due,
   late-fee, gate-pass and storage logic shows real states. */
const SEED_PURCHASES = []; // purchases are created by real auction wins

const SAVED_SEARCHES = []; // users create their own saved searches

const SHIP_DEST = [
  { code: "UAE", label: "🇦🇪 UAE · Jebel Ali", freight: 1180 },
  { code: "KSA", label: "🇸🇦 Saudi Arabia · Dammam", freight: 1290 },
  { code: "OMN", label: "🇴🇲 Oman · Sohar", freight: 1340 },
  { code: "QAT", label: "🇶🇦 Qatar · Hamad Port", freight: 1420 },
  { code: "UZB", label: "🇺🇿 Uzbekistan · Tashkent", freight: 2180 },
];

/* ---- Destination economics: duty/VAT, FX, and est. retail uplift ----
   Simplified rates for the landed-cost calculator + margin estimator. */
const DEST_ECON = {
  UAE: { duty: 0.05, vat: 0.05, cur: "AED", fx: 3.6725, retailFactor: 1.14, city: "Dubai" },
  KSA: { duty: 0.05, vat: 0.15, cur: "SAR", fx: 3.75, retailFactor: 1.17, city: "Riyadh" },
  OMN: { duty: 0.05, vat: 0.05, cur: "OMR", fx: 0.3845, retailFactor: 1.15, city: "Muscat" },
  QAT: { duty: 0.05, vat: 0.00, cur: "QAR", fx: 3.64, retailFactor: 1.13, city: "Doha" },
  UZB: { duty: 0.10, vat: 0.12, cur: "UZS", fx: 12650, retailFactor: 1.26, city: "Tashkent" },
};
function destEcon(code) { return DEST_ECON[code] || DEST_ECON.UAE; }
function fmtLocal(usd, code) {
  const e = destEcon(code);
  const v = usd * e.fx;
  const opts = e.cur === "UZS" ? { maximumFractionDigits: 0 } : { maximumFractionDigits: 0 };
  return e.cur + " " + Number(Math.round(v)).toLocaleString("en-US", opts);
}
const VESSELS = ["MV Al Wasl Express", "MV Gulf Pioneer", "MV Jebel Ali Trader", "MV Indus Star", "MV Khaleej Voyager"];

const MAKES = ["Toyota", "Lexus", "Honda", "Nissan", "Hyundai", "Ford", "Mitsubishi"];
const BODIES = ["Sedan", "SUV", "Pickup"];
const TITLES = ["Clean", "Rebuilt", "Salvage", "Flood", "Fire", "Hail", "Lemon buyback", "Odometer brand"];

/* ---- Fixed buyer fees (disclosed before bid) ---- */
const BUYER_FEE = 345;             // flat buyer fee
const TITLE_INSPECTION_FEE = 170;  // title + inspection (combined)
const TOTAL_BUYER_FEES = BUYER_FEE + TITLE_INSPECTION_FEE; // 515

/* map a destination name/port/code from an uploaded sheet → SHIP_DEST code */
function matchShipCode(name) {
  const n = String(name == null ? "" : name).toLowerCase().trim();
  if (!n) return null;
  if (/uae|u\.a\.e|dubai|jebel|abu\s*dhabi|emirat|sharjah/.test(n)) return "UAE";
  if (/saudi|ksa|dammam|jeddah|riyadh|jubail/.test(n)) return "KSA";
  if (/oman|sohar|muscat|salalah/.test(n)) return "OMN";
  if (/qatar|hamad|doha/.test(n)) return "QAT";
  if (/uzbek|tashkent|\buzb\b/.test(n)) return "UZB";
  const up = n.toUpperCase();
  if (["UAE", "KSA", "OMN", "QAT", "UZB"].includes(up)) return up;
  return null;
}

Object.assign(window, {
  RAW_LISTINGS, SEED_PURCHASES, SAVED_SEARCHES, SHIP_DEST,
  MAKES, BODIES, TITLES, PHOTO_CATS, gradeColor, gradeLabel, marketSignal,
  BUYER_FEE, TITLE_INSPECTION_FEE, TOTAL_BUYER_FEES, matchShipCode,
  SOLD_HISTORY, compsFor, estimateFromComps, median,
  DEST_ECON, destEcon, fmtLocal, VESSELS,
  saleLight, DEST_RULES, eligibleFor,
});
