<script lang="ts">
import Spacer from "$lib/Layout/Spacer.svelte";
import Popup from "./Layout/Popup.svelte";
import announcementHash from "$stores/announcementHash";
import { env } from "$env/dynamic/public";
import identity from "$stores/identity";

const announcement = env.PUBLIC_ANNOUNCEMENT;
const dismissButton = env.PUBLIC_ANNOUNCEMENT_DISMISS;
const loggedIn = $identity !== undefined && $identity.id !== -2;

const hash = (s: string) =>
	s
		.split("")
		.reduce(
			(previous, current) =>
				((previous << 5) - previous + current.charCodeAt(0)) | 0,
			0,
		);

const dismiss = () => {
	if (announcement) announcementHash.set(hash(announcement));
};

const maxWidth = (input: string, max = 100) => {
	let output = "";
	let line = "";

	for (const word of input.split(" ")) {
		if (line.length + word.length > max) {
			output += line + "\n";
			line = "";
		}

		line += word + " ";
	}

	return output + line;
};
</script>

{#if loggedIn && announcement && $announcementHash !== hash(announcement) && $announcementHash !== 0}
  <Popup fullscreen onLeave={dismiss}>
    {#each maxWidth(announcement).split('\n') as line}
      {line}<br />
    {/each}

    <Spacer />

    <button onclick={dismiss} class="dismiss" data-umami-event="Dismiss Announcement"
      >{dismissButton || 'Dismiss'}</button
    >
  </Popup>
{/if}

<style>
  .dismiss {
    float: right;
  }
</style>
