<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>EBG - Dashboard</title>
    <!-- Essential JS -->
    <script>
      const lang = <%- JSON.stringify(language) %>
    </script>
    <script src="<%= domain %>/appjs/i18next.js?<%= curentUnixTime %>"></script>
    <!-- CSS files -->
    <link href="<%= domain %>/dist/css/tabler.min.css?<%= curentUnixTime %>" rel="stylesheet" />
    <link href="<%= domain %>/dist/css/tabler-flags.min.css?<%= curentUnixTime %>" rel="stylesheet" />
  </head>
  <body>
    <script src="/appjs/format.js"></script>
    <div class="page">
      <!-- Navbar -->
      <%- html_content.navbar %>
      <div class="page-wrapper">
        <!-- Page header -->
        <div class="page-header d-print-none">
          <div class="container-xl">
            <div class="row g-2 align-items-center">
              <div class="col">
                <h2 class="page-title" data-translate="Settings.Misc.SettingsName"></h2>
              </div>
            </div>
          </div>
        </div>
        <!-- Page body -->
        <div class="page-body">
          <div class="container-xl">
            <div class="card">
              <!-- Sidebar Toggle Button for Small Screens -->
              <div class="card-body d-md-none">
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
                </button>
              </div>
              <div class="row g-0">
                <div class="col-12 col-md-3 collapse d-md-block border-end" id="sidebar-menu">
                  <div class="card-body">
                    <div class="list-group list-group-transparent">
                      <a href="/profile-dropdown/settings-account" class="list-group-item list-group-item-action d-flex align-items-center" data-translate="Settings.Side.Account"></a>
                      <a href="/profile-dropdown/settings-misc" class="list-group-item list-group-item-action d-flex align-items-center" data-translate="Settings.Side.Misc"></a>
                      <a href="/profile-dropdown/settings-links" class="list-group-item list-group-item-action d-flex align-items-center active" data-translate="Settings.Side.Links"></a>
                      <a href="/profile-dropdown/settings-integrations" class="list-group-item list-group-item-action d-flex align-items-center" data-translate="Settings.Side.Integrations"></a>
                    </div>
                  </div>
                </div>
                <div class="col d-flex flex-column">
                  <div class="card-body">
                    <h2 class="mb-4" data-translate="Settings.Links.LingsHeadline"></h2>
                    <h3 class="card-title" data-translate="Settings.Links.Links"></h3>
                    <div class="row g-3">
                      <div class="col-md-3">
                        <div class="form-label" data-translate="Settings.Links.Platform"></div>
                        <select type="text" class="form-select mb-3" id="SettingsPlatform" onchange="updateInputField()" value="">
                          <% for(const element in linkableapps) { %>
                          <option value="<%= element %>"><%= element %></option>
                          <% } %>
                        </select>
                      </div>
                      <div class="col-md">
                        <div class="form-label" data-translate="Settings.Links.Profile"></div>
                        <input type="text" class="form-control" value="" onchange="handleInputChange(this.id)" id="SettingsProfile" />
                      </div>
                    </div>
                    <p class="text-muted" data-translate="Settings.Links.EditDiscription"></p>
                    <div class="table-responsive">
                      <h3 class="card-title mt-5" data-translate="Settings.Links.CurrentLinks"></h3>
                      <p class="text-muted" data-translate="Settings.Links.CurrentLinksDescription"></p>
                      <table class="table table-vcenter card-table table-striped">
                        <thead>
                          <tr>
                            <th data-translate="Settings.Links.LinksListLable.HeadPlatform"></th>
                            <th data-translate="Settings.Links.LinksListLable.HeadData"></th>
                            <th class="w-1"></th>
                          </tr>
                        </thead>
                        <tbody id="Settings.Links.TableData"></tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <%- html_content.footer %>
      </div>
    </div>
    <!-- Libs JS -->
    <!-- Tabler Core -->
    <script src="<%= domain %>/appjs/permission.js?<%= curentUnixTime %>" defer></script>
    <script src="<%= domain %>/appjs/translate.js?<%= curentUnixTime %>"></script>
    <script src="<%= domain %>/dist/js/tabler.min.js?<%= curentUnixTime %>" defer></script>
    <script src="<%= domain %>/appjs/layout.js?<%= curentUnixTime %>"></script>
    <script>
      let linkableapps = {};

      document.addEventListener("DOMContentLoaded", async () => {
        // Pupulate the LinkTable
        await loadTable();
      });

      const updateInputField = () => {
        document.getElementById("SettingsProfile").value = linkableapps[document.getElementById("SettingsPlatform").value] ?? "";
      };

      const loadTable = async () => {
        const response = await fetch("/api/v1/user/links", {
          method: "GET",
          headers: {
            "Content-Type": "application/json",

            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        });

        if (response.ok) {
          const { links } = await response.json();

          const tableData = document.getElementById("Settings.Links.TableData");

          // Clear the table
          tableData.innerHTML = "";
          linkableapps = {};

          for (const element of links) {
            linkableapps[element.platform] = element.data_val;
            // Set current value to the input field
            if (document.getElementById("SettingsPlatform").value === element.platform) {
              document.getElementById("SettingsProfile").value = element.data_val;
            }

            const row = document.createElement("tr");

            const platform = document.createElement("td");
            platform.innerText = element.platform;

            const data = document.createElement("td");
            data.innerText = element.data_val;

            const deleteButton = document.createElement("td");
            const deleteButtonSVG = document.createElement("svg");
            deleteButton.innerHTML = `<a class="icon" onclick="deleteLink('${element.platform}')"><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-trash" width="24" height="24" viewBox="0 0 24 24" stroke-width="2"
              stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path
              d="M4 7l16 0" /><path d="M10 11l0 6" /><path d="M14 11l0 6" /><path
              d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12" /><path
              d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3" /></svg></a>`;

            row.appendChild(platform);
            row.appendChild(data);
            row.appendChild(deleteButton);
            tableData.appendChild(row);
          }
        }
      };

      const deleteLink = async (platform) => {
        const response = await fetch(`/api/v1/user/links/${platform}`, {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",

            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        });

        if (response.ok) {
          await loadTable();
        }
      };

      // Handle changes to all imput fields (VanillaJS)
      const handleInputChange = async () => {
        const inputElement = document.getElementById("SettingsProfile");
        const response = await fetch("/api/v1/user/links", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
          body: JSON.stringify({
            value: document.getElementById("SettingsProfile").value,
            platform: document.getElementById("SettingsPlatform").value,
          }),
        });

        if (response.ok) {
          inputElement.classList.remove("is-invalid");
          inputElement.classList.add("is-valid");

          await loadTable();

          setTimeout(() => {
            inputElement.classList.remove("is-valid");
          }, 3000);
        } else {
          inputElement.classList.add("is-invalid");
        }
      };
    </script>
  </body>
</html>
