const apiUrl = 'https://kirche.social/api/v1/timelines/tag/fedikirche?limit=20';
const defaultInstance = 'kirche.social';

export async function loadPostwall() {
    const container = document.getElementById('postswall-container');

    const scrollStep = 300; // Definiert die Scrollweite in Pixeln

    // Links- und Rechtspfeile definieren
    const arrowLeft = document.getElementById('arrow-left');
    const arrowRight = document.getElementById('arrow-right');

    if (arrowLeft && arrowRight) {
        arrowLeft.addEventListener('click', () => {
            container.scrollBy({ left: -scrollStep, behavior: 'smooth' });
        });

        arrowRight.addEventListener('click', () => {
            container.scrollBy({ left: scrollStep, behavior: 'smooth' });
        });
    }

    // Posts laden
    async function fetchPosts() {
        try {
            const response = await fetch(apiUrl);
            if (!response.ok) {
                throw new Error('Fehler beim Laden der Posts');
            }
    
            const posts = await response.json();
            renderPosts(posts);
    
            // Button hinzufügen
            addReadMoreButton();
        } catch (error) {
            console.error('Fehler:', error);
            container.innerHTML = '<p>Fehler beim Laden der Posts.</p>';
        }
    }

    // Posts rendern
    function renderPosts(posts) {
        container.innerHTML = ''; // Vorherige Inhalte leeren

        posts.forEach(post => {
            const postElement = document.createElement('a');
            postElement.classList.add('post');
            postElement.href = post.url; // Link zum Originalpost
            postElement.target = '_blank';
            postElement.rel = 'noopener noreferrer';
            postElement.setAttribute('aria-label', 'Zum Originalpost auf Mastodon');
        
            // Zeitstempel berechnen
            const postDate = new Date(post.created_at);
            const timeAgo = getTimeAgo(postDate);
    
            let content = post.content || 'Kein Inhalt verfügbar.';
            const author = post.account.display_name || post.account.username;

            // Prüfen, ob der Username den Serverteil enthält
            let username = post.account.acct;
            if (!username.includes('@')) {
                username = `${username}@${defaultInstance}`;
            }
            username = `@${username}`;

            const avatar = post.account.avatar || 'src/assets/default-avatar.png';
        
            // Links deaktivieren
            const tempContainer = document.createElement('div');
            tempContainer.innerHTML = content;
    
            const links = tempContainer.querySelectorAll('a');
            links.forEach(link => {
                link.removeAttribute('href');
                link.style.pointerEvents = 'none';
                link.style.color = 'blue';
                link.style.textDecoration = 'underline';
            });
    
            // Bilder bearbeiten
            const images = tempContainer.querySelectorAll('img');
            images.forEach(img => {
                img.style.maxHeight = '200px';
                img.style.width = 'auto';
                img.style.display = 'block';
                img.style.margin = '10px 0';
            });
    
            content = tempContainer.innerHTML;
    
            const mediaAttachments = post.media_attachments || [];
            let mediaHTML = '';
            mediaAttachments.forEach(media => {
                if (media.type === 'image') {
                    mediaHTML += `
                        <img src="${media.url}" alt="Medienanhang" style="max-height: 200px; width: auto; display: block; margin: 10px 0;">
                    `;
                }
            });
    
            postElement.innerHTML = `
                <div class="post-header">
                    <img src="${avatar}" alt="${author}" class="avatar">
                    <div class="post-author">
                        <span class="post-authorname">${author}</span>
                        <span class="post-username">${username}</span>
                    </div>
                    <span class="post-timestamp">${timeAgo}</span>
                </div>
                <div class="post-content">${content}</div>
                <div class="post-media">${mediaHTML}</div>
                <div class="post-footer">…</div>
            `;
            container.appendChild(postElement);
        });
    }

    // Lade die Posts
    fetchPosts();
}

// Zeitberechnung für Posts
function getTimeAgo(date) {
    const now = new Date();
    const secondsAgo = Math.floor((now - date) / 1000);

    if (secondsAgo < 60) {
        return `${secondsAgo} Sek.`;
    } else if (secondsAgo < 3600) {
        const minutes = Math.floor(secondsAgo / 60);
        return `${minutes} Min.`;
    } else if (secondsAgo < 86400) {
        const hours = Math.floor(secondsAgo / 3600);
        return `${hours} Std.`;
    } else {
        const days = Math.floor(secondsAgo / 86400);
        return `${days} T.`;
    }
}

// "Lese weiter"-Button hinzufügen
function addReadMoreButton() {
    const container = document.getElementById('postswall-container');
    const readMoreButton = document.createElement('a');
    readMoreButton.href = 'https://kirche.social/tags/fedikirche';
    readMoreButton.target = '_blank';
    readMoreButton.rel = 'noopener noreferrer';
    readMoreButton.classList.add('read-more-button');
    readMoreButton.innerText = 'weiterlesen';
    container.appendChild(readMoreButton);
}
