// people_profile_posts.js — Posts tab for People Profile (Phase 3)
// Shows all posts by the selected member as card list, sortable.

var PeopleProfilePosts = (function() {
    'use strict';

    let rendered = false;
    let currentSkoolId = null;
    let currentSort = 'date_desc';

    // Strip Skool mention syntax
    const cleanMentions = function(text) {
        return text.replace(/\[@([^\]]+)\]\(obj:\/\/user\/[^)]+\)/g, '@$1');
    };

    function render(skoolId, profileData) {
        // Avoid re-rendering if same person
        if (rendered && currentSkoolId === skoolId) return;
        rendered = true;
        currentSkoolId = skoolId;

        const container = document.getElementById('profile-posts-container');
        if (!container) return;

        const posts = profileData.posts || [];
        const comments = profileData.comments || [];
        const likedPosts = profileData.likedPosts || [];

        // Build unified feed
        const feedItems = [];

        for (const p of posts) {
            const meta = p.metadata ? JSON.parse(p.metadata) : {};
            feedItems.push({
                type: 'post',
                title: meta.title || p.name || '(Untitled)',
                content: meta.content ? (cleanMentions(meta.content).slice(0, 200)) : '',
                upvotes: p.upvotes || 0,
                commentCount: p.comments || 0,
                community: p.community_slug,
                timestamp: p.created_at || 0,
                skoolCreatedAt: p.skool_created_at || ''
            });
        }

        for (const c of comments) {
            const meta = c.metadata ? JSON.parse(c.metadata) : {};
            const content = cleanMentions(meta.content || '(No content)');
            feedItems.push({
                type: 'comment',
                title: null,
                content: content.length > 200 ? content.slice(0, 200) + '...' : content,
                upvotes: c.upvotes || 0,
                commentCount: 0,
                community: c.community_slug,
                timestamp: c.created_at || 0,
                skoolCreatedAt: c.skool_created_at || ''
            });
        }

        for (const lp of likedPosts) {
            const meta = lp.metadata ? JSON.parse(lp.metadata) : {};
            const isComment = lp.is_toplevel === 0;
            let displayText;
            if (isComment) {
                const content = cleanMentions(meta.content || '(No content)');
                displayText = content.length > 200 ? content.slice(0, 200) + '...' : content;
            } else {
                displayText = meta.title || lp.name || '(Untitled)';
            }
            feedItems.push({
                type: 'liked',
                title: isComment ? null : displayText,
                content: isComment ? displayText : null,
                upvotes: lp.upvotes || 0,
                commentCount: 0,
                community: lp.community_slug,
                author: lp.user_name,
                timestamp: lp.created_at || 0,
                skoolCreatedAt: lp.skool_created_at || ''
            });
        }

        // Sort
        sortItems(feedItems, currentSort);

        // Render
        let html = '';

        // Filter + sort bar
        html += '<div class="pp-posts-toolbar">';
        html += '<div class="pp-posts-chips">';
        html += '<button class="pp-chip pp-chip--active" data-feed-type="all" onclick="PeopleProfilePosts.filter(\'all\')">All (' + feedItems.length + ')</button>';
        html += '<button class="pp-chip" data-feed-type="post" onclick="PeopleProfilePosts.filter(\'post\')">Posts (' + posts.length + ')</button>';
        html += '<button class="pp-chip" data-feed-type="comment" onclick="PeopleProfilePosts.filter(\'comment\')">Comments (' + comments.length + ')</button>';
        html += '<button class="pp-chip" data-feed-type="liked" onclick="PeopleProfilePosts.filter(\'liked\')">Liked (' + likedPosts.length + ')</button>';
        html += '</div>';
        html += '<select class="pp-posts-sort" onchange="PeopleProfilePosts.sort(this.value)">';
        html += '<option value="date_desc"' + (currentSort === 'date_desc' ? ' selected' : '') + '>Newest first</option>';
        html += '<option value="date_asc"' + (currentSort === 'date_asc' ? ' selected' : '') + '>Oldest first</option>';
        html += '<option value="upvotes_desc"' + (currentSort === 'upvotes_desc' ? ' selected' : '') + '>Most upvotes</option>';
        html += '</select>';
        html += '</div>';

        if (feedItems.length === 0) {
            html += '<div style="color:var(--color-text-disabled);font-size:0.85rem;padding:var(--space-4) 0;">No content found for this member.</div>';
        }

        // Items
        for (let i = 0; i < feedItems.length; i++) {
            const item = feedItems[i];
            const typeLabel = item.type === 'liked' ? 'Liked' : item.type === 'post' ? 'Post' : 'Comment';
            const typeClass = 'pp-feed-type--' + item.type;

            html += '<div class="pp-feed-item" data-item-type="' + item.type + '" data-feed-idx="' + i + '">';
            html += '<span class="pp-feed-type ' + typeClass + '">' + typeLabel + '</span>';
            if (item.title) {
                html += '<div class="pp-feed-item__title">' + lib.escapeHtml(item.title) + '</div>';
            }
            if (item.content) {
                html += '<div class="pp-feed-item__content">' + lib.escapeHtml(item.content) + '</div>';
            }
            let metaParts = [];
            if (item.upvotes) metaParts.push(item.upvotes + ' upvotes');
            if (item.commentCount) metaParts.push(item.commentCount + ' comments');
            if (item.author) metaParts.push('by ' + item.author);
            if (item.skoolCreatedAt) {
                const d = new Date(item.skoolCreatedAt);
                if (!isNaN(d.getTime())) metaParts.push(d.toLocaleDateString());
            }
            if (item.community) metaParts.push(item.community);
            if (metaParts.length) {
                html += '<div class="pp-feed-item__meta">' + metaParts.join(' &middot; ') + '</div>';
            }
            html += '</div>';
        }

        container.innerHTML = html;
    }

    function sortItems(items, sortKey) {
        if (sortKey === 'date_desc') items.sort(function(a, b) { return b.timestamp - a.timestamp; });
        else if (sortKey === 'date_asc') items.sort(function(a, b) { return a.timestamp - b.timestamp; });
        else if (sortKey === 'upvotes_desc') items.sort(function(a, b) { return b.upvotes - a.upvotes; });
    }

    function filter(type) {
        document.querySelectorAll('.pp-chip[data-feed-type]').forEach(function(chip) {
            chip.classList.toggle('pp-chip--active', chip.dataset.feedType === type);
        });
        const items = document.querySelectorAll('.pp-feed-item[data-item-type]');
        items.forEach(function(item) {
            const matches = type === 'all' || item.dataset.itemType === type;
            item.style.display = matches ? '' : 'none';
        });
    }

    function sort(value) {
        currentSort = value;
        rendered = false;
        render(currentSkoolId, PeopleProfile.getProfileData());
    }

    function reset() {
        rendered = false;
        currentSkoolId = null;
    }

    return {
        render: render,
        filter: filter,
        sort: sort,
        reset: reset
    };
})();
