$(document).ready(function () {
  'use strict';

  // Add pet dropdown to options menu
  if (window.Options && Options.get_tab('general') && window.jQuery) {
    Options.extend_tab('general', `
      <label id="pet-selector">
        <select id="petDropdown">
          <option value="off">OFF</option>
          <option value="pet">Default Pet</option>
          <option value="alice">Alice</option>
          <option value="bob">Bob</option>
        </select> 
        Select your virtual pet
      </label>
    `);

    // Load the saved pet choice from localStorage
    const savedPet = localStorage.getItem('selectedPet') || 'off';
    $('#petDropdown').val(savedPet);

    // Listen for changes in the dropdown and update the selected pet
    $('#petDropdown').on('change', function () {
      const selectedPet = $(this).val();
      localStorage.setItem('selectedPet', selectedPet);
      loadPet(selectedPet);
    });

    // Load the selected pet when the page loads
    loadPet(savedPet);
  }

  // Function to load the selected pet
  function loadPet(petChoice) {
    // Remove any existing pet container
    $('#pet-container').remove();

    // If "OFF" is selected, do nothing
    if (petChoice === 'off') {
      return;
    }

    // Create a container for the pet in the bottom-right corner
    const petContainer = document.createElement('div');
    petContainer.id = 'pet-container';
    document.body.appendChild(petContainer);

    // Dynamically load the correct pet script based on the choice
    const petScript = document.createElement('script');
    petScript.src = `/static/pets/${petChoice}.js`; // Make sure your pet scripts are in this directory
    document.body.appendChild(petScript);

    // Handle any additional setup after loading the pet script
    petScript.onload = function() {
      petContainer.innerHTML = '<div id="pet"></div>';
    };
  }
});