<script lang="ts">
    import { _ } from "svelte-i18n"
    import { getContent, getArticles } from "../../api"
    import { generalInfo, currentLang, location } from "../../store"
    import { navigate } from "svelte-routing"

    import ArticlesList from "../widgets/ArticlesList.svelte"
    import ArticleDetails from "../routes/ArticleDetails.svelte"

    export let path: string

    let loading = true
    let content: Content
    let article: TibiArticle
    let connectedContentNotFound: boolean = false

    const loadContent = (type?: string) => {
        // Set default API call filter
        let filter = {
            locale: $currentLang,
            path,
        }

        // API call filter without locale if URL changed
        if (path !== content?.path) {
            delete filter.locale
        }

        // Changed filter to find simmilar content for changed language
        if (type === "changedLanguage" && content?.pages) {
            filter = {
                _id: { $in: content?.pages },
                locale: $currentLang,
            }
            delete filter.path
        }

        // Get content by API call
        let apiParams: APIParams = {
            filter,
        }

        loading = true
        getContent(apiParams)
            .then((c) => {
                if (c) {
                    if (type === "changedLanguage") {
                        let newPath = c.path + $location.search
                        window.history.pushState({}, document.getElementsByTagName("title")[0].innerHTML, newPath + "/")
                        path = newPath
                    }

                    connectedContentNotFound = false
                    content = c
                } else {
                    // Show message if not found simmilar content for changed language
                    if (filter.tags) {
                        connectedContentNotFound = true
                    }
                    content = null
                }

                // Redirect to HOME if no content has been found. So the page 404 content will never shown.
                if (!content) {
                    navigate("/")
                }
            })
            .finally(() => {
                loading = false
            })
    }

    const loadArticle = (type?: string) => {
        let pathParts = path.split("/")
        let slugOrId = pathParts[pathParts.length - 1].toString()

        // Set default API call filter

        let filter = {
            "article.general.locale": $currentLang,
            "article.content.slug": slugOrId,
        }

        // Changed filter to find simmilar content for changed language
        if (type === "changedLanguage") {
            // filter = {
            //     tags: { $in: content?.tags },
            //     locale: $currentLang,
            // }
            // delete filter["article.general.locale"]
            // delete filter["article.content.slug"]
        }

        // Get content by API call
        let apiParams: APIParams = {
            filter,
        }

        loading = true
        getArticles("articles", apiParams)
            .then((respoonse) => {
                article = respoonse[0]
            })
            .finally(() => {
                loading = false
            })
    }

    currentLang.subscribe(() => {
        if (content) {
            loadContent("changedLanguage")
        } else if (article) {
            loadArticle("changedLanguage")
        }
    })

    $: if (path) {
        content = null
        article = null

        // Update current language when lang in URL not equal to current language
        let pathParts = window.location.pathname.split("/")
        if (pathParts.length > 3 && $currentLang !== pathParts[1]) {
            $currentLang = pathParts[1]
        }

        if (window.location.pathname.endsWith("/")) {
            loadContent()
        } else {
            loadArticle()
        }
    }
</script>

<svelte:head>
    <title
        >{content?.name ? content?.name + " - " : ""}{content?.meta?.metaTitle
            ? content?.meta?.metaTitle
            : $generalInfo?.meta?.metaTitle}</title
    >
    <meta
        name="description"
        content="{content?.meta?.metaDescription
            ? content?.meta?.metaDescription
            : $generalInfo?.meta?.metaDescription}"
    />
    <meta
        name="keywords"
        content="{content?.meta?.metaKeywords
            ? content?.meta?.metaKeywords.replaceAll(' ', '')
            : $generalInfo?.meta?.metaKeywords.replaceAll(' ', '')}"
    />
    <meta
        name="robots"
        content="{content?.meta?.metaTagRobots ? content?.meta?.metaTagRobots : $generalInfo?.meta?.metaTagRobots}"
    />
    {#if $generalInfo?.person?.firstname || $generalInfo?.person?.lastname}
        <meta
            name="author"
            content="{$generalInfo?.person?.firstname ? $generalInfo?.person?.firstname : ''} {$generalInfo?.person
                ?.lastname
                ? $generalInfo?.person?.lastname
                : ''}"
        />
    {/if}
</svelte:head>

{#if loading}
    <!-- Loader -->
{:else if article}
    <ArticleDetails entry="{article}" />
{:else if content}
    <ArticlesList path="{path}" tags="{content?.tags}" />
{:else}
    <!-- <div class="page-404">
        <div>
            <Image
                collectionName="general"
                entryId="{$generalInfo.id}"
                file="{$generalInfo?.media?.brand}"
                alt="{$generalInfo?.meta?.metaTitle}"
                cssClass="brand"
            />
        </div>

        <h1>{$_("pageNotFound")}</h1>

        <p class="mb-md">
            {#if connectedContentNotFound}
                <div>
                    {@html $_("connectedContentNotFound", {
                        values: {
                            url: currentDomain + "/" + path,
                            lang: $_($currentLang) + ` (${$currentLang})`,
                        },
                    })}
                </div>
            {:else}
                <strong>
                    <a href="{currentDomain + '/' + path}">{currentDomain + "/" + path}</a>
                </strong>
            {/if}
        </p>
        <p>
            {@html $_("pageNotFoundInformation", {
                values: {
                    url: currentDomain,
                    backUrl: currentDomain + "/" + path,
                },
            })}
        </p>
    </div> -->
{/if}
