class vhstands {
  constructor() {
    this.exhibitions = [];
    this.categories = new Set();
    this.uniquePageIds = new Set();
    this.sceneNameToPageId = new Map();
    this.currentFilter = null;
    this.buttonActive = false;
  }
  setFilter(filter) {
    this.currentFilter = filter;
    this.showStands();
  }
  resetFilter() {
    this.currentFilter = null;
    this.showStands();
  }
  hasStands() {
    return this.exhibitions.length > 0;
  }
  onUserLogin() {
    this.loadExhibitions(vhapp.scenes);
  }
  toggleButtonState() {
    this.buttonActive = !this.buttonActive;
    this.showStands(); // Refresh the display to reflect the new state
  }
  renderButton() {
    const buttonLabel = this.buttonActive ? "Hide Filters" : "Show Filters";
    const buttonClass = this.buttonActive ? "btn active" : "btn";
    return `
      <div class="${buttonClass}" onclick="standsInstance.toggleButtonState()">
          ${buttonLabel}
      </div>
  `;
  }
  initHtml() {
    let filterContent = `<select class='stands-filter' onchange='standsInstance.setFilter(this.value)'>`;
    filterContent += `<option value='all'>All</option>`;
    this.categories.forEach(category => {
      filterContent += `<option value='${category}'>${category}</option>`;
    });
    filterContent += `</select>`;
    // Append or update the existing HTML structure with this filterContent
  }
  async initMenuContent() {
    await fetch(vhapp.getApiUrl(`/menubaritems?hiveid=${vhapp.getHiveID()}&language=${vhTrans?.langCodes[0]}`), {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${vhapp.session.getLoginToken()}`
      }
    }).then(res => res.json()).then(res => {
      this.menuItems = res;
    });
    let exhibitionHallsData;
    Object.keys(vhapp.scenes).map((key, index) => {
      if (vhapp.scenes[key].name === "All") {
        exhibitionHallsData = vhapp.scenes[key].code;
      }
    });
  }
  showStands() {
    let activeSceneId = vhapp.getActiveSceneName();
    if ($(".stands-layer").length > 0) {
      $(".stands-layer").remove();
    } else {
      let filterContent = `<select class='stands-filter'>
                             <option class='stands-options' value='all'>${vhTrans.tr("ALL_EXHIBITIONS_HALLS")}</option>`;
      this.sceneNameToPageId.forEach((pageId, sceneName) => {
        filterContent += `<option value='${pageId}' ${activeSceneId === pageId ? "selected" : ""}>${sceneName}</option>`;
      });
      filterContent += `</select>`;

      // Determine initial filter content
      let initialFilter = this.getSceneNameForPageId(activeSceneId) || "all";
      let standsContent = this.constructStandsContent(initialFilter);
      let content = `
            <div class='stands-layer'>
              <div class='stands-header'>
                <div class='stands-close'>X</div>
                ${filterContent}
              </div>
              <div class='stands-content'>
                ${standsContent}
              </div>
            </div>`;
      $(".scenestatic").append(content);
      $(".stands-close").on("click", () => $(".stands-layer").remove());
      $(".stands-filter").on("change", this.handleFilterChange.bind(this));

      // Apply filter based on initial selection if not 'all'
      if (initialFilter !== "all") {
        this.filterByPresentOnPageIds(initialFilter);
      }
    }
  }

  // Helper method to get scene name for a given page ID
  getSceneNameForPageId(pageId) {
    for (let [sceneName, id] of this.sceneNameToPageId) {
      if (id === pageId) {
        return sceneName;
      }
    }
    return null;
  }
  static handleStandItemClick(code) {
    vhapp.goToScene(code, false);
    $(".stands-layer").remove();
  }
  handleFilterChange() {
    const selectedFilter = $(".stands-filter").val();
    if (selectedFilter === "all") {
      this.showFilteredStands(this.exhibitions);
    } else {
      // Get the corresponding scene name for the selected filter
      let selectedSceneName = this.getSceneNameForPageId(selectedFilter);
      if (selectedSceneName) {
        this.filterByPresentOnPageIds(selectedSceneName);
      }
    }
  }
  constructStandsContent(filter) {
    let filteredExhibitions = filter === "all" ? this.exhibitions : this.exhibitions.filter(exhibition => exhibition.category.includes(filter));
    return filteredExhibitions.map(exhibition => {
      let logoUrl = exhibition.logo ? vhapp.parseUrl(exhibition.logo) : "/img/logoplaceholder.png";
      // Join multiple scene names IF there is any
      let sceneNameStr = exhibition.sceneNames.join(", ");
      return `<div class='stand-item' onclick='vhstands.handleStandItemClick("${exhibition.code}")'>
        <img class='stand-item-img' src='${logoUrl}' alt='${exhibition.name}' />
        <div class='stand-info'>
            <div>
                <p class='stand-item-title'>${exhibition.name}</p>
                <p class='stand-item-description'>${exhibition.description || ''}</p>
            </div>
            <p class='stand-scene-name'>${sceneNameStr}</p>
        </div>  
    </div>`;
    }).join("");
  }
  loadExhibitions(scenes) {
    let filter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.currentFilter;
    this.exhibitions = [];
    this.uniquePageIds.clear();
    this.sceneNameToPageId.clear();
    for (var prop in scenes) {
      let scene = scenes[prop];
      if (scene.getMetadataString("type") === "ExhibitionStand" && scene.data && scene.data.presentOnPageIds) {
        const presentIds = scene.data.presentOnPageIds.split(";").filter(id => id.trim() !== "");
        presentIds.forEach(id => {
          if (scenes[id] && scenes[id].name) {
            this.uniquePageIds.add(id);
            this.sceneNameToPageId.set(scenes[id].name, id);
          }
        });
        if ((!filter || scene.data.keywords.includes(filter)) && this.isFilterMatch(scene)) {
          let sceneNames = presentIds.map(id => scenes[id] ? scenes[id].name : null).filter(name => name);
          let exhibition = {
            code: prop,
            name: vhtr(scene.name),
            description: scene.data.description,
            logo: scene.getMetadataString("logo"),
            standtype: scene.getMetadataString("standtype"),
            category: scene.data.keywords,
            presentOnPageIds: scene.data.presentOnPageIds,
            sceneNames: sceneNames
          };
          this.exhibitions.push(exhibition);
        }
      }
    }
  }
  isFilterMatch(scene) {
    if (!this.currentFilter) return true;
    return scene.data.keywords.includes(this.currentFilter) || scene.name.includes(this.currentFilter);
  }

  // This will apply the new filter(half baked code :-)... )
  filterByPresentOnPageIds(sceneName) {
    // Retrieve the corresponding pageId for the selected scene name
    const pageId = this.sceneNameToPageId.get(sceneName);
    if (!pageId) {
      return;
    }
    const filteredExhibitions = this.exhibitions.filter(exhibition => {
      const presentIds = exhibition.presentOnPageIds.split(";").map(id => id.trim());
      return presentIds.includes(pageId);
    });
    this.showFilteredStands(filteredExhibitions);
  }
  showFilteredStands(filteredExhibitions) {
    // Construct the stands content with filtered exhibitions applied
    let standsContent = filteredExhibitions.map(exhibition => {
      let logoUrl = exhibition.logo ? vhapp.parseUrl(exhibition.logo) : "/img/logoplaceholder.png";
      let sceneNameStr = exhibition.sceneNames.join(", ");
      return `<div class='stand-item' onclick='vhstands.handleStandItemClick("${exhibition.code}")'>
        <img class='stand-item-img' src='${logoUrl}' alt='${exhibition.name}' />
        <div class='stand-info'>
            <div>
                <p class='stand-item-title'>${exhibition.name}</p>
                <p class='stand-item-description'>${exhibition.description || ''}</p>
            </div>
            <p class='stand-scene-name'>${sceneNameStr}</p>
        </div>  
    </div>`;
    }).join("");
    $(".stands-content").html(standsContent);
  }
  onVHReady() {}
}