// people_profile.js — People Profile Dossier (Phase 3)
// Loads and renders the full profile in the right panel of people.html.
// Sub-modules: people_profile_overview.js, people_profile_posts.js, people_profile_connections.js

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

    let currentSkoolId = null;
    let currentMember = null;
    let activeTab = 'general';

    // Toggle community dropdown in header
    window._toggleCommunityDropdown = function(event) {
        event.stopPropagation();
        const dropdown = document.getElementById('pp-community-dropdown');
        const toggle = event.currentTarget;
        if (!dropdown) return;
        const isVisible = dropdown.style.display !== 'none';
        dropdown.style.display = isVisible ? 'none' : 'flex';
        toggle.textContent = isVisible ? ('+' + toggle.dataset.count + ' more') : 'show less';
    };

    // Cached data per profile load
    let profileData = {
        posts: [],
        comments: [],
        likedPosts: [],
        communities: [],
        profileCommunities: [],
        dailyActivities: null,
        communityActivities: null,
        churnScore: null
    };

    // ========== Profile Loading ==========

    async function loadProfile(skoolId) {
        if (!skoolId) return;
        currentSkoolId = skoolId;
        activeTab = 'general';

        const panel = document.getElementById('people-profile-panel');
        if (!panel) return;

        panel.innerHTML = '<div class="people-profile-placeholder"><div class="people-profile-placeholder__icon"><span class="thinking-dots-inline"></span></div><div class="people-profile-placeholder__text">Loading profile...</div></div>';

        // Find the member from the people list data
        currentMember = people.find(m => m.skool_id === skoolId) || null;

        // Load all profile data in parallel
        const [postsRes, commentsRes, communitiesRes, profileCommunitiesRes, likedPostsRes, dailyActivitiesRes, communityActivitiesRes] = await Promise.all([
            get('/api/user/' + skoolId + '/posts'),
            get('/api/user/' + skoolId + '/comments'),
            get('/api/user/' + skoolId + '/communities'),
            get('/api/user/' + skoolId + '/profile-communities'),
            get('/api/user/' + skoolId + '/liked-posts'),
            get('/api/user/' + skoolId + '/daily-activities'),
            get('/api/user/' + skoolId + '/community-activities')
        ]);

        profileData.posts = postsRes.ok ? postsRes.data : [];
        profileData.comments = commentsRes.ok ? commentsRes.data : [];
        profileData.communities = communitiesRes.ok ? communitiesRes.data : [];
        profileData.profileCommunities = profileCommunitiesRes.ok ? profileCommunitiesRes.data : [];
        profileData.likedPosts = likedPostsRes.ok ? likedPostsRes.data : [];
        profileData.dailyActivities = dailyActivitiesRes.ok ? dailyActivitiesRes.data : null;
        profileData.communityActivities = communityActivitiesRes.ok ? communityActivitiesRes.data : null;
        profileData.churnScore = peopleChurnScores.get(skoolId) ?? null;

        // If skoolId changed during loading, abort
        if (currentSkoolId !== skoolId) return;

        renderProfile(panel);
    }

    // ========== Profile Rendering ==========

    function renderProfile(panel) {
        const member = currentMember;
        const skoolId = currentSkoolId;
        if (!member || !skoolId) return;

        let html = '';

        html += '<div class="ck-profile-layout">';

        // HEADER
        html += '<div class="ck-profile-layout__header">';
        html += renderProfileHeader(member, skoolId);

        // TABS
        html += '<div class="ck-profile-tabs">';
        html += '<button class="ck-profile-tab ck-profile-tab--active" data-profile-tab="general" onclick="PeopleProfile.switchTab(\'general\')">General</button>';
        html += '<button class="ck-profile-tab" data-profile-tab="analysis" onclick="PeopleProfile.switchTab(\'analysis\')">AI Analysis</button>';
        html += '<button class="ck-profile-tab" data-profile-tab="posts" onclick="PeopleProfile.switchTab(\'posts\')">Posts</button>';
        html += '<button class="ck-profile-tab" data-profile-tab="connections" onclick="PeopleProfile.switchTab(\'connections\')">Connections</button>';
        html += '</div>';
        html += '</div>'; // close header

        // TAB PANELS
        html += '<div class="ck-profile-panel-content ck-profile-panel--active" data-profile-panel="general" id="profile-tab-general">';
        html += PeopleProfileOverview.render(member, skoolId, profileData);
        html += '</div>';

        html += '<div class="ck-profile-panel-content" data-profile-panel="analysis" id="profile-tab-analysis">';
        html += '<div id="pp-analysis-section" data-skool-id="' + skoolId + '"><small style="color:var(--color-text-secondary)">Loading...</small></div>';
        html += '</div>';

        html += '<div class="ck-profile-panel-content" data-profile-panel="posts" id="profile-tab-posts">';
        html += '<div id="profile-posts-container"><div style="color:var(--color-text-secondary);padding:var(--space-3);">Click tab to load posts...</div></div>';
        html += '</div>';

        html += '<div class="ck-profile-panel-content" data-profile-panel="connections" id="profile-tab-connections">';
        html += '<div id="profile-connections-container"><div style="color:var(--color-text-secondary);padding:var(--space-3);">Click tab to load connections...</div></div>';
        html += '</div>';

        html += '</div>'; // close ck-profile-layout

        panel.innerHTML = html;

        // Load async data for overview tab
        PeopleProfileOverview.loadAsync(skoolId);
    }

    function renderProfileHeader(member, skoolId) {
        const firstName = member.first_name || '';
        const lastName = member.last_name || '';
        const displayName = (firstName + ' ' + lastName).trim() || member.name || skoolId;
        const initial = (firstName || member.name || '?')[0].toUpperCase();
        const hue = Math.abs((skoolId || '').charCodeAt(0) * 137.5) % 360;

        // Avatar
        let avatarHtml;
        if (skoolId) {
            avatarHtml = '<img class="pp-header__avatar" src="/api/image/' + skoolId + '" onclick="PeopleProfile.showImageOverlay(\'/api/image/' + skoolId + '\')" title="Click to enlarge" onerror="this.style.display=\'none\';this.nextElementSibling.style.display=\'flex\';" alt="">' +
                '<div class="pp-header__avatar pp-header__avatar--placeholder" style="display:none;background:hsl(' + hue + ',55%,45%);">' + initial + '</div>';
        } else {
            avatarHtml = '<div class="pp-header__avatar pp-header__avatar--placeholder" style="background:hsl(' + hue + ',55%,45%);">' + initial + '</div>';
        }

        // Bio from profile data
        const profile = peopleProfiles.get(skoolId);
        const bio = profile ? (profile.bio || '') : '';

        // Member age
        const memberAge = formatMemberAge(member.member_created_at);
        const memberAgeText = memberAge ? 'Member for ' + memberAge : '';

        // Churn score
        const churnScore = profileData.churnScore;
        const churnScoreText = churnScore != null ? 'Churn ' + churnScore : '';

        // Stats
        const postsCount = profileData.posts.length;
        const commentsCount = profileData.comments.length;
        const likesCount = profileData.likedPosts.length;

        // Communities pills
        const allCommunities = profileData.profileCommunities.length ?
            profileData.profileCommunities :
            profileData.communities.map(function(c) { return typeof c === 'string' ? { name: c, slug: c } : c; });

        let commPillsHtml = '';
        if (allCommunities.length > 0) {
            commPillsHtml = '<div class="pp-header__communities">';
            const maxPills = 4;
            for (let i = 0; i < Math.min(allCommunities.length, maxPills); i++) {
                const c = allCommunities[i];
                const cName = lib.escapeHtml(c.name || c.slug || c);
                commPillsHtml += '<span class="pp-community-pill">' + cName + '</span>';
            }
            if (allCommunities.length > maxPills) {
                const remainingCount = allCommunities.length - maxPills;
                commPillsHtml += '<span class="pp-community-pill pp-community-pill--more pp-community-pill--toggle" data-count="' + remainingCount + '" onclick="window._toggleCommunityDropdown(event)" style="cursor:pointer;">+' + remainingCount + ' more</span>';
                commPillsHtml += '<div class="pp-community-dropdown" id="pp-community-dropdown" style="display:none;">';
                for (let i = maxPills; i < allCommunities.length; i++) {
                    const c = allCommunities[i];
                    const cName = lib.escapeHtml(c.name || c.slug || c);
                    commPillsHtml += '<span class="pp-community-pill">' + cName + '</span>';
                }
                commPillsHtml += '</div>';
            }
            commPillsHtml += '</div>';
        }

        let html = '<div class="pp-header">';
        html += '<div class="pp-header__avatar-wrap">' + avatarHtml + '</div>';
        html += '<div class="pp-header__info">';
        html += '<div class="pp-header__name">' + lib.escapeHtml(displayName) + '</div>';
        if (bio) html += '<div class="pp-header__bio">' + lib.escapeHtml(bio) + '</div>';
        html += '<div class="pp-header__meta">' + memberAgeText + (member.member_role ? ' &middot; ' + lib.escapeHtml(member.member_role) : '') + '</div>';
        html += '<div class="pp-header__stats">' + postsCount + ' Posts &middot; ' + commentsCount + ' Comments &middot; ' + likesCount + ' Likes' + (churnScoreText ? ' &middot; ' + churnScoreText : '') + '</div>';
        html += '<div class="pp-header__ai-actions" style="margin-top:var(--space-2);">';
        html += '<button class="acb-action-btn" onclick="lib.generateProfileQuestion(\'' + lib.escapeHtml(skoolId) + '\', \'' + lib.escapeHtml(displayName).replace(/'/g, "\\'") + '\')"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2z"/></svg> Ask AI about this person</button>';
        html += '</div>';
        html += commPillsHtml;
        html += '</div></div>';

        return html;
    }

    // ========== Tab Switching ==========

    function switchTab(tabName) {
        if (activeTab === tabName) return;
        activeTab = tabName;

        document.querySelectorAll('.ck-profile-tab[data-profile-tab]').forEach(function(btn) {
            btn.classList.toggle('ck-profile-tab--active', btn.dataset.profileTab === tabName);
        });
        document.querySelectorAll('.ck-profile-panel-content[data-profile-panel]').forEach(function(panel) {
            panel.classList.toggle('ck-profile-panel--active', panel.dataset.profilePanel === tabName);
        });

        // Lazy-load tab content
        if (tabName === 'analysis') {
            PeopleProfileOverview.loadAnalysis(currentSkoolId);
        } else if (tabName === 'posts') {
            PeopleProfilePosts.render(currentSkoolId, profileData);
        } else if (tabName === 'connections') {
            PeopleProfileConnections.render(currentSkoolId, profileData);
        }
    }

    // ========== Image overlay ==========

    function showImageOverlay(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 = function() { 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);
    }

    // ========== Public API ==========

    return {
        loadProfile: loadProfile,
        switchTab: switchTab,
        showImageOverlay: showImageOverlay,
        getProfileData: function() { return profileData; },
        getCurrentSkoolId: function() { return currentSkoolId; }
    };
})();

// Global shortcut used by selectPerson() in people_list.js
async function loadProfile(skoolId) {
    await PeopleProfile.loadProfile(skoolId);
}
