const API = '/api/dashboard/notes';

async function post(){
    const inp = document.getElementById('input');
    const text = inp.value.trim();
    if(!text) return;
    inp.value = '';
    await fetch(API, {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({title:'', content:text, category:'note', pinned:false})
    });
    load();
}

async function load(){
    const r = await fetch(API);
    const data = await r.json();
    const notes = data.notes || [];
    
    if(!notes.length){
        document.getElementById('feed').innerHTML = '<div class="empty">Chưa có ghi chú nào.</div>';
        return;
    }

    document.getElementById('feed').innerHTML = notes.map(n => {
        const d = new Date(n.created_at);
        const time = d.toLocaleDateString('vi-VN') + ' ' + d.toLocaleTimeString('vi-VN',{hour:'2-digit',minute:'2-digit'});
        const title = n.title ? `<div class="memo-title">${esc(n.title)}</div>` : '';
        return `
        <div class="memo">
            <div class="memo-head">
                <span class="memo-time">${time}</span>
                ${n.pinned ? '<span class="memo-pin">PIN</span>' : ''}
            </div>
            ${title}
            <div class="memo-text">${esc(n.content)}</div>
            <div class="memo-act">
                <button onclick="pin('${n.id}',${!n.pinned})">${n.pinned?'Bỏ pin':'Pin'}</button>
                <button class="del" onclick="del('${n.id}')">Xóa</button>
            </div>
        </div>`;
    }).join('');
}

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

async function pin(id,val){
    await fetch(API+'/'+id+'/pin',{method:'PATCH'});
    load();
}
async function del(id){
    if(!confirm('Xóa ghi chú này?')) return;
    await fetch(API+'/'+id,{method:'DELETE'});
    load();
}

load();