// ═══════════════════════════════════════════════════════
const API = '/api/notes/v2';
let currentTag = '';
let currentSearch = '';
let newTags = [];
let searchTimer = null;
let activeTab = 'memos';
let currentMemoUid = null;

// Real data fetched from the API
let currentNotesList = [];

// ═══════════════════════════════════════════════════════
// INIT
// ═══════════════════════════════════════════════════════
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();
    
    const params = new URLSearchParams(location.search);
    const isSharedMode = (params.get('shared') === '1' || params.get('shared') === 'true') && params.get('memo');
    
    initApp(isSharedMode);
    
    if (!isSharedMode) {
        setupTagInput();
        setupShortcuts();
        
        // Setup Navigation Tabs
        document.querySelectorAll('.nav-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const target = e.currentTarget.dataset.target;
                const url = new URL(window.location);
                url.searchParams.delete('memo');
                window.history.pushState({}, '', url);
                switchTab(target);
            });
        });

        // Composer Actions
        const postBtn = document.getElementById('postBtn');
        if (postBtn) postBtn.addEventListener('click', saveNote);

        // Chatbot actions
        const chatFab = document.getElementById('chatFab');
        if (chatFab) chatFab.addEventListener('click', toggleChat);
        const minimizeBtn = document.getElementById('minimizeChatBtn');
        if (minimizeBtn) minimizeBtn.addEventListener('click', toggleChat);
        const expandBtn = document.getElementById('expandChatBtn');
        if (expandBtn) expandBtn.addEventListener('click', toggleExpand);
        const chatSendBtn = document.getElementById('chatSendBtn');
        if (chatSendBtn) chatSendBtn.addEventListener('click', sendChatMessage);
        const chatInput = document.getElementById('chatInput');
        if (chatInput) chatInput.addEventListener('keydown', e => {
            if(e.key === 'Enter') sendChatMessage();
        });

        // Details comment Actions
        const commentBtn = document.getElementById('btnSubmitComment');
        if (commentBtn) commentBtn.addEventListener('click', submitComment);

        // Filter
        const searchInput = document.getElementById('searchInput');
        if (searchInput) searchInput.addEventListener('input', debounceSearch);

        // Handle browser back
        window.addEventListener('popstate', handleRouting);
        const backBtn = document.getElementById('btnBack');
        if (backBtn) backBtn.addEventListener('click', closeMemoDetail);
    }
});

function initApp(isSharedMode) {
    handleRouting();
    if (!isSharedMode) loadInboxBadge();
}

function reIcon() {
    setTimeout(() => lucide.createIcons(), 10);
}

// ═══════════════════════════════════════════════════════
// API LAYER
// ═══════════════════════════════════════════════════════
async function apiGet(path) {
    const res = await fetch(`${API}${path}`);
    return res.json();
}
async function apiPost(path, body) {
    const res = await fetch(`${API}${path}`, {
        method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body)
    });
    return res.json();
}
async function apiPatch(path, body) {
    const res = await fetch(`${API}${path}`, {
        method: 'PATCH', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body)
    });
    return res.json();
}
async function apiDelete(path) {
    const res = await fetch(`${API}${path}`, { method: 'DELETE' });
    return res.json();
}

// ═══════════════════════════════════════════════════════
// LOAD DATA
// ═══════════════════════════════════════════════════════
async function loadNotes() {
    let p = '/?limit=100';
    if (currentTag) p += `&tag=${encodeURIComponent(currentTag)}`;
    if (currentSearch) p += `&search=${encodeURIComponent(currentSearch)}`;

    const data = await apiGet(p);
    currentNotesList = data.data || [];
    renderNotes(currentNotesList, 'noteListContainer', null);
    renderMemoExplorer(); // Refresh right sidebar with new aggregate tags and stats
}

async function loadArchived() {
    const data = await apiGet('/?include_archived=true&limit=100');
    const archived = (data.data || []).filter(n => n.row_status === 'ARCHIVED');
    renderArchivedNotes(archived);
}

// ═══════════════════════════════════════════════════════
// DYNAMIC 3-COLUMN ROUTING
// ═══════════════════════════════════════════════════════
function handleRouting() {
    const params = new URLSearchParams(location.search);
    const memoUid = params.get('memo');
    const isShared = params.get('shared') === '1' || params.get('shared') === 'true';

    if (isShared && memoUid) {
        // SHARED MODE: read-only, single memo only
        document.getElementById('appShell').classList.add('shared-mode');
        if(!document.getElementById('sharedBanner')) {
            const banner = document.createElement('div');
            banner.id = 'sharedBanner';
            banner.className = 'shared-banner';
            banner.innerHTML = '<i data-lucide="share-2"></i> You are viewing a shared memo.';
            document.body.insertBefore(banner, document.getElementById('appShell'));
            reIcon();
        }
        renderStandaloneDetailWrapper(memoUid, false);
        return; // Don't load anything else
    }

    if (memoUid) {
        document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
        renderStandaloneDetailWrapper(memoUid, false); 
    } else {
        document.getElementById('appShell').classList.remove('shared-mode');
        const banner = document.getElementById('sharedBanner');
        if(banner) banner.remove();
        showListView();
    }
}

function showListView() {
    document.getElementById('detailView').classList.remove('active');
    document.getElementById('listView').classList.add('active');
    document.title = 'CuCu Note';
    currentMemoUid = null;
    
    if (activeTab === 'memos') {
        loadNotes();
    }
}

function openMemoDetail(uid) {
    const url = new URL(window.location);
    url.searchParams.set('memo', uid);
    window.history.pushState({}, '', url);
    renderStandaloneDetailWrapper(uid, true);
}

function closeMemoDetail() {
    const url = new URL(window.location);
    url.searchParams.delete('memo');
    window.history.pushState({}, '', url);
    showListView();
}

async function renderStandaloneDetailWrapper(uid, fromClick) {
    currentMemoUid = uid;
    document.getElementById('listView').classList.remove('active');
    document.getElementById('detailView').classList.add('active');

    try {
        const data = await apiGet(`/${uid}`);
        const note = data.data;
        if (!note) { toast('Note not found.'); closeMemoDetail(); return; }

        document.title = `${(note.content || '').substring(0, 20)}...`;

        // 1. Render Center
        const detailContainer = document.getElementById('detailContainer');
        detailContainer.innerHTML = generateNoteCardHTML(note, false); // false = detail content
        
        // 2. Render Comments
        loadComments(uid);

        // 3. Render Right Context Sidebar
        renderMemoDetailSidebar(note);

        reIcon();
    } catch(e) {
        toast('Error loading note');
        closeMemoDetail();
    }
}

// ═══════════════════════════════════════════════════════
// RIGHT CONTEXTUAL SIDEBAR RENDERERS
// ═══════════════════════════════════════════════════════

function renderMemoExplorer() {
    const sidebar = document.getElementById('rightSidebarContent');
    if (!sidebar) return;
    
    // Aggregate tags
    const allTags = new Set();
    currentNotesList.forEach(n => (n.tags || []).forEach(t => allTags.add(t)));
    let tagsHtml = Array.from(allTags).map(t => 
        `<span class="note-tag" onclick="filterByTag(null, '${t}')" style="${currentTag === t ? 'background:var(--primary);color:white' : ''}">#${t}</span>`
    ).join('');
    
    // Stats
    const memoCount = currentNotesList.length;

    sidebar.innerHTML = `
        <div class="explorer-block pt-12">
            <div class="explorer-title">Tags</div>
            <div class="sidebar-tag-list">
                ${tagsHtml || '<span class="meta-value" style="color:var(--muted-foreground)">No tags</span>'}
            </div>
        </div>
        
        <div class="explorer-block" style="margin-top: 24px;">
            <div id="activityCalendarWrap">
                <!-- Activity Calendar renders here -->
                <div style="font-size:0.75rem; color:var(--muted-foreground); text-align:center;">Loading activity...</div>
            </div>
        </div>
    `;
    
    // Trigger async load for heatmap
    loadAndRenderActivityCalendar('activityCalendarWrap');
    
    reIcon();
}

// ═══════════════════════════════════════════════════════
// ACTIVITY CALENDAR HEATMAP
// ═══════════════════════════════════════════════════════
async function loadAndRenderActivityCalendar(containerId) {
    try {
        const res = await apiGet('/activity');
        const counts = res.data || {};
        
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth();
        const monthName = now.toLocaleString('en-US', { month: 'long', year: 'numeric' });
        
        // First day of month and total days
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const totalDays = lastDay.getDate();
        const startDow = firstDay.getDay(); // 0=Sun
        
        let html = `
        <div class="activity-calendar">
            <div class="cal-header">
                <div class="cal-title">${monthName}</div>
            </div>
            <div class="cal-weekdays">
                <span class="weekend">S</span><span>M</span><span>T</span><span>W</span><span>T</span><span>F</span><span class="weekend">S</span>
            </div>
            <div class="cal-grid">
        `;

        // Empty cells before first day
        for (let i = 0; i < startDow; i++) {
            html += `<div class="cal-cell outside"></div>`;
        }

        // Each day of month
        const todayStr = now.toISOString().split('T')[0];
        for (let day = 1; day <= totalDays; day++) {
            const d = new Date(year, month, day);
            const dateStr = `${year}-${String(month+1).padStart(2,'0')}-${String(day).padStart(2,'0')}`;
            const count = counts[dateStr] || 0;
            
            let lvl = 0;
            if (count === 1) lvl = 1;
            else if (count >= 2 && count <= 3) lvl = 2;
            else if (count >= 4 && count <= 6) lvl = 3;
            else if (count > 6) lvl = 4;

            const isToday = dateStr === todayStr;
            const isWeekend = d.getDay() === 0 || d.getDay() === 6;
            const isFuture = d > now;
            
            let classes = `cal-cell lvl-${lvl}`;
            if (isToday) classes += ' today';
            if (isFuture) classes += ' outside';
            if (isWeekend && !isToday) classes += ' weekend';
            
            html += `<div class="${classes}" title="${dateStr}: ${count} memos">${day}</div>`;
        }

        html += `
            </div>
            <div class="cal-legend">
                <span>Less</span>
                <div class="cal-legend-blocks">
                    <div class="cal-legend-block lvl-0" title="0 memos"></div>
                    <div class="cal-legend-block lvl-1" title="1 memo"></div>
                    <div class="cal-legend-block lvl-2" title="2-3 memos"></div>
                    <div class="cal-legend-block lvl-3" title="4-6 memos"></div>
                    <div class="cal-legend-block lvl-4" title="7+ memos"></div>
                </div>
                <span>More</span>
            </div>
        </div>`;

        const container = document.getElementById(containerId);
        if (container) container.innerHTML = html;

    } catch(e) {
        console.error("Failed to load activity", e);
        const container = document.getElementById(containerId);
        if (container) container.innerHTML = '<div style="color:#ef4444; font-size:0.75rem;">Failed to load activity heatmap</div>';
    }
}

function renderMemoDetailSidebar(note) {
    const sidebar = document.getElementById('rightSidebarContent');
    if (!sidebar) return;

    const tagsHtml = (note.tags || []).length > 0 
        ? note.tags.map(t => `<span class="note-tag">#${t}</span>`).join('')
        : '<span class="meta-value" style="color:var(--muted-foreground);">No tags</span>';
        
    const timeStr = note.created_at ? new Date(note.created_at).toLocaleString('en-US', {month:'short', day:'numeric', year:'numeric', hour:'numeric', minute:'2-digit'}) : 'Unknown';
    const visIconName = note.visibility === 'PUBLIC' ? 'globe' : (note.visibility === 'PROTECTED' ? 'users' : 'lock');

    sidebar.innerHTML = `
        <div class="explorer-block">
            <div class="explorer-title">Memo Properties</div>
            
            <div class="meta-row">
                <div class="meta-label">Created At</div>
                <div class="meta-value">${timeStr}</div>
            </div>
            
            <div class="meta-row">
                <div class="meta-label">Visibility</div>
                <div class="meta-value capitalize" style="display:flex; align-items:center; gap:6px;">
                    <i data-lucide="${visIconName}" style="width:14px;height:14px;"></i>
                    ${note.visibility.toLowerCase()}
                </div>
            </div>
            
            <div class="meta-row">
                <div class="meta-label">Pinned</div>
                <div class="meta-value">${note.pinned ? 'Yes' : 'No'}</div>
            </div>
        </div>
        
        <div class="explorer-block" style="margin-top: 32px;">
            <div class="explorer-title">Labels</div>
            <div class="sidebar-tag-list">
                ${tagsHtml}
            </div>
        </div>
        
        <div class="explorer-block" style="margin-top: 32px;">
            <div class="explorer-title">Relations</div>
            <div class="empty-state" style="padding: 24px 12px; background: transparent; border-color: transparent;">
                <i data-lucide="git-commit" style="width:24px;height:24px;"></i>
                <div style="font-size:0.875rem;">No relations</div>
            </div>
        </div>
    `;
    reIcon();
}


// ═══════════════════════════════════════════════════════
// TAB SWITCHING (Fake SPA for other sections)
// ═══════════════════════════════════════════════════════
function switchTab(tabId) {
    const rawTab = tabId.replace('tab-', '');
    activeTab = rawTab;

    document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
    const btn = document.querySelector(`[data-target="${tabId}"]`);
    if(btn) btn.classList.add('active');

    document.querySelectorAll('.page-section').forEach(s => s.classList.remove('active'));
    
    // Clear right sidebar if not memos
    if (activeTab !== 'memos') {
        document.getElementById('rightSidebarContent').innerHTML = '';
    }

    const section = document.getElementById(tabId);
    if(section) section.classList.add('active');

    if (activeTab === 'memos') showListView();
    if (activeTab === 'inbox') loadInbox();
    if (activeTab === 'archived') loadArchived();
    // Explore could load public notes
}

// ═══════════════════════════════════════════════════════
// ACTION FUNCTIONS (Create, Edit, Delete, Pin)
// ═══════════════════════════════════════════════════════
async function saveNote() {
    const input = document.getElementById('composerInput');
    const content = input.value.trim();
    if (!content) return;

    const vis = 'PUBLIC'; // Default to public
    const btn = document.getElementById('postBtn');
    btn.disabled = true;

    // Build tags from composerTagInput if provided
    const tagInputStr = document.getElementById('composerTagInput').value.trim();
    const parsedTags = tagInputStr ? tagInputStr.split(' ').map(t => t.replace(/^#/, '')).filter(t => !!t) : [...newTags];

    try {
        await apiPost('/', { content, tags: parsedTags, visibility: vis });
        input.value = '';
        document.getElementById('composerTagInput').value = '';
        newTags = [];
        currentTag = '';  // Clear filter so new note shows
        currentSearch = '';
        document.getElementById('searchInput').value = '';
        toast('Memo created successfully');
        loadNotes();
    } catch { toast('Error saving note'); }
    finally { btn.disabled = false; }
}

async function startEdit(uid) { document.getElementById(`note-${uid}`).classList.add('editing'); }
async function cancelEdit(uid) { document.getElementById(`note-${uid}`).classList.remove('editing'); }

async function confirmEdit(uid) {
    const content = document.getElementById(`edit-${uid}`).value.trim();
    if (!content) return;
    await apiPatch(`/${uid}`, { content });
    toast('Memo updated');
    loadNotes();
    if(currentMemoUid === uid) renderStandaloneDetailWrapper(uid, false);
}

async function pinNote(uid) {
    await apiPost(`/${uid}/pin`);
    toast('Pin status updated');
    loadNotes();
    if(currentMemoUid === uid) renderStandaloneDetailWrapper(uid, false);
}

async function deleteNote(uid) {
    if (!confirm('Archive this memo?')) return;
    await apiDelete(`/${uid}`);
    toast('Memo archived');
    loadNotes();
    if(currentMemoUid === uid) closeMemoDetail();
}

async function restoreNote(uid) {
    await apiPatch(`/${uid}`, { row_status: 'NORMAL' });
    toast('Memo restored');
    loadArchived();
}

async function hardDeleteNote(uid) {
    if (!confirm('Permanent delete? This cannot be undone.')) return;
    await apiDelete(`/${uid}?hard=true`);
    toast('Memo deleted forever');
    loadArchived();
}

async function changeVisibility(uid, newVis) {
    try {
        await apiPatch(`/${uid}`, { visibility: newVis });
        toast(`Visibility changed to ${newVis.toLowerCase()}`);
        document.querySelectorAll('.action-menu-dropdown.show').forEach(m => m.classList.remove('show'));
        loadNotes();
        if(currentMemoUid === uid) renderStandaloneDetailWrapper(uid, false);
    } catch { toast('Error changing visibility'); }
}


// ═══════════════════════════════════════════════════════
// CORE COMPONENT RENDERER
// ═══════════════════════════════════════════════════════
function generateNoteCardHTML(note, isListContext = true, isArchivedView=false) {
    const html = marked.parse(note.content || '', { breaks: true });
    
    // Time & Vis
    const time = note.created_at ? new Date(note.created_at).toLocaleString('en-US', {month:'short', day:'numeric', hour:'numeric', minute:'2-digit'}) : '';
    const creatorId = note.creator_id || 'System';
    const initials = creatorId.slice(0,2).toUpperCase();
    const commentCount = note.comment_count || 0;
    
    const visClass = (note.visibility||'PRIVATE').toLowerCase();
    const visLabel = (note.visibility||'PRIVATE') === 'PRIVATE' ? 'Workspace' : (note.visibility||'PRIVATE');
    const visIconName = visClass === 'public' ? 'globe' : (visClass === 'protected' ? 'users' : 'lock');

    const pinClass = note.pinned && isListContext ? ' pinned' : '';

    // Action Menu Drops
    let menuItems = '';
    if (isArchivedView) {
        menuItems = `
            <button class="action-menu-item" onclick="restoreNote('${note.uid}')"><i data-lucide="refresh-cw"></i> Restore</button>
            <div class="menu-separator"></div>
            <button class="action-menu-item danger" onclick="hardDeleteNote('${note.uid}')"><i data-lucide="trash-2"></i> Delete Forever</button>`;
    } else {
        // Visibility cycle: PRIVATE → PUBLIC → PROTECTED → PRIVATE
        const nextVis = (note.visibility||'PRIVATE') === 'PRIVATE' ? 'PUBLIC' : ((note.visibility||'PRIVATE') === 'PUBLIC' ? 'PROTECTED' : 'PRIVATE');
        const nextVisIcon = nextVis === 'PUBLIC' ? 'globe' : (nextVis === 'PROTECTED' ? 'users' : 'lock');
        const nextVisLabel = nextVis === 'PUBLIC' ? 'Public' : (nextVis === 'PROTECTED' ? 'Protected' : 'Private');
        menuItems = `
            <button class="action-menu-item" onclick="startEdit('${note.uid}')"><i data-lucide="edit-2"></i> Edit</button>
            <button class="action-menu-item" onclick="pinNote('${note.uid}')"><i data-lucide="pin"></i> ${note.pinned ? 'Unpin' : 'Pin'}</button>
            <button class="action-menu-item" onclick="changeVisibility('${note.uid}','${nextVis}')"><i data-lucide="${nextVisIcon}"></i> Set ${nextVisLabel}</button>
            <button class="action-menu-item" onclick="shareNoteLink('${note.uid}')"><i data-lucide="link"></i> Copy Link</button>
            <div class="menu-separator"></div>
            <button class="action-menu-item danger" onclick="deleteNote('${note.uid}')"><i data-lucide="archive"></i> Archive</button>`;
    }


    const detailClass = !isListContext ? ' detail-note-card' : '';
    const onClickAttr = isListContext ? `onclick="openMemoDetail('${note.uid}')"` : '';

    // CuCu Note hides tags in Detail Card Body (since they are in the Right Sidebar)
    const tagsHtml = isListContext && (note.tags || []).length > 0 
        ? note.tags.map(t => `<span class="note-tag" onclick="filterByTag(event, '${t}')">#${t}</span>`).join('')
        : '';

    return `
    <div class="note-card${pinClass}${detailClass}" id="note-${note.uid}">
        <div class="note-header-row">
            <div class="note-creator">
                <div class="avatar">${initials}</div>
                <div class="creator-info">
                    <span class="creator-name">${esc(creatorId)} 
                        <span class="vis-icon ${visClass}" title="Visibility"><i data-lucide="${visIconName}"></i> ${visLabel}</span>
                    </span>
                    <span class="creator-time">${time}</span>
                </div>
            </div>
            <div class="action-menu-container">
                <button class="action-menu-trigger" onclick="toggleActionMenu(event,'menu-${note.uid}')"><i data-lucide="more-horizontal"></i></button>
                <div class="action-menu-dropdown" id="menu-${note.uid}">${menuItems}</div>
            </div>
        </div>
        
        <div class="note-body" ${onClickAttr}>${html}</div>
        
        <div class="edit-panel">
            <textarea class="edit-textarea" id="edit-${note.uid}">${esc(note.content || '')}</textarea>
            <div class="edit-actions">
                <button class="btn-secondary" onclick="cancelEdit('${note.uid}')">Cancel</button>
                <button class="btn-primary" onclick="confirmEdit('${note.uid}')">Save</button>
            </div>
        </div>

        ${tagsHtml ? `<div class="note-tags">${tagsHtml}</div>` : ''}

        <div class="note-footer" ${!isListContext ? 'style="display:none"' : ''}>
            <button class="footer-btn" ${onClickAttr} title="Comments">
                <i data-lucide="message-square"></i> ${commentCount}
            </button>
        </div>
    </div>`;
}

function renderNotes(notes, containerId, emptyId) {
    const list = document.getElementById(containerId);
    if (!list) return;

    if (!notes.length) {
        list.innerHTML = `<div class="empty-state"><i data-lucide="list-x"></i><div class="empty-state-title">No memos found</div></div>`;
        reIcon();
        return;
    }
    list.innerHTML = notes.map(n => generateNoteCardHTML(n, true, false)).join('');
    reIcon();
}

function renderArchivedNotes(notes) {
    const target = document.getElementById('tab-archived');
    if (!target) return;
    
    // Quick inject container if not exists
    if (!document.getElementById('archivedListContainer')) {
        target.innerHTML = `<div class="topbar-title" style="margin-bottom:24px;">Archived</div><div class="note-list" id="archivedListContainer"></div>`;
    }

    const list = document.getElementById('archivedListContainer');
    if (!notes.length) {
        list.innerHTML = `<div class="empty-state"><i data-lucide="list-x"></i><div class="empty-state-title">No archived memos</div></div>`;
        reIcon();
        return;
    }
    list.innerHTML = notes.map(n => generateNoteCardHTML(n, true, true)).join('');
    reIcon();
}

function filterByTag(e, tag) {
    if(e) e.stopPropagation();
    if (tag) currentTag = (currentTag === tag) ? '' : tag;
    loadNotes();
}

function debounceSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        currentSearch = document.getElementById('searchInput').value.trim();
        loadNotes();
    }, 300);
}

// ═══════════════════════════════════════════════════════
// MISC HANDLERS
// ═══════════════════════════════════════════════════════
function toggleActionMenu(e, menuId) {
    e.stopPropagation();
    document.querySelectorAll('.action-menu-dropdown.show').forEach(m => {
        if (m.id !== menuId) m.classList.remove('show');
    });
    document.getElementById(menuId).classList.toggle('show');
}

function shareNoteLink(uid) {
    const url = `${location.origin}${location.pathname}?memo=${uid}&shared=1`;
    navigator.clipboard.writeText(url).then(() => toast('Link copied to clipboard')).catch(() => toast('Copy failed'));
    document.querySelectorAll('.action-menu-dropdown.show').forEach(m => m.classList.remove('show'));
}

// ── Comments ──
async function loadComments(uid) {
    try {
        const data = await apiGet(`/${uid}/comments`);
        const comments = data.data || [];
        
        const list = document.getElementById('commentThread');
        if (comments.length === 0) {
            list.innerHTML = '<div style="color:var(--muted-foreground);font-size:0.875rem">No comments yet.</div>';
        } else {
            list.innerHTML = comments.map(c => {
                const name = c.creator_name || c.creator_id || 'Anonymous';
                const initials = name.slice(0,2).toUpperCase();
                const time = c.created_at ? new Date(c.created_at).toLocaleString('en-US', {month:'short', day:'numeric', hour:'numeric', minute:'2-digit'}) : '';
                const content = marked.parse(c.content || '', { breaks: true });
                return `
                <div class="comment-item">
                    <div class="avatar">${initials}</div>
                    <div class="comment-content">
                        <div class="comment-header">
                            <span class="comment-author">${esc(name)}</span>
                            <span class="comment-time">${time}</span>
                        </div>
                        <div class="comment-text">${content}</div>
                        <div class="comment-actions-bar">
                            <button class="comment-action-btn">Reply</button>
                        </div>
                    </div>
                </div>`;
            }).join('');
        }
        reIcon();
    } catch (e) { console.error(e); }
}

async function submitComment() {
    if (!currentMemoUid) return;
    const content = document.getElementById('commentInput').value.trim();
    if (!content) return;

    const btn = document.getElementById('btnSubmitComment');
    btn.disabled = true;
    try {
        await apiPost(`/${currentMemoUid}/comments`, {
            content,
            creator_name: 'Sys Admin',
            creator_id: 'sysadmin',
        });
        document.getElementById('commentInput').value = '';
        toast('Comment added');
        loadComments(currentMemoUid);
        loadNotes();
    } catch (e) {
        toast('Error positing comment');
    } finally {
        btn.disabled = false;
    }
}

// ── Inbox ──
async function loadInbox() {
    try {
        const url = '/notifications/list?recipient_id=system';
        const data = await apiGet(url);
        const notifications = data.data || [];
        
        const target = document.getElementById('tab-inbox');
        if (!document.getElementById('notificationList')) {
            target.innerHTML = `<div class="topbar-title" style="margin-bottom:24px;">Inbox</div>
                                <button class="btn-primary" onclick="markAllRead()" style="margin-bottom:16px;">Mark all read</button>
                                <div class="note-list" id="notificationList"></div>`;
        }

        if (notifications.length === 0) {
            document.getElementById('notificationList').innerHTML = '<div class="empty-state"><i data-lucide="bell"></i><div class="empty-state-title">Inbox is empty</div></div>';
            reIcon();
            return;
        }

        document.getElementById('notificationList').innerHTML = notifications.map(n => {
            const name = n.sender_name || n.sender_id || 'Someone';
            const initials = name.slice(0,2).toUpperCase();
            const time = n.created_at ? new Date(n.created_at).toLocaleString() : '';
            const isUnread = n.status === 'UNREAD';
            return `
            <div class="notification-item" style="display:flex;gap:12px;padding:12px;border:1px solid var(--border);border-radius:var(--radius);cursor:pointer;background:${isUnread?'var(--muted)':'var(--card)'}" onclick="openMemoDetail('${n.note_uid}')">
                <div class="user-avatar" style="flex-shrink:0">${initials}</div>
                <div>
                    <div><strong>${esc(name)}</strong> commented on your note</div>
                    <div style="font-size:0.75rem;color:var(--muted-foreground);margin-top:4px;">${time}</div>
                </div>
            </div>`;
        }).join('');
        reIcon();
    } catch (e) {}
}

async function markAllRead() {
    try {
        await apiPost('/notifications/read-all?recipient_id=system', {});
        toast('Marked all as read');
        loadInbox();
        loadInboxBadge();
    } catch {}
}

async function loadInboxBadge() {
    try {
        const data = await apiGet('/notifications/list?recipient_id=system&limit=1');
        const unread = data.unread_count || 0;
        const badge = document.getElementById('inboxBadge');
        if (unread > 0) { badge.textContent = unread; badge.style.display = ''; }
        else { badge.style.display = 'none'; }
    } catch {}
}

// ═══════════════════════════════════════════════════════
// UI UTILS
// ═══════════════════════════════════════════════════════
function setupTagInput() {}
function setupShortcuts() {
    document.addEventListener('keydown', e => {
        if (e.ctrlKey && e.key === 'Enter' && document.activeElement.id === 'composerInput') {
            e.preventDefault(); saveNote();
        }
    });
}
function esc(s) { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

function toast(msg) {
    const t = document.getElementById('globalToast');
    if(t) {
        t.textContent = msg;
        t.classList.add('show');
        setTimeout(() => t.classList.remove('show'), 2400);
    }
}

marked.setOptions({ breaks: true, gfm: true });

// ═══════════════════════════════════════════════════════
// AI CHATBOT WIDGET
// ═══════════════════════════════════════════════════════
let chatOpen = false;
let chatExpanded = false;
let chatMessages = [];

function toggleChat() {
    chatOpen = !chatOpen;
    const panel = document.getElementById('chatPanel');
    const fabIcon = document.getElementById('chatFab').querySelector('i');

    if (chatOpen) {
        panel.classList.add('show');
        fabIcon.setAttribute('data-lucide', 'x');
        reIcon();
        if (chatMessages.length === 0) {
            chatMessages = [{ role: 'ai', content: 'Hi there! I am the Context Assistant matching CuCu architecture.' }];
            renderChatMessages();
        }
    } else {
        panel.classList.remove('show');
        fabIcon.setAttribute('data-lucide', 'bot');
        reIcon();
    }
}

function toggleExpand() {
    chatExpanded = !chatExpanded;
    const panel = document.getElementById('chatPanel');
    const expIcon = document.getElementById('expandChatBtn').querySelector('i');
    if (chatExpanded) {
        panel.classList.add('expanded');
        expIcon.setAttribute('data-lucide', 'minimize-2');
    } else {
        panel.classList.remove('expanded');
        expIcon.setAttribute('data-lucide', 'maximize-2');
    }
    reIcon();
}

function renderChatMessages() {
    const container = document.getElementById('chatMessages');
    let html = '';
    chatMessages.forEach(msg => {
        if (msg.role === 'user') {
            html += `<div style="align-self:flex-end;background:var(--primary);color:var(--primary-foreground);padding:10px 14px;border-radius:12px;border-bottom-right-radius:4px;font-size:0.875rem;max-width:85%;margin-bottom:8px;margin-left:auto;">${esc(msg.content)}</div>`;
        } else {
            const parsed = marked.parse(msg.content || '', { breaks: true });
            html += `<div style="align-self:flex-start;background:var(--muted);color:var(--foreground);padding:10px 14px;border-radius:12px;border-bottom-left-radius:4px;font-size:0.875rem;max-width:85%;line-height:1.6;margin-bottom:8px;">${parsed}</div>`;
        }
    });
    container.innerHTML = html;
    container.scrollTop = container.scrollHeight;
}

async function sendChatMessage() {
    const input = document.getElementById('chatInput');
    const msg = input.value.trim();
    if (!msg) return;
    
    input.value = '';
    chatMessages.push({ role: 'user', content: msg });
    renderChatMessages();
    
    // Show typing indicator
    const typingId = 'typing-' + Date.now();
    chatMessages.push({ role: 'ai', content: '⏳ Thinking...', id: typingId });
    renderChatMessages();
    
    try {
        const res = await fetch('/api/agent/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ user_query: msg })
        });
        const data = await res.json();
        // Remove typing indicator
        chatMessages = chatMessages.filter(m => m.id !== typingId);
        const aiReply = data.response || data.answer || data.text || JSON.stringify(data);
        chatMessages.push({ role: 'ai', content: aiReply });
    } catch(e) {
        chatMessages = chatMessages.filter(m => m.id !== typingId);
        chatMessages.push({ role: 'ai', content: '❌ Error: Could not reach AI. Try again.' });
    }
    renderChatMessages();
}
