<h2><%=t(:field_vehicle)%> #<%=@vehicle.id%></h2>

<% unless @vehicle.vin_decoded? %>
  <div id="vin-status" class="flash <%= @vehicle.error ? "error" : "notice" %>">
    <% if @vehicle.error%>
      <%= @vehicle.error %>
    <% else %>
      <%= t :notice_decoding_vin %>
    <% end %>
  </div>
<% end %>

<%= render partial: 'vehicles/details', locals: {vehicle: @vehicle} %>

<div class="splitcontent">
    <div class="splitcontentleft">
        <h4><%=t(:estimates)%>:</h4>
        <%= render partial: 'estimates/list', locals: {estimates: @vehicle.estimates} %>
    </div>

    <div class="splitcontentleft">
        <h4><%=t(:label_invoices)%>:</h4>
        <%= render partial: 'invoices/list', locals: {invoices: @vehicle.invoices} %>
    </div>
</div>

<h3><%=@open_issues.count%> <%=t(:label_open_issues)%></h3>

<%= render partial: 'issues/list_simple', locals: {issues: @open_issues} %>

<h3><%=@closed_issues.count%> <%=t(:label_closed_issues)%></h3>

<%= render partial: 'issues/list_simple', locals: {issues: (@closed_issues)} %>

<script>
  (function() {
    const vehicleId = <%= @vehicle.id %>;
    const alreadyDecoded = <%= @vehicle.vin_decoded? ? 'true' : 'false' %>;

    if (alreadyDecoded) return;

    const interval = 3000;
    let attempts = 0;
    const maxAttempts = 40;

    const statusEl = document.getElementById("vin-status");

    const checkStatus = () => {
      fetch(`/vehicles/${vehicleId}/status`, {
        headers: { 'Accept': 'application/json' }
      })
        .then(res => res.json())
        .then(data => {

          // SUCCESS → reload
          if (data.decoded) {
            window.location.reload();
            return;
          }

          // ERROR → stop + show message
          if (data.error) {
            clearInterval(timer);

            if (statusEl) {
              statusEl.classList.remove("notice");
              statusEl.classList.add("error");
              statusEl.textContent = data.error;
            }

            console.warn("VIN decode failed:", data.error);
            return;
          }

          // continue polling
          attempts++;
          if (attempts >= maxAttempts) {
            clearInterval(timer);

            if (statusEl) {
              statusEl.classList.remove("notice");
              statusEl.classList.add("warning");
              statusEl.textContent = "VIN decode timed out. Please refresh or try again.";
            }

            console.warn("VIN decode polling timed out");
          }
        })
        .catch(err => {
          clearInterval(timer);

          if (statusEl) {
            statusEl.classList.remove("notice");
            statusEl.classList.add("error");
            statusEl.textContent = "Error checking VIN status.";
          }

          console.error("Polling error:", err);
        });
    };

    const timer = setInterval(checkStatus, interval);
  })();
</script>