<script lang="ts">
    import Navbar from "../../Navbar.svelte";
    import { unmined } from "../../stores";

    import {
        ol_proxy,
        type UnminedOptions,
        type UnminedRegions,
    } from "./unmined";

    export let id = "map";

    type Metadata = {
        properties: UnminedOptions;
        regions: UnminedRegions;
    };

    async function get_unmined() {
        if ($unmined === null) {
            let resp = await fetch("map/unmined.js");
            let code = await resp.text();
            $unmined = Function("ol", code).call({}, ol_proxy);
        }

        let resp = await fetch("map/metadata.js");
        let code = await resp.text();
        let meta: Metadata = Function(code).call({}); // TODO possibly vulnerable to prototype pollution
        return meta;
    }

    function setupMap(node: HTMLDivElement, metadata: Metadata) {
        $unmined.map(node.id, metadata.properties, metadata.regions);

        return {
            destroy() {
                if ($unmined.openlayersMap) {
                    $unmined.openlayersMap.setTarget(null);
                    $unmined.openlayersMap = null;
                }
            },
        };
    }
</script>

<div class="map-outer">
    <Navbar />
    {#await get_unmined() then metadata}
        <div class="map-target" {id} use:setupMap={metadata} />
    {:catch err}
        <div class="container">
            <article class="message is-danger mt-5">
                <div class="message-header">
                    <p>Error loading map</p>
                </div>
                <div class="message-body">
                    <p>Something went wrong:</p>
                    <figure>
                        <pre>{err}</pre>
                    </figure>
                </div>
            </article>
        </div>
    {/await}
</div>

<style>
    .map-outer {
        display: flex;
        flex-direction: column;
        height: 100vh;
    }
    .map-target {
        flex-grow: 1;
        background-color: #e2e2e2;
    }
</style>
