import {axiosInstance} from "./bootstrap";
import "../sass/app.scss";
import Account from "./svelte/Account.svelte";
import Channel from "./svelte/Channel.svelte";
import * as bootstrap from "bootstrap";
import Mustache from "mustache";

Mustache.escape = function (value) {
    return value;
};

function enableTooltipsAnywhere() {
    // Enable tooltips everywhere
    let tooltipTriggerList = [].slice.call(
        document.querySelectorAll('[data-bs-toggle="tooltip"]')
    );
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// Define all components
const entryComponents = {
    account: Account,
    channel: Channel,
};

let loadedComponents = [];

let loadSvelte = function () {
    loadedComponents.map((comp) => comp.$destroy());
    loadedComponents = [];

    const elements = document.body.querySelectorAll(".lucent-component");
    if (elements.length === 0) {
        return;
    }
    const loadElement = function (element) {
        const componentId = element.attributes["data-layout"].value;
        const [_, component] = Object.entries(entryComponents).find(
            ([key, _]) => componentId === key
        );
        if (!component) {
            return [];
        }

        const jsonData = document.getElementById(
            "json-" + componentId
        ).innerHTML;
        const props = JSON.parse(jsonData);
        props.axios = axiosInstance;
        const compOptions = {
            target: element,
            props: props,
        };

        loadedComponents = [...loadedComponents, new component(compOptions)];
    };
    Array.from(elements).map(loadElement);
};

// document.addEventListener("turbo:load", loadSvelte);
document.addEventListener("DOMContentLoaded", loadSvelte);
document.addEventListener("DOMContentLoaded", enableTooltipsAnywhere);
