// ─────────────────────────────────────────────────────────────────────
// ADD VEHICLE — reference data for guided entry.
//
// Canonical manufacturers + known models drive the autocomplete so the
// archive stays normalized (no free-typed "Porshe" / "Porche"). Both lists
// are curated collector-marque data, not derived from the live collection —
// they are the vocabulary a new vehicle is identified against.
//
// VEHICLE IDENTIFIER is modelled as an extensible type registry. Each entry
// declares how the identifier is captured and how it is displayed elsewhere
// in the platform. Adding a future type (e.g. "Registration Number") is a
// single row here — nothing downstream changes.
// ─────────────────────────────────────────────────────────────────────

// Canonical manufacturers. `code` = 1–2 letter marque monogram used in the
// lightweight suggestion thumbnails (mirrors the receipt allocator).
const AV_MAKES = [
  { name: 'Alfa Romeo', code: 'AR' },
  { name: 'Aston Martin', code: 'A' },
  { name: 'Bentley', code: 'B' },
  { name: 'BMW', code: 'BM' },
  { name: 'Bugatti', code: 'BG' },
  { name: 'Chevrolet', code: 'C' },
  { name: 'Dodge', code: 'D' },
  { name: 'Ferrari', code: 'F' },
  { name: 'Ford', code: 'FD' },
  { name: 'Jaguar', code: 'J' },
  { name: 'Lamborghini', code: 'LB' },
  { name: 'Lancia', code: 'L' },
  { name: 'Lotus', code: 'LO' },
  { name: 'Maserati', code: 'MA' },
  { name: 'Mercedes-Benz', code: 'M' },
  { name: 'Porsche', code: 'P' },
  { name: 'Rolls-Royce', code: 'RR' },
  { name: 'Shelby', code: 'S' },
  { name: 'Datsun', code: 'DA' },
  { name: 'Toyota', code: 'TY' },
];

const AV_MAKE_CODE = {};
AV_MAKES.forEach(m => { AV_MAKE_CODE[m.name] = m.code; });

// Known models per marque. Enough to feel real; free entry is always allowed
// for anything not listed (coachbuilt one-offs, obscure variants).
const AV_MODELS = {
  'Porsche': ['356 Speedster', '356B Coupe', '550 Spyder', '911 2.0 SWB', '911S 2.4', '911 Carrera RS 2.7', '911 Carrera 3.0', '930 Turbo 3.3', '911 SC', '911 Carrera 3.2', '959', '964 Carrera RS', '993 Carrera RS', '993 Turbo S', 'Carrera GT', '918 Spyder'],
  'Ferrari': ['166 MM Barchetta', '250 GT SWB', '250 GT Lusso', '250 GTO', '275 GTB/4', '365 GTB/4 Daytona', 'Dino 246 GT', '365 GT4 BB', '308 GTB', '288 GTO', 'F40', 'F50', '550 Maranello', 'Enzo', 'LaFerrari'],
  'Mercedes-Benz': ['540K Special Roadster', '300SL Gullwing', '300SL Roadster', '280SL Pagoda', '280SE 3.5 Cabriolet', '600 Pullman', '450SEL 6.9', '190E 2.5-16 Evo II', '500E'],
  'Jaguar': ['XK120', 'C-Type', 'D-Type', 'XKSS', 'E-Type Series 1', 'E-Type Series 2', 'Mk2 3.8', 'XJ13'],
  'Aston Martin': ['DB4', 'DB4 GT Zagato', 'DB5', 'DB6 Vantage', 'V8 Vantage', 'DB4 GT'],
  'Alfa Romeo': ['8C 2900B', 'Giulietta Sprint Veloce', 'Giulia TZ', '33 Stradale', 'Montreal'],
  'Lamborghini': ['Miura SV', 'Countach LP400', 'Espada', 'Diablo', 'Murciélago'],
  'Maserati': ['A6GCS Berlinetta', 'Ghibli SS', 'Bora', 'Merak'],
  'Lancia': ['Aurelia B24 Spider', 'Stratos HF Stradale', 'Delta Integrale'],
  'Lotus': ['Elan S1', 'Esprit S1', 'Seven S2', 'Elite'],
  'Shelby': ['Cobra 289', 'Cobra 427', 'GT350', 'GT500'],
  'Ford': ['GT40 Mk I', 'GT40 Mk II', 'Mustang Boss 302', 'GT'],
  'Chevrolet': ['Corvette Sting Ray', 'Corvette L88', 'Camaro Z/28', 'Bel Air'],
  'BMW': ['507', '3.0 CSL Batmobile', 'M1', '2002 Turbo', '328'],
  'Bentley': ['Continental R-Type', 'Blower 4½ Litre', 'Speed Six'],
  'Rolls-Royce': ['Silver Cloud III', 'Silver Ghost', 'Phantom II'],
  'Bugatti': ['Type 35', 'Type 57 Atlantic', 'EB110 SS'],
  'Toyota': ['2000GT', 'Supra A80'],
  'Datsun': ['240Z', 'Fairlady 2000'],
  'Dodge': ['Charger R/T 426 Hemi', 'Challenger R/T', 'Viper'],
};

// Case-insensitive prefix-weighted match against the canonical make list.
function searchMakes(q) {
  const t = (q || '').trim().toLowerCase();
  if (!t) return [];
  const starts = [], contains = [];
  AV_MAKES.forEach(m => {
    const n = m.name.toLowerCase();
    if (n.startsWith(t)) starts.push(m);
    else if (n.includes(t)) contains.push(m);
  });
  return [...starts, ...contains];
}

// Known models for a make, filtered by query. Returns [] when the make is
// unknown/unset — the field still accepts free entry in that case.
function searchModels(make, q) {
  const list = AV_MODELS[make] || [];
  const t = (q || '').trim().toLowerCase();
  if (!t) return list.slice(0, 8);
  const starts = [], contains = [];
  list.forEach(m => {
    const n = m.toLowerCase();
    if (n.startsWith(t)) starts.push(m);
    else if (n.includes(t)) contains.push(m);
  });
  return [...starts, ...contains];
}

// ─────────────────────────────────────────────────────────────────────
// VEHICLE IDENTIFIER — extensible type registry.
//   id        stable key stored on the record
//   label     onboarding option label (Title Case)
//   display   short label shown THROUGHOUT the product (VIN / Chassis / …)
//   full      one-line description under the option
//   holder    true = an actual number is captured; false = deferred
//   placeholder / hint for the value field
// ─────────────────────────────────────────────────────────────────────
const AV_IDENTIFIER_TYPES = [
  { id: 'vin',     label: 'VIN',            display: 'VIN',     full: 'Vehicle Identification Number — modern standardized format', holder: true, placeholder: '9113600542' },
  { id: 'chassis', label: 'Chassis Number', display: 'Chassis', full: 'Frame or chassis plate — common on pre-VIN vehicles',        holder: true, placeholder: '2735 GT' },
  { id: 'engine',  label: 'Engine Number',  display: 'Engine',  full: 'Stamped engine or block number',                            holder: true, placeholder: '30 A 105' },
  { id: 'body',    label: 'Body Number',    display: 'Body',    full: 'Coachbuilder or body plate number',                         holder: true, placeholder: 'B-467' },
  { id: 'later',   label: "I'll Add It Later", display: '',      full: 'Create the vehicle now — add the identifier from its record', holder: false, placeholder: '' },
];

const AV_IDENTIFIER_BY_ID = {};
AV_IDENTIFIER_TYPES.forEach(t => { AV_IDENTIFIER_BY_ID[t.id] = t; });

// Mask all but the last four characters. "9113600542" → "••••0542".
function maskIdentifier(value) {
  const v = (value || '').replace(/\s+/g, '');
  if (!v) return '';
  const tail = v.slice(-4).toUpperCase();
  return '••••' + tail;
}

// The canonical way to render a vehicle's primary identifier ANYWHERE in the
// product: "Chassis ••••8475". Never shows the neutral "Vehicle Identifier"
// label — always the actual stored type. Returns null when none is set.
function identifierLabel(vehicle) {
  if (!vehicle) return null;
  const id = vehicle.identifier;
  // Back-compat: legacy records carry a bare `vin` string.
  if (!id) return vehicle.vin ? { display: 'VIN', masked: maskIdentifier(vehicle.vin) } : null;
  if (!id.value) return null;
  const type = AV_IDENTIFIER_BY_ID[id.type];
  const display = (type && type.display) || 'ID';
  return { display, masked: maskIdentifier(id.value) };
}

Object.assign(window, {
  AV_MAKES, AV_MAKE_CODE, AV_MODELS, searchMakes, searchModels,
  AV_IDENTIFIER_TYPES, AV_IDENTIFIER_BY_ID, maskIdentifier, identifierLabel,
});
