<template>
    <div id="map" :class="isDark ? 'dark' : ''"></div>
</template>


<script>
import dark from '../plugins/dark.ts';
import walsLanguages from '../assets/languages.csv';
import locales from '../locale/locales.ts';
import { clearUrl } from '~/src/helpers.ts';

const MOBILE_BREAKPOINT = 992;

const localesByWalsCode = locales.reduce((acc, language) => {
    if (language.walsCode && language.published) {
        acc[language.walsCode] = language;
    }
    return acc;
}, {});

export default dark.extend({
    async mounted() {
        await this.$loadStylesheet(
            'leaflet',
            'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
        );
        await this.$loadScript(
            'leaflet',
            'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js',
        );
        await this.$loadScript(
            'tinyworldmap',
            'https://tinyworldmap.com/dist/v3/tiny-world-borders.js',
        );

        const pos = window.innerWidth < MOBILE_BREAKPOINT ? [45, 15] : [40, 65];
        const map = window.L.map('map', { attributionControl: false }).setView(pos, 3);

        window.L.control.attribution({ position: 'bottomright' })
            .addAttribution('&copy; <a href="https://doi.org/10.5281/zenodo.7385533" target="_blank" title="Dryer, Matthew S. & Haspelmath, Martin (eds.) 2013. The World Atlas of Language Structures Online. Leipzig: Max Planck Institute for Evolutionary Anthropology.">WALS</a>')
            .addAttribution('<a href="https://wals.info" target="_blank">wals.info</a>')
            .addTo(map);

        new window.L.GridLayer.TinyWorld({ maxZoom: 19 }).addTo(map);

        for (const walsLanguage of walsLanguages) {
            if (!localesByWalsCode.hasOwnProperty(walsLanguage.id)) {
                continue;
            }
            const locale = localesByWalsCode[walsLanguage.id];

            const circle = window.L.circle([walsLanguage.latitude, walsLanguage.longitude], {
                color: '#971064',
                fillColor: '#c71585',
                fillOpacity: 0.5,
                radius: 300000 * Math.cos(walsLanguage.latitude * Math.PI / 180),  // compensate for Mercator projection
            }).addTo(map);
            circle.bindTooltip(`<strong>${locale.name}</strong><br/>${clearUrl(locale.url)}`);
            circle.on('click', () => {
                window.open(locale.url);
            });
        }
    },
});
</script>

<style lang="scss">
#map {
    height: 500px;
    z-index: 0;
    &.dark {
        .leaflet-layer,
        .leaflet-control-zoom-in,
        .leaflet-control-zoom-out,
        .leaflet-control-attribution {
            filter: invert(100%) hue-rotate(180deg) brightness(95%) contrast(90%);
            svg, img {
                filter: invert(100%) hue-rotate(180deg) brightness(95%) contrast(90%);
            }
        }
    }
}
</style>
