//
            //
            // region PROFILE DETAILS
            //
            //

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

            // Track active profile tab
            let activeProfileTab = 'overview';

            // Member Notes functions
            async function loadMemberNotes(skoolId) {
                const container = document.getElementById('member-notes-list');
                if (!container) return;
                const notes = await MemberNote.forMember(skoolId);
                if (!notes.length) {
                    container.innerHTML = '<small style="color:var(--color-text-secondary)">No notes yet</small>';
                    return;
                }
                let html = '';
                for (const note of notes) {
                    const date = note.created_at ? new Date(note.created_at * 1000).toLocaleString() : '';
                    const escaped = (note.content || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
                    html += `<div class="ck-note-item">`;
                    html += `<span class="ck-note-item__date">${date}</span>`;
                    html += `<button class="ck-note-item__delete" onclick="deleteMemberNote(${note.id},'${skoolId}')" title="Delete note">x</button>`;
                    html += `<div style="white-space:pre-wrap;margin-top:4px;">${escaped}</div>`;
                    html += `</div>`;
                }
                container.innerHTML = html;
            }

            async function saveNewNote() {
                const section = document.getElementById('member-notes-section');
                const input = document.getElementById('new-note-input');
                if (!section || !input) return;
                const skoolId = section.dataset.skoolId;
                const content = input.value.trim();
                if (!content) return;
                const note = new MemberNote({ member_skool_id: skoolId, content });
                const res = await note.save();
                if (res.ok) {
                    input.value = '';
                    await loadMemberNotes(skoolId);
                }
            }

            async function deleteMemberNote(noteId, skoolId) {
                const note = new MemberNote({ id: noteId });
                note.id = noteId;
                await note.delete();
                await loadMemberNotes(skoolId);
            }

            // Profile Analysis functions
            async function loadProfileAnalysis(skoolId) {
                const container = document.getElementById('profile-analysis-section');
                if (!container) return;
                try {
                    const res = await get(`/api/profile-analysis?skool_id=${encodeURIComponent(skoolId)}`);
                    if (!res.ok || !res.data || !res.data.has_cached) {
                        container.innerHTML = `<button class="ck-btn ck-btn--secondary ck-btn--sm" onclick="generateProfileAnalysis('${skoolId}')">Generate Analysis</button>
                            <br><small style="color:var(--color-text-secondary);margin-top:4px;display:inline-block;">AI-powered member analysis. Uses your configured AI provider.</small>`;
                        return;
                    }
                    renderProfileAnalysis(container, res.data.analysis, skoolId);
                } catch (e) {
                    container.innerHTML = `<button class="ck-btn ck-btn--secondary ck-btn--sm" onclick="generateProfileAnalysis('${skoolId}')">Generate Analysis</button>
                        <br><small style="color:var(--color-text-secondary)">AI-powered member analysis.</small>`;
                }
            }

            async function generateProfileAnalysis(skoolId) {
                const container = document.getElementById('profile-analysis-section');
                if (!container) return;
                container.innerHTML = `<div style="display:flex;align-items:center;gap:8px;">
                    <span class="thinking-dots-inline"></span>
                    <small>Generating analysis... This may take 10-30 seconds.</small>
                </div>`;
                try {
                    const res = await post('/api/profile-analysis/generate', { skool_id: skoolId });
                    if (!res.ok || !res.data || !res.data.ok) {
                        const errMsg = (res.data && res.data.error) || res.error || 'Unknown error';
                        container.innerHTML = `<div style="color:var(--color-error);margin-bottom:8px;">Analysis failed: ${errMsg}</div>
                            <button class="ck-btn ck-btn--secondary ck-btn--sm" onclick="generateProfileAnalysis('${skoolId}')">Retry</button>`;
                        return;
                    }
                    renderProfileAnalysis(container, res.data.analysis, skoolId);
                } catch (e) {
                    container.innerHTML = `<div style="color:var(--color-error);margin-bottom:8px;">Analysis failed: ${e.message || 'Network error'}</div>
                        <button class="ck-btn ck-btn--secondary ck-btn--sm" onclick="generateProfileAnalysis('${skoolId}')">Retry</button>`;
                }
            }

            function formatAnalysisText(text) {
                if (!text) return '';
                return text
                    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
                    .replace(/## (.+)/g, '<h5 style="margin:12px 0 4px 0;color:var(--brand-primary)">$1</h5>')
                    .replace(/\*\*(.+?)\*\*/g, '<b>$1</b>')
                    .replace(/\*(.+?)\*/g, '<em>$1</em>')
                    .replace(/`([^`]+)`/g, '<code style="background:rgba(255,255,255,0.08);padding:1px 4px;border-radius:3px;">$1</code>')
                    .replace(/^- (.+)$/gm, '<div style="padding-left:12px;">- $1</div>')
                    .replace(/\n/g, '<br>');
            }

            function renderProfileAnalysis(container, analysis, skoolId) {
                const date = analysis.created_at ? new Date(analysis.created_at * 1000).toLocaleString() : '';
                const staleNote = analysis.is_stale
                    ? ` <span style="color:var(--color-warning)">(outdated)</span>` : '';
                const durationNote = analysis.generation_time_ms
                    ? ` | ${(analysis.generation_time_ms / 1000).toFixed(1)}s` : '';
                const providerNote = analysis.ai_provider ? ` | ${analysis.ai_provider}` : '';

                let html = `<div class="ck-analysis-card">`;
                html += `<div class="ck-analysis-card__header">`;
                html += `<small style="color:var(--color-text-disabled)">${date}${providerNote}${durationNote}${staleNote}</small>`;
                html += `<button class="ck-btn ck-btn--secondary ck-btn--xs" onclick="generateProfileAnalysis('${skoolId}')" title="Regenerate analysis">Regenerate</button>`;
                html += `</div>`;
                html += `<div class="ck-analysis-card__body">${formatAnalysisText(analysis.content)}</div>`;
                html += `</div>`;
                container.innerHTML = html;
            }

            // Align community activity data to the same date range as the reference heatmap.
            let alignActivityData = (communityData, refStartDate, refTotalDays) => {
                const aligned = new Array(refTotalDays).fill(0);
                if (!communityData || !communityData.counts || !communityData.startDate) return aligned;

                const refStart = new Date(refStartDate);
                const commStart = new Date(communityData.startDate);
                const offsetDays = Math.round((commStart - refStart) / (24 * 60 * 60 * 1000));

                for (let i = 0; i < communityData.counts.length; i++) {
                    const idx = offsetDays + i;
                    if (idx >= 0 && idx < refTotalDays) {
                        aligned[idx] = communityData.counts[i];
                    }
                }
                return aligned;
            };

            // Render a GitHub-style activity heatmap SVG
            let renderActivityHeatmap = (counts, startDate, title) => {
                let html = '';
                const maxVal = Math.max(...counts, 1);
                const totalActivity = counts.reduce((a, b) => a + b, 0);
                const activeDays = counts.filter(c => c > 0).length;

                html += `<div style="font-size:var(--font-size-small);color:var(--color-text-secondary);margin-bottom:var(--space-2);">${totalActivity.toLocaleString()} actions · ${activeDays} active days</div>`;

                const cellSize = 10;
                const cellGap = 2;
                const step = cellSize + cellGap;
                const dayLabels = ['', 'Mon', '', 'Wed', '', 'Fri', ''];
                const labelWidth = 28;

                const startDow = startDate.getUTCDay();
                const totalDays = counts.length;
                const totalWeeks = Math.ceil((startDow + totalDays) / 7);

                const svgWidth = labelWidth + totalWeeks * step + 2;
                const svgHeight = 7 * step + 18;

                html += `<div style="overflow-x: auto;">`;
                html += `<svg width="${svgWidth}" height="${svgHeight}" style="font-size:9px; font-family:monospace">`;

                for (let d = 0; d < 7; d++) {
                    if (dayLabels[d]) {
                        html += `<text x="0" y="${18 + d * step + cellSize - 1}" fill="var(--color-text-secondary)">${dayLabels[d]}</text>`;
                    }
                }

                const [r, g, b] = lib.primaryColorRGB;
                let lastMonth = -1;
                for (let i = 0; i < totalDays; i++) {
                    const date = new Date(startDate);
                    date.setUTCDate(date.getUTCDate() + i);
                    const month = date.getUTCMonth();
                    const weekCol = Math.floor((startDow + i) / 7);
                    if (month !== lastMonth) {
                        const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                        html += `<text x="${labelWidth + weekCol * step}" y="10" fill="var(--color-text-secondary)">${monthNames[month]}</text>`;
                        lastMonth = month;
                    }
                }

                for (let i = 0; i < totalDays; i++) {
                    const date = new Date(startDate);
                    date.setUTCDate(date.getUTCDate() + i);
                    const dow = (startDow + i) % 7;
                    const weekCol = Math.floor((startDow + i) / 7);
                    const val = counts[i];
                    const dateStr = date.toISOString().slice(0, 10);

                    let fill;
                    if (val === 0) {
                        fill = document.documentElement.getAttribute('data-theme') === 'dark'
                            ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)';
                    } else {
                        const intensity = Math.min(val / maxVal, 1);
                        const alpha = 0.2 + intensity * 0.8;
                        fill = `rgba(${r},${g},${b},${alpha.toFixed(2)})`;
                    }

                    const x = labelWidth + weekCol * step;
                    const y = 18 + dow * step;
                    html += `<rect x="${x}" y="${y}" width="${cellSize}" height="${cellSize}" rx="2" fill="${fill}">`;
                    html += `<title>${dateStr}: ${val} action${val !== 1 ? 's' : ''}</title></rect>`;
                }

                html += `</svg></div>`;
                return html;
            };

            // Show profile image in a fullscreen overlay
            let showProfileImageOverlay = (src) => {
                const overlay = document.createElement('div');
                overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;z-index:10001;cursor:pointer;';
                overlay.onclick = () => overlay.remove();
                const img = document.createElement('img');
                img.src = src;
                img.style.cssText = 'max-width:90vw;max-height:90vh;border-radius:var(--radius-sm);object-fit:contain;';
                overlay.appendChild(img);
                document.body.appendChild(overlay);
            };

            // Switch profile tab
            let switchProfileTab = (tabName) => {
                activeProfileTab = tabName;
                document.querySelectorAll('.ck-tab[data-profile-tab]').forEach(btn => {
                    btn.classList.toggle('ck-tab--active', btn.dataset.profileTab === tabName);
                });
                document.querySelectorAll('.ck-tab-panel[data-profile-panel]').forEach(panel => {
                    panel.classList.toggle('ck-tab-panel--active', panel.dataset.profilePanel === tabName);
                });
            };

            // Filter content feed by type
            let filterContentFeed = (type) => {
                document.querySelectorAll('.ck-feed-chip[data-feed-type]').forEach(chip => {
                    chip.classList.toggle('ck-feed-chip--active', chip.dataset.feedType === type);
                });
                const items = document.querySelectorAll('.ck-feed-item[data-item-type]');
                const showMoreBtn = document.getElementById('feed-show-more');
                let visibleCount = 0;
                items.forEach(item => {
                    const matches = type === 'all' || item.dataset.itemType === type;
                    item.style.display = matches ? '' : 'none';
                    if (matches) visibleCount++;
                });
                // Update show more button visibility
                if (showMoreBtn) {
                    showMoreBtn.style.display = visibleCount > 10 ? '' : 'none';
                }
            };

            // render profile details
            let loadAndRenderProfileDetails = (memberId) => {
                (async ()=>{
                    lib.showLoading();

                    currentSecondaryView = "";
                    if (!secondaryViewVisible) {
                        secondaryViewVisible = true;
                    }
                    updateActionButtons();
                    await renderMembersView();

                    const secondaryView = document.getElementById("secondary-view");
                    if (!secondaryView) {
                        console.error("secondary-view container not found after attempting to show it");
                        lib.hideLoading();
                        return;
                    }
                    secondaryView.innerHTML = `<div style="padding:var(--space-4);color:var(--color-text-secondary)">Loading...</div>`;
                    console.log(`[ProfileDetails] Loading user with DB id=${memberId}`);
                    const user = await User.get(memberId);
                    if (!user) {
                        console.error(`[ProfileDetails] User.get(${memberId}) returned null`);
                        secondaryView.innerHTML = `<div style="padding:var(--space-4)"><h3>User not found</h3><small>Could not load user with ID ${memberId}.</small></div>`;
                        lib.hideLoading();
                        return;
                    }
                    const skoolId = user.skool_id;

                    const [postsRes, communitiesRes, profileCommunitiesRes, likedPostsRes, commentsRes, dailyActivitiesRes, communityActivitiesRes] = await Promise.all([
                        get(`/api/user/${skoolId}/posts`),
                        get(`/api/user/${skoolId}/communities`),
                        get(`/api/user/${skoolId}/profile-communities`),
                        get(`/api/user/${skoolId}/liked-posts`),
                        get(`/api/user/${skoolId}/comments`),
                        get(`/api/user/${skoolId}/daily-activities`),
                        get(`/api/user/${skoolId}/community-activities`)
                    ]);
                    const posts = postsRes.ok ? postsRes.data : [];
                    const communities = communitiesRes.ok ? communitiesRes.data : [];
                    const profileCommunities = profileCommunitiesRes.ok ? profileCommunitiesRes.data : [];
                    const likedPosts = likedPostsRes.ok ? likedPostsRes.data : [];
                    const comments = commentsRes.ok ? commentsRes.data : [];
                    const dailyActivities = dailyActivitiesRes.ok ? dailyActivitiesRes.data : null;
                    const communityActivities = communityActivitiesRes.ok ? communityActivitiesRes.data : null;

                    // Compute stats for header
                    const hasGeneral = dailyActivities && dailyActivities.counts && dailyActivities.counts.length > 0;
                    const refStartDate = hasGeneral ? new Date(dailyActivities.startDate) : null;
                    const refTotalDays = hasGeneral ? dailyActivities.counts.length : 0;
                    const activeDays = hasGeneral ? dailyActivities.counts.filter(c => c > 0).length : 0;

                    // ============================================================
                    // HEADER
                    // ============================================================
                    let profileImgHtml = '';
                    if (hideProfileImages) {
                        const initial = (user.first_name || user.name || '?')[0].toUpperCase();
                        const hue = (user.skool_id || '').split('').reduce((a, c) => a + c.charCodeAt(0), 0) % 360;
                        profileImgHtml = `<div class="ck-profile-header__avatar ck-profile-header__avatar--placeholder" style="background:hsl(${hue},55%,45%);">${initial}</div>`;
                    } else {
                        const imgSrc = user.skool_id ? `/api/image/${user.skool_id}` : '';
                        profileImgHtml = imgSrc
                            ? `<img class="ck-profile-header__avatar" src="${imgSrc}" onclick="showProfileImageOverlay('${imgSrc}')" title="Click to enlarge" onerror="this.style.display='none'">`
                            : '';
                    }

                    let html = `<div class="ck-profile-header">`;
                    html += profileImgHtml;
                    html += `<div class="ck-profile-header__info">`;
                    html += `<div class="ck-profile-header__name">${user.first_name || ''} ${user.last_name || ''}</div>`;
                    html += `<div class="ck-profile-header__meta">@${user.name} · ${user.member_role || 'member'}</div>`;
                    html += `<div class="ck-profile-header__stats">${posts.length} posts · ${comments.length} comments · ${activeDays} active days</div>`;

                    // Community pills in header (max 3 + overflow)
                    const allCommunities = profileCommunities.length ? profileCommunities : communities.map(c => typeof c === 'string' ? { name: c, slug: c } : c);
                    if (allCommunities.length) {
                        html += `<div class="ck-profile-header__communities">`;
                        const maxPills = 3;
                        for (let i = 0; i < Math.min(allCommunities.length, maxPills); i++) {
                            const c = allCommunities[i];
                            const name = c.name || c;
                            const slug = c.slug || c;
                            html += `<span class="ck-community-pill" onclick="window.location.href='/communities.html?community=${encodeURIComponent(slug)}'">${name}</span>`;
                        }
                        if (allCommunities.length > maxPills) {
                            html += `<span class="ck-community-pill" style="cursor:default;opacity:0.7">+${allCommunities.length - maxPills} more</span>`;
                        }
                        html += `</div>`;
                    }

                    html += `</div></div>`;

                    // ============================================================
                    // TABS
                    // ============================================================
                    html += `<div class="ck-tabs">`;
                    html += `<button class="ck-tab ck-tab--active" data-profile-tab="overview" onclick="switchProfileTab('overview')">Overview</button>`;
                    html += `<button class="ck-tab" data-profile-tab="content" onclick="switchProfileTab('content')">Content</button>`;
                    html += `<button class="ck-tab" data-profile-tab="notes" onclick="switchProfileTab('notes')">Notes</button>`;
                    html += `</div>`;

                    // ============================================================
                    // OVERVIEW TAB
                    // ============================================================
                    html += `<div class="ck-tab-panel ck-tab-panel--active" data-profile-panel="overview">`;

                    // Activity heatmap with toggle
                    if (hasGeneral) {
                        const alignedCounts = alignActivityData(communityActivities, refStartDate, refTotalDays);

                        html += `<div style="margin-bottom:var(--space-4);">`;
                        html += `<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:var(--space-2);">`;
                        html += `<span style="font-size:var(--font-size-small);font-weight:var(--font-weight-semibold);color:var(--color-text-primary);">Activity</span>`;
                        html += `<div class="ck-heatmap-toggle">`;
                        html += `<button class="ck-heatmap-toggle__btn ck-heatmap-toggle__btn--active" data-heatmap-mode="skool" onclick="toggleHeatmap('skool')">Skool</button>`;
                        html += `<button class="ck-heatmap-toggle__btn" data-heatmap-mode="community" onclick="toggleHeatmap('community')">Community</button>`;
                        html += `</div>`;
                        html += `</div>`;
                        html += `<div id="heatmap-container">`;
                        html += renderActivityHeatmap(dailyActivities.counts, refStartDate, 'Skool Activity');
                        html += `</div>`;
                        html += `</div>`;

                        // Store data for toggle switching
                        window._profileHeatmapData = {
                            skoolCounts: dailyActivities.counts,
                            communityCounts: alignedCounts,
                            startDate: refStartDate
                        };
                    }

                    // Interests section
                    const interestsList = memberInterests.get(skoolId);
                    if (interestsList && interestsList.length > 0) {
                        html += `<div style="margin-bottom:var(--space-4);">`;
                        html += `<div style="font-size:var(--font-size-small);font-weight:var(--font-weight-semibold);color:var(--color-text-primary);margin-bottom:var(--space-2);">Interests</div>`;
                        html += `<div style="display:flex;flex-direction:column;gap:6px;">`;
                        for (const t of interestsList) {
                            const hue = categoryToHue(t.category);
                            const pct = Math.round(t.weight * 100);
                            const barWidth = Math.max(pct, 5);
                            html += `<div style="display:flex;align-items:center;gap:8px;">`;
                            html += `<span style="padding:2px 8px;border-radius:var(--radius-sm);font-size:0.85em;min-width:120px;
                                background:hsl(${hue},50%,25%);color:hsl(${hue},80%,80%);
                                border:1px solid hsl(${hue},50%,35%);">${t.category}</span>`;
                            html += `<div style="flex:1;height:6px;background:rgba(255,255,255,0.08);border-radius:var(--radius-sm);overflow:hidden;">`;
                            html += `<div style="width:${barWidth}%;height:100%;background:hsl(${hue},60%,50%);border-radius:var(--radius-sm);"></div>`;
                            html += `</div>`;
                            html += `<small style="color:var(--color-text-disabled);min-width:35px;text-align:right;">${pct}%</small>`;
                            html += `</div>`;
                        }
                        html += `</div></div>`;
                    } else if (labelsLoaded) {
                        // Try individual fetch for interests
                        html += `<div id="profile-interests-placeholder"></div>`;
                        (async () => {
                            try {
                                const res = await fetch(`/api/member-interests?skool_id=${encodeURIComponent(skoolId)}`);
                                if (!res.ok) return;
                                const data = await res.json();
                                if (data.interests && data.interests.length > 0) {
                                    memberInterests.set(skoolId, data.interests);
                                    const anchor = document.getElementById('profile-interests-placeholder');
                                    if (anchor) {
                                        let ihtml = `<div style="margin-bottom:var(--space-4);">`;
                                        ihtml += `<div style="font-size:var(--font-size-small);font-weight:var(--font-weight-semibold);color:var(--color-text-primary);margin-bottom:var(--space-2);">Interests</div>`;
                                        ihtml += `<div style="display:flex;flex-direction:column;gap:6px;">`;
                                        for (const t of data.interests) {
                                            const hue = categoryToHue(t.category);
                                            const pct = Math.round(t.weight * 100);
                                            const barWidth = Math.max(pct, 5);
                                            ihtml += `<div style="display:flex;align-items:center;gap:8px;">`;
                                            ihtml += `<span style="padding:2px 8px;border-radius:var(--radius-sm);font-size:0.85em;min-width:120px;
                                                background:hsl(${hue},50%,25%);color:hsl(${hue},80%,80%);
                                                border:1px solid hsl(${hue},50%,35%);">${t.category}</span>`;
                                            ihtml += `<div style="flex:1;height:6px;background:rgba(255,255,255,0.08);border-radius:var(--radius-sm);overflow:hidden;">`;
                                            ihtml += `<div style="width:${barWidth}%;height:100%;background:hsl(${hue},60%,50%);border-radius:var(--radius-sm);"></div>`;
                                            ihtml += `</div>`;
                                            ihtml += `<small style="color:var(--color-text-disabled);min-width:35px;text-align:right;">${pct}%</small>`;
                                            ihtml += `</div>`;
                                        }
                                        ihtml += `</div></div>`;
                                        anchor.innerHTML = ihtml;
                                    }
                                }
                            } catch (e) { /* ignore */ }
                        })();
                    }

                    html += `</div>`; // end overview tab

                    // ============================================================
                    // CONTENT TAB (Unified Feed)
                    // ============================================================
                    html += `<div class="ck-tab-panel" data-profile-panel="content">`;

                    // Build unified feed items
                    const feedItems = [];

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

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

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

                    // Sort by timestamp descending
                    feedItems.sort((a, b) => b.timestamp - a.timestamp);

                    // Filter chips
                    html += `<div class="ck-feed-filters">`;
                    html += `<button class="ck-feed-chip ck-feed-chip--active" data-feed-type="all" onclick="filterContentFeed('all')">All (${feedItems.length})</button>`;
                    html += `<button class="ck-feed-chip" data-feed-type="post" onclick="filterContentFeed('post')">Posts (${posts.length})</button>`;
                    html += `<button class="ck-feed-chip" data-feed-type="comment" onclick="filterContentFeed('comment')">Comments (${comments.length})</button>`;
                    html += `<button class="ck-feed-chip" data-feed-type="liked" onclick="filterContentFeed('liked')">Liked (${likedPosts.length})</button>`;
                    html += `</div>`;

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

                    // Render feed items (first 10 visible, rest hidden)
                    const INITIAL_VISIBLE = 10;
                    for (let i = 0; i < feedItems.length; i++) {
                        const item = feedItems[i];
                        const hidden = i >= INITIAL_VISIBLE ? ' style="display:none"' : '';
                        const typeClass = `ck-feed-item--${item.type}`;
                        const chipClass = `ck-feed-item__type--${item.type}`;
                        const typeLabel = item.type === 'liked' ? 'Liked' : item.type === 'post' ? 'Post' : 'Comment';

                        html += `<div class="ck-feed-item ${typeClass}" data-item-type="${item.type}" data-feed-idx="${i}"${hidden}>`;
                        html += `<span class="ck-feed-item__type ${chipClass}">${typeLabel}</span>`;
                        if (item.title) {
                            html += `<div class="ck-feed-item__content"><b>${item.title}</b></div>`;
                        } else if (item.content) {
                            html += `<div class="ck-feed-item__content">${item.content}</div>`;
                        }
                        let metaParts = [];
                        if (item.upvotes) metaParts.push(`${item.upvotes} upvotes`);
                        if (item.comments) metaParts.push(`${item.comments} comments`);
                        if (item.author) metaParts.push(`by ${item.author}`);
                        if (item.community) metaParts.push(item.community);
                        if (metaParts.length) {
                            html += `<div class="ck-feed-item__meta">${metaParts.join(' · ')}</div>`;
                        }
                        html += `</div>`;
                    }

                    // Show more button
                    if (feedItems.length > INITIAL_VISIBLE) {
                        html += `<button id="feed-show-more" class="ck-btn ck-btn--secondary ck-btn--sm" style="width:100%;margin-top:var(--space-2);" onclick="showMoreFeedItems()">Show ${feedItems.length - INITIAL_VISIBLE} more</button>`;
                    }

                    html += `</div>`; // end content tab

                    // ============================================================
                    // NOTES TAB
                    // ============================================================
                    html += `<div class="ck-tab-panel" data-profile-panel="notes">`;

                    // AI Analysis
                    html += `<div style="margin-bottom:var(--space-4);">`;
                    html += `<div style="font-size:var(--font-size-small);font-weight:var(--font-weight-semibold);color:var(--color-text-primary);margin-bottom:var(--space-2);">AI Analysis</div>`;
                    html += `<div id="profile-analysis-section" data-skool-id="${skoolId}">`;
                    html += `<small style="color:var(--color-text-secondary)">Loading...</small>`;
                    html += `</div></div>`;

                    // Notes
                    html += `<div style="margin-bottom:var(--space-4);">`;
                    html += `<div style="font-size:var(--font-size-small);font-weight:var(--font-weight-semibold);color:var(--color-text-primary);margin-bottom:var(--space-2);">Notes</div>`;
                    html += `<div id="member-notes-section" data-skool-id="${skoolId}">`;
                    html += `<div id="member-notes-list"><small style="color:var(--color-text-secondary)">Loading notes...</small></div>`;
                    html += `<div style="margin-top:var(--space-3);">`;
                    html += `<textarea id="new-note-input" rows="3" class="ck-input" placeholder="Add a note..." style="width:100%;resize:vertical;"></textarea>`;
                    html += `<button class="ck-btn ck-btn--secondary ck-btn--sm" onclick="saveNewNote()" style="margin-top:var(--space-2);">Save Note</button>`;
                    html += `</div></div></div>`;

                    html += `</div>`; // end notes tab

                    secondaryView.innerHTML = html;

                    // Load async data
                    setTimeout(() => loadMemberNotes(skoolId), 0);
                    setTimeout(() => loadProfileAnalysis(skoolId), 0);

                    lib.hideLoading();
                })();
            };

            // Toggle heatmap between Skool and Community
            let toggleHeatmap = (mode) => {
                const data = window._profileHeatmapData;
                if (!data) return;

                document.querySelectorAll('.ck-heatmap-toggle__btn').forEach(btn => {
                    btn.classList.toggle('ck-heatmap-toggle__btn--active', btn.dataset.heatmapMode === mode);
                });

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

                const counts = mode === 'community' ? data.communityCounts : data.skoolCounts;
                container.innerHTML = renderActivityHeatmap(counts, data.startDate, mode === 'community' ? 'Community Activity' : 'Skool Activity');
            };

            // Show more feed items
            let showMoreFeedItems = () => {
                document.querySelectorAll('.ck-feed-item[data-feed-idx]').forEach(item => {
                    item.style.display = '';
                });
                const btn = document.getElementById('feed-show-more');
                if (btn) btn.remove();
                // Re-apply active filter
                const activeChip = document.querySelector('.ck-feed-chip.ck-feed-chip--active');
                if (activeChip && activeChip.dataset.feedType !== 'all') {
                    filterContentFeed(activeChip.dataset.feedType);
                }
            };
