<script lang="ts">
    import type { Preferences } from "$lib/stores/preferences";
    import { preferences } from "$lib/stores/preferences";
    import { onDestroy, onMount } from "svelte";
    import { browser } from "$app/environment";

    let pref: Preferences

    const unsubscribe = preferences.subscribe((value => {
        pref = value;
    }))

    onMount(() => {
        const threshold = Date.now() - 30*24*60*60*1000;
        const lastRequested = pref.telemetryRequested?.getTime() ?? 0;

        if (!pref.telemetry && lastRequested < threshold) {
            document.querySelector<HTMLDialogElement>("#analytics-consent")?.showModal();
        }
    })

    onDestroy(() => {
        unsubscribe();
    })

    // Setting Function Calls - Update to call new Store
    function setAcceptAnalytics() {
        preferences.update(current => ({
            ...current,
            telemetry: true,
            telemetryRequested: new Date(),
        }));
        document.querySelector<HTMLDialogElement>("#analytics-consent")?.close();
    }
    function setDenyAnalytics() {
        preferences.update(current => ({
            ...current,
            telemetry: false,
            telemetryRequested: new Date(),
        }));
        document.querySelector<HTMLDialogElement>("#analytics-consent")?.close();
    }

    // Reactively call telemetry script functions - Update to call new Store
    $: {
        if (browser) {
          if ($preferences.telemetry) {
                loadTelemetryScript();
          } else {
                removeTelemetryScript();
          }
        }
    }

    function loadTelemetryScript() {
        console.log("Activating telemetry script")
        if (browser) {
        if (document.querySelector("script[data-entity='owlboard-frontend']")) return; // Prevent duplicate loading

        const script = document.createElement("script");
        script.type = "module";
        script.dataset.entity = "owlboard-frontend";
        script.src = "https://liwan.fjla.uk/script.js";
        document.body.appendChild(script);
        }
    }

    function removeTelemetryScript() {
        console.log("Deactivating telemetry script")
        if (browser) {
        document.querySelector("script[data-entity='owlboard-frontend']")?.remove();
        }
    }
</script>

<dialog id="analytics-consent">
    <h1>Telemetry</h1>
    <p>
        OwlBoard collects <strong>anonymous</strong> usage data, such as the most visited pages. Any personal data is anonymized to ensure it cannot be linked to individuals.
    </p>
    <p>
        This data is used to focus efforts, improving the most used features.
    </p>
    <p>
        By selecting Accept, you are helping to steer OwlBoard's future - if
        you change your mind, head over to Settings.
    </p>
    <p>
        Nobody can be identified using any data stored, all data is available for
        all to see <a href="https://liwan.fjla.uk" target="_blank">here</a>.
    </p>
    <p>
        Further information can be found in the <a href="/more/privacy">Privacy Policy</a>.
    </p>
    <button class="modal-button" type="button" on:click={setAcceptAnalytics}>Accept</button>
    <button class="modal-button" id="deny-button" type="button" on:click={setDenyAnalytics}>Deny</button>
</dialog>

<style>
    ::backdrop {
        background-color: var(--main-bg-color);
        opacity: 75%;
    }

    #analytics-consent {
        width: 75vw;
        max-width: 700px;
        border-radius: 25px;
        background-color: var(--island-bg-color);
        opacity: 100;
        color: var(--island-text-color);
        border: none;
    }

    .modal-button {
        width: 25%;
        min-width: 120px;
        height: 40px;
        font-size: larger;
        margin: 5px;
        border-radius: 30px;
        background-color: var(--second-bg-color);
        color: var(--island-text-color);
        box-shadow: var(--box-shadow);
        border: none;
        font-family: urwgothic, sans-serif;
    }

    #deny-button {
        background-color: var(--main-bg-color);
    }
</style>