
            //
            //
            // region COMMUNITIES MAIN
            //
            //

            var allCommunities = [];
            var filteredCommunities = [];
            let communitiesPage = 1;
            const communitiesLimit = 100;

            let communitiesFilterState = {
                sortBy: 'shared_count_desc',
                searchTerm: '',
                minSharedMembers: 2
            };

            let setCommunitiesSort = (value) => {
                communitiesFilterState.sortBy = value;
            };

            // Load all communities from the global endpoint, then filter/sort locally
            var loadCommunities = async (skipAnimation = false) => {
                if (!skipAnimation) lib.showLoading();
                let data;
                try {
                    const rawRes = await fetch('/api/communities/global');
                    if (!skipAnimation) lib.hideLoading();
                    if (!rawRes.ok) {
                        lib.showSectionError('communities-list', 'Communities', 'loadCommunities', 'communities-global');
                        return;
                    }
                    data = await rawRes.json();
                } catch (e) {
                    if (!skipAnimation) lib.hideLoading();
                    lib.showSectionError('communities-list', 'Communities', 'loadCommunities', 'communities-global');
                    return;
                }

                if (data.parse_errors && data.parse_errors > 0) {
                    console.warn('[Communities] parse_errors:', data.parse_errors, '— some community counts may be understated');
                }

                lib.retryCounters['communities-global'] = 0;
                // Support both legacy plain-array response and new {communities: [...], parse_errors: N} shape
                allCommunities = Array.isArray(data) ? data : (data.communities || data.items || []);
                applyLocalFilter();
            };

            let applyLocalFilter = () => {
                let results = [...allCommunities];
                const search = communitiesFilterState.searchTerm.toLowerCase();
                const minShared = communitiesFilterState.minSharedMembers || 0;

                // Search filter
                if (search) {
                    results = results.filter(c => {
                        const name = (c.name || '').toLowerCase();
                        const slug = (c.slug || '').toLowerCase();
                        return name.includes(search) || slug.includes(search);
                    });
                }

                // Min shared members
                if (minShared > 0) {
                    results = results.filter(c => (c.shared_user_count || 0) >= minShared);
                }

                // Sort
                switch (communitiesFilterState.sortBy) {
                    case 'shared_count_desc':
                        results.sort((a, b) => (b.shared_user_count || 0) - (a.shared_user_count || 0));
                        break;
                    case 'shared_count_asc':
                        results.sort((a, b) => (a.shared_user_count || 0) - (b.shared_user_count || 0));
                        break;
                    case 'name_asc':
                        results.sort((a, b) => (a.name || a.slug || '').localeCompare(b.name || b.slug || ''));
                        break;
                    case 'name_desc':
                        results.sort((a, b) => (b.name || b.slug || '').localeCompare(a.name || a.slug || ''));
                        break;
                }

                filteredCommunities = results;
                communitiesPage = 1;
                document.getElementById("communityAmount").innerText = filteredCommunities.length.toString();
                renderCommunitiesView();
            };

            let applyCommunitiesFilter = () => {
                applyLocalFilter();
            };

            let clearCommunitiesFilter = () => {
                communitiesFilterState = {
                    sortBy: 'shared_count_desc',
                    searchTerm: '',
                    minSharedMembers: 2
                };
                document.getElementById('communities-search-input').value = '';
                document.getElementById('communities-sort-select').value = 'shared_count_desc';
                renderCommunitiesFilterPanel();
                applyLocalFilter();
            };

            let setCommunitiesPage = (page) => {
                communitiesPage = page;
                renderCommunitiesView();
                document.getElementById("communities-view").scrollIntoView({behavior: 'smooth'});
            };

            let renderCommunitiesPagination = () => {
                const total = filteredCommunities.length;
                const pages = Math.ceil(total / communitiesLimit);
                if (pages <= 1) return '';
                const start = (communitiesPage - 1) * communitiesLimit + 1;
                const end = Math.min(communitiesPage * communitiesLimit, total);
                let html = `<div style="margin:10px 0;display:flex;gap:5px;align-items:center;flex-wrap:wrap;">`;
                html += `<span>${start}-${end} of ${total} | Page ${communitiesPage}/${pages}</span>`;
                html += `<button onclick="setCommunitiesPage(1)" ${communitiesPage===1?'disabled':''}>&#171;</button>`;
                html += `<button onclick="setCommunitiesPage(${communitiesPage-1})" ${communitiesPage===1?'disabled':''}>&#8249;</button>`;
                const pStart = Math.max(1, communitiesPage - 2);
                const pEnd = Math.min(pages, communitiesPage + 2);
                for (let i = pStart; i <= pEnd; i++) {
                    html += `<button onclick="setCommunitiesPage(${i})" ${i===communitiesPage?'style="font-weight:bold"':''}>${i}</button>`;
                }
                html += `<button onclick="setCommunitiesPage(${communitiesPage+1})" ${communitiesPage===pages?'disabled':''}>&#8250;</button>`;
                html += `<button onclick="setCommunitiesPage(${pages})" ${communitiesPage===pages?'disabled':''}>&#187;</button>`;
                html += `</div>`;
                return html;
            };

            const renderCommunityCard = (c) => {
                const name = c.name || c.slug;
                const aboutFetched = c.about_fetched ? 'details fetched' : 'not fetched';
                const aboutColor = c.about_fetched ? 'green' : '#888';

                // Try to parse about_data for additional info
                let description = '';
                let memberCount = '';
                if (c.about_data) {
                    try {
                        const about = JSON.parse(c.about_data);
                        if (about.description) description = about.description;
                        if (about.memberCount) memberCount = `${about.memberCount} total members`;
                    } catch(e) {}
                }

                const descHtml = description ? `<small style="color: #aaa; display: block; margin: 3px 0;">${description.substring(0, 120)}${description.length > 120 ? '...' : ''}</small>` : '';
                const memberCountHtml = memberCount ? ` | ${memberCount}` : '';

                return `
                    <article style="margin: 4px 0; padding: 10px; border: 1px solid #444; border-radius: 6px; cursor: pointer"
                        onclick="showCommunityMembers('${c.slug.replace(/'/g, "\\'")}')">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <b>${name}</b>
                            <span style="color: ${aboutColor}; font-size: 0.8em;">${aboutFetched}</span>
                        </div>
                        ${descHtml}
                        <small>
                            <b>${c.shared_user_count}</b> shared members${memberCountHtml} |
                            slug: ${c.slug}
                        </small>
                    </article>
                `;
            };

            const renderCommunitiesView = () => {
                const listEl = document.getElementById("communities-list");
                if (!listEl) return;

                const offset = (communitiesPage - 1) * communitiesLimit;
                const pageCommunities = filteredCommunities.slice(offset, offset + communitiesLimit);

                let html = '';
                for (const c of pageCommunities) {
                    html += renderCommunityCard(c);
                }
                html += renderCommunitiesPagination();

                if (filteredCommunities.length === 0) {
                    html = '<p style="color: #888; padding: 20px;">No communities found matching filters.</p>';
                }

                listEl.innerHTML = html;
            };

            // Show members of a specific community in the secondary view
            let selectedCommunitySlug = null;
            let cachedProfiles = null;

            let showCommunityMembers = async (slug) => {
                selectedCommunitySlug = slug;
                const secondaryView = document.getElementById('communities-secondary-view');
                if (!secondaryView) return;

                secondaryView.innerHTML = `<h3>Loading members...</h3>`;

                // Load profiles once and cache (already deduplicated by backend)
                if (!cachedProfiles) {
                    const res = await get('/api/profile');
                    if (!res.ok) {
                        secondaryView.innerHTML = `<h3>Error loading profiles</h3>`;
                        return;
                    }
                    cachedProfiles = res.data;
                }

                // Find members who belong to the selected community
                const matchingMembers = [];
                for (const p of cachedProfiles) {
                    if (!p.groups_member_of) continue;
                    try {
                        const groups = JSON.parse(p.groups_member_of);
                        if (Array.isArray(groups)) {
                            for (const g of groups) {
                                if (g.name === slug) {
                                    matchingMembers.push(p);
                                    break;
                                }
                            }
                        }
                    } catch(e) {}
                }

                const communityInfo = allCommunities.find(c => c.slug === slug);
                const communityName = communityInfo ? (communityInfo.name || slug) : slug;

                let html = `<h3>${communityName}</h3>`;
                html += `<small>${matchingMembers.length} shared members</small><br><br>`;

                for (const m of matchingMembers) {
                    const name = [m.first_name, m.last_name].filter(Boolean).join(' ') || m.name || m.skool_id;
                    html += `<article style="margin: 4px 0; padding: 6px 8px; border-left: 3px solid var(--theme-color, #4a90d9);">
                        <b>${name}</b> <small style="color:#888">@${m.name || ''}</small><br>
                        <small>ID: ${m.skool_id}</small>
                    </article>`;
                }

                if (matchingMembers.length === 0) {
                    html += `<small style="color:#999">No matching members found (profiles may not be fetched yet)</small>`;
                }

                secondaryView.innerHTML = html;
            };

            // Filter panel rendering
            let communitiesBuildFilterRow = (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>`;
            };

            let renderCommunitiesFilterPanel = () => {
                let html = '';

                // Min shared members
                html += communitiesBuildFilterRow('min_shared', 'Min Shared Members',
                    `<div class="numeric-range-wrap">
                        <input type="number" min="1" value="${communitiesFilterState.minSharedMembers}"
                            onchange="communitiesFilterState.minSharedMembers = parseInt(this.value) || 1" style="width: 80px;">
                    </div>`);

                // Apply button
                html += '<div style="margin-top: 12px;"><button onclick="applyCommunitiesFilter()" style="width: 100%; padding: 8px; font-weight: bold; background: var(--theme-color, #4a90d9); color: white !important; border: none; border-radius: 4px; cursor: pointer;">Apply</button></div>';

                // Clear button
                html += '<div style="margin-top: 8px;"><button onclick="clearCommunitiesFilter()" style="width: 100%; padding: 8px; font-weight: bold; background: #d9534f; color: white !important; border: none; border-radius: 4px; cursor: pointer;">Clear</button></div>';

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