<script setup lang="ts">
import { useNuxtApp } from 'nuxt/app';

import type Answer from '~/components/Answer.vue';
import useConfig from '~/composables/useConfig.ts';
import useHash from '~/composables/useHash.ts';
import useSimpleHead from '~/composables/useSimpleHead.ts';

type AnswerInstanceType = InstanceType<typeof Answer>;

definePageMeta({
    translatedPaths: (config) => translatedPathByConfigModule(config.faq),
});

const { $translator: translator } = useNuxtApp();
useSimpleHead({
    title: translator.translate('faq.headerLong'),
}, translator);

const { handleHash, setHash } = useHash();

const config = useConfig();

const filter = ref('');

const elementByHash = ref<Map<string, AnswerInstanceType>>(new Map());
const normaliseHash = (hash: string): string => {
    return hash.replaceAll('-', '_');
};

onMounted(() => {
    handleHash('', (hash) => {
        elementByHash.value.get(normaliseHash(hash))?.focus();
    }, false);
});
</script>

<template>
    <Page>
        <LinksNav v-if="config.links.enabled" />

        <h2 class="mb-4">
            <Icon v="map-marker-question" />
            <T>faq.headerLong</T>
        </h2>

        <FilterBar v-model="filter" />

        <details v-show="!filter || $t('home.mission.header').toLowerCase().includes(filter.toLowerCase())" class="border mb-3" open>
            <summary class="d-none"></summary>
            <div class="px-3">
                <Mission />
            </div>
        </details>

        <AdPlaceholder :phkey="['content-0', 'content-mobile-0']" />

        <section itemscope itemtype="https://schema.org/FAQPage">
            <Answer
                v-for="question in Object.keys($t('faq.questions'))"
                v-show="!filter ||
                    $t(`faq.questions.${question}.question`).toLowerCase().includes(filter.toLowerCase()) ||
                    $t<string[]>(`faq.questions.${question}.answer`).join('|').toLowerCase().includes(filter.toLowerCase())"
                :id="question"
                :key="question"
                :ref="(el) => el
                    ? elementByHash.set(normaliseHash(question), el as AnswerInstanceType)
                    : elementByHash.delete(normaliseHash(question))"
                :question="question"
                name="faq"
                @click="setHash('', question)"
            />
        </section>

        <AdPlaceholder :phkey="['content-1', 'content-mobile-1']" />

        <section>
            <Share :title="$t('faq.headerLong')" />
        </section>
    </Page>
</template>

<style lang="scss" scoped>
    @import "assets/variables";

    details {
        summary {
            font-weight: bold;
        }
        &[open] {
            box-shadow: $box-shadow;
        }
    }
</style>
