<script lang="ts">
import { onMount, tick } from "svelte";
import { browser } from "$app/environment";
import Popup from "$lib/Layout/Popup.svelte";
import { parseJsonStringWithSchemaOrDefault } from "$lib/Effect/json";
import { Schema } from "effect";

export let targetID = "easter-target";
export let id: number;

let visible = false;
let showPopup = false;
const clickedEggsSchema = Schema.Array(Schema.Number);
const readClickedEggs = () => [
	...parseJsonStringWithSchemaOrDefault(
		localStorage.getItem("easter2025ClickedEggs") || "[]",
		clickedEggsSchema,
		[],
	),
];

$: eggCount = browser ? readClickedEggs().length : 0;

onMount(() => {
	let intervalId: number | undefined;

	const updatePosition = async () => {
		await tick();

		const targetElement = document.getElementById(targetID);

		if (!targetElement) return;

		const clickedEggs = readClickedEggs();
		const eggVisual = document.getElementById(`egg-visual-${targetID}-${id}`);
		const eggClick = document.getElementById(`egg-click-${targetID}-${id}`);
		const pageWidth = document.documentElement.clientWidth;

		visible = !clickedEggs.includes(id) && clickedEggs.length < 4;

		if (eggVisual && eggClick) {
			const verticalPosition = targetElement.offsetHeight * 0.9;
			const eggWidthPercent = (100 / pageWidth) * 100;
			const horizontalPosition =
				targetElement.offsetWidth - eggWidthPercent / 2;

			eggVisual.style.top = `${verticalPosition}px`;
			eggVisual.style.left = `${horizontalPosition}px`;
			eggVisual.style.zIndex = "-1";
			eggClick.style.top = `${verticalPosition}px`;
			eggClick.style.left = `${horizontalPosition}px`;
			eggClick.style.zIndex = "9999";
		}
	};

	intervalId = setInterval(updatePosition, 100) as unknown as number;

	updatePosition();

	return () => {
		if (intervalId) clearInterval(intervalId);
	};
});

const handleClick = (event: MouseEvent) => {
	if (event.button === 0) {
		const clickedEggs = readClickedEggs();

		if (!clickedEggs.includes(id)) {
			clickedEggs.push(id);
			localStorage.setItem(
				"easter2025ClickedEggs",
				JSON.stringify(clickedEggs),
			);
		}

		visible = false;

		if (clickedEggs.length >= 3) showPopup = true;

		umami.track("Easter Egg Clicked", { id });
	} else if (event.button === 1) {
		visible = true;

		localStorage.setItem("easter2025ClickedEggs", "[]");
	}
};

const copyCode = (source: string) => {
	navigator.clipboard.writeText(
		`<img src="${source}" alt="due.moe × AniList Badges Badge Prize" width="200px">`,
	);
};

const onLeavePopup = () => {
	showPopup = false;

	const clickedEggs = readClickedEggs();

	clickedEggs.push(-1);
	localStorage.setItem("easter2025ClickedEggs", JSON.stringify(clickedEggs));
};
</script>

{#if visible}
  <img
    id="egg-visual-{targetID}-{id}"
    src="https://images.vexels.com/media/users/3/162149/isolated/preview/7f9f0546b21308e4851956e9c15313c9-egg-easter-painted-easter-egg-easter-egg-spot-pattern-stripe-flat.png"
    alt="Easter Egg"
    loading="lazy"
    decoding="async"
    class="egg"
  />

  <div
    id="egg-click-{targetID}-{id}"
    role="button"
    tabindex="0"
    onmousedown={handleClick}
    class="egg click-layer"
  ></div>
{/if}

{#if eggCount == 3 || showPopup}
  <Popup fullscreen center onLeave={onLeavePopup}>
    <div class="event-popup">
      <div class="event-popup-banner">
        <a
          href={'#'}
          onclick={() =>
            copyCode(
              'https://files.anilist-badges.com/badges/events/2025/04/20-Easter-2025-Epexity-event-banner-1.png'
            )}
        >
          <img
            src="https://files.anilist-badges.com/badges/events/2025/04/20-Easter-2025-Epexity-event-banner-1.png"
            alt="Banner"
            loading="lazy"
            decoding="async"
          />
        </a>
      </div>

      <div class="event-popup-text">
        Congratulations! You've found all the eggs! Here are some prizes for you to claim!
        <br />
        Make sure to mention due.moe and AniList Badges in your posts so others can participate!
        <br />
        <div class="opaque">Click a banner/badge to copy its claim-code</div>
      </div>

      <div class="event-popup-badges">
        <a
          href={'#'}
          onclick={() =>
            copyCode(
              'https://files.anilist-badges.com/badges/events/2025/04/20-Easter-2025-Basurahan-1.png'
            )}
        >
          <img
            src="https://files.anilist-badges.com/badges/events/2025/04/20-Easter-2025-Basurahan-1.png"
            alt="Badge 1"
            loading="lazy"
            decoding="async"
          />
        </a>

        <a
          href={'#'}
          onclick={() =>
            copyCode(
              'https://files.anilist-badges.com/badges/events/2025/04/20-Easter-2025-Dxvxdffm-1.png'
            )}
        >
          <img
            src="https://files.anilist-badges.com/badges/events/2025/04/20-Easter-2025-Dxvxdffm-1.png"
            alt="Badge 2"
            loading="lazy"
            decoding="async"
          />
        </a>
      </div>

      <div class="event-popup-footer opaque">due.moe × AniList Badges</div>
    </div>
  </Popup>
{/if}

<style lang="scss">
  .egg {
    position: absolute;
    width: 100px;
    height: 100px;
    transform: rotate(15deg);
  }

  .click-layer {
    cursor: pointer;
    background: transparent;
    z-index: 9999;
  }

  .event-popup {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .event-popup-banner {
    max-width: 37.5vw;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 1rem;
  }

  .event-popup-text {
    margin-bottom: 1.5rem;
    text-align: center;
  }

  .event-popup-badges {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
    align-items: center;

    img {
      width: 175px;
      border-radius: 8px;
    }
  }
</style>
