let data = [];
        let activeFilter = 'all';

        function esc(s) { return s ? s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;') : ''; }

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

        function render() {
            const grid = document.getElementById('linksGrid');
            let f = data;
            if (activeFilter === 'pinned') f = data.filter(l => l.pinned);
            else if (activeFilter !== 'all') f = data.filter(l => l.category === activeFilter);
            f.sort((a,b) => (a.pinned&&!b.pinned?-1:!a.pinned&&b.pinned?1:0));

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

            grid.innerHTML = f.map(l => `
                <div class="link-card ${l.pinned?'pinned':''}">
                    <div class="link-icon-box">${l.icon||'??'}</div>
                    <div class="link-info">
                        <div class="link-cat-tag lcat-${l.category}">${l.category}</div>
                        <div class="link-title">${esc(l.title)}</div>
                        <div class="link-url" onclick="window.open('${l.url}','_blank')">${l.url}</div>
                        ${l.description?`<div class="link-desc">${esc(l.description)}</div>`:''}
                    </div>
                    <div class="link-actions-row">
                        <button class="link-act" title="Open" onclick="window.open('${l.url}','_blank')">?</button>
                        <button class="link-act" title="Pin" onclick="togglePin('${l.id}')">??</button>
                        <button class="link-act" title="Edit" onclick="edit('${l.id}')">??</button>
                        <button class="link-act" title="Delete" onclick="del('${l.id}')">???</button>
                    </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 openModal() { document.getElementById('modal').classList.add('show'); document.getElementById('editId').value=''; document.getElementById('fTitle').value=''; document.getElementById('fUrl').value=''; document.getElementById('fDesc').value=''; document.getElementById('fCat').value='tool'; document.getElementById('fIcon').value=''; document.getElementById('fPin').checked=false; document.getElementById('modalTitle').textContent='?? Add Resource'; setTimeout(()=>document.getElementById('fTitle').focus(),100); }
        function closeModal() { document.getElementById('modal').classList.remove('show'); }

        function edit(id) { const l=data.find(x=>x.id===id); if(!l)return; document.getElementById('modal').classList.add('show'); document.getElementById('editId').value=id; document.getElementById('fTitle').value=l.title; document.getElementById('fUrl').value=l.url; document.getElementById('fDesc').value=l.description||''; document.getElementById('fCat').value=l.category; document.getElementById('fIcon').value=l.icon||''; document.getElementById('fPin').checked=l.pinned; document.getElementById('modalTitle').textContent='?? Edit Resource'; }

        async function save() {
            const id=document.getElementById('editId').value, title=document.getElementById('fTitle').value.trim(), url=document.getElementById('fUrl').value.trim();
            if(!title){document.getElementById('fTitle').focus();return;} if(!url){document.getElementById('fUrl').focus();return;}
            const body={title,url,description:document.getElementById('fDesc').value.trim(),category:document.getElementById('fCat').value,icon:document.getElementById('fIcon').value.trim(),pinned:document.getElementById('fPin').checked};
            try { await fetch(id?`/api/dashboard/links/${id}`:'/api/dashboard/links',{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/links/${id}/pin`,{method:'PATCH'});await load();}catch(e){} }
        async function del(id) { if(!confirm('Delete this resource?'))return; try{await fetch(`/api/dashboard/links/${id}`,{method:'DELETE'});await load();}catch(e){} }

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