let initialized = {
  hardware: false,
  doors: false,
  schedule: false,
  access: false,
  qr_code: false,
  settings: false,
  streets: false,
};

$(document).ready(function () {
  get_or_update_recent_tab({ get_active_property_tab: true });
});

async function RedirectToActiveTab(active) {
  get_or_update_recent_tab({
    set_active_property_tab: true,
    active_tab: active,
  });

  try {
    if (active == 1) {
      initializeContent(
        "include/property_builder/doors/doors.php",
        "doors",
        "Doors-content"
      );
    } else if (active == 2) {
      initializeContent(
        "/include/property_builder/hardwares/hardwares.php",
        "hardware",
        "Hardware-content"
      );
    } else if (active == 3) {
      initializeContent("shared/coming_soon.php", "access", "access");
    } else if (active == 4) {
      initializeContent(
        "include/property_builder/schedule/schedule.php",
        "schedule",
        "schedules-content"
      );
    } else if (active == 6) {
      initializeContent(
        "/include/property_builder/qr_code/qr_code.php",
        "qr_code",
        "qr_code_content"
      );
    } else if (active == 7) {
      initializeContent(
        "/include/property_builder/property_settings/property_settings.php",
        "settings",
        "settings_content"
      );
    } else if (active == 8) {
      initializeContent(
        "/include/property_builder/streets/streets.php",
        "streets",
        "streets_content"
      );
    }
  } catch (error) {}
}

async function initializeContent(url, screen, content_tag) {
  if (!initialized[screen]) {
    $.ajax({
      url,
      success: function (data) {
        $(`#${content_tag}`).html(data);
        initialized[screen] = true;
      },
    });
  }
}

function get_or_update_recent_tab(data) {
  $.ajax({
    url: "/include/property_builder/property_settings/property_settings_request.php",
    method: "POST",
    data,
    success: function (resp) {
      if (data?.get_active_property_tab && resp?.active_tab) {
        RedirectToActiveTab(Number(resp?.active_tab));
      } else if (data?.get_active_property_tab) {
        RedirectToActiveTab(1);
      }
    },
    error: function () {
      $("#display-div").html("<p>Error loading page. Please refresh the page.</p>"); // Show an error message on failure
    },
  });
}
