body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #121212;
      color: #fff;
      display: flex;
    }

    .sidebar {
      width: 250px;
      background: #1c1c1c;
      padding: 20px;
      height: 100vh;
      box-shadow: 2px 0 5px rgba(0, 0, 0, 0.2);
    }

    .sidebar h2 {
      color: #fff;
      text-align: center;
      margin-bottom: 20px;
    }

    .sidebar form {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .sidebar input {
      padding: 10px;
      font-size: 14px;
      border: 1px solid #444;
      border-radius: 5px;
      background-color: #333;
      color: #fff;
    }

    .sidebar button {
      padding: 10px;
      font-size: 14px;
      background-color: #e74c3c;
      border: none;
      border-radius: 5px;
      color: #fff;
      cursor: pointer;
    }

    .sidebar button:hover {
      background-color: #c0392b;
    }

    .accounts-list {
      margin-top: 20px;
      z-index: 2;
    }

    .accounts-list h3 {
      color: #fff;
      margin-bottom: 10px;
    }

    .accounts-list ul {
      list-style: none;
      padding: 0;
    }

    .accounts-list li {
      padding: 10px;
      background: #333;
      margin-bottom: 5px;
      border-radius: 5px;
      cursor: pointer;
      transition: background 0.3s;
      display: flex; /* Enable flex layout for list items */
      align-items: center; /* Vertically align items in list */
      justify-content: space-between; /* Distribute space between items */
    }

    .accounts-list li:hover {
      background: #444;
    }

    .accounts-list li.active {
      background: #e74c3c;
      font-weight: bold;
    }

    .main-content {
      flex: 1;
      padding: 20px;
    }

    h1 {
      text-align: center;
      color: #fff;
      margin-top: 20px;
    }

    .tabs {
      display: flex;
      margin-bottom: 20px;
      border-bottom: 2px solid #444;
    }

    .tab {
      padding: 10px 20px;
      cursor: pointer;
      border: 1px solid #444;
      border-bottom: none;
      background: #1c1c1c;
      color: #fff;
      transition: background 0.3s;
    }

    .tab:hover {
      background: #333;
    }

    .tab.active {
      background: #444;
      border-bottom: 2px solid #444;
      font-weight: bold;
    }

    .tab-content {
      display: none;
    }

    .tab-content.active {
      display: block;
    }

    form {
      display: flex;
      flex-direction: column;
      gap: 10px;
      max-width: 600px;
      margin: 0 auto;
      background: #2c2c2c;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    select,
    input,
    textarea,
    button {
      padding: 10px;
      font-size: 16px;
      border: 1px solid #444;
      border-radius: 5px;
      background-color: #333;
      color: #fff;
    }

    button {
      background-color: #e74c3c;
      border: none;
      cursor: pointer;
    }

    button:hover {
      background-color: #c0392b;
    }

    #productsGrid,
    #sourceProductsGrid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 15px;
      margin-top: 20px;
    }

    .product-card {
      background: #333;
      padding: 10px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      text-align: center;
    }

    .product-card img {
      max-width: 100%;
      max-height: 100px;
      object-fit: cover;
      border-radius: 10px;
    }

    .product-card h3 {
      font-size: 14px;
      margin: 10px 0;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .notification {
      position: fixed;
      top: 10px;
      right: 10px;
      background: #27ae60;
      color: white;
      padding: 15px;
      border-radius: 5px;
      display: none;
      z-index: 1000;
    }

    .notification.error {
      background: #e74c3c;
    }

    .edit-icon {
      cursor: pointer;
      margin-left: 5px;
      color: #e74c3c;
    }

    .edit-icon:hover {
      background-color: #c0392b;
    }

    .popup {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 1000;
      justify-content: center;
      align-items: center;
    }

    .popup-content {
      background: #2c2c2c;
      padding: 20px;
      border-radius: 10px;
      width: 80%;
      max-width: 600px;
      position: relative;
    }

    .close-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      font-size: 24px;
      cursor: pointer;
      color: #fff;
    }

    .close-btn:hover {
      color: #e74c3c;
    }

    .pagination {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin-bottom: 20px;
    }

    .pagination button {
      padding: 5px 10px;
      background-color: #444;
      border: none;
      color: #fff;
      cursor: pointer;
      border-radius: 5px;
    }

    .pagination button.active {
      background-color: #e74c3c;
    }

    .pagination button:hover:not(.active) {
      background-color: #555;
    }

    #transferProductsForm {
      display: flex;
      flex-direction: column;
      gap: 10px;
      max-width: 600px;
      margin: 0 auto;
      background: #2c2c2c;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    #transferProductsButton {
      margin: 20px auto;
      padding: 10px 20px;
      background-color: #27ae60;
      border: none;
      border-radius: 5px;
      color: #fff;
      cursor: pointer;
    }

    #transferProductsButton:hover {
      background-color: #219653;
    }

    #apiPermissions {
      max-width: 600px;
      margin: 0 auto;
      background: #2c2c2c;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    #permissionsList {
      margin-top: 20px;
    }

    #permissionsList p {
      color: #ccc;
      font-size: 14px;
    }

    #storeDetails {
      padding: 20px;
    }

    #storeInfo {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 15px;
      background: #2c2c2c;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    #storeInfo p {
      margin: 5px 0;
      font-size: 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    #storeInfo strong {
      color: #bbb;
    }

    #contactInfoPopup,
    #contactInfoUSPopup,
    #privacyPolicyPopup,
    #refundPolicyPopup,
    #shippingPolicyPopup,
    #termsOfServicePopup {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 1001;
      justify-content: center;
      align-items: center;
    }

    #contactInfoContent,
    #contactInfoUSContent,
    #privacyPolicyContent,
    #refundPolicyContent,
    #shippingPolicyContent,
    #termsOfServiceContent {
      background: #2c2c2c;
      padding: 20px;
      border-radius: 10px;
      width: 80%;
      max-width: 600px;
      position: relative;
      color: #fff;
      max-height: 50vh; /* Limit to ~7 lines of text */
      overflow-y: auto; /* Enable vertical scroll if content exceeds the height */
      white-space: pre-wrap; /* Preserve formatting and wrap text */
    }

    .policy-button {
      padding: 10px 20px;
      margin-bottom: 10px;
      border: none;
      border-radius: 5px;
      color: white;
      cursor: pointer;
      display: block;
      width: 200px;
      text-align: center;
    }

    .policy-button.contact-info {
      background-color: #007bff;
    }

    .policy-button.privacy-policy {
      background-color: #6610f2;
    }

    .policy-button.refund-policy {
      background-color: #6f42c1;
    }

    .policy-button.shipping-policy {
      background-color: #dc3545;
    }

    .policy-button.terms-of-service {
      background-color: #28a745;
    }

    .submit-all-policies-button {
      background-color: #ffc107; /* Gold color */
      color: #333; /* Dark text for contrast */
      transition: background-color 0.3s, color 0.3s;
    }

    .submit-all-policies-button:hover {
      background-color: #e0a800; /* Darker gold on hover */
      color: #fff;
    }

    .submit-all-policies-button:active {
      background-color: #c29500; /* Even darker gold when active */
      color: #fff;
    }

    .submit-all-policies-button:disabled {
      background-color: #d4ac0d; /* Muted gold when disabled */
      color: #777;
      cursor: not-allowed;
    }

    .delete-account-button {
      background-color: #e74c3c;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      padding: 5px 10px;
      font-size: 0.8em;
      margin-left: 10px;
    }

    .delete-account-button:hover {
      background-color: #c0392b;
    }

    .csv-upload-section {
      margin-top: 20px;
      background: #2c2c2c;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .csv-upload-section h3 {
      margin-top: 0;
      color: #fff;
    }

    .csv-upload-section input[type="file"] {
      margin-bottom: 10px;
      color: #fff;
    }

    .csv-upload-section button {
      background-color: #27ae60;
      color: #fff;
      border: none;
      border-radius: 5px;
      padding: 10px 20px;
      cursor: pointer;
    }

    .csv-upload-section button:hover {
      background-color: #219653;
    }

    .sidebar-buttons {
      margin-top: 10px;
      padding: 0 20px;
    }

    .sidebar-buttons button.combined-policies-button {
      background-color: #ffc107;
      color: #333;
      border: none;
      border-radius: 5px;
      padding: 10px 20px;
      cursor: pointer;
      width: 100%;
      text-align: center;
      transition: background-color 0.3s, color 0.3s;
      margin-bottom: 10px; /* Space between buttons if needed */
    }

    .sidebar-buttons button.combined-policies-button:hover {
      background-color: #e0a800;
      color: #fff;
    }

    .tab-content#policies button.combined-policies-button {
      background-color: #ffc107;
      color: #333;
      transition: background-color 0.3s, color 0.3s;
      width: auto; /* Adjust width for tab context */
      display: inline-block; /* Align with other buttons in tab */
      margin-left: 10px; /* Space from other buttons in tab */
    }

    .tab-content#policies button.combined-policies-button:hover {
      background-color: #e0a800;
      color: #fff;
    }
</style>
  <boltAction type="file" filePath="script.js">
    let shopifyCode = "";
    let accessToken = "";
    let accounts = [];
    let selectedAccountIndex = -1;
    let totalProducts = 0;
    const productsPerPage = 49;
    let nextPageUrl = null;
    let previousPageUrl = null;
    let currentPage = 1;
    let totalPages = 1;
    let currentPolicyType = '';
    const policyTypeToName = {
      'CONTACT_INFORMATION': 'Contact Information',
      'PRIVACY_POLICY': 'Privacy Policy',
      'REFUND_POLICY': 'Refund Policy',
      'SHIPPING_POLICY': 'Shipping Policy',
      'TERMS_OF_SERVICE': 'Terms of Service'
    };

    // Show notification
    function showNotification(message, isError = false) {
      const notification = document.getElementById("notification");
      notification.textContent = message;
      notification.style.backgroundColor = isError ? "#e74c3c" : "#27ae60";
      notification.style.display = "block";
      setTimeout(() => notification.style.display = "none", 3000);
    }

    // Add a new account
    function addAccount(code, token, storeName) {
      accounts.push({ code, token, storeName });
      updateAccountsList();
    }

    // Update the accounts list
    function updateAccountsList() {
      const accountsList = document.getElementById("accountsList");
      accountsList.innerHTML = "";
      accounts.forEach((account, index) => {
        const li = document.createElement("li");

        // Checkbox for account selection
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.classList.add('account-checkbox');
        checkbox.value = index; // Use index to identify account
        li.appendChild(checkbox);

        // Account name
        const accountNameSpan = document.createElement("span");
        accountNameSpan.textContent = account.storeName;
        accountNameSpan.style.marginLeft = '5px'; // Add some spacing
        accountNameSpan.addEventListener("click", () => switchAccount(index)); // Make name clickable to switch account
        if (index === selectedAccountIndex) {
          accountNameSpan.classList.add("active");
        }
        li.appendChild(accountNameSpan);


        // Delete button
        const deleteButton = document.createElement('button');
        deleteButton.textContent = 'X';
        deleteButton.classList.add('delete-account-button');
        deleteButton.addEventListener('click', (event) => {
          event.stopPropagation(); // Prevent switching account when delete is clicked
          deleteAccount(index);
        });
        li.appendChild(deleteButton);


        accountsList.appendChild(li);
      });
    }

    // Delete an account
    function deleteAccount(index) {
      accounts.splice(index, 1); // Remove account from array
      if (index === selectedAccountIndex) {
        selectedAccountIndex = -1; // Deselect if deleted account was selected
        updateDashboardTitle('Shopify Admin Dashboard'); // Reset dashboard title
        clearDashboardData(); // Clear store details and products
      } else if (index < selectedAccountIndex) {
        selectedAccountIndex--; // Adjust selected index if deleting before it
      }
      updateAccountsList(); // Update the displayed list
      showNotification('Account deleted successfully!');
    }

    // Function to clear dashboard data
    function clearDashboardData() {
      document.getElementById('storeName').textContent = 'Loading...';
      document.getElementById('storeEmail').textContent = 'Loading...';
      document.getElementById('storeAddress').textContent = 'Loading...';
      document.getElementById('storeWebsite').textContent = 'Loading...';
      document.getElementById('storePhone').textContent = 'Loading...';
      document.getElementById('storeCreatedAt').textContent = 'Loading...';
      document.getElementById('storeCurrency').textContent = 'Loading...';
      document.getElementById('storeCustomerEmail').textContent = 'Loading...';
      document.getElementById('productsGrid').innerHTML = '';
      document.getElementById('productCount').textContent = '0';
      document.getElementById('pagination').innerHTML = '';
      document.getElementById('permissionsList').innerHTML = '<p>Loading permissions...</p>';
    }


    // Switch between accounts
    function switchAccount(index) {
      selectedAccountIndex = index;
      const account = accounts[index];
      shopifyCode = account.code;
      accessToken = account.token;
      updateAccountsList();
      updateDashboardTitle(account.storeName);
      loadStoreDetails();
      loadProductCount();
      loadProducts();
      fetchAPIPermissions();
    }

    // Update the dashboard title
    function updateDashboardTitle(storeName) {
      document.getElementById("dashboardTitle").textContent = `${storeName} Admin Dashboard`;
    }

    let storeDetails = {};

    // Load store details
    async function loadStoreDetails() {
      const proxy = "https://cors-anywhere.herokuapp.com/";
      const url = `https://${shopifyCode}.myshopify.com/admin/api/2023-01/shop.json`;
      const headers = {
        "X-Shopify-Access-Token": accessToken,
        "Content-Type": "application/json",
      };

      console.log("Fetching store details from:", url);
      console.log("Headers:", headers);

      try {
        const response = await fetch(proxy + url, {
          method: "GET",
          headers: headers,
        });

        console.log("Response status:", response.status);

        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`HTTP error! status: ${response.status}, text: ${errorText}`);
        }

        const data = await response.json();
        const store = data.shop;

        storeDetails = store;

        // Update store details in the dashboard
        document.getElementById("storeName").innerHTML = `${store.name} <span class="edit-icon" data-field="name"></span>`;
        document.getElementById("storeEmail").innerHTML = `${store.email} <span class="edit-icon" data-field="email"></span>`;
        document.getElementById("storeAddress").innerHTML = `${store.address1 || ''}, ${store.city || ''}, ${store.country || ''} <span class="edit-icon" data-field="address"></span>`;
        document.getElementById("storeWebsite").innerHTML = `${store.myshopify_domain} <span class="edit-icon" data-field="website"></span>`;
        document.getElementById("storePhone").innerHTML = `${store.phone || 'Not available'} <span class="edit-icon" data-field="phone"></span>`;
        document.getElementById("storeCreatedAt").textContent = new Date(store.created_at).toLocaleDateString();
        document.getElementById("storeCurrency").textContent = store.currency;
        document.getElementById("storeCustomerEmail").innerHTML = `${store.customer_email} <span class="edit-icon" data-field="customer_email"></span>`;

        // Add event listeners to edit icons
        document.querySelectorAll('.edit-icon').forEach(icon => {
          icon.addEventListener('click', openEditPopup);
        });

      } catch (error) {
        console.error("Error fetching store details:", error);
        showNotification(`Error fetching store details: ${error.message}`, true);
      }
    }

    // Function to open the edit popup
    function openEditPopup(event) {
      const field = event.target.dataset.field;
      if (!field) {
        console.error("No field specified for editing.");
        return;
      }
      const popup = document.getElementById("editPopup");
      const popupTitle = document.getElementById("popupTitle");
      const popupLabel = document.getElementById("popupLabel");
      const editField = document.getElementById("editField");
      const saveEditButton = document.getElementById("saveEdit");
      const closePopupButton = document.getElementById("closePopup");

      popupTitle.textContent = `Edit ${field.charAt(0).toUpperCase() + field.slice(1)}`;
      popupLabel.textContent = `New ${field.charAt(0).toUpperCase() + field.slice(1)}:`;
      editField.value = document.getElementById(`store${field.charAt(0).toUpperCase() + field.slice(1)}`).textContent;

      popup.style.display = "flex";

      // Save the field to be edited in a data attribute
      saveEditButton.dataset.field = field;

      // Event listeners for save and close
      saveEditButton.onclick = () => saveStoreDetails(saveEditButton.dataset.field);
      closePopupButton.onclick = closeEditPopup;
    }

    // Function to close the edit popup
    function closeEditPopup() {
      const popup = document.getElementById("editPopup");
      popup.style.display = "none";
    }

    // Function to save the edited store details
    async function saveStoreDetails(field) {
      const popup = document.getElementById("editPopup");
      const editField = document.getElementById("editField");
      let newValue = editField.value;

      let updateData = {};
      updateData[field] = newValue;

      const proxy = "https://cors-anywhere.herokuapp.com/";
      const url = `https://${shopifyCode}.myshopify.com/admin/api/2023-01/shop.json`;
      const headers = {
        "X-Shopify-Access-Token": accessToken,
        "Content-Type": "application/json",
      };

      try {
        const response = await fetch(proxy + url, {
          method: "PUT",
          headers: headers,
          body: JSON.stringify({ shop: updateData }),
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        // Update the displayed value and close the popup
        document.getElementById(`store${field.charAt(0).toUpperCase() + field.slice(1)}`).innerHTML = `${newValue} <span class="edit-icon" data-field="${field}"></span>`;
        document.querySelectorAll('.edit-icon').forEach(icon => {
          icon.addEventListener('click', openEditPopup);
        });
        closeEditPopup();
        showNotification('Store details updated successfully!');
      } catch (error) {
        console.error("Error updating store details:", error);
        showNotification(`Error updating store details: ${error.message}`, true);
      }
    }

    // Load product count
    async function loadProductCount() {
      const proxy = "https://cors-anywhere.herokuapp.com/";
      const url = `https://${shopifyCode}.myshopify.com/admin/api/2023-01/products/count.json`;
      const headers = {
        "X-Shopify-Access-Token": accessToken,
        "Content-Type": "application/json",
      };

      try {
        const response = await fetch(proxy + url, {
          method: "GET",
          headers: headers,
        });

        console.log("Product count response status:", response.status);

        if (response.status === 429) {
          showNotification("Rate limit exceeded. Please wait before trying again.", true);
          return;
        }

        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`HTTP error! status: ${response.status}, text: ${errorText}`);
        }

        const data = await response.json();
        totalProducts = data.count;
        totalPages = Math.ceil(totalProducts / productsPerPage);
        updateProductTabTitle();
      } catch (error) {
        console.error("Error fetching product count:", error);
        showNotification(`Error fetching product count: ${error.message}`, true);
      }
    }

    function updateProductTabTitle() {
      document.getElementById("productCount").textContent = `${totalProducts} (${totalPages} Pages)`;
    }

    // Load products with pagination
    async function loadProducts(pageUrl = null) {
      const proxy = "https://cors-anywhere.herokuapp.com/";
      const baseUrl = `https://${shopifyCode}.myshopify.com/admin/api/2023-01/products.json?limit=${productsPerPage}`;
      const url = pageUrl ? proxy + pageUrl : proxy + baseUrl;
      const headers = {
        "X-Shopify-Access-Token": accessToken,
        "Content-Type": "application/json",
      };

      try {
        const response = await fetch(url, {
          method: "GET",
          headers: headers,
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        const productsGrid = document.getElementById("productsGrid");
        productsGrid.innerHTML = "";
        data.products.forEach((product) => {
          const imgSrc = product.images.length > 0 ? product.images[0].src : "";
          const card = `
        <div class="product-card">
          <img src="${imgSrc}" alt="${product.title}" />
          <h3>${product.title}</h3>
        </div>
      `;
          productsGrid.innerHTML += card;
        });

        // Update pagination buttons
        const linkHeader = response.headers.get("link");
        nextPageUrl = getNextPageUrl(linkHeader);
        previousPageUrl = getPreviousPageUrl(linkHeader);

        currentPage = calculateCurrentPage(pageUrl);

        updatePagination();
      } catch (error) {
        console.error("Error fetching products:", error);
        showNotification(`Error fetching products: ${error.message}`, true);
      }
    }

    function calculateCurrentPage(pageUrl) {
      if (!pageUrl) return 1;
      const urlParams = new URLSearchParams(pageUrl);
      const pageInfo = urlParams.get("page_info");

      if (!pageInfo) return 1;

      try {
        const decodedPageInfo = atob(pageInfo);
        const startValue = parseInt(decodedPageInfo.split(":")[0]);
        return Math.ceil(startValue / productsPerPage);
      } catch (error) {
        console.error("Error decoding page info:", error);
        return 1;
      }
    }

    // Get next page URL from Link header
    function getNextPageUrl(linkHeader) {
      if (!linkHeader) return null;
      const links = linkHeader.split(",");
      for (const link of links) {
        if (link.includes('rel="next"')) {
          const url = link.substring(link.indexOf("<") + 1, link.indexOf(">"));
          return url;
        }
      }
      return null;
    }

    // Get previous page URL from Link header
    function getPreviousPageUrl(linkHeader) {
      if (!linkHeader) return null;
      const links = linkHeader.split(",");
      for (const link of links) {
        if (link.includes('rel="previous"')) {
          const url = link.substring(link.indexOf("<") + 1, link.indexOf(">"));
          return url;
        }
      }
      return null;
    }

    // Update pagination buttons
    function updatePagination() {
      const pagination = document.getElementById("pagination");
      pagination.innerHTML = "";

      // Previous button
      if (previousPageUrl) {
        const prevButton = document.createElement("button");
        prevButton.textContent = "Previous";
        prevButton.addEventListener("click", () => {
          loadProducts(previousPageUrl);
        });
        pagination.appendChild(prevButton);
      }

      // Current page number
      const pageNumberSpan = document.createElement("span");
      pageNumberSpan.textContent = `Page ${currentPage} of ${totalPages}`;
      pagination.appendChild(pageNumberSpan);

      // Next button
      if (nextPageUrl) {
        const nextButton = document.createElement("button");
        nextButton.textContent = "Next";
        nextButton.addEventListener("click", () => {
          loadProducts(nextPageUrl);
        });
        pagination.appendChild(nextButton);
      }
    }

    // Add account form submission
    document.getElementById("sidebarLoginForm").addEventListener("submit", async (e) => {
      e.preventDefault();
      const code = document.getElementById("sidebarShopifyCode").value;
      const token = document.getElementById("sidebarAccessToken").value;

      // Clear the form fields
      document.getElementById("sidebarShopifyCode").value = "";
      document.getElementById("sidebarAccessToken").value = "";

      // Get store name
      const storeName = await getStoreName(code, token);
      if (storeName) {
        addAccount(code, token, storeName);
        switchAccount(accounts.length - 1);
      } else {
        showNotification("Failed to fetch store details.", true);
      }
    });

    // Get store name
    async function getStoreName(code, token) {
      const proxy = "https://cors-anywhere.herokuapp.com/";
      const url = `https://${code}.myshopify.com/admin/api/2023-01/shop.json`;
      const headers = {
        "X-Shopify-Access-Token": token,
        "Content-Type": "application/json",
      };

      try {
        const response = await fetch(proxy + url, {
          method: "GET",
          headers: headers,
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data.shop.name;
      } catch (error) {
        console.error("Error fetching store name:", error);
        return null;
      }
    }

    // Function to replace placeholders in policy text
    function replacePlaceholders(text) {
      if (!storeDetails) return text;

      const website = storeDetails.myshopify_domain;
      const name = storeDetails.name;
      const mobileNumber = storeDetails.phone || "Not Available";
      const address = storeDetails.address1 || "Not Available";
      const email = storeDetails.email; // Get email from storeDetails

      let replacedText = text.replace(/\{\{ Input WEBSITE \}\}/g, website);
      replacedText = replacedText.replace(/\{\{ WEBSITE \}\}/g, website);
      replacedText = replacedText.replace(/\{\{name of store\}\}/g, name);
      replacedText = replacedText.replace(/\{\{MobileNumber\}\}/g, mobileNumber);
      replacedText = replacedText.replace(/\{\{YourAddress\}\}/g, address);
      replacedText = replacedText.replace(/\{\{storeEmail\}\}/g, email); // Replace storeEmail

      return replacedText;
    }


    // Function to get today's date in "Month Day, Year" format
    function getTodaysDate() {
      const today = new Date();
      const month = today.toLocaleString('default', { month: 'long' });
      const day = today.getDate();
      const year = today.getFullYear();
      return `${month} ${day}, ${year}`;
    }

    async function fetchAPIPermissions() {
      const proxy = "https://cors-anywhere.herokuapp.com/";
      const url = `https://${shopifyCode}.myshopify.com/admin/oauth/access_scopes.json`;
      const headers = {
        "X-Shopify-Access-Token": accessToken,
        "Content-Type": "application/json",
      };

      try {
        const response = await fetch(proxy + url, {
          method: "GET",
          headers: headers,
        });

        if (response.status === 429) {
          showNotification("Rate limit exceeded. Please wait before trying again.", true);
          return;
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        displayPermissions(data.access_scopes);
      } catch (error) {
        console.error("Error fetching API permissions:", error);
        document.getElementById("permissionsList").innerHTML = "<p>Failed to fetch permissions: " + error.message + "</p>";
      }
    }

    // Function to display permissions
    function displayPermissions(permissions) {
      const permissionsList = document.getElementById("permissionsList");
      permissionsList.innerHTML = "";

      if (permissions.length === 0) {
        permissionsList.innerHTML = "<p>No permissions found.</p>";
        return;
      }

      const ul = document.createElement("ul");
      permissions.forEach((scope) => {
        const li = document.createElement("li");
        li.textContent = scope.handle;
        ul.appendChild(li);
      });

      permissionsList.appendChild(ul);
    }

    // Function to switch between tabs
    function setupTabs() {
      const tabs = document.querySelectorAll(".tab");
      const tabContents = document.querySelectorAll(".tab-content");

      tabs.forEach((tab) => {
        tab.addEventListener("click", () => {
          // Remove active class from all tabs and contents
          tabs.forEach((t) => t.classList.remove("active"));
          tabContents.forEach((content) => content.classList.remove("active"));

          // Add active class to the clicked tab
          tab.classList.add("active");
          const targetTab = tab.getAttribute("data-tab");
          document.getElementById(targetTab).classList.add("active");

          // Fetch data based on the selected tab
          if (targetTab === "apiPermissions") {
            fetchAPIPermissions();
          } else if (targetTab === "products") {
            loadProducts();
          } else if (targetTab === "transferProducts") {
            document.getElementById("transferProductsButton").style.display = "none";
          }
        });
      });
    }

    // Initialize tabs
    setupTabs();

    // Load initial product count and tab title
    loadProductCount();

    // Load store details on initial load
    loadStoreDetails();


    // Policy buttons event listeners
    document.getElementById('contactInfoButton').addEventListener('click', () => {
      currentPolicyType = 'CONTACT_INFORMATION';
      submitPolicy(currentPolicyType);
    });
    document.getElementById('privacyPolicyButton').addEventListener('click', () => {
      currentPolicyType = 'PRIVACY_POLICY';
      submitPolicy(currentPolicyType);
    });
    document.getElementById('refundPolicyButton').addEventListener('click', () => {
      currentPolicyType = 'REFUND_POLICY';
      submitPolicy(currentPolicyType);
    });
    document.getElementById('shippingPolicyButton').addEventListener('click', () => {
      currentPolicyType = 'SHIPPING_POLICY';
      submitPolicy(currentPolicyType);
    });
    document.getElementById('termsOfServiceButton').addEventListener('click', () => {
      currentPolicyType = 'TERMS_OF_SERVICE';
      submitPolicy(currentPolicyType);
    });

    // Submit All Policies Button
    const submitAllPoliciesButton = document.getElementById('submitAllPoliciesButton');
    submitAllPoliciesButton.addEventListener('click', submitAllPoliciesSequentially);

    // Create Menu and Submit Policies Button (Policies Tab)
    const createAndSubmitPoliciesButton = document.getElementById('createAndSubmitPoliciesButton');
    createAndSubmitPoliciesButton.addEventListener('click', createMenuAndSubmitPoliciesSequentially);

    // Create Menu and Submit Policies Button (Sidebar)
    const createAndSubmitPoliciesButtonSidebar = document.getElementById('createAndSubmitPoliciesButtonSidebar');
    createAndSubmitPoliciesButtonSidebar.addEventListener('click', createMenuAndSubmitPoliciesSequentially);


    async function submitPolicy(policyType) {
      if (!shopifyCode || !accessToken) {
        showNotification("Please log in first.", true);
        return;
      }

      const proxy = "https://cors-anywhere.herokuapp.com/";
      // const policyType = currentPolicyType; // No need to redeclare
      let policyBody = "";
      let policyFile = "";

      // Determine policy file based on policyType
      switch (policyType) {
        case "CONTACT_INFORMATION":
          policyFile = "contact.txt";
          break;
        case "PRIVACY_POLICY":
          policyFile = "privacy.txt";
          break;
        case "REFUND_POLICY":
          policyFile = "refund.txt";
          break;
        case "SHIPPING_POLICY":
          policyFile = "shipping.txt";
          break;
        case "TERMS_OF_SERVICE":
          policyFile = "terms.txt";
          break;
        default:
          showNotification("Unknown policy type.", true);
          return;
      }

      // Fetch policy content from the corresponding text file
      try {
        const response = await fetch(policyFile);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        policyBody = await response.text();
      } catch (error) {
        console.error(`Error loading ${policyFile}:`, error);
        showNotification(`Error loading ${policyTypeToName[policyType] || 'policy'} text.`, true);
        return;
      }


      // Function to get today's date in "Month Day, Year" format
      function getTodaysDate() {
        const today = new Date();
        const month = today.toLocaleString('default', { month: 'long' });
        const day = today.getDate();
        const year = today.getFullYear();
        return `${month} ${day}, ${year}`;
      }

      // Update Privacy Policy with current date before submission
      if (policyType === "PRIVACY_POLICY") {
        const todaysDate = getTodaysDate();
        policyBody = policyBody.replace(/<span id="privacyPolicyLastUpdated"><\/span>/, `<span id="privacyPolicyLastUpdated">${todaysDate}</span>`);
      }

      policyBody = replacePlaceholders(policyBody);

      const url = proxy + `https://${shopifyCode}.myshopify.com/admin/api/2023-01/graphql.json`;
      const headers = {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": accessToken
      };
      const body = JSON.stringify({
        query: `mutation shopPolicyUpdate($shopPolicy: ShopPolicyInput!) {
      shopPolicyUpdate(shopPolicy: $shopPolicy) {
        shopPolicy {
          id
          type
          body
        }
        userErrors {
          field
          message
        }
      }
    }`,
        variables: { shopPolicy: { type: policyType, body: policyBody } },
      });

      console.log("Submitting policy:", policyType);
      console.log("GraphQL Query Body:", body);

      try {
        const response = await fetch(url, {
          method: "POST",
          headers: headers,
          body: body
        });
        const data = await response.json();
        console.log("Policy response data:", data);

        if (data.errors) {
          console.error("GraphQL errors:", data.errors);
          showNotification(`GraphQL errors: ${data.errors.map(err => err.message).join(", ")}`, true);
        } else if (data.data && data.data.shopPolicyUpdate && data.data.shopPolicyUpdate.userErrors.length > 0) {
          let errors = data.data.shopPolicyUpdate.userErrors.map(error => error.message).join(", ");
          showNotification(`Failed to update ${policyTypeToName[policyType] || 'policy'}. User Errors: ${errors}`, true);
        } else {
          showNotification(`${policyTypeToName[policyType] || 'Policy'} updated successfully!`);
        }
      } catch (error) {
        console.error("Error submitting policy:", error);
        showNotification(`Error submitting ${policyTypeToName[policyType] || 'policy'}: ${error.message}`, true);
      }
    }

    async function submitAllPoliciesSequentially() {
      const policyTypes = ['CONTACT_INFORMATION', 'REFUND_POLICY', 'SHIPPING_POLICY', 'TERMS_OF_SERVICE', 'PRIVACY_POLICY'];
      const submitAllPoliciesButton = document.getElementById('submitAllPoliciesButton');
      const createAndSubmitPoliciesButton = document.getElementById('createAndSubmitPoliciesButton');
      const createAndSubmitPoliciesButtonSidebar = document.getElementById('createAndSubmitPoliciesButtonSidebar');


      submitAllPoliciesButton.disabled = true;
      submitAllPoliciesButton.textContent = 'Submitting Policies...';
      createAndSubmitPoliciesButton.disabled = true;
      createAndSubmitPoliciesButtonSidebar.disabled = true;
      createAndSubmitPoliciesButton.textContent = 'Submitting Policies...';
      createAndSubmitPoliciesButtonSidebar.textContent = 'Submitting Policies...';


      for (const policyType of policyTypes) {
        submitAllPoliciesButton.textContent = `Submitting ${policyTypeToName[policyType]}...`;
        createAndSubmitPoliciesButton.textContent = `Submitting ${policyTypeToName[policyType]}...`;
        createAndSubmitPoliciesButtonSidebar.textContent = `Submitting ${policyTypeToName[policyType]}...`;
        await submitPolicyWithDelay(policyType, 400);
      }

      submitAllPoliciesButton.disabled = false;
      submitAllPoliciesButton.textContent = 'Submit All Policies';
      createAndSubmitPoliciesButton.disabled = false;
      createAndSubmitPoliciesButtonSidebar.disabled = false;
      createAndSubmitPoliciesButton.textContent = 'Create Menu & Submit All Policies';
      createAndSubmitPoliciesButtonSidebar.textContent = 'Create Menu & Submit All Policies';
      showNotification('All policies submitted!');
    }

    async function submitPolicyWithDelay(policyType, delay) {
      await submitPolicy(policyType);
      await delayAsync(delay);
    }

    function delayAsync(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }


    async function createPoliciesMenu() {
      if (!shopifyCode || !accessToken) {
        showNotification("Please log in first.", true);
        return;
      }

      const proxy = "https://cors-anywhere.herokuapp.com/";
      const policiesUrl = `https://${shopifyCode}.myshopify.com/admin/api/2025-01/policies.json`;
      const headers = {
        "X-Shopify-Access-Token": accessToken,
        "Content-Type": "application/json",
      };

      try {
        const policiesResponse = await fetch(proxy + policiesUrl, {
          method: "GET",
          headers: headers,
        });
        const policiesData = await policiesResponse.json();

        const menuItems = [];
        if (policiesData && policiesData.policies) {
          policiesData.policies.forEach((policy) => {
            let policyName = policy.title.toLowerCase().replace(/ /g, "-");
            menuItems.push({
              title: policy.title,
              type: "HTTP",
              url: `https://${shopifyCode}.myshopify.com/policies/${policyName}`,
            });
          });
        }

        const url = `https://${shopifyCode}.myshopify.com/admin/api/2025-01/graphql.json`;
        const graphqlQuery = {
          query: `mutation CreateMenu($title: String!, $handle: String!, $items: [MenuItemCreateInput!]!) {
                menuCreate(title: $title, handle: $handle, items: [MenuItemCreateInput!]!) {
                    menu {
                        id
                        handle
                        items {
                            id
                            title
                        }
                    }
                    userErrors {
                        field
                        message
                    }
                }
            }`,
          variables: {
            title: "Policies",
            handle: "policies",
            items: menuItems,
          },
        };

        const response = await fetch(proxy + url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-Shopify-Access-Token": accessToken,
          },
          body: JSON.stringify(graphqlQuery),
        });

        const data = await response.json();
        console.log("Menu creation response:", data);

        if (data.errors) {
          console.error("GraphQL Errors:", data.errors);
          showNotification(`Failed to create menu: ${data.errors.map((e) => e.message).join(", ")}`, true);
        } else if (data.data && data.data.menuCreate && data.data.menuCreate.userErrors.length > 0) {
          console.error("User Errors:", data.data.menuCreate.userErrors);
          showNotification(`Failed to create menu: ${data.data.menuCreate.userErrors.map((e) => e.message).join(", ")}`, true);
        } else {
          showNotification("Policies menu created successfully!");
        }

        // document.getElementById("response").innerText = JSON.stringify(data, null, 2);
      } catch (error) {
        console.error("Error creating menu:", error);
        showNotification(`Error creating menu: ${error.message}`, true);
        // document.getElementById("response").innerText = `Error: ${error.message}`;
      }
    }


    async function createMenuAndSubmitPoliciesSequentially() {
      await createPoliciesMenu();
      await submitAllPoliciesSequentially();
    }


    function handleCsvUpload() {
      const csvFile = document.getElementById('csvUpload').files[0];
      if (!csvFile) {
        showNotification('Please select a CSV file.', true);
        return;
      }

      console.log("CSV file selected:", csvFile.name); // Log CSV file name

      // Implement CSV parsing and product import logic here
      // ... (CSV parsing and Shopify API calls will be added in the next steps) ...

      showNotification('CSV upload started. Product import is under development.'); // Placeholder notification
    }
