<script lang="ts">
  import { run } from 'svelte/legacy';

  import { browser } from '$app/environment';
  import { onMount } from 'svelte';

  interface Props {
    onLeave?: any;
    card?: boolean;
    smallCard?: boolean;
    fullscreen?: boolean;
    show?: boolean;
    locked?: boolean;
    center?: boolean;
    children?: import('svelte').Snippet;
  }

  let {
    onLeave = () => {
    return;
  },
    card = true,
    smallCard = false,
    fullscreen = false,
    show = $bindable(true),
    locked = false,
    center = false,
    children
  }: Props = $props();

  const handleClickOutside = (event: any) => {
    if (!locked && event.target.classList.contains('popup')) {
      show = false;

      onLeave();
    }
  };

  onMount(() => {
    if (browser) document.body.style.overflow = 'auto';
  });

  run(() => {
    if (browser) {
      document.body.style.overflow = 'auto';

      if (show) document.body.style.overflow = 'hidden';
      else document.body.style.overflow = 'auto';
    }
  });
</script>

<svelte:window onclick={handleClickOutside} />

{#if show}
  <div class={`popup ${fullscreen ? 'popup-fullscreen' : ''}`}>
    <span
      class={`${card ? `card ${smallCard ? 'card-small' : ''}` : ''} ${center ? 'centered' : ''}`}
    >
      {@render children?.()}
    </span>
  </div>
{/if}

<style>
  .popup {
    z-index: 3;
  }

  .centered {
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
