<div class="container-divider"></div>
<div class="container">
  <nav class="sub-nav">
    {{breadcrumbs}}
    <div class="search-container">
      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" focusable="false" viewBox="0 0 12 12"
        class="search-icon">
        <circle cx="4.5" cy="4.5" r="4" fill="none" stroke="currentColor" />
        <path stroke="currentColor" stroke-linecap="round" d="M11 11L7.5 7.5" />
      </svg>
      {{search submit=false}}
    </div>
  </nav>

  <h1>
    {{t 'submit_a_request'}}
    <span class="follow-up-hint">
      {{follow_up}}
    </span>
  </h1>

  <div id="main-content" class="form">
    {{request_form wysiwyg=true}}
  </div>
</div>

<style>
  .request_custom_fields_1500002741122.loading:after {
    color: #999;
    content: " ";
    line-height: 1em;
    position: absolute;
    transform: translateY(-50%);
    width: 15px;
    height: 15px;
    border: 3px solid #ccc;
    border-top-color: #000;
    border-radius: 50%;
    animation: spin 0.7s linear infinite;
    margin-left: -30px;
    margin-top: 10px;
  }

  .error-labelid {
    color: #f00;
    line-height: 1em;
    font-size: smaller;
  }

  .request_custom_fields_30546051788307 {
    display: none !important;
  }

  .form-field.boolean label,
  .form-field.boolean p {
    width: 100%;
    margin-left: 25px;
  }

  .form-field input[type="checkbox"] {
    position: absolute;
    margin-top: -22px;
  }

  .field-block {
    border: 1px solid rgba(255, 176, 87, 0.37);
    border-radius: 10px;
    padding: 10px 25px 35px 25px;
    margin-top: 15px;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  .hc-multiselect-menu li label input[type=checkbox] {
    position: relative !important;
  }

  .hc-multiselect-toggle li span[aria-label]::before {
    top: 1px !important;
  }
  .request_custom_fields_40793635772307 {
  	display: none !important;
  }
</style>

<script>
  const PREFIX = 'form_';
  const fieldLabelId = "1500002741122";
  const fieldLabelName = "1500002740962";
  const fieldLabelTier = "30546051788307";
  const contentProtectionForm = "40793107333523";
  let inputFieldLabelId;
  let inputFieldLabelName;
  let inputFieldLabelTier;
  let inputFieldLabelIdContainer;

  document.addEventListener("DOMContentLoaded", () => {
    const panels = document.querySelectorAll('.nesty-panel');
    panels.forEach(panel => {
      let idsToRemove = [];
  		idsToRemove.push("full_campaign__proactive_pre-release_leak_protection___post-release_infringement_takedowns_for_2_weeks_after_release_date"); //temporary removal
      const observer = new MutationObserver(() => {
        idsToRemove.forEach(id => {
          const element = document.getElementById(id);
          if (element) {
            element.remove();
          }
        });
      });

      observer.observe(panel, {
        childList: true,
        subtree: true,
      });
    });
    blockLimiter();

    // Function to save data to localStorage with a prefix
    const saveFieldData = (fieldId, value) => {
      const now = new Date();
      const item = {
        value: value,
        expiry: now.getTime() + 8 * 60 * 60 * 1000, // 8 hours in milliseconds
      };
      localStorage.setItem(`${PREFIX}${fieldId}`, JSON.stringify(item));
    };

    // Function to retrieve data from localStorage with a prefix
    const getFieldData = (fieldId) => {
      const itemStr = localStorage.getItem(`${PREFIX}${fieldId}`);
      if (!itemStr) {
        return null;
      }

      const item = JSON.parse(itemStr);
      const now = new Date();

      if (now.getTime() > item.expiry) {
        localStorage.removeItem(`${PREFIX}${fieldId}`);
        return null;
      }
      return item.value;
    };

    // Monitor all input and select fields for changes
    //const fields = document.querySelectorAll('input, select, textarea');
    const fields = [];

    fields.forEach(field => {
      const fieldId = field.id || field.name;
      if (!fieldId || ['request_issue_type_select', 'query', 'utf8', 'commit'].includes(fieldId)) {
        return; // Skip fields without ID or the specific fields to ignore
      }

      // Restore field value from localStorage if available
      const savedValue = getFieldData(fieldId);
      if (savedValue !== null && savedValue !== undefined) {
        if (field.type === 'checkbox') {
          field.checked = savedValue === true || savedValue === 'on';
        } else {
          field.value = savedValue;
        }
      }

      // Add event listener to save changes to localStorage
      if (field.type === 'checkbox') {
        field.addEventListener('change', (event) => {
          saveFieldData(fieldId, event.target.checked);
        });
      } else {
        field.addEventListener('input', (event) => {
          saveFieldData(fieldId, event.target.value);
        });
        field.addEventListener('change', (event) => {
          saveFieldData(fieldId, event.target.value);
        });
      }
    });
  });

  /** Polyfill - AbortController */
  if (typeof window.AbortController === 'undefined') {
    window.AbortController = function () {
      this.signal = {};
      this.abort = function () {
        console.warn("[Polyfill] AbortController is not supported in this browser.");
      };
    };
  }

  /** Global variables */
  let auth0Client;
  let fetchController;


  /** Adds event for initialization */
  document.addEventListener('DOMContentLoaded', async () => {
    document.querySelectorAll('p[id$="_hint"]').forEach(p => {
      let html = p.innerHTML;
      html = html.replace(/<a[^>]*>(.*?)<\/a>/gi, '$1');
      html = html.replace(/\[link="([^"]+)"\](.*?)\[\/link\]/gi, (match, url, text) => {
        return `<a href="${url}" target="_blank" rel="noopener noreferrer">${text}</a>`;
      });
      html = html.replace(/\[block_date\](.*?)\[\/block_date\]/gi, (match, innerText) => {
        return `<div class="block-date-link" style="color: #0073e6; text-decoration: underline; cursor: pointer; display: inline;">${innerText}</div>`;
      });

      p.innerHTML = html;
      const blockDateLink = p.querySelector('.block-date-link');
      if (blockDateLink) {
        blockDateLink.addEventListener('click', () => {
          const container = p.closest('.form-field');
          if (container) {
            const visibleInput = container.querySelector('input.datepicker');
            if (visibleInput) {
              visibleInput.value = '2099-12-31';
              visibleInput.dispatchEvent(new Event('change', { bubbles: true }));
            }
          }
        });
      }
    });
  	try {
      const submitBtn = document.querySelector('input[type="submit"][name="commit"]');
      submitBtn.addEventListener('click', function (event) {
        clearFormData();
      });
  	} catch {}

    try {
      await configureClient();

      if (window.location.search.includes('code=') && window.location.search.includes('state=')) {
        await auth0Client.handleRedirectCallback();
        const user = await auth0Client.getUser();
        const token = await auth0Client.getTokenSilently();
        window.history.replaceState({}, document.title, window.location.pathname);
      }

      inputFieldLabelId = document.getElementById(`request_custom_fields_${fieldLabelId}`);
      inputFieldLabelName = document.getElementById(`request_custom_fields_${fieldLabelName}`);
      inputFieldLabelTier = document.getElementById(`request_custom_fields_${fieldLabelTier}`);
      inputFieldLabelIdContainer = document.querySelector(`.request_custom_fields_${fieldLabelId}`);

      if (inputFieldLabelId && inputFieldLabelName && inputFieldLabelTier) {
        const dataInputFieldLabelId = getWithExpiry('labelId');
        if (dataInputFieldLabelId) {
          const idElem = document.getElementById(`request_custom_fields_${fieldLabelId}`);
          idElem.value = dataInputFieldLabelId || "";
          await getData(dataInputFieldLabelId);
          localStorage.removeItem('labelId');
        }

        inputFieldLabelId.addEventListener("input", async function (event) {
          event.preventDefault();

          const inputValue = event.target.value;

          if (!inputValue || /\D/.test(inputValue.trim())) {
            console.warn("[EventListener] Input ignored: not a valid number.");
            return;
          }

          setWithExpiry('labelId', inputValue, 1);
          await getData(inputValue);
        });
      }
    } catch (error) {
      console.error("[DOMContentLoaded] Error during initialization:", error);
    }
  });

  /** Configure Auth0 Client */
  const configureClient = async () => {
    try {
      const response = await fetch("{{asset 'auth_config.json'}}");
      const config = await response.json();

      auth0Client = await auth0.createAuth0Client({
        domain: config.domain,
        clientId: config.clientId,
        useRefreshTokens: true,
        authorizationParams: {
          audience: config.audience,
          organization: config.orgId,
          redirect_uri: window.location.href
        },
        scope: 'openid profile email offline_access',
        cacheLocation: "localstorage"
      });
    } catch (error) {
      console.error("[configureClient] Error configuring Auth0 client:", error);
    }
  };

  /** Login function */
  const login = async () => {
    try {
      await auth0Client.loginWithRedirect({
        authorizationParams: {
          redirect_uri: window.location.href
        }
      });
    } catch (error) {
      console.error("[login] Error during login:", error);
    }
  };

  /** Logout function */
  const logout = async () => {
    try {
      await auth0Client.logout({
        logoutParams: { returnTo: window.location.href }
      });
    } catch (error) {
      console.error("[logout] Error during logout:", error);
    }
  };

  /** Get Identity if Needed */
  const getIdentityIfNeeded = async () => {

    try {

      const token = await auth0Client.getTokenSilently();
      const user = await auth0Client.getUser();
      

      const grassIdentity = user?.['https://grass.theorchard.com/identity'];
      if (!grassIdentity?.profiles || !Array.isArray(grassIdentity.profiles)) {
        console.error("[getIdentity] Missing or malformed identity profiles");
        return;
      }

      const orchAdminProfile = grassIdentity.profiles.find(profile => profile.profileType === 'OrchAdminProfile');
      if (!orchAdminProfile) {
        console.error("[getIdentity] No profile with type 'OrchAdminProfile' found.");
        showError('You don’t have permission for auto-filling. Please complete the form manually.');
        return;
      }

      const profile_id = orchAdminProfile.profileId;
      const profile_type = orchAdminProfile.profileType;
      const uuid = grassIdentity.id;

      return { token, profile_id, profile_type, uuid };
    } catch (error) {
      console.error(String(error));
      if (error.error === "login_required" || error.error === "missing_refresh_token") {
        console.warn("[getIdentityIfNeeded] Login required. Redirecting...");
        await login();
        return;
      } else {
        console.error("[getIdentityIfNeeded] Unexpected error:", error);
        showError('Something went wrong with authentication. Please fill out the form manually.');
        return;
      }
    }
  };

  /** Get Data Based on Label ID */
  const getData = async (labelIdValue) => {

    if (fetchController) fetchController.abort();
    fetchController = new AbortController();
    const signal = fetchController.signal;

    try {
      await delay(500);

      hideError();
      inputFieldLabelIdContainer.classList.add("loading");

      const identityData = await getIdentityIfNeeded();
      if (!identityData) return;

      const response = await fetch(
        'https://ows-grass.theorchard.io/graphql-router/graphql',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': `Bearer ${identityData.token}`,
            'apollographql-client-name': 'zendesk-helpcenter',
            'orchard-profile-id': identityData.profile_id,
            'orchard-profile-type': identityData.profile_type,
            'orchard-identity-uuid': identityData.uuid,
          },
          body: JSON.stringify({
            query: 'query Vendor($vendorId: Int!) { vendor(vendorId: $vendorId) { name serviceTier { displayName name } } }',
            variables: { vendorId: parseInt(labelIdValue) }
          }),
          signal,
        }
      );

      if (!response.ok) throw new Error("[getData] Failed to fetch data");

      const result = await response.json();
      if (result?.data?.vendor) {
        const vendorName = result.data.vendor.name;
        const serviceTierName = result.data.vendor.serviceTier?.name;

        setFormLabelData(vendorName, serviceTierName);

        const nameField = document.getElementById(`request_custom_fields_${fieldLabelName}`);
        if (nameField) {
          nameField.style.display = "none";
        } else {
          console.warn("[getData] Name field element not found.");
        }
        hideError();
      } else {
        console.warn("[getData] Vendor data not found.");
        setFormLabelData(null, null);
        showError('Please enter a valid Label ID or complete the form manually.');
      }
    } catch (error) {
      if (error.name === 'AbortError') {
        console.error("[getData] Request aborted.");
      } else {
        console.error("[getData] Error occurred:", error);
        showError('Oops! Data extraction failed. Please fill out the form manually.');
      }
    }
  };

  /** Set Form Label Data */
  const setFormLabelData = (fieldLabelNameValue, fieldLabelTierValue) => {
    try {
      const nameElem = document.getElementById(`request_custom_fields_${fieldLabelName}`);
      const tierElem = document.getElementById(`request_custom_fields_${fieldLabelTier}`);
      nameElem.value = fieldLabelNameValue || "";
      tierElem.value = fieldLabelTierValue || "";

      const existingValueElem = document.getElementById(`request_custom_fields_${fieldLabelName}_value`);
      if (fieldLabelNameValue) {
        if (!existingValueElem) {
          if (nameElem) {
            nameElem.insertAdjacentHTML('afterend', `<div id="request_custom_fields_${fieldLabelName}_value">${fieldLabelNameValue}</div>`);
          } else {
            console.warn("[setFormLabelData] Field name element not found.");
          }
        } else {
          existingValueElem.textContent = fieldLabelNameValue;
        }
      } else if (existingValueElem) {
        existingValueElem.remove();
      }
    } catch (error) {
      console.error("[setFormLabelData] Error setting form label data:", error);
    }
  };

  /** Function to display error */
  const showError = (message) => {
    const inputFieldLabelIdContainer = document.querySelector(`.request_custom_fields_${fieldLabelId}`);
    inputFieldLabelIdContainer.classList.remove("loading");
    const existingErrorSpan = document.querySelector('.error-labelid');
    if (existingErrorSpan) {
      existingErrorSpan.remove();
    }
    const errorHTML = `<span class="error-labelid">${message}</span>`;
    inputFieldLabelId.insertAdjacentHTML('afterend', errorHTML);
    setFormLabelData(null, null);
    document.getElementById(`request_custom_fields_${fieldLabelName}`).style.display = "block";
  };

  /** Function to hide error */
  const hideError = () => {
    const inputFieldLabelIdContainer = document.querySelector(`.request_custom_fields_${fieldLabelId}`);
    inputFieldLabelIdContainer.classList.remove("loading");
    const existingErrorSpan = document.querySelector('.error-labelid');
    if (existingErrorSpan) {
      existingErrorSpan.remove();
    }
  };

  // Save a value in localStorage with an expiration time (in minutes)
  function setWithExpiry(key, value, minutes) {
    const now = new Date();
    const item = {
      value: value,
      expiry: now.getTime() + minutes * 60 * 1000,
    };
    localStorage.setItem(key, JSON.stringify(item));
  }

  // Retrieve a value from localStorage, return null if expired
  function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) return null;

    const item = JSON.parse(itemStr);
    const now = new Date();

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key);
      return null;
    }

    return item.value;
  }

  // Field grouping into blocks
  async function blockLimiter() {
    await sleep(500);

    const fieldBlockArray = [
      { id: "field-block-full-campaign", title: "", description: "", fields: [40793968493459, 40794110152339, 40793968321555, 40794099271571, 42086101393043, 40794059256211, 40794004318355, 40793995545875, 40794108428563, 42087016538643, 42087036456595, 42087075744659, 42087152399251] },
      { id: "field-block-product-leaked", title: "", description: "", fields: [40794092310803, 40794055776275, 40968321727251, 40794071577491, 40968406486803, 40968712764051, 40794231713939] },
      { id: "field-block-ingringing-content", title: "", description: "", fields: [40794090993555, 42086097248403] },
      { id: "field-block-additional-infringements", title: "", description: "", fields: [40794147411091, 40794141839251, 40794163955091] },
      { id: "field-block-muso-protection", title: "", description: "", fields: [40794151857299, 40794230004755, 40794187310867, 40794204617491, 40794182187667, 40794174183443, 40794191925267, 40794246006419, 40794192631827, 40794228519315] },
      { id: "field-block-websheriff-protection", title: "", description: "", fields: [40794200690835, 40794226897043, 40968064676755, 40968986572179, 40969497935763, 42230456238867] },
      { id: "field-block-investigation", title: "", description: "", fields: [40794247541523] }
    ];

    for (const block of fieldBlockArray) {
      const blockHtml = `<div id="${block.id}" class="field-block" hidden>
          <h2>${block.title}</h2>
          <p class="description">${block.description}</p>
        </div>`;

      let blockInserted = false;

      for (const fieldId of block.fields) {
        const selector = block.id === "field-block-details"
          ? `.${fieldId}`
          : `.request_custom_fields_${fieldId}`;
        const fieldElement = document.querySelector(selector);
        if (fieldElement) {
          fieldElement.insertAdjacentHTML('beforebegin', blockHtml);
          blockInserted = true;
          break;
        }
      }

      if (!blockInserted) continue;

      const blockDiv = document.getElementById(block.id);

      const observeBlockVisibility = () => {
        const anyFieldVisible = block.fields.some(fieldId => {
          const selector = block.id === "field-block-details"
            ? `.${fieldId}`
            : `.request_custom_fields_${fieldId}`;
          const fieldElement = document.querySelector(selector);
          if (!fieldElement) return false;
          return block.id === "field-block-details"
            ? fieldElement.style.display !== 'none'
            : !fieldElement.hidden;
        });
        blockDiv.hidden = !anyFieldVisible;
      };

      for (const fieldId of block.fields) {
        const selector = block.id === "field-block-details"
          ? `.${fieldId}`
          : `.request_custom_fields_${fieldId}`;
        const fieldElement = document.querySelector(selector);
        if (fieldElement) {
          blockDiv.appendChild(fieldElement);
          if (block.id === "field-block-details") {
            if (fieldElement.style.display !== 'none') {
              blockDiv.hidden = false;
            }
            const observer = new MutationObserver(() => observeBlockVisibility());
            observer.observe(fieldElement, { attributes: true, attributeFilter: ['style'] });
          } else {
            if (!fieldElement.hidden) {
              blockDiv.hidden = false;
            }
            const observer = new MutationObserver(() => observeBlockVisibility());
            observer.observe(fieldElement, { attributes: true, attributeFilter: ['hidden'] });
          }
        }
      }
    }
  }

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

  /** Function to delay execution */
  const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
  
  const clearFormData = () => {
  	console.log("clearFormData");
    Object.keys(localStorage).forEach((key) => {
      if (key.startsWith(PREFIX)) {
        localStorage.removeItem(key);
      }
    });
  };

</script>
