/*!
 * 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('PreauthForm');
    form.addEventListener('submit', (event) => {
      event.stopPropagation();
      event.preventDefault();

      const inputBaseURL = document.getElementById('id_base_url');
      const baseURL = inputBaseURL.value;

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

      api.runtime.sendMessage({
        type: 'HotPocket:Extension:setBaseURL',
        result: baseURL,
      });

      const loginURL = new URL('/integrations/extension/authenticate/', inputBaseURL.value);
      window.location.replace(loginURL.toString());

      return false;
    });
  });
})();
