// conversations_feed.js — Post feed with list + detail + comments
// Adapted from postsjs/posts_filter.js for the Conversations page.

// Strip Skool mention syntax: [@Name](obj://user/UUID) → @Name
function feedStripMentions(text) {
    if (!text) return '';
    return text.replace(/\[@([^\]]+)\]\(obj:\/\/user\/[^)]+\)/g, '@$1');
}

// ========== Attachments ==========

function feedRenderAttachments(meta) {
    var html = '';
    if (!meta) return html;
    var attachments = null;
    try {
        if (meta.attachments_data) {
            attachments = typeof meta.attachments_data === 'string' ? JSON.parse(meta.attachments_data) : meta.attachments_data;
        }
    } catch (e) {}
    if (!attachments || !attachments.length) return html;
    for (var i = 0; i < attachments.length; i++) {
        var att = attachments[i];
        var ct = (att.metadata && att.metadata.content_type) || '';
        var url = (att.metadata && (att.metadata.read_url || att.metadata.src_read_url || att.metadata.image_md_url)) || '';
        if (url && ct.startsWith('image/')) {
            html += '<img src="' + lib.escapeHtml(url) + '" style="max-width:100%; max-height:400px; border-radius:8px; margin-top:8px; display:block;" onerror="this.style.display=\'none\'">';
        } else if (url) {
            var fname = (att.metadata && att.metadata.file_name) || 'Attachment';
            html += '<a href="' + lib.escapeHtml(url) + '" target="_blank" style="color:var(--brand-primary); font-size:13px; display:block; margin-top:6px;">' + lib.escapeHtml(fname) + '</a>';
        }
    }
    return html;
}

// ========== State ==========

var feedPosts = [];
var feedPage = 1;
var feedLimit = 100;
var feedSelectedPostId = null;

var feedFilterState = {
    sortBy: 'newest',
    searchTerm: '',
    filters: {
        date_range: { from: 1, to: 1825 },
        upvotes: { from: 0, to: 9999 },
        comments: { from: 0, to: 9999 },
        author_name: ''
    }
};

// ========== Date helpers ==========

var feedDaysSliderSteps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,30,60,90,120,150,180,365,730,1095,1460,1825];

function feedDaysToStepIndex(days) {
    var best = 0;
    for (var i = 0; i < feedDaysSliderSteps.length; i++) {
        if (Math.abs(feedDaysSliderSteps[i] - days) <= Math.abs(feedDaysSliderSteps[best] - days)) best = i;
    }
    return best;
}

function feedDaysAgoToDate(days) {
    var d = new Date();
    d.setHours(0, 0, 0, 0);
    d.setDate(d.getDate() - (days - 1));
    return d;
}

function feedDateToISO(date) {
    return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
}

function feedISOToDays(isoStr) {
    var parts = isoStr.split('-');
    var date = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
    var now = new Date();
    now.setHours(0, 0, 0, 0);
    date.setHours(0, 0, 0, 0);
    return Math.max(1, Math.round((now - date) / (1000 * 60 * 60 * 24)) + 1);
}

var feedTodayISO = feedDateToISO(new Date());
var feedOldestISO = feedDateToISO(feedDaysAgoToDate(1825));

function feedFormatDaysDisplay(days) {
    return feedDateToISO(feedDaysAgoToDate(days));
}

// ========== Filter slider helpers ==========

function feedHandleDualSliderInput(key, side, stepIdx) {
    var days = feedDaysSliderSteps[stepIdx];
    var elem = document.getElementById('feed_input_' + key + '_' + side);
    if (elem) elem.value = feedFormatDaysDisplay(days);
}

function feedHandleDateInput(key, side, isoValue) {
    if (!isoValue) return;
    var days = feedISOToDays(isoValue);
    if (days < 1) return;
    feedSetRangeFilterValue(key, side, Math.min(1825, days));
    feedSyncRangeUI(key);
}

function feedHandleDualSliderChange(key, side, stepIdx) {
    var days = feedDaysSliderSteps[stepIdx];
    feedSetRangeFilterValue(key, side, days);
    feedSyncRangeUI(key);
}

function feedSetRangeFilterValue(key, side, days) {
    if (!feedFilterState.filters[key]) return;
    days = Math.max(1, Math.min(1825, days));
    if (side === 'from') {
        feedFilterState.filters[key].from = days;
        if (feedFilterState.filters[key].to < days) feedFilterState.filters[key].to = days;
    } else {
        feedFilterState.filters[key].to = days;
        if (feedFilterState.filters[key].from > days) feedFilterState.filters[key].from = days;
    }
}

function feedSyncRangeUI(key) {
    var f = feedFilterState.filters[key];
    if (!f) return;
    var fromSlider = document.getElementById('feed_slider_' + key + '_from');
    var toSlider = document.getElementById('feed_slider_' + key + '_to');
    if (fromSlider) fromSlider.value = feedDaysToStepIndex(f.from);
    if (toSlider) toSlider.value = feedDaysToStepIndex(f.to);
    var fromDisplay = document.getElementById('feed_input_' + key + '_from');
    var toDisplay = document.getElementById('feed_input_' + key + '_to');
    if (fromDisplay) fromDisplay.value = feedFormatDaysDisplay(f.from);
    if (toDisplay) toDisplay.value = feedFormatDaysDisplay(f.to);
}

// ========== Filter panel rendering ==========

function feedBuildDualRangeSlider(key) {
    var f = feedFilterState.filters[key];
    if (!f) return '';
    var fromIdx = feedDaysToStepIndex(f.from);
    var toIdx = feedDaysToStepIndex(f.to);
    var maxIdx = feedDaysSliderSteps.length - 1;
    var fromDisplay = feedFormatDaysDisplay(f.from);
    var toDisplay = feedFormatDaysDisplay(f.to);
    return '<div class="dual-range-wrap">' +
        '<div class="dual-range-labels">' +
            '<input type="date" class="dual-range-date-input" id="feed_input_' + key + '_from" value="' + fromDisplay + '" min="' + feedOldestISO + '" max="' + feedTodayISO + '" onchange="feedHandleDateInput(\'' + key + '\',\'from\',this.value); this.blur();">' +
            '<span class="dual-range-unit">&mdash;</span>' +
            '<input type="date" class="dual-range-date-input" id="feed_input_' + key + '_to" value="' + toDisplay + '" min="' + feedOldestISO + '" max="' + feedTodayISO + '" onchange="feedHandleDateInput(\'' + key + '\',\'to\',this.value); this.blur();">' +
        '</div>' +
        '<div class="dual-range-track">' +
            '<input type="range" id="feed_slider_' + key + '_from" min="0" max="' + maxIdx + '" value="' + fromIdx + '" oninput="feedHandleDualSliderInput(\'' + key + '\',\'from\',this.value)" onchange="feedHandleDualSliderChange(\'' + key + '\',\'from\',this.value)">' +
            '<input type="range" id="feed_slider_' + key + '_to" min="0" max="' + maxIdx + '" value="' + toIdx + '" oninput="feedHandleDualSliderInput(\'' + key + '\',\'to\',this.value)" onchange="feedHandleDualSliderChange(\'' + key + '\',\'to\',this.value)">' +
        '</div>' +
    '</div>';
}

function feedBuildFilterRow(key, label, controlsHtml) {
    return '<div class="filter-row filter-row-enabled">' +
        '<div class="filter-row-header"><span class="filter-row-label">' + label + '</span></div>' +
        '<div class="filter-row-controls">' + controlsHtml + '</div>' +
    '</div>';
}

function renderFeedFilterPanel() {
    var f = feedFilterState.filters;
    var html = '';

    // Date range
    html += feedBuildFilterRow('date_range', 'Date Range', feedBuildDualRangeSlider('date_range'));

    // Upvotes range
    html += feedBuildFilterRow('upvotes', 'Upvotes',
        '<div class="numeric-range-wrap">' +
            '<input type="number" min="0" value="' + f.upvotes.from + '" onchange="feedFilterState.filters.upvotes.from = parseInt(this.value) || 0">' +
            '<span class="numeric-range-sep">to</span>' +
            '<input type="number" min="0" value="' + f.upvotes.to + '" onchange="feedFilterState.filters.upvotes.to = parseInt(this.value) || 0">' +
        '</div>');

    // Comments range
    html += feedBuildFilterRow('comments', 'Comments',
        '<div class="numeric-range-wrap">' +
            '<input type="number" min="0" value="' + f.comments.from + '" onchange="feedFilterState.filters.comments.from = parseInt(this.value) || 0">' +
            '<span class="numeric-range-sep">to</span>' +
            '<input type="number" min="0" value="' + f.comments.to + '" onchange="feedFilterState.filters.comments.to = parseInt(this.value) || 0">' +
        '</div>');

    // Author name
    html += feedBuildFilterRow('author_name', 'Author',
        '<input type="text" placeholder="Author name..." value="' + (f.author_name || '') + '" onchange="feedFilterState.filters.author_name = this.value" style="width: 100%;">');

    // Apply + Clear buttons
    html += '<div style="margin-top: 12px;"><button onclick="applyFeedFilter()" class="ck-btn ck-btn--primary" style="width: 100%;">Apply</button></div>';
    html += '<div style="margin-top: 8px;"><button onclick="clearFeedFilter()" class="ck-btn ck-btn--danger" style="width: 100%;">Clear</button></div>';

    var panel = document.getElementById('feed-filter-body');
    if (panel) panel.innerHTML = html;
}

// ========== Sort & Filter API ==========

function setFeedSort(value) {
    feedFilterState.sortBy = value;
    loadFeed();
}

function applyFeedFilter() {
    feedPage = 1;
    loadFeed();
}

function clearFeedFilter() {
    feedFilterState = {
        sortBy: 'newest',
        searchTerm: '',
        filters: {
            date_range: { from: 1, to: 1825 },
            upvotes: { from: 0, to: 9999 },
            comments: { from: 0, to: 9999 },
            author_name: ''
        }
    };
    var searchInput = document.getElementById('feed-search-input');
    if (searchInput) searchInput.value = '';
    var sortSelect = document.getElementById('feed-sort-select');
    if (sortSelect) sortSelect.value = 'newest';
    renderFeedFilterPanel();
    loadFeed();
}

// ========== Data loading ==========

async function loadFeed(skipAnimation) {
    if (!skipAnimation) lib.showLoading('Loading posts');
    var res = await post('/api/post/filter', feedFilterState);
    if (!skipAnimation) lib.hideLoading();
    if (res.ok) {
        feedPosts = res.data.posts;
        feedPage = 1;
        var countEl = document.getElementById('feedPostCount');
        if (countEl) countEl.textContent = feedPosts.length.toString();
        renderFeedList();
        // If previously selected post is still in the list, keep it; otherwise clear detail
        if (feedSelectedPostId) {
            var stillExists = feedPosts.some(function(p) { return p.skool_id === feedSelectedPostId; });
            if (!stillExists) {
                feedSelectedPostId = null;
                renderFeedDetailPlaceholder();
            }
        }
    }
}

// ========== Pagination ==========

function setFeedPage(page) {
    feedPage = page;
    renderFeedList();
    var listPanel = document.getElementById('feed-list-panel');
    if (listPanel) listPanel.scrollTop = 0;
}

function renderFeedPagination() {
    var total = feedPosts.length;
    var pages = Math.ceil(total / feedLimit);
    if (pages <= 1) return '';
    var start = (feedPage - 1) * feedLimit + 1;
    var end = Math.min(feedPage * feedLimit, total);
    var html = '<div class="conv-pagination">';
    html += '<span>' + start + '-' + end + ' of ' + total + '</span>';
    html += '<button onclick="setFeedPage(1)"' + (feedPage === 1 ? ' disabled' : '') + '>&laquo;</button>';
    html += '<button onclick="setFeedPage(' + (feedPage - 1) + ')"' + (feedPage === 1 ? ' disabled' : '') + '>&lsaquo;</button>';
    var pStart = Math.max(1, feedPage - 2);
    var pEnd = Math.min(pages, feedPage + 2);
    for (var i = pStart; i <= pEnd; i++) {
        html += '<button onclick="setFeedPage(' + i + ')"' + (i === feedPage ? ' class="is-current"' : '') + '>' + i + '</button>';
    }
    html += '<button onclick="setFeedPage(' + (feedPage + 1) + ')"' + (feedPage === pages ? ' disabled' : '') + '>&rsaquo;</button>';
    html += '<button onclick="setFeedPage(' + pages + ')"' + (feedPage === pages ? ' disabled' : '') + '>&raquo;</button>';
    html += '</div>';
    return html;
}

// ========== Feed list rendering ==========

function renderFeedPostCard(p) {
    var meta = p.metadata ? JSON.parse(p.metadata) : {};
    var title = meta.title || p.name || '(Untitled)';
    var content = meta.content || '';
    var preview = content.length > 120 ? content.substring(0, 120) + '...' : content;
    var createdAt = p.skool_created_at ? new Date(p.skool_created_at).toLocaleDateString() : '-';
    var commentCount = p.comments || 0;
    var upvotes = p.upvotes || 0;
    var label = meta.label || '';
    var labelHtml = label ? '<span class="conv-post-label">' + lib.escapeHtml(label) + '</span>' : '';
    var selectedClass = (feedSelectedPostId === p.skool_id) ? ' conv-post-card--selected' : '';
    var authorName = lib.escapeHtml(p.user_name || 'Unknown');

    return '<div class="conv-post-card' + selectedClass + '" onclick="selectFeedPost(\'' + p.skool_id + '\')">' +
        '<div class="conv-post-card__title">' + lib.escapeHtml(title) + labelHtml + '</div>' +
        '<div class="conv-post-card__preview">' + lib.escapeHtml(feedStripMentions(preview)) + '</div>' +
        '<div class="conv-post-card__meta">' +
            '<span class="conv-post-card__author" onclick="event.stopPropagation(); window.location.href=\'/people.html?id=' + (p.user_id || '') + '\'">' + authorName + '</span>' +
            ' &middot; ' + createdAt +
            ' &middot; ' + upvotes + ' &#9650; &middot; ' + commentCount + ' &#128172;' +
        '</div>' +
    '</div>';
}

function renderFeedList() {
    var listPanel = document.getElementById('feed-list-panel');
    if (!listPanel) return;
    var offset = (feedPage - 1) * feedLimit;
    var pagePosts = feedPosts.slice(offset, offset + feedLimit);

    if (pagePosts.length === 0) {
        listPanel.innerHTML = '<div class="conv-empty">No posts found.</div>';
        return;
    }

    var html = '';
    for (var i = 0; i < pagePosts.length; i++) {
        html += renderFeedPostCard(pagePosts[i]);
    }
    html += renderFeedPagination();
    listPanel.innerHTML = html;
}

// ========== Post detail ==========

function renderFeedDetailPlaceholder() {
    var detail = document.getElementById('feed-detail-panel');
    if (!detail) return;
    detail.innerHTML = '<div class="conv-detail-placeholder">' +
        '<div class="conv-detail-placeholder__icon">&#128196;</div>' +
        '<div class="conv-detail-placeholder__text">Click on a post to read it.</div>' +
    '</div>';
}

async function selectFeedPost(skoolId) {
    feedSelectedPostId = skoolId;
    // Re-render list to update selection highlight
    renderFeedList();

    var p = feedPosts.find(function(post) { return post.skool_id === skoolId; });
    if (!p) return;

    var detail = document.getElementById('feed-detail-panel');
    if (!detail) return;

    var meta = p.metadata ? JSON.parse(p.metadata) : {};
    var title = meta.title || p.name || '(Untitled)';
    var content = meta.content || '';
    var createdAt = p.skool_created_at ? new Date(p.skool_created_at).toLocaleDateString() : '-';
    var commentCount = p.comments || 0;
    var upvotes = p.upvotes || 0;
    var label = meta.label || '';
    var labelHtml = label ? '<span class="conv-post-label">' + lib.escapeHtml(label) + '</span>' : '';
    var authorName = lib.escapeHtml(p.user_name || 'Unknown');
    var authorId = p.user_id || '';

    // Build author row with avatar
    var avatarHtml = '';
    if (authorId) {
        avatarHtml = '<img class="conv-detail__author-avatar" src="/api/image/' + authorId + '" onerror="this.style.display=\'none\'">';
    }

    var html = '<div class="conv-detail">';
    html += '<div class="conv-detail__header">';
    html += '<div class="conv-detail__title">' + lib.escapeHtml(title) + ' ' + labelHtml + '</div>';
    html += '<div class="conv-detail__author-row">';
    html += avatarHtml;
    html += '<a href="/people.html?id=' + authorId + '" class="conv-detail__author-link">' + authorName + '</a>';
    html += '<span class="conv-detail__date">' + createdAt + '</span>';
    html += '</div>';
    html += '<div class="conv-detail__stats">' + upvotes + ' upvotes &middot; ' + commentCount + ' comments</div>';
    html += '</div>';

    // Post content
    html += '<div class="conv-detail__content">' + lib.escapeHtml(feedStripMentions(content)) + feedRenderAttachments(meta) + '</div>';

    // Comments section
    html += '<div class="conv-detail__comments" id="feed-detail-comments">';
    html += '<div class="conv-detail__comments-header">Comments (' + commentCount + ')</div>';
    html += '<div class="conv-detail__comments-loading">Loading comments...</div>';
    html += '</div>';

    html += '</div>';
    detail.innerHTML = html;
    detail.scrollTop = 0;

    // Load comments
    loadFeedPostComments(skoolId, commentCount);
}

async function loadFeedPostComments(postSkoolId, expectedCount) {
    var container = document.getElementById('feed-detail-comments');
    if (!container) return;

    try {
        var res = await get('/api/post/' + postSkoolId + '/comments');
        var comments = res.ok ? res.data : [];

        if (comments.length === 0) {
            container.innerHTML = '<div class="conv-detail__comments-header">Comments (0)</div>' +
                '<div class="conv-detail__comments-empty">No comments yet.</div>';
            return;
        }

        var html = '<div class="conv-detail__comments-header">Comments (' + comments.length + ')</div>';
        for (var i = 0; i < comments.length; i++) {
            var c = comments[i];
            var cmeta = c.metadata ? JSON.parse(c.metadata) : {};
            var ccontent = cmeta.content || '';
            var cdate = c.skool_created_at ? new Date(c.skool_created_at).toLocaleDateString() : '-';
            var cAuthorName = lib.escapeHtml(c.user_name || 'Unknown');
            var cAuthorId = c.user_id || '';
            var cAvatarHtml = cAuthorId
                ? '<img class="conv-comment__avatar" src="/api/image/' + cAuthorId + '" onerror="this.style.display=\'none\'">'
                : '';

            html += '<div class="conv-comment">';
            html += '<div class="conv-comment__header">';
            html += cAvatarHtml;
            html += '<a href="/people.html?id=' + cAuthorId + '" class="conv-comment__author">' + cAuthorName + '</a>';
            html += '<span class="conv-comment__date">' + cdate + '</span>';
            html += '</div>';
            html += '<div class="conv-comment__body">' + lib.escapeHtml(feedStripMentions(ccontent)) + feedRenderAttachments(cmeta) + '</div>';
            html += '</div>';
        }
        container.innerHTML = html;
    } catch (e) {
        container.innerHTML = '<div class="conv-detail__comments-header">Comments</div>' +
            '<div class="conv-detail__comments-empty" style="color:var(--color-error)">Failed to load comments.</div>';
    }
}
