type Option = {
  name: string;
  value: string;
  color: string;
};

let selectorInstanceId = 0;
let openSelector: Selector | null = null;

function showOverlay(selector: Selector) {
  openSelector = selector;
  $("#overlay").removeAttr("hidden");
}

function hideOverlay() {
  openSelector = null;
  $("#overlay").attr("hidden", "");
}

function onOverlayClick() {
  openSelector?.collapse();
  hideOverlay();
}

class Selector {
  private id: string;
  private options: Option[];
  private selectedOption: Option;
  private onChange: (option: Option) => void;
  private onExpand: () => void;
  private tabbable: boolean;
  private mounted = false;

  constructor({
    options,
    onChange,
    onExpand,
    tabbable = true,
  }: {
    options: Option[];
    onChange: (option: Option) => void;
    onExpand: () => void;
    // false takes the trigger button out of the Tab order (still clickable) —
    // for selectors sitting between inputs the user expects to Tab through.
    tabbable?: boolean;
  }) {
    this.id = "selector_" + selectorInstanceId++;
    this.options = options;
    this.selectedOption = options[0];
    this.onChange = onChange;
    this.onExpand = onExpand;
    this.tabbable = tabbable;
  }

  // Safe to call repeatedly (e.g. every time a container gets its innerHTML
  // regenerated): the trigger button is re-rendered and rewired each time,
  // but the dropdown overlay is only ever appended once per instance.
  mount(container: string) {
    $(container).html(this.html());
    $(`#${this.id}_button`).on("click", () => this.toggle());
    if (!this.mounted) {
      $("#overlay").append(this.containerHtml());
      $(`#${this.id}_container`).on("click", (e) => e.stopPropagation());
      for (const option of this.options) {
        $(`#${this.id}_option_${option.value}`).on("click", () => this.pickOption(option));
      }
      this.mounted = true;
    }
    this.setValue(this.selectedOption);
    this.collapse();
  }

  setValue(option: Option) {
    this.selectedOption = option;
    $(`#${this.id}_value`).text(option.name); //.css("color", option.color);
    $(`#${this.id}_inner .checkIcon`).css("opacity", "0");
    $(`#${this.id}_option_${option.value} .checkIcon`).css("opacity", "1");
  }

  pickOption(option: Option) {
    this.setValue(option);
    this.collapse();
    this.onChange(option);
  }

  toggle() {
    const isOpen = ($(`#${this.id}_container`).height() ?? 0) > 0;
    isOpen ? this.collapse() : this.expand();
  }

  expand() {
    if (openSelector && openSelector !== this) openSelector.collapse();
    $(`#${this.id}_container`).css("opacity", "1");
    showOverlay(this);

    const borderWidth = 1;
    let height = ($(`#${this.id}_inner`).outerHeight() ?? 0) + borderWidth * 2;

    const selectedIndex = this.options.findIndex((o) => o.value === this.selectedOption.value);
    let top = -(16 + 16) * selectedIndex;

    const e = document.getElementById(this.id)!;
    const rect = e.getBoundingClientRect();
    const windowHeight = $(window).height() ?? 0;
    const padding = 16;

    let scrollToBottom = false;
    if (-top > rect.top + padding) {
      height -= -top - rect.top + padding;
      top = -rect.top + padding;
      scrollToBottom = true;
    }

    if (rect.top + top + height > windowHeight + padding) {
      height -= rect.top + top + height - windowHeight + padding;
    }

    $(`#${this.id}_container`).css({
      top: rect.top + top + "px",
      left: rect.left + "px",
      width: rect.width + "px",
      height: height + "px",
    });
    $(`#${this.id}_scroll`).css("height", height + "px");
    if (scrollToBottom) {
      const container = document.getElementById(`${this.id}_scroll`)!;
      container.scrollTo({
        top: 1000,
      });
    }
    this.onExpand();
  }

  collapse() {
    $(`#${this.id}_container`).css("height", "0");
    $(`#${this.id}_container`).css("opacity", "0");
    if (openSelector === this) hideOverlay();
  }

  private html() {
    return `
      <div class="selector" id="${this.id}">
        <button id="${this.id}_button" class="selectedOption"${this.tabbable ? "" : ' tabindex="-1"'}>
          <p id="${this.id}_value">${this.selectedOption.name}</p>
          ${chevronDownIcon()}
        </button>
      </div>
    `;
  }

  private containerHtml() {
    let optionsHtml = "";
    for (const option of this.options) {
      optionsHtml += `
        <div id="${this.id}_option_${option.value}" class="option">
          ${checkIcon()}
          <p style="color: ${option.color}; line-height: 1rem">
            ${option.name}
          </p>
        </div>`;
    }

    return `
      <div class="selectorOptions" id="${this.id}_container">
        <div id="${this.id}_scroll" style="overflow-y: scroll">
          <div class="options innerSelectorContainer" id="${this.id}_inner">
            ${optionsHtml}
          </div>
        </div>
      </div>
    `;
  }
}
