import { Controller } from "stimulus";

export default class extends Controller {
  static targets = ["source", "select"];
  static values = { options: Array };

  handleSelectChange() {
    this.populateSelect(parseInt(this.sourceTarget.value));
  }

  populateSelect(sourceId) {
    this.removeCurrentOptions()

    this.dependantOptionsFor(sourceId).forEach((item) => {
      this.addOption(item[0], item[1])
    });
  }

  removeCurrentOptions() {
    this.selectTarget.innerHTML = ""
  }

  addOption(label, value) {
    const newOption = document.createElement("option")
    newOption.innerHTML = label
    newOption.value = value
    this.selectTarget.appendChild(newOption)
  }

  dependantOptionsFor(sourceId) {
    return this.optionsValue.find((option) => option[0] === sourceId)[1]
  }
}

@@ -245,16 +245,30 @@
 );%0A  %7D%0A%0A
+  // private%0A%0A
   popula
@@ -320,20 +320,270 @@
 tions()%0A
-%0A
    
+ this.populateNewOptions(sourceId)%0A  %7D%0A%0A  removeCurrentOptions() %7B%0A    this.selectTarget.innerHTML = %22%22%0A%0A    this.selectTarget.tomselect?.clear()%0A    this.selectTarget.tomselect?.clearOptions()%0A  %7D%0A%0A  populateNewOptions(sourceId) %7B%0A    const options =
  this.de
@@ -609,16 +609,29 @@
 ourceId)
+%0A%0A    options
 .forEach
@@ -694,76 +694,106 @@
 %7D);%0A
+%0A
   
-%7D%0A%0A  removeCurrentOptions() %7B%0A    this.selectTarget.innerHTML = %22%22
+  this.selectTarget.tomselect?.sync()%0A    this.selectTarget.tomselect?.addItem(options%5B0%5D?.%5B1%5D)
 %0A  %7D

Refactor dependant-selector further and (conditionally) update TomSelect if present