class FinanceForm {
  constructor(vehicle,appointmentForm, notifyParentCallback) {
    this.notifyParentCallback = notifyParentCallback;
    this.inputs = [
      'loanTerm',
      'intRate',
      'downPayment',
      'tradeValue',
      'paymentFrequency',
      'rate',
      'customRateValue',
    ];
    this.modalDiv = null;
    this.name = 'financeForm';
    this.appointmentForm = appointmentForm;
    this.frequencyMap = {
      12: 'Monthly',
      26: 'Bi-Weekly',
      52: 'Weekly',
    };

    if (!vehicle.advertise_price) {
      vehicle['advertise_price'] = 0;
      this.inputs.push('advertise_price')
    }

    this.vehicle = vehicle;

    // Default values
    this.loanTerm = 12;
    this.intRate = 7.99;
    this.downPayment = 0;
    this.tradeValue = 0;
    this.paymentFrequency = 26;

    // Check if values exist in localStorage, and if so, override default values
    const storedValues =
      JSON.parse(localStorage.getItem(`autocart_${this.name}`)) || {};
    if (storedValues) {
      this.loanTerm = parseInt(storedValues.loanTerm) || this.loanTerm;
      this.intRate = parseFloat(storedValues.customRateValue) || this.intRate;
      this.downPayment = parseInt(storedValues.downPayment) || this.downPayment;
      this.tradeValue = parseInt(storedValues.tradeValue) || this.tradeValue;
      this.paymentFrequency =
        parseInt(storedValues.paymentFrequency) || this.paymentFrequency;
    }

    // Calculate other values based on the provided vehicle and overridden inputs
    let amount = parseFloat(this.vehicle.advertise_price) || 0;
    let months = parseFloat(this.loanTerm) || 0;
    let down = parseFloat(this.downPayment) || 0;
    let trade = parseFloat(this.tradeValue) || 0;
    let totalDown = down + trade;
    let annInterest = parseFloat(this.intRate) || 0;
    let monInt = annInterest / 1200;
    let financeTotal = amount - totalDown;
    let numberOfPayments = months / (12 / this.paymentFrequency);

    // Fix calculation for total cost of credit
    let interest = financeTotal * monInt * numberOfPayments;
    this.totalCostOfCredit = interest.toFixed(2);

    this.totalObligation = (
      financeTotal + parseFloat(this.totalCostOfCredit)
    ).toFixed(2);

    this.payment =
      (
        (monInt + monInt / (Math.pow(1 + monInt, months) - 1)) *
        (amount - (totalDown || 0))
      ).toFixed(2) /
      (this.paymentFrequency / 12);

    // Notify parent callback with the updated values
    this.notifyParentCallback(this);

    // Initialize the form
    this.initForm();
    this.initializeFormInputs();
  }

  generateLoanTermOptions(vehicleAge) {
  const defaultOptions = [
      { year: 2, terms: [12, 24, 36, 48, 60, 72, 84, 96] },
      { year: 5, terms: [12, 24, 36, 48, 60, 72, 84] },
      { year: 7, terms: [12, 24, 36, 48, 60, 72] },
      { year: 8, terms: [12, 24, 36, 48, 60] },
      { year: 10, terms: [12, 24, 36, 48] }
  ];

  const selectedOptions = defaultOptions.find(option => vehicleAge <= option.year);

  if (selectedOptions) {
      const optionsHTML = selectedOptions.terms.map(term => `<option value="${term}">${term} Month Term</option>`).join('\n');
      return optionsHTML;
  } else {
      return '';
  }
}

  generateAdvertisePriceInput(){
    return (this.vehicle.advertise_price == 0) ? `<div>
    <label for="advertise_price" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Vehicle price</label>
      <div class="flex">
        <span class="inline-flex items-center px-3 text-sm text-gray-900 bg-gray-200 border rounded-e-0 border-gray-300 rounded-s-md dark:bg-gray-600 dark:text-gray-400 dark:border-gray-600 rounded-l-lg">
          <i class="fas fa-dollar-sign"></i>
        </span>
        <input type="number" value="25000" id="advertise_price" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-r-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
      </div>
  </div>` : '';
  }

  initForm() {
    // console.log('initForm')
    this.modalDiv = document.createElement('div');
    const currentYear = new Date().getFullYear();
    const vehicleYear = this.vehicle.year || 2024;
    const vehicleAge = currentYear - vehicleYear;
    const loanTermOptions = this.generateLoanTermOptions(vehicleAge);
    const advertise_price = this.generateAdvertisePriceInput()

    // const modalDiv = document.createElement('div');
    this.modalDiv.innerHTML = `
            <div class="bg-white rounded-md grid lg:grid-cols-6 gap-4">
            <div class="lg:col-span-4"> 

            <!-- Tab Navigation -->
            <ul id="tabList" class="grid lg:grid-cols-2 text-sm font-medium text-center text-gray-500 dark:text-gray-400 mb-6 w-full list-none">
                <li class="flex-1">
                    <a href="#" class="tab-link inline-block px-4 py-3 rounded-lg hover:text-gray-900 hover:bg-gray-100 w-full active bg-gray-600 text-white" data-tab="tab1">Personalize Your Options</a>
                </li>
                <li class="flex-1">
                    <a href="#" class="tab-link inline-block px-4 py-3 rounded-lg hover:text-gray-900 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-white w-full" data-tab="tab2">Apply For Financing</a>
                </li>
            
            </ul>
            
            <div id="tab-viewer" class="gap-6">
                
            </div>

            
            <div class="tab-content" data-content="tab1">
                <h4 class="text-xl mb-2 finance-view-only">Let’s Structure a Deal That Works For You</h4>
                <p class="mb-4 finance-view-only">
                    We understand that purchasing a vehicle is a big decision, so we want you to be paying a price that you’re comfortable with. 
                    <strong>Let’s structure a deal that works for you below:</strong>
                </p>

                        <span class="inline-block p-4 bg-gray-200 border rounded-t-lg">
                            <h5 class="text-lg font-bold">Finance Option</h5>
                            <p class="mb-2">
                                <strong class="paymentSpan">${this.payment}</strong> / <span class="paymentFrequencySpan">${this.frequencyMap[this.paymentFrequency]}</span>
                            </p>
                            <p class="text-sm"><span class="rateSpan">${this.intRate}</span>% APR for <span class="loanTermSpan">${this.loanTerm}</span> Months</p>
                        </span>
                    
                    <form class="p-4 md:p-5 bg-gray-200 rounded-r-lg rounded-b-lg">
                            <div class="grid gap-4 mb-4 lg:grid-cols-2">
                                <div>
                                  <label for="downPayment" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Down Payment</label>
                                    <div class="flex">
                                      <span class="inline-flex items-center px-3 text-sm text-gray-900 bg-gray-200 border rounded-e-0 border-gray-300 rounded-s-md dark:bg-gray-600 dark:text-gray-400 dark:border-gray-600 rounded-l-lg">
                                        <i class="fas fa-dollar-sign"></i>
                                      </span>
                                      <input type="number" value="0" id="downPayment" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-r-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
                                    </div>
                                </div>

                                ${advertise_price}
                                
                                <div>
                                <label for="tradeValue" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Vehicle Trade-in</label>
                                    <div class="flex">
                                    <span class="inline-flex items-center px-3 text-sm text-gray-900 bg-gray-200 border rounded-e-0 border-gray-300 rounded-s-md dark:bg-gray-600 dark:text-gray-400 dark:border-gray-600 rounded-l-lg">
                                        <i class="fas fa-dollar-sign"></i>
                                    </span>
                                    <input type="number" id="tradeValue" value="0" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-r-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
                                    </div>
                                </div>
                                <div>
                                    <label for="loanTerm" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Loan Term</label>
                                    <select  name="loanTerm" id="loanTerm" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required="">
                                    ${loanTermOptions}
                                    </select>
                                </div>
                                <div>
                                    <label for="paymentFrequency" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Payment Frequency</label>
                                    <select id="paymentFrequency" name="paymentFrequency" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
                                        <option value="12">Monthly</option>
                                        <option value="26" selected>Bi-Weekly</option>
                                        <option value="52">Weekly</option>
                                    </select>
                                </div>
                                <div class="">
                                    <label for="rate" name="rate" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Program Rates (APR)</label>
                                    <select id="rate" name="rate" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500 xl:w-96">
                                        <option value="default-rate">Financing [Dealer Rate] (7.99%)</option>
                                        <option value="custom-rate">Set Custom Rate</option>
                                    </select>
                                </div>
                                <div class="text-gray-500 ml-2 text-3xl p-5" id="default-rate">
                                    7.99%
                                </div>
                                <div class="hidden" id="custom-rate">
                                    <label for="customRateValue" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Custom Rate</label>
                                    <div class="flex">
                                        <span class="inline-flex items-center px-3 text-sm text-gray-900 bg-gray-200 border rounded-e-0 border-gray-300 rounded-s-md dark:bg-gray-600 dark:text-gray-400 dark:border-gray-600 rounded-l-lg">
                                            <i class="fas fa-percentage"></i>
                                        </span>
                                        <input type="number" id="customRateValue" value="5.99" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-r-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

            <div class="tab-content hidden" data-content="tab2">
                <h4 class="text-xl mb-2 finance-view-only">Let’s Structure a Deal That Works For You</h4>

                <p class="mb-4 finance-view-only">
                    We understand that purchasing a vehicle is a big decision, so we want you to be paying a price that you’re comfortable with.
                    <strong>Let’s structure a deal that works for you below:</strong>
                </p>
                <div id="appointmentFormContainer">
                </div>
                
            </div>
        </div>
        <div class="lg:col-span-2 p-6 bg-gray-200 rounded-md">
            <div class="col ">
                <div class="mb-4">
                    <h4 class="text-lg font-bold">Vehicle Price</h4>
                    <ul class="transmission-container list-none text-gray-900 w-48  text-sm font-medium rounded-lg  w-full">
                        <li class="w-full flex items-center  flex-wrap justify-between items-start flex-row w-full rounded-t-lg  flex items-center justify-between transition duration-400 autocart-filters">
                            <span class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400  font-normal text-base">Vehicle Price</span>
                            <span class="autocart_count advertisePriceSpan text-gray-500 ml-2 transition duration-400 font-normal text-base">
                                ${this.vehicle.advertise_price.toLocaleString('en-CA', { style: 'currency', currency: 'CAD', minimumFractionDigits: 0, maximumFractionDigits: 0 })}
                            </span>
                        </li>
                    </ul>
                </div>
                <hr class="my-4 border-t border-gray-300">
                
                <div class="mb-4">
                    <ul class="transmission-container list-none text-gray-900 w-48  text-sm font-medium rounded-lg  w-full">
                        <li class="w-full flex items-center  flex-wrap justify-between items-start flex-row w-full rounded-t-lg  flex items-center justify-between transition duration-400 autocart-filters">
                            <span class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400  font-normal text-base">Finance Total</span>
                            <span class="autocart_count advertisePriceSpan text-gray-500 ml-2 transition duration-400 font-normal text-base">
                                ${this.vehicle.advertise_price.toLocaleString('en-CA', { style: 'currency', currency: 'CAD', minimumFractionDigits: 0, maximumFractionDigits: 0 })}
                            </span>
                        </li>
                    </ul>
                </div>
                <div class="mb-4">
                    <h4 class="text-lg font-bold">Finance Payment</h4>
                    <ul class="transmission-container list-none text-gray-900 w-48  text-sm font-medium rounded-lg  w-full">
                        <li class="w-full flex items-center  flex-wrap justify-between items-start flex-row w-full rounded-t-lg  flex items-center justify-between transition duration-400 autocart-filters">
                            <span class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400  font-normal text-base">Loan Term</span>
                            <span class="autocart_count text-gray-500 ml-2 transition duration-400 font-normal text-base ">
                                <span class="loanTermSpan">${this.loanTerm} </span> Months
                            </span> 
                        </li>
                        <li class="w-full flex items-center  flex-wrap justify-between items-start flex-row w-full rounded-t-lg  flex items-center justify-between transition duration-400 autocart-filters">
                            <span class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400  font-normal text-base">Program Rate</span>
                            <span class="autocart_count text-gray-500 ml-2 transition duration-400 font-normal text-base">
                                <span class="rateSpan">7.99</span>%
                            </span>
                        </li>
                        <li class="w-full flex items-center  flex-wrap justify-between items-start flex-row w-full rounded-t-lg  flex items-center justify-between transition duration-400 autocart-filters">
                            <span class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400  font-normal text-base">Frequency</span>
                            <span class="autocart_count text-gray-500 ml-2 transition duration-400 font-normal text-base paymentFrequencySpan">
                                ${this.frequencyMap[this.paymentFrequency]}
                            </span>
                        </li>

                    </ul>
                </div>
                <div class="mb-4">
                    <h4 class="text-lg font-bold">Total</h4>
                    <ul class="transmission-container list-none text-gray-900 w-48  text-sm font-medium rounded-lg  w-full">
                        <li class="w-full flex items-center  flex-wrap justify-between items-start flex-row w-full rounded-t-lg  flex items-center justify-between transition duration-400 autocart-filters">
                            <span class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400  font-normal text-base">Total Cost of Credit</span>
                            <span class="autocart_count text-gray-500 ml-2 tran∂sition duration-400 font-normal text-base totalCostOfCreditSpan">
                                ${this.totalCostOfCredit.toLocaleString('en-CA', { style: 'currency', currency: 'CAD', minimumFractionDigits: 0, maximumFractionDigits: 0 })}
                            </span>
                        </li>
                        <li class="w-full flex items-center  flex-wrap justify-between items-start flex-row w-full rounded-t-lg  flex items-center justify-between transition duration-400 autocart-filters">
                            <span class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400  font-normal text-base">Total Obligation</span>
                            <span class="autocart_count text-gray-500 ml-2 transition duration-400 font-normal text-base totalObligationSpan">
                                ${this.totalObligation.toLocaleString('en-CA', { style: 'currency', currency: 'CAD', minimumFractionDigits: 0, maximumFractionDigits: 0 })}
                            </span>
                        </li>
                    </ul>
                </div>
            
                </div>
                <div class="mb-4 items-center flex flex-col">
                    <div class="py-2 inline-block transition duration-300">
                        <p>
                            <span class="paymentSpan">${(Number(this.payment) || 0).toLocaleString('en-CA', { style: 'currency', currency: 'CAD' })}</span>
                            / <span class="paymentFrequencySpan">
                            ${this.frequencyMap[this.paymentFrequency]}
                            </span>
                        </p>
                    </div>
                    <button class="w-full bg-gray-500 hover:bg-gray-800 text-white p-2 rounded-md transition duration-300" id="next-step">Next Step</button>
                </div>
            </div>
        </div>
        </div>
        `;

        const formContainer = this.modalDiv.querySelector(
          '#appointmentFormContainer'
        );
        
        formContainer.appendChild(this.appointmentForm.initForm());
    
        this.initializeTabNavigation(this.modalDiv);
        this.initializeFormEventListeners(this.modalDiv);
        return this.modalDiv;
      }

  // initializeFormInputs() {
  //     const storedValues = JSON.parse(localStorage.getItem(`autocart_${this.name}`)) || {};
  //     // const mergedValues = { ...this.defaultValues, ...storedValues };
  //     console.log(storedValues);
  //     for (const key in storedValues) {
  //     console.log(key);

  //         const inputElement = document.getElementById(key);
  //         if (inputElement) {
  //             inputElement.value = storedValues[key];
  //         }
  //     }
  //     this.updateView()
  // }

  initializeFormInputs() {
    const storedValues = JSON.parse(localStorage.getItem(`autocart_${this.name}`)) || {};
    const selectElements = document.querySelectorAll('select');

    for (const key in storedValues) {
        const inputElement = document.getElementById(key);
        if (inputElement) {
            inputElement.value = storedValues[key];
            if (inputElement.tagName.toLowerCase() === 'select') {
              const optionValues = Array.from(inputElement.options).map(option => option.value);
              const selectedValue = storedValues[key];
              
              if (!optionValues.includes(selectedValue)) {
                  const closestValue = optionValues.reduce((a, b) => Math.abs(b - selectedValue) < Math.abs(a - selectedValue) ? b : a);
                  inputElement.value = closestValue;
              }
          }
          inputElement.dispatchEvent(new Event('input')); 
        }
    }
    this.updateView();
}

  calculatePayments() {
    
    var vehiclePrice = this.vehicle.advertise_price;
    if(this.inputs.includes('advertise_price')){
      vehiclePrice = document.getElementById('advertise_price').value;
    }
    this.loanTerm = document.getElementById('loanTerm').value;
    this.paymentFrequency = document.getElementById('paymentFrequency').value;
    this.intRate = document.getElementById('rate').value == 'default-rate'
        ? 7.99
        : document.getElementById('customRateValue').value;
    this.downPayment = document.getElementById('downPayment').value;
    this.tradeValue = document.getElementById('tradeValue').value;
    var amount = parseFloat(vehiclePrice) || 0,
      months = parseFloat(this.loanTerm) || 0,
      down = parseFloat(this.downPayment) || 0,
      trade = parseFloat(this.tradeValue) || 0,
      totalDown = down + trade,
      annInterest = parseFloat(this.intRate) || 0,
      monInt = annInterest / 1200;
    var financeTotal = amount - totalDown;
    var numberOfPayments = months / (12 / this.paymentFrequency);

    var monthlyPayment =
      (
        (monInt + monInt / (Math.pow(1 + monInt, months) - 1)) *
        (amount - (totalDown || 0))
      ).toFixed(2) /
      (this.paymentFrequency / 12);
    this.totalCostOfCredit = (
      monthlyPayment * numberOfPayments -
      financeTotal
    ).toFixed(2);
    this.totalObligation = (
      parseFloat(this.totalCostOfCredit) + parseFloat(financeTotal)
    ).toFixed(2);
    this.payment =
      (
        (monInt + monInt / (Math.pow(1 + monInt, months) - 1)) *
        (amount - (totalDown || 0))
      ).toFixed(2) /
      (this.paymentFrequency / 12);

    this.updateView();
  }

  updateView() {
    ['default-rate', 'custom-rate'].forEach((el) => {
      document.getElementById(el)?.classList?.add('hidden');
    });
    if(document.getElementById('rate')){
      document.getElementById(document.getElementById('rate').value)
      .classList.remove('hidden');
    }
   

    if (document.querySelectorAll('.loanTermSpan').length) {
      document.querySelectorAll('.loanTermSpan').forEach((el) => {
        el.innerHTML = `${this.loanTerm}`;
      });
    }

    if (document.querySelectorAll('.rateSpan').length) {
      document.querySelectorAll('.rateSpan').forEach((el) => {
        el.innerHTML = `${this.intRate}`;
      });
    }

    if (document.querySelectorAll('.paymentSpan').length) {
      document.querySelectorAll('.paymentSpan').forEach((el) => {
        el.innerHTML = (Number(this.payment) || 0).toLocaleString('en-CA', {
          style: 'currency',
          currency: 'CAD',
        });
      });
    }

    if (document.querySelectorAll('.paymentFrequencySpan').length) {
      document.querySelectorAll('.paymentFrequencySpan').forEach((el) => {
        el.innerHTML = this.frequencyMap[this.paymentFrequency];
      });
    }

    if (document.querySelectorAll('.totalCostOfCreditSpan').length) {
      document.querySelectorAll('.totalCostOfCreditSpan').forEach((el) => {
        el.innerHTML = (Number(this.totalCostOfCredit) || 0).toLocaleString(
          'en-CA',
          { style: 'currency', currency: 'CAD' }
        );
      });
    }

    if (document.querySelectorAll('.advertisePriceSpan').length) {
      document.querySelectorAll('.advertisePriceSpan').forEach((el) => {
        el.innerHTML = (Number(document.getElementById('advertise_price').value) || 0).toLocaleString(
          'en-CA',
          { style: 'currency', currency: 'CAD' }
        );
      });
    }



    if (document.querySelectorAll('.totalObligationSpan').length) {
      document.querySelectorAll('.totalObligationSpan').forEach((el) => {
        el.innerHTML = (Number(this.totalObligation) || 0).toLocaleString(
          'en-CA',
          { style: 'currency', currency: 'CAD' }
        );
      });
    }
  }

  goToNextTab() {
    let tab1 = document.querySelector('[data-tab="tab1"]');
    let tab2 = document.querySelector('[data-tab="tab2"]');
    let backButton = document.getElementById('next-step');

    if (tab1 && tab2 && backButton) {
      if (tab1.classList.contains('active')) {
        // Switch to tab2 and update button text to "Back"
        tab2.click();
        backButton.innerText = 'Back';
      } else if (tab2.classList.contains('active')) {
        // Switch to tab1 and update button text to "Next step"
        tab1.click();
        backButton.innerText = 'Next step';
      }
    }
  }

  initializeTabNavigation(modalDiv) {
    const tabLinks = modalDiv.querySelectorAll('.tab-link');
    const tabContents = modalDiv.querySelectorAll('.tab-content');
    let nextStepButton = modalDiv.querySelector('#next-step');
    if (nextStepButton) {
      nextStepButton.addEventListener('click', this.goToNextTab.bind(this));
    }
    tabLinks.forEach(function (tabLink) {
      tabLink.addEventListener('click', function (event) {
        event.preventDefault();

        tabLinks.forEach(function (link) {
          link.classList.remove('active', 'bg-gray-600', 'text-white');
        });
        tabContents.forEach(function (content) {
          content.classList.add('hidden');
        });

        const targetTab = this.getAttribute('data-tab');
        this.classList.add('active', 'bg-gray-600', 'text-white');

        let backButtonTexts = { tab1: 'Next Step', tab2: 'Back To Options' };
        nextStepButton.innerText = backButtonTexts[targetTab];
        modalDiv
          .querySelector(`.tab-content[data-content="${targetTab}"]`)
          .classList.remove('hidden');
      });
    });
  }

  initializeFormEventListeners(modalDiv) {
   

    this.inputs.forEach((id) => {
      const inputElement = modalDiv.querySelector(`#${id}`);
      if (inputElement) {
        inputElement.addEventListener('input', () => {
          this.calculatePayments();
          this.saveFormValues(); // Save form values whenever an input changes
        });
      }
    });
  }

  saveFormValues() {
  
    const formValues = {};

    this.inputs.forEach((input) => {
      const inputElement = document.getElementById(input);
      if (inputElement) {
        formValues[input] = inputElement.value;
      }
    });

    if (formValues['rate'] == 'default-rate') {
      formValues['customRateValue'] = 7.99;
    }

    localStorage.setItem(`autocart_${this.name}`, JSON.stringify(formValues));
  }
}
