/*!
 * HotPocket by BTHLabs (https://hotpocket.app/)
 * Copyright 2025-present BTHLabs <contact@bthlabs.pl> (https://bthlabs.pl/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(() => {
  'use strict';

  document.addEventListener('DOMContentLoaded', (event) => {
    const form = document.getElementById('OptionsForm');
    const fieldBaseURL = document.getElementById('div_id_base_url');
    const fieldNeedsSetup = document.getElementById('div_id_needs_setup');
    const inputBaseURL = document.getElementById('id_base_url');
    const inputSubmit = document.getElementById('id_submit');
    let formLoader = form.querySelector('.loader');

    let api = window.browser || null;
    if (api === null && window.chrome) {
      api = window.chrome;
    }

    const updateForm = () => {
      if (inputBaseURL.value) {
        fieldBaseURL.classList.remove('d-none');
        fieldNeedsSetup.classList.add('d-none');

        inputSubmit.classList.remove('btn-primary');
        inputSubmit.classList.add('btn-secondary');
        inputSubmit.value = 'Log out';
      } else {
        fieldBaseURL.classList.add('d-none');
        fieldNeedsSetup.classList.remove('d-none');

        inputSubmit.classList.remove('btn-secondary');
        inputSubmit.classList.add('btn-primary');
        inputSubmit.value = 'Log in';
      }
    };

    const loadBaseURL = async (options) => {
      options = {
        initial: false,
        ...(options || {}),
      };

      formLoader.classList.remove('d-none');

      const storageResult = await api.storage.local.get(['baseURL']);

      if (storageResult.baseURL) {
        inputBaseURL.value = storageResult.baseURL;
      }

      if (options.initial === true) {
        formLoader.classList.add('d-none');
      }

      updateForm();

      return storageResult.baseURL || null;
    };

    const startPollingBaseURL = async () => {
      let timeout = null;

      formLoader.classList.remove('d-none');

      window.setTimeout(
        async () => {
          window.clearTimeout(timeout);

          const result = await loadBaseURL();

          if (result === null) {
            startPollingBaseURL();
          } else {
            formLoader.classList.add('d-none');
          }
        },
        5000,
      );
    };

    form.addEventListener('submit', (event) => {
      event.stopPropagation();
      event.preventDefault();

      if (inputBaseURL.value) {
        api.runtime.sendMessage({
          type: 'HotPocket:ExtensionOptions:logOut',
        });
        inputBaseURL.value = '';
      } else {
        api.runtime.sendMessage({
          type: 'HotPocket:ExtensionOptions:logIn',
        });
        startPollingBaseURL();
      }

      updateForm();

      return false;
    });

    loadBaseURL({initial: true});
  });
})();
