import { fetchProfile } from './profile-utils.js';
import { extractHostname, getServerClass } from './instances.js';

export function createRecommendationPopup(accounts, title, authors, description) {
    const template = document.getElementById('popup-template').content.cloneNode(true);

    const popup = template.querySelector('.recommendation-popup');
    popup.querySelector('h3').textContent = title;

    // Anzahl der Accounts anzeigen
    const profileCount = popup.querySelector('.profile-line2');
    if (profileCount) {
        profileCount.textContent = `${accounts.length}`;
    }

    // Autoren hinzufügen
    const authorsContainer = popup.querySelector('.authors-container');
    populateAuthorsContainer(authorsContainer, authors);

    // Informationen in die Kachel einfügen
    const infoTile = popup.querySelector('.info-tile');
    if (infoTile) {
        // Beschreibung hinzufügen
        const descriptionElement = document.createElement('div');
        descriptionElement.classList.add('description');
        descriptionElement.textContent = description;
        infoTile.appendChild(descriptionElement);
    }

    document.documentElement.classList.add('html-no-scroll');
    history.pushState({ popupOpen: true }, null, '');

    // Event-Listener für den "Zurück"-Button hinzufügen
    const onPopState = () => {
        closePopup(popup, onPopState);
    };
    window.addEventListener('popstate', onPopState);

    // Schließen-Button
    const closeButton = popup.querySelector('.close-popup');
    closeButton.addEventListener('click', () => {
        closePopup(popup, onPopState);
    });

    const body = popup.querySelector('.account-list');
    const spinner = popup.querySelector('#loading-spinner'); // Spinner-Element

    // Spinner anzeigen
    spinner.style.display = 'block';

    // Lade Profile parallel und sortiere nach letzter Aktivität
    const fetchProfilesSorted = async (accounts) => {
        const profiles = await Promise.all(
            accounts.map(async (accountUrl) => {
                try {
                    const { card, data } = await fetchProfile(accountUrl, { createCard: true });
                    return { card, lastStatusAt: data.last_status_at };
                } catch (error) {
                    console.error(`Fehler beim Laden des Accounts: ${accountUrl}`, error);
                    return null;
                }
            })
        );

        // Entferne ungültige Profile und sortiere nach `last_status_at`
        return profiles
            .filter(profile => profile !== null)
            .sort((a, b) => {
                const dateA = new Date(a.lastStatusAt || 0);
                const dateB = new Date(b.lastStatusAt || 0);
                return dateB - dateA; // Neueste zuerst
            });
    };

    fetchProfilesSorted(accounts).then(sortedProfiles => {
        spinner.style.display = 'none'; // Spinner ausblenden

        // Karten in der sortierten Reihenfolge hinzufügen
        sortedProfiles.forEach(profile => {
            if (profile.card) {
                body.appendChild(profile.card);
            }
        });
    });

    popup.addEventListener('click', function (event) {
        if (event.target === popup) {
            closePopup(popup, onPopState);
        }
    });

    document.body.appendChild(popup);
    return popup;
}

function closePopup(popup, onPopState) {
    popup.remove();
    document.documentElement.classList.remove('html-no-scroll');
    window.removeEventListener('popstate', onPopState);
    history.back();
}


export function populateAuthorsContainer(authorsContainer, authors) {
    if (!authorsContainer) {
        console.error('Fehlendes Element: .authors-container. Bitte prüfen!');
        return;
    }

    authorsContainer.innerHTML = ''; // Container leeren

    if (authors && authors.length > 0) {
        const authorsToShow = authors.slice(0, 2); // Maximal zwei Autoren anzeigen
        const additionalAuthorsCount = authors.length - authorsToShow.length;

        authorsToShow.forEach(author => {
            const authorLink  = document.createElement('a');
            authorLink.classList.add('account');
            authorLink.target = '_blank'; // Link öffnet neues Fenster

            fetchProfile(author, { returnData: true }).then((data) => {
                authorLink.href = data.url;

                const avatarImage = document.createElement('img');
                avatarImage.classList.add('account-avatar');
                avatarImage.alt = data.display_name || data.name || 'Profilbild nicht verfügbar';
                avatarImage.src = data.avatar || '';

                authorLink.appendChild(avatarImage);

                // Server-Klasse für Avatar hinzufügen
                const hostname = extractHostname(author);
                const serverClass = getServerClass(hostname);
                if (serverClass) {
                    avatarImage.classList.add(serverClass);
                }
            });

            authorsContainer.appendChild(authorLink);
        });

        // Hinweis auf zusätzliche Autoren
        if (additionalAuthorsCount > 0) {
            const additionalAuthorsText = document.createElement('span');
            additionalAuthorsText.classList.add('additional-authors');
            additionalAuthorsText.textContent = `+ ${additionalAuthorsCount}`;
            authorsContainer.appendChild(additionalAuthorsText);
        }
    }
}
