import { getServerClass } from './instances.js';

export async function fetchProfile(handle, options = {}) {
    const { returnData = null, createCard = false } = options;

    try {
        const data = await fetchProfileViaMastodon(handle);

        if (returnData) {
            return data;
        } else if (createCard) {
            const url = new URL(data.url);
            const card = createAccountCard(data, data.url, url.hostname);
            return { card, data };
        }
    } catch (error) {
        console.error('Fehler beim Abrufen des Profils:', error);
        throw error;
    }
}

async function fetchProfileViaMastodon(handle) {
    const lookupUrl = `https://kirche.social/api/v1/accounts/lookup?acct=${handle}`;

    const response = await fetch(lookupUrl);
    if (!response.ok) throw new Error(`Mastodon-Profil ${handle} nicht gefunden`);
    return await response.json();
}

export function createAccountCard(data, href, instance) {
    const serverClass = getServerClass(instance);
    const link = document.createElement('a');
    link.classList.add('account-card-link');
    link.href = href;
    link.target = '_blank';

    // Haupt-Container der Karte
    const card = document.createElement('div');
    card.classList.add('account-card');

    // Header-Bereich der Karte (Avatar + Info)
    const headerContainer = document.createElement('div');
    headerContainer.classList.add('account-card-header');

    // Avatar
    const avatarImage = document.createElement('img');
    avatarImage.classList.add('account-avatar');
    avatarImage.alt = data.avatar ? `Profilbild von ${data.username}` : 'Profilbild nicht verfügbar';
    avatarImage.src = data.avatar || '';

    if (serverClass) {
        avatarImage.classList.add(serverClass);
    }

    const infoContainer = document.createElement('div');
    infoContainer.classList.add('account-info');

    const displayNameElement = document.createElement('h3');
    displayNameElement.classList.add('display-name');
    displayNameElement.textContent = data.display_name || data.username;

    const handleElement = document.createElement('p');
    handleElement.classList.add('handle');
    handleElement.textContent = `@${data.username}`;

    const serverHandleElement = document.createElement('span');
    serverHandleElement.classList.add('server-handle');
    serverHandleElement.textContent = `@${instance}`;

    if (serverClass) {
        serverHandleElement.classList.add(serverClass);
    }

    handleElement.appendChild(serverHandleElement);

    infoContainer.appendChild(displayNameElement);
    infoContainer.appendChild(handleElement);

    headerContainer.appendChild(avatarImage);
    headerContainer.appendChild(infoContainer);

    const contentContainer = document.createElement('div');
    contentContainer.classList.add('account-card-content');

    const noteElement = document.createElement('p');
    noteElement.classList.add('note');
    noteElement.innerHTML = data.note || '<p>Keine Beschreibung verfügbar.</p>';
    contentContainer.appendChild(noteElement);

    const footerContainer = document.createElement('div');
    footerContainer.classList.add('account-card-footer');

    const followerCount = document.createElement('div');
    followerCount.classList.add('follower-count');

    const followerLine1 = document.createElement('span');
    followerLine1.classList.add('line1');
    followerLine1.textContent = 'Follower';

    const followerLine2 = document.createElement('span');
    followerLine2.classList.add('line2');
    followerLine2.textContent = data.followers_count || '0';

    followerCount.appendChild(followerLine1);
    followerCount.appendChild(document.createElement('br'));
    followerCount.appendChild(followerLine2);

    const lastPostContainer = document.createElement('div');
    lastPostContainer.classList.add('last-post');

    const lastPostLine1 = document.createElement('span');
    lastPostLine1.classList.add('line1');
    lastPostLine1.textContent = 'letzter Beitrag';

    const formattedDate = formatLastPostDate(data.last_status_at); // Datum formatieren

    if (formattedDate !== 'hide') {
        const lastPostLine2 = document.createElement('span');
        lastPostLine2.classList.add('line2');
        lastPostLine2.textContent = formattedDate;

        lastPostContainer.appendChild(lastPostLine1);
        lastPostContainer.appendChild(document.createElement('br'));
        lastPostContainer.appendChild(lastPostLine2);

        footerContainer.appendChild(followerCount);
        footerContainer.appendChild(lastPostContainer);
    } else {
        footerContainer.appendChild(followerCount);
    }

    card.appendChild(headerContainer);
    card.appendChild(contentContainer);
    card.appendChild(footerContainer);

    link.appendChild(card);

    return link;
}

function formatLastPostDate(lastStatusAt) {
    if (!lastStatusAt) return 'Keine Beiträge';

    const postDate = new Date(lastStatusAt);
    const currentDate = new Date();

    const timeDiff = currentDate - postDate;
    const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

    if (daysDiff === 0) {
        return 'heute';
    } else if (daysDiff === 1) {
        return 'gestern';
    } else if (daysDiff > 1 && daysDiff <= 20) {
        return `vor ${daysDiff} Tagen`;
    } else {
        return 'hide';
    }
}