/**
 * pyramid.js — 3-tier memory pyramid widget.
 * Takes { prefrontal, hippocampus, cortex } counts, renders proportional bars.
 * Each tier is clickable → filters memory list.
 * Hover → fetches sample entries via /api/memory/samples?tier=&limit=3.
 */

import { api } from '../api.js';

const TIER_META = [
    { key: 'prefrontal',  label: 'Working',   cls: 'working',  color: 'var(--accent)'    },
    { key: 'hippocampus', label: 'Episodic',  cls: 'episodic', color: 'var(--secondary)' },
    { key: 'cortex',      label: 'Semantic',  cls: 'semantic', color: 'var(--violet)'    },
];

/**
 * Render the pyramid into a container element.
 * @param {HTMLElement} container
 * @param {{ prefrontal: number, hippocampus: number, cortex: number }} counts
 * @param {string|null} activeTier - Currently selected tier filter (or null)
 * @param {Function} onTierClick   - Called with tier key when a tier is clicked
 */
export function renderPyramid(container, counts, activeTier, onTierClick) {
    if (!container) return;

    const total = (counts.prefrontal || 0) + (counts.hippocampus || 0) + (counts.cortex || 0);

    container.innerHTML = TIER_META.map(({ key, label, cls }) => {
        const count = counts[key] || 0;
        // sqrt scaling so 1 memory isn't 1px tall
        const pct = total > 0 ? Math.round((Math.sqrt(count) / Math.sqrt(total)) * 100) : 0;
        const isActive = activeTier === key;
        return `
        <div class="pyramid-tier${isActive ? ' active' : ''}" data-tier="${key}" role="button" tabindex="0"
             aria-label="${label}: ${count} memories">
            <span class="pyramid-label">${label}</span>
            <div class="pyramid-bar-wrap">
                <div class="pyramid-bar ${cls}" style="width:${pct}%"></div>
            </div>
            <span class="pyramid-count">${count}</span>
        </div>`;
    }).join('');

    // Click handlers
    container.querySelectorAll('.pyramid-tier').forEach(el => {
        el.addEventListener('click', () => {
            const tier = el.dataset.tier;
            onTierClick?.(activeTier === tier ? null : tier);
        });
        el.addEventListener('keydown', e => {
            if (e.key === 'Enter' || e.key === ' ') el.click();
        });
    });

    // Hover tooltip — fetch 3 sample entries per tier
    _attachSampleTooltips(container);
}

function _attachSampleTooltips(container) {
    const _cache = new Map();

    container.querySelectorAll('.pyramid-tier').forEach(el => {
        let tooltip = null;

        el.addEventListener('mouseenter', async () => {
            const tier = el.dataset.tier;
            let samples = _cache.get(tier);
            if (!samples) {
                const d = await api(`/api/memory/samples?tier=${tier}&limit=3`, 15_000);
                samples = d?.samples || [];
                _cache.set(tier, samples);
            }
            if (!samples.length) return;

            tooltip = document.createElement('div');
            tooltip.className = 'pyramid-tooltip';
            tooltip.style.cssText = 'position:absolute;right:calc(100% + 8px);top:0;min-width:200px;max-width:280px;background:var(--bg-panel);border:1px solid var(--border);border-radius:var(--radius);padding:8px 10px;font-size:var(--text-sm);z-index:50;pointer-events:none;';
            tooltip.innerHTML = samples.map(m => {
                const excerpt = (m.excerpt || m.content || m.title || '').slice(0, 80);
                return `<div style="padding:3px 0;border-bottom:1px solid var(--border);color:var(--text-muted);line-height:1.4">${_esc(excerpt)}</div>`;
            }).join('');
            el.style.position = 'relative';
            el.appendChild(tooltip);
        });

        el.addEventListener('mouseleave', () => {
            tooltip?.remove();
            tooltip = null;
        });
    });
}

function _esc(s) {
    return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
