let data = [], activeFilter = 'all', selectedColor = 'var(--gold, #B8860B)';
        function esc(s) { return s ? s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;') : ''; }
        function fmtTime(iso) { if(!iso)return''; const d=new Date(iso),now=new Date(),diff=(now-d)/1000; if(diff<60)return'vừa xong'; if(diff<3600)return Math.floor(diff/60)+' phút trước'; if(diff<86400)return Math.floor(diff/3600)+' giờ trước'; if(diff<604800)return Math.floor(diff/86400)+' ngày trước'; return d.toLocaleDateString('vi-VN',{day:'2-digit',month:'2-digit',year:'numeric'}); }
        const catIcons = {note:'📝',doc:'📄',todo:'✅',announcement:'📢'};

        async function load() {
            try { const r=await fetch('/api/dashboard/notes'); const j=await r.json(); data=j.notes||[]; render(); }
            catch(e) { console.error(e); }
        }

        function render() {
            const grid = document.getElementById('notesGrid');
            let f = data;
            if (activeFilter === 'pinned') f = data.filter(n=>n.pinned);
            else if (activeFilter !== 'all') f = data.filter(n=>n.category===activeFilter);
            f.sort((a,b)=>(a.pinned&&!b.pinned?-1:!a.pinned&&b.pinned?1:new Date(b.updated_at||b.created_at)-new Date(a.updated_at||a.created_at)));

            if (!f.length) { grid.innerHTML = `<div class="empty-state"><div class="empty-icon">📝</div><p>No notes found.</p></div>`; return; }

            grid.innerHTML = f.map(n=>`
                <div class="note-card ${n.pinned?'pinned':''}" style="--nc:${n.color||'var(--gold, #B8860B)'}">
                    <div class="note-header">
                        <span class="note-cat">${catIcons[n.category]||'📝'} ${n.category}</span>
                        ${n.pinned?'<span style="font-size:0.8em">📌</span>':''}
                    </div>
                    <div class="note-title">${esc(n.title)}</div>
                    <div class="note-body">${esc(n.content)}</div>
                    <div class="note-footer">
                        <span class="note-time">${fmtTime(n.updated_at||n.created_at)}</span>
                        <div class="note-actions">
                            <button class="note-act-btn ${n.pinned?'pin-active':''}" title="Pin" onclick="togglePin('${n.id}')">✏️</button>
                            <button class="note-act-btn" title="Edit" onclick="edit('${n.id}')">✏️</button>
                            <button class="note-act-btn" title="Delete" onclick="del('${n.id}')">🗑️</button>
                        </div>
                    </div>
                </div>`).join('');
        }

        function filter(f,el) { activeFilter=f; document.querySelectorAll('.filter-chip').forEach(c=>c.classList.remove('active')); el.classList.add('active'); render(); }
        function pickColor(c,el) { selectedColor=c; document.querySelectorAll('.color-dot').forEach(d=>d.classList.remove('active')); el.classList.add('active'); }

        function openModal() { document.getElementById('modal').classList.add('show'); document.getElementById('editId').value=''; document.getElementById('fTitle').value=''; document.getElementById('fContent').value=''; document.getElementById('fCat').value='note'; document.getElementById('fPin').checked=false; selectedColor='var(--gold, #B8860B)'; document.querySelectorAll('.color-dot').forEach(d=>{d.classList.remove('active');if(d.style.background==='rgb(88, 166, 255)')d.classList.add('active');}); document.getElementById('modalTitle').textContent='📝 New Note'; setTimeout(()=>document.getElementById('fTitle').focus(),100); }
        function closeModal() { document.getElementById('modal').classList.remove('show'); }

        function edit(id) { const n=data.find(x=>x.id===id); if(!n)return; document.getElementById('modal').classList.add('show'); document.getElementById('editId').value=id; document.getElementById('fTitle').value=n.title; document.getElementById('fContent').value=n.content||''; document.getElementById('fCat').value=n.category; document.getElementById('fPin').checked=n.pinned; selectedColor=n.color||'var(--gold, #B8860B)'; document.querySelectorAll('.color-dot').forEach(d=>{d.classList.remove('active');if(d.style.background===selectedColor||`rgb(${parseInt(selectedColor.slice(1,3),16)}, ${parseInt(selectedColor.slice(3,5),16)}, ${parseInt(selectedColor.slice(5,7),16)})`===d.style.background)d.classList.add('active');}); document.getElementById('modalTitle').textContent='✏️ Edit Note'; }

        async function save() {
            const id=document.getElementById('editId').value,title=document.getElementById('fTitle').value.trim(),content=document.getElementById('fContent').value.trim();
            if(!title){document.getElementById('fTitle').focus();return;}
            const body={title,content,category:document.getElementById('fCat').value,color:selectedColor,pinned:document.getElementById('fPin').checked};
            try { await fetch(id?`/api/dashboard/notes/${id}`:'/api/dashboard/notes',{method:id?'PUT':'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}); closeModal(); await load(); } catch(e){alert(e.message);}
        }

        async function togglePin(id) { try{await fetch(`/api/dashboard/notes/${id}/pin`,{method:'PATCH'});await load();}catch(e){} }
        async function del(id) { if(!confirm('Delete this note?'))return; try{await fetch(`/api/dashboard/notes/${id}`,{method:'DELETE'});await load();}catch(e){} }

        document.addEventListener('keydown',e=>{if(e.key==='Escape')closeModal();});
        load();