document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
    new bootstrap.Tooltip(el);
  });

  function setActiveNavItem(id) {
    const element = document.getElementById(id);
    if (element) {
      element.classList.add("active");
    }
  }

  waitForElement("#main", function () {
    let loggedin = localStorage.getItem("loggedIn");
    const UserId = localStorage.getItem('UserId');
    const adminUserId = 1;

    waitForElement("#loginSubmitServerModal", function () {
      document.getElementById("loginSubmitServerModal").addEventListener("click", function (e) {
        IsAdmin();
      });
    });

    waitForElement("#configurationServerButton", function () {
      document.getElementById("configurationServerButton").addEventListener("click", function (e) {
        if (!document.getElementById("modal-admin")) {
          document.body.insertAdjacentHTML("beforeend", '<div id="modal-admin"></div>');
        }

        const ModalContainer = new Containers("modal-admin");
        ModalContainer.CreateModal();

        const authModalObj = document.getElementById("authModal");
        if (authModalObj) {
          const authModal = new bootstrap.Modal(authModalObj);
          authModal.show();
          if (!(UserId === adminUserId)) {
            addLog("Abriu o Modal de configuração do Servidor", UserId, 1, "OPENED_MODAL_CONFIG_SERVER");
          }
        } else {
          addLog(`Modal não encontrado line ${e.lineNumber}!`, UserId, 0, "ERROR_MODAL_CONFIG_SERVER");
        }
      });
    });

    waitForElement("#signOut", function (element) {
      if (loggedin != null) {
        document.getElementById("signOut").addEventListener("click", function (e) {
          e.preventDefault();
          const formData = new FormData();
          formData.append("id", "logout");

          ajaxRequest("./php/data.php", formData, function (data) {
            if (data.success) {
              localStorage.removeItem("loggedIn");
              localStorage.removeItem("UserId");
              localStorage.removeItem("username");
              localStorage.removeItem("firstname");
              localStorage.removeItem("lastname");
              localStorage.removeItem("language");
              localStorage.removeItem("translations");
              localStorage.setItem("notifyMessage", "Logout bem sucedido");
              localStorage.setItem("notifyType", "success");
              window.location.href = "index.html";
            }
          });
        });
      }
    });

    waitForElement("#configurationUserButton", function () {
      document.getElementById("configurationUserButton").addEventListener("click", function (e) {
        if (!document.getElementById("configUserModal")) {
          let MainContainer = new Containers("main");
          MainContainer.CreateUserModal();
        }
        let configUserModal = new bootstrap.Modal(document.getElementById("configUserModal"));
        configUserModal.show();
        addLog(`Abriu o Modal de configuração do Usuário`, UserId, true, "OPENED_MODAL_CONFIG_CLIENT");
      });
    });

    waitForElement("#sidebarUL", function () {
      const sidebarUL = document.getElementById("sidebarUL");
      if (sidebarUL) {
        waitForElement("#sidebarUL .nav-item a", function () {
            const links = sidebarUL.querySelectorAll(".nav-item a");
            links.forEach(link => {
                link.addEventListener("click", function(e) {
                    links.forEach(l => l.classList.remove("active"));
                    this.classList.add("active");
                    const pagina = this.dataset.pagina;
                    if (pagina) {
                      const container = document.getElementById("navegacao");
                      fetch(pagina)
                        .then(res => res.text())
                        .then(data => {
                          container.innerHTML = data;
                          window.scrollTo(0, 0);
                        })
                        .catch(() => {
                          container.innerHTML = "<p>Erro ao carregar conteúdo.</p>";
                        });
                    }
                });
            });
        });
      }
      
      const formData = new FormData();
      formData.append("id", "getPermissions");
      formData.append("user_id", UserId);

      ajaxRequest("./php/data.php", formData, function (response) {
        if (response.success === true) {
          let sidebar = new Containers("sidebarUL");
          let classBoss = new Containers("classBoss");
          let classManager = new Containers("classManager");
          let classConstruct = new Containers("classConstruct");
          let classRestaurant = new Containers("classRestaurant");
          let classDefinicoes = new Containers("classDefinicoes");
          let classDashboard = new Containers("classDashboard");
          let classWizard = new Containers("classWizard");
          let userMenu = new Containers("settingsButton");
          let classGestao = new Containers("classGestao");

          for (let i = 0; i < response.data.length; i++) {
            let perms = response.data[i];
            let dkey = perms["dkey"];
            switch (dkey) {
              case "boss":
                classBoss.CreateCategoryBoss();
                classDashboard.CreateCategoryDashboard();
                setActiveNavItem("dashboard");
                carregarConteudoNavegacao("./php/dashboard.php", false);
                break;
              case "construct":
                classConstruct.CreateCategoryConstruct();
                break;
              case "restaurant":
                classRestaurant.CreateCategoryRestaurant();
                break;
              case "manager":
                classManager.CreateCategoryManager();
                break;
              case "admin":
                let setCompanyPrincipal = localStorage.getItem("setCompanyPrincipal");
                if (setCompanyPrincipal == null) {
                  userMenu.CreateConfigServerButton();
                } else {
                  classWizard.CreateCategoryWizard();
                }
                break;
              case "user":
                userMenu.CreateConfigUserButton();
                break;
            }
          }
        }
      }, function (xhr, status, error) {
        console.error(error);
        MainContainer.Notify(error, "error", 5000);
      });
    });

    // --- Função carregar conteúdos ---
    function carregarConteudoNavegacao(pagina, append = false) {
      waitForElement("#navegacao", function () {
        const container = document.getElementById("navegacao");

        fetch(pagina)
          .then(response => response.text())
          .then(data => {
            if (append) {
              container.insertAdjacentHTML("beforeend", data);
            } else {
              container.innerHTML = data;
            }
            window.scrollTo(0, 0);
          })
          .catch(() => {
            container.insertAdjacentHTML("beforeend", "<p>Erro ao carregar conteúdo.</p>");
          });
      });
    }
  });
});
