// people_profile_overview.js — Overview tab for People Profile (Phase 3)
// Shows: Activity heatmap, Bio, Interests, Communities, Notes (CRUD), AI Analysis

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

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

    // ========== Render (synchronous parts) ==========

    function render(member, skoolId, profileData) {
        let html = '';

        // Activity heatmap
        const da = profileData.dailyActivities;
        const ca = profileData.communityActivities;
        const hasGeneral = da && da.counts && da.counts.length > 0;

        if (hasGeneral) {
            const refStartDate = new Date(da.startDate);
            const refTotalDays = da.counts.length;
            const alignedCounts = alignActivityData(ca, refStartDate, refTotalDays);

            html += '<div class="pp-section">';
            html += '<div class="pp-section__header">';
            html += '<span class="pp-section__title">Activity</span>';
            html += '<div class="pp-heatmap-toggle">';
            const preferredMode = localStorage.getItem('pp-heatmap-mode') || 'skool';
            const skoolActive = preferredMode === 'skool';
            html += '<button class="pp-heatmap-toggle__btn' + (skoolActive ? ' pp-heatmap-toggle__btn--active' : '') + '" data-heatmap-mode="skool" onclick="PeopleProfileOverview.toggleHeatmap(\'skool\')">Skool</button>';
            html += '<button class="pp-heatmap-toggle__btn' + (!skoolActive ? ' pp-heatmap-toggle__btn--active' : '') + '" data-heatmap-mode="community" onclick="PeopleProfileOverview.toggleHeatmap(\'community\')">Community</button>';
            html += '</div>';
            html += '</div>';
            html += '<div id="pp-heatmap-container">';
            const initialCounts = preferredMode === 'community' ? alignedCounts : da.counts;
            html += renderActivityHeatmap(initialCounts, refStartDate, preferredMode);
            html += '</div>';
            html += '</div>';

            // Store for toggle
            window._ppHeatmapData = {
                skoolCounts: da.counts,
                communityCounts: alignedCounts,
                startDate: refStartDate
            };
        }

        // Interests section
        const interests = peopleMemberInterests.get(skoolId);
        if (interests && interests.length > 0) {
            html += '<div class="pp-section">';
            html += '<div class="pp-section__title">Interests</div>';
            html += '<div class="pp-interests">';
            for (const t of interests) {
                const hue = peopleCategoryHueMap[t.category] ?? 0;
                const pct = Math.round(t.weight * 100);
                const barWidth = Math.max(pct, 5);
                html += '<div class="pp-interest-row">';
                html += '<span class="pp-interest-pill" style="background:hsl(' + hue + ',50%,25%);color:hsl(' + hue + ',80%,80%);border:1px solid hsl(' + hue + ',50%,35%);">' + lib.escapeHtml(t.category) + '</span>';
                html += '<div class="pp-interest-bar"><div class="pp-interest-bar__fill" style="width:' + barWidth + '%;background:hsl(' + hue + ',60%,50%);"></div></div>';
                html += '<small class="pp-interest-pct">' + pct + '%</small>';
                html += '</div>';
            }
            html += '</div></div>';
        } else {
            html += '<div id="pp-interests-placeholder"></div>';
        }

        // Notes section (async load)
        html += '<div class="pp-section">';
        html += '<div class="pp-section__title">Notes</div>';
        html += '<div id="pp-notes-section" data-skool-id="' + skoolId + '">';
        html += '<div id="pp-notes-list"><small style="color:var(--color-text-secondary)">Loading notes...</small></div>';
        html += '<div style="margin-top:var(--space-2);">';
        html += '<textarea id="pp-new-note-input" rows="2" class="pp-textarea" placeholder="Add a note..."></textarea>';
        html += '<button class="ck-btn ck-btn--secondary ck-btn--sm" onclick="PeopleProfileOverview.saveNote()" style="margin-top:var(--space-1);">Save Note</button>';
        html += '</div></div></div>';

        return html;
    }

    // ========== Async loading (notes + analysis) ==========

    function loadAsync(skoolId) {
        loadNotes(skoolId);
        loadInterestsIfMissing(skoolId);
    }

    // ========== Activity Heatmap ==========

    function 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;
    }

    function renderActivityHeatmap(counts, startDate, mode) {
        let html = '';
        const maxVal = Math.max(...counts, 1);
        const totalActivity = counts.reduce(function(a, b) { return a + b; }, 0);
        const activeDays = counts.filter(function(c) { return c > 0; }).length;

        const tooltip = mode === 'community'
            ? 'Posts & comments in your community (likes excluded)'
            : 'All activity across all Skool communities (posts, comments & likes)';
        html += '<div style="font-size:0.78rem;color:var(--color-text-secondary);margin-bottom:var(--space-1);">' + totalActivity.toLocaleString() + ' actions &middot; ' + activeDays + ' active days <span class="ck-help-icon">?<span class="ck-help-tip">' + tooltip + '</span></span></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;
        const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        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) {
                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') === 'light'
                    ? 'rgba(0,0,0,0.06)' : 'rgba(255,255,255,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;
    }

    function toggleHeatmap(mode) {
        const data = window._ppHeatmapData;
        if (!data) return;

        localStorage.setItem('pp-heatmap-mode', mode);

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

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

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

    // ========== Notes CRUD ==========

    async function loadNotes(skoolId) {
        const container = document.getElementById('pp-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="pp-note-item">';
            html += '<div class="pp-note-item__header">';
            html += '<span class="pp-note-item__date">' + date + '</span>';
            html += '<button class="pp-note-item__delete" onclick="PeopleProfileOverview.deleteNote(' + note.id + ',\'' + skoolId + '\')" title="Delete note">&times;</button>';
            html += '</div>';
            html += '<div class="pp-note-item__body">' + escaped + '</div>';
            html += '</div>';
        }
        container.innerHTML = html;
    }

    async function saveNote() {
        const section = document.getElementById('pp-notes-section');
        const input = document.getElementById('pp-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: content });
        const res = await note.save();
        if (res.ok) {
            input.value = '';
            await loadNotes(skoolId);
        }
    }

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

    // ========== AI Analysis ==========

    async function loadAnalysis(skoolId) {
        const container = document.getElementById('pp-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="PeopleProfileOverview.generateAnalysis(\'' + 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;
            }
            renderAnalysis(container, res.data.analysis, skoolId);
        } catch (e) {
            container.innerHTML = '<button class="ck-btn ck-btn--secondary ck-btn--sm" onclick="PeopleProfileOverview.generateAnalysis(\'' + skoolId + '\')">Generate Analysis</button>' +
                '<br><small style="color:var(--color-text-secondary)">AI-powered member analysis.</small>';
        }
    }

    async function generateAnalysis(skoolId) {
        const container = document.getElementById('pp-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="PeopleProfileOverview.generateAnalysis(\'' + skoolId + '\')">Retry</button>';
                return;
            }
            renderAnalysis(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="PeopleProfileOverview.generateAnalysis(\'' + 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 renderAnalysis(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="pp-analysis-card">';
        html += '<div class="pp-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="PeopleProfileOverview.generateAnalysis(\'' + skoolId + '\')" title="Regenerate analysis">Regenerate</button>';
        html += '</div>';
        html += '<div class="pp-analysis-card__body">' + formatAnalysisText(analysis.content) + '</div>';
        html += '</div>';
        container.innerHTML = html;
    }

    // ========== Interests lazy load ==========

    async function loadInterestsIfMissing(skoolId) {
        if (peopleMemberInterests.has(skoolId)) return;
        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) {
                peopleMemberInterests.set(skoolId, data.interests);
                const anchor = document.getElementById('pp-interests-placeholder');
                if (anchor) {
                    let html = '<div class="pp-section">';
                    html += '<div class="pp-section__title">Interests</div>';
                    html += '<div class="pp-interests">';
                    for (const t of data.interests) {
                        const hue = peopleCategoryHueMap[t.category] ?? 0;
                        const pct = Math.round(t.weight * 100);
                        const barWidth = Math.max(pct, 5);
                        html += '<div class="pp-interest-row">';
                        html += '<span class="pp-interest-pill" style="background:hsl(' + hue + ',50%,25%);color:hsl(' + hue + ',80%,80%);border:1px solid hsl(' + hue + ',50%,35%);">' + lib.escapeHtml(t.category) + '</span>';
                        html += '<div class="pp-interest-bar"><div class="pp-interest-bar__fill" style="width:' + barWidth + '%;background:hsl(' + hue + ',60%,50%);"></div></div>';
                        html += '<small class="pp-interest-pct">' + pct + '%</small>';
                        html += '</div>';
                    }
                    html += '</div></div>';
                    anchor.innerHTML = html;
                }
            }
        } catch (e) { /* ignore */ }
    }

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

    return {
        render: render,
        loadAsync: loadAsync,
        loadAnalysis: loadAnalysis,
        toggleHeatmap: toggleHeatmap,
        saveNote: saveNote,
        deleteNote: deleteNote,
        generateAnalysis: generateAnalysis
    };
})();
