<script lang="ts">
  import { page } from '$app/state';
  import { onDestroy, onMount } from 'svelte';

  let _target = $derived(page.url.searchParams.get('next') || '/');
  let target = $derived(
    new URL(_target, page.url.href).host !== page.url.host ? '/' : _target
  );
  let loopDetected = $state(false);
  let mounted = $state(false);
  onMount(() => {
    try {
      if (
        Number(
          sessionStorage.getItem('lastLoginRedirect') ?? Date.now().toString()
        ) +
          1000 >
        Date.now() - 2500
      ) {
        if (sessionStorage.getItem('loopCheck')) {
          loopDetected = true;
        }
        setTimeout(() => sessionStorage.setItem('loopCheck', '1'), 100);
      } else {
        sessionStorage.removeItem('loopCheck');
      }
      sessionStorage.setItem('lastLoginRedirect', Date.now().toString());
    } catch (error) {
      console.warn('Loop Detect Error:', error);
    }
    mounted = true;
  });
  onDestroy(() => (mounted = false));
</script>

<svelte:head>
  {#if !loopDetected}
    <noscript>
      <meta http-equiv="refresh" content="0.1; url={target}" />
    </noscript>
  {/if}
  {#if mounted && !loopDetected}
    <meta http-equiv="refresh" content="0.1; url={target}" />
  {/if}
</svelte:head>

{#if loopDetected}
  <h2 class="text-xl">Loop Detected</h2>
  <p>
    We detected a possible redirect loop and as such did not automatically
    continue.
  </p>
  <p>
    To continue anyway, click <a
      href={target}
      onclick={() => {
        loopDetected = false;
        sessionStorage.setItem('lastLoginRedirect', Date.now().toString());
        sessionStorage.removeItem('loopCheck');
      }}>here</a
    >.
  </p>
{:else}
  <h2 class="text-xl">Redirecting...</h2>
  <p>If nothing happens, click <a href={target}>here</a>.</p>
{/if}
