import { handleHtml } from '../helpers/athena-global-helper.js';
import { athenaConfig, athenaConfigOptions } from '../athena-config.js';

let globalSuffix = null;

export function refreshDidYouMean(
    external = false
)
{
    if(external && globalSuffix === 'search') return;

    const didYouMeanContainer = document.querySelector(`#athena-did-you-mean__container-${globalSuffix}`);
    if(!didYouMeanContainer) return;
    didYouMeanContainer?.remove();
}

function removeDidYouMeanListener()
{
    const didYouMeanX = document.querySelector(`#did-you-mean__x-${globalSuffix}`);
    if(!didYouMeanX) return;
    didYouMeanX?.addEventListener('click', (event) => {
        globalSuffix = event.currentTarget.dataset.suffix;
        refreshDidYouMean();
    });
}

function redirectToSearch(
    keywordText
)
{
    if (athenaConfigOptions.queryOptions['query']) {
        const queries = athenaConfigOptions.queryOptions['query'];

        let finalQuery = `${athenaConfig.formUrl}?q=` + encodeURIComponent(keywordText);

        for (const queryKey in queries) {
            if (queryKey !== 'service' && queryKey !== 'q') {
                finalQuery += `&${queryKey}=${queries[queryKey]}`;
            }
        }

        window.location.href = finalQuery;
    } else {
        window.location.href = `${athenaConfig.formUrl}?q=` + encodeURIComponent(keywordText);
    }
}

function clickDidYouMeanKeywordListener()
{
    const didYouMeanKeywords = document.querySelectorAll(`.did-you-mean-query__item-${globalSuffix}`);
    if(!didYouMeanKeywords.length) return;

    didYouMeanKeywords.forEach(didYouMeanKeyword => {
        didYouMeanKeyword?.addEventListener('click', (event) => {
            const keywordText = event.target.dataset.text || null;
            if(!keywordText) return;

            redirectToSearch(keywordText);
        });
    });
}

export default function (
    response,
    container,
    suffix
)
{
    globalSuffix = suffix;

    if(!response) return;

    if(!container) {
        console.error('Athena XAI: No Container provided for did you mean functionality!');
        return;
    }

    const { queries, title } = response;
    if(!queries.length) return;
    refreshDidYouMean();

    container.prepend(
        handleHtml(
            `<div id="athena-did-you-mean__container-${suffix}">
                        <div id="did-you-mean__title-container-${suffix}">
                            <span id="did-you-mean__title-${suffix}">${title}</span>
                        </div>
                        <div id="did-you-mean__queries-container-${suffix}"></div>
                        <div id="did-you-mean__x-${suffix}" data-suffix="${suffix}">
                            <svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M1 1.36914L4.5 4.86914M8 8.36914L4.5 4.86914M4.5 4.86914L8 1.36914L1 8.36914" stroke="#4F4F69" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </div>
                  </div>`
        , `#athena-did-you-mean__container-${suffix}`)
    );

    const queriesContainer = document.querySelector(`#did-you-mean__queries-container-${suffix}`);
    if(!queriesContainer) {
        console.error('Athena XAI: No queries container found in did you mean functionality!')
        return;
    }

    queries.forEach((query, index) => {
        queriesContainer.append(
            handleHtml(`
                    <div class="did-you-mean-item__container-${suffix}">
                        <span id="did-you-mean-query__item-${index}-${suffix}" class="did-you-mean-query__item-${suffix}" style="font-style: italic;" data-text="${query}">'${query}'</span>
                        ${index === queries.length - 1 ? 
                            `<span class="did-you-mean-question__mark-${suffix}">?</span>` :
                            `<span class="did-you-mean-query__separator-${suffix}">${athenaConfig.didYouMeanSeparator}</span>`
                        }
                    </div>
                `,
                `.did-you-mean-item__container-${suffix}`
            )
        );
    });

    removeDidYouMeanListener();
    clickDidYouMeanKeywordListener();
}