<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vehicle Search with NHTSA API</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
   <style>
    body {
        background-color: #f4f7fa;
        color: #2c3e50;
        font-family: 'Segoe UI', Tahoma, sans-serif;
    }

    .search-container {
        max-width: 800px;
        margin: 30px auto;
        padding: 25px;
        border-radius: 10px;
        background-color: #ffffff;
        border: 1px solid #e0e6ed;
        box-shadow: 0 4px 15px rgba(0,0,0,0.08);
    }

    .form-select {
        margin-bottom: 0;
        background-color: #fff;
        color: #2c3e50;
        border: 1px solid #ced4da;
        transition: all 0.2s ease;
    }

    .form-select:focus {
        box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.25);
        border-color: #3498db;
    }

    .form-label {
        color: #34495e;
        margin-bottom: 0.5rem;
        font-weight: 500;
    }

    .loading {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(0,0,0,.1);
        border-radius: 50%;
        border-top-color: #3498db;
        animation: spin 1s ease-in-out infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    .btn-primary {
        background-color: #3498db;
        border-color: #3498db;
        color: #fff;
        transition: background-color 0.2s ease;
    }

    .btn-primary:hover {
        background-color: #2980b9;
        border-color: #2980b9;
    }

    .table-responsive {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        overflow: hidden;
        margin-top: 15px;
    }

    .table {
        background-color: #fff;
        color: #2c3e50;
    }

    .table thead th {
        background-color: #f0f4f8;
        border-bottom: 2px solid #dee2e6;
    }

    .table tbody tr td {
        border-bottom: 1px solid #eee;
    }

    .table-striped > tbody > tr:nth-child(odd) {
        background-color: #f9fbfd;
    }

    .table-striped tbody tr:hover {
        background-color: #eaf3fc;
    }

    /* Flexbox layout for inputs */
    .form-row {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin-bottom: 15px;
    }

    .form-row > div {
        flex: 1;
        min-width: 200px;
    }
</style>

</head>
<body>
    <div class="container search-container">
        <h2 class="text-center mb-4">Vehicle Search with NHTSA Data - HAT INC</h2>
        <form id="vehicleSearchForm">
            <div class="form-row">
                <div class="col-md-3">
                    <label for="vehicleType" class="form-label">Vehicle Type</label>
                    <select class="form-select" id="vehicleType" required>
                        <option value="" selected disabled>Select Vehicle Type</option>
                        <option value="car">Passenger Car</option>
                        <option value="truck">Truck</option>
                        <option value="motorcycle">Motorcycle</option>
                        <option value="agriculture">Agriculture</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="make" class="form-label">Make</label>
                    <select class="form-select" id="make" disabled required>
                        <option value="" selected disabled>Select Make</option>
                    </select>
                    <div id="makeLoading" class="mt-2" style="display: none;">
                        <span class="loading"></span> Loading makes...
                    </div>
                </div>
                <div class="col-md-3">
                    <label for="model" class="form-label">Model</label>
                    <select class="form-select" id="model" disabled required>
                        <option value="" selected>All Models</option>
                    </select>
                    <div id="modelLoading" class="mt-2" style="display: none;">
                        <span class="loading"></span> Loading models...
                    </div>
                </div>
                <div class="col-md-3">
                    <label for="year" class="form-label">Year</label>
                    <select class="form-select" id="year" disabled>
                        <option value="" selected>All Years</option>
                    </select>
                    <div id="yearLoading" class="mt-2" style="display: none;">
                        <span class="loading"></span> Loading years...
                    </div>
                </div>
            </div>
            
            <div class="d-grid">
                <button type="submit" class="btn btn-primary">Search</button>
            </div>
        </form>
        
        <div id="results" class="mt-4" style="display: none;">
            <h4>Search Results</h4>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Make</th>
                            <th>Model</th>
                            <th>Year</th>
                            <th>Vehicle Type</th>
                        </tr>
                    </thead>
                    <tbody id="resultsBody">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
  const vehicleSearchForm = document.getElementById('vehicleSearchForm');
  const vehicleTypeSelect = document.getElementById('vehicleType');
  const makeSelect = document.getElementById('make');
  const modelSelect = document.getElementById('model');
  const yearSelect = document.getElementById('year');
  const resultsDiv = document.getElementById('results');
  const resultsBody = document.getElementById('resultsBody');
  const makeLoadingIndicator = document.getElementById('makeLoading');
  const modelLoadingIndicator = document.getElementById('modelLoading');

  const NHTSA_API_BASE_URL = 'https://vpic.nhtsa.dot.gov/api/vehicles';
  const CAR_IMAGE_API_BASE = 'https://www.carimagery.com/api.asmx/GetImageUrl';

  // helper to fetch JSON from NHTSA
  async function fetchJson(url) {
    const res = await fetch(url);
    if (!res.ok) throw new Error("Network response was not ok");
    const j = await res.json();
    return j.Results || [];
  }

  // helper to fetch image URL from CarImagery
  async function fetchCarImage(make, model, year) {
    // build the search term – CarImagery supports make + model + optionally year
    let term = encodeURIComponent(`${make} ${model}` + (year ? ` ${year}` : ""));
    const url = `${CAR_IMAGE_API_BASE}?searchTerm=${term}`;
    try {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`Image API error: ${res.status}`);
      const text = await res.text();
      // parse XML string like: <string xmlns="…">http://…</string>
      const parser = new DOMParser();
      const xml = parser.parseFromString(text, "application/xml");
      const strNode = xml.getElementsByTagName("string")[0];
      if (strNode && strNode.textContent) {
        return strNode.textContent;
      } else {
        return null;
      }
    } catch (err) {
      console.error("Error fetching car image:", err);
      return null;
    }
  }

  async function populateMakeDropdown(vehicleType) {
    makeSelect.innerHTML = '<option value="">Select Make</option>';
    makeSelect.disabled = true;
    modelSelect.innerHTML = '<option value="">Select Model</option>';
    modelSelect.disabled = true;
    yearSelect.innerHTML = '<option value="">Select Year</option>';
    yearSelect.disabled = true;
    resultsDiv.style.display = 'none';

    if (!vehicleType) return;

    makeLoadingIndicator.style.display = 'block';
    const makes = await fetchJson(
      `${NHTSA_API_BASE_URL}/GetMakesForVehicleType/${vehicleType}?format=json`
    );
    makeLoadingIndicator.style.display = 'none';

    makes.forEach(m => {
      const opt = document.createElement("option");
      opt.value = m.MakeName;
      opt.textContent = m.MakeName;
      makeSelect.appendChild(opt);
    });
    makeSelect.disabled = false;
  }

  async function populateModelDropdown(make) {
    modelSelect.innerHTML = '<option value="">Select Model</option>';
    modelSelect.disabled = true;
    yearSelect.innerHTML = '<option value="">Select Year</option>';
    yearSelect.disabled = true;
    resultsDiv.style.display = 'none';

    if (!make) return;

    modelLoadingIndicator.style.display = 'block';
    const models = await fetchJson(
      `${NHTSA_API_BASE_URL}/GetModelsForMake/${make}?format=json`
    );
    modelLoadingIndicator.style.display = 'none';

    models.forEach(m => {
      const opt = document.createElement("option");
      opt.value = m.Model_Name;
      opt.textContent = m.Model_Name;
      modelSelect.appendChild(opt);
    });
    modelSelect.disabled = false;
  }

  function populateYearDropdown() {
    const currentYear = new Date().getFullYear();
    yearSelect.innerHTML = '<option value="">All Years</option>';
    for (let y = currentYear; y >= 1990; y--) {
      const opt = document.createElement("option");
      opt.value = y;
      opt.textContent = y;
      yearSelect.appendChild(opt);
    }
    yearSelect.disabled = false;
  }

  vehicleTypeSelect.addEventListener("change", e => {
    populateMakeDropdown(e.target.value);
  });

  makeSelect.addEventListener("change", e => {
    populateModelDropdown(e.target.value);
  });

  modelSelect.addEventListener("change", () => {
    populateYearDropdown();
  });

  vehicleSearchForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    const make = makeSelect.value;
    const model = modelSelect.value;
    const year = yearSelect.value;

    if (!make || !model) {
      alert("Please select both make and model.");
      return;
    }

    // call NHTSA for vehicle data
    const vehicles = await fetchJson(
      `${NHTSA_API_BASE_URL}/GetModelsForMakeYear/make/${make}/modelyear/${year}?format=json`
    );

    resultsBody.innerHTML = "";

    for (const v of vehicles) {
      // for each vehicle, also get the image
      const imgUrl = await fetchCarImage(make, model, year);

      const tr = document.createElement("tr");

      tr.innerHTML = `
        <td>${v.Make_Name || make}</td>
        <td>${v.Model_Name || model}</td>
        <td>${year || "—"}</td>
        <td>${v.VehicleTypeName || ""}</td>
        <td>${imgUrl ? `<img src="${imgUrl}" alt="${make} ${model}" width="200" />` : "No image"}</td>
      `;

      resultsBody.appendChild(tr);
    }

    resultsDiv.style.display = vehicles.length > 0 ? "block" : "none";
  });
</script>

</body>
</html>
