<script lang="ts">
import { onMount } from "svelte";
import type { Badge } from "$lib/Database/SB/User/badges";
import ParallaxImage from "$lib/Image/ParallaxImage.svelte";
import Spacer from "$lib/Layout/Spacer.svelte";
import { cdn, thumbnail } from "$lib/Utility/image";
import root from "$lib/Utility/root";
import { databaseTimeToDate } from "$lib/Utility/time";
import locale from "$stores/locale";
import { classifyDesigner, classifySource } from "./badgeLinks";

export let selectedBadge: Badge | undefined;
export let onNext: () => void = () => undefined;
export let onPrevious: () => void = () => undefined;
export let hasNext: boolean;
export let hasPrevious: boolean;

let source = cdn(thumbnail(selectedBadge?.image || "")) || "";
let badgeReference: HTMLImageElement;

$: {
	if (selectedBadge?.image) {
		const image = new Image();

		image.src = cdn(selectedBadge.image) || "";
		image.onload = () => {
			source = image.src;
		};
	}
}

$: {
	if (selectedBadge)
		fetch(root(`/api/badges?incrementClickCount=${selectedBadge.id}`), {
			method: "PUT",
		});
}

onMount(() => {
	badgeReference = document.querySelector(
		".badge-container-image",
	) as HTMLImageElement;

	const handleClickOutside = (event: MouseEvent) => {
		if ((event.target as HTMLElement).classList.contains("popup"))
			selectedBadge = undefined;
	};

	document.addEventListener("click", handleClickOutside);

	return () => {
		document.removeEventListener("click", handleClickOutside);
	};
});

const onClick = (event: MouseEvent) => {
	event.preventDefault();

	if (
		event.clientX <
		badgeReference.getBoundingClientRect().left +
			badgeReference.getBoundingClientRect().width / 2
	) {
		onPrevious();
	} else {
		onNext();
	}
};
</script>

{#if selectedBadge}
  <div class="badge-preview">
    <div class="badge-preview-badge">
      {#if selectedBadge.image}
        <div role="img" class="badge-container">
          <a href={'#'} onclick={onClick} class="badge-container-image">
            <ParallaxImage
              {source}
              alternativeText={selectedBadge.description ?? ''}
              limit={100}
              duration={1500}
            />
          </a>
        </div>

        <Spacer />
      {/if}
    </div>

    <div class="badge-preview-information">
      {#if selectedBadge.time}
        {$locale().dateFormatter(databaseTimeToDate(selectedBadge.time))}

        {#if (selectedBadge.designer || selectedBadge.source || selectedBadge.post) && !selectedBadge.description}
          <Spacer />
        {:else if selectedBadge.description}
          <br />
        {/if}
      {/if}

      {#if selectedBadge.description}
        {selectedBadge.description}

        <Spacer />
      {/if}

      {#if selectedBadge.designer}
        <b>{$locale().badgePreview?.designer}</b>

        {@const designerLink = classifyDesigner(selectedBadge.designer)}
        {#if designerLink.href}
          <a href={designerLink.href} target="_blank" rel="noopener noreferrer">
            @{designerLink.label}
          </a>
        {:else}
          @{designerLink.label}
        {/if}

        <br />
      {/if}

      {#if selectedBadge.post && selectedBadge.post !== '#'}
        <b
          >{selectedBadge.post.includes('forum')
            ? $locale().badgePreview?.forum
            : $locale().badgePreview?.activity}:</b
        >

        <a href={selectedBadge.post} target="_blank">
          {selectedBadge.post}
        </a>

        <br />
      {/if}

      {#if selectedBadge.source}
        <b>{$locale().badgePreview?.source}</b>

        {@const sourceLink = classifySource(selectedBadge.source)}
        {#if sourceLink.href}
          <a href={sourceLink.href} target="_blank" rel="noopener noreferrer">
            {sourceLink.label}
          </a>
        {:else}
          {sourceLink.label}
        {/if}

        <br />
      {/if}

      {#if selectedBadge.category}
        <b>{$locale().badgePreview?.category}</b>

        <a href={`?category=${selectedBadge.category}`} onclick={() => (selectedBadge = undefined)}>
          {selectedBadge.category}
        </a>

        <br />
      {/if}

      <b>{$locale().badgePreview?.sauceNAO}</b>
      <a href={`https://saucenao.com/search.php?url=${selectedBadge.image}`} target="_blank">
        {$locale().badgePreview?.search}
      </a>

      <div class="badge-preview-seek">
        {#if hasPrevious}
          <button onclick={onPrevious}>{$locale().badgePreview?.previous}</button>
        {/if}

        {#if hasNext}
          <button onclick={onNext} style="float: right;">{$locale().badgePreview?.next}</button>
        {/if}
      </div>
    </div>
  </div>
{/if}

<style lang="scss">
  @use "breakpoints" as *;

  :global(.badge-preview img) {
    border-radius: 8px;
    max-height: 50vh;
    height: auto;
  }

  .badge-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .badge-preview {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    gap: 1rem;
  }

  @media (max-width: $bp-md) {
    .badge-preview {
      flex-direction: column;
    }
  }

  .badge-preview-seek {
    padding-top: 2rem;
  }
</style>
