import { translator } from "../i18n/translator.js";
import { I18N_LOADED_EVENT } from "../i18n/i18nLoadedEvent.js";

function getLanguageToggle() {
    const toggle = document.createElement('template');
    toggle.id = 'language-toggle-template';
    toggle.innerHTML = `
<style>
    :host {
        display: inline-flex;
    }
    
    .icon {
        width: 1em;
        height: 1em;
        margin: 0.5em;
        flex: 0 0 auto;
    }
    
    @media (prefers-color-scheme: dark) {
        .icon {
            filter: invert(100%);
        }
    }

    select {
        background: none;
        border: none;
        font-family: var(--font-family), monospace;
    }
</style>

<label for="language-dropdown"></label>
<img class="icon" src="/assets/images/icons/language.svg" alt="Change language" data-i18n="languageToggle.change"/>
<select id="language-dropdown">
    <option value="en" data-i18n="lang.en">English</option>
    <option value="nl" data-i18n="lang.nl">Dutch</option>
</select>
    `;

    return toggle;
}

class LanguageToggle extends HTMLElement {
    constructor() {
        super();

        const templateContent = getLanguageToggle().content;
        const shadowRoot = this.attachShadow({ mode: 'open' });
        const languageToggle = templateContent.cloneNode(true);
        shadowRoot.appendChild(languageToggle);
    }

    connectedCallback() {
        const shadow = this.shadowRoot;

        const languageDropdown = shadow.querySelector('#language-dropdown');
        const languageIcon = shadow.querySelector('.icon');

        // Load preferred language
        languageDropdown.value = translator.prefferedLanguage;
        translator.load(null, shadow);

        // Change language on selection
        languageDropdown.addEventListener('change', () => {
            const language = languageDropdown.value;
            console.info(`[navbar] Setting language to: ${language}`);
            translator.setPreferredLanguage(language);
        });

        languageIcon.addEventListener('click', () => languageDropdown.showPicker());

        window.addEventListener(I18N_LOADED_EVENT, (event) => {
            console.log(`[language-toggle] i18nLoaded event received`);

            const translations = event.detail.translations;
            translator.translate(translations, shadow);
        });
    }
}

customElements.define('language-dropdown', LanguageToggle);
