let currentNoteId = null;
if(localStorage.getItem("mood") == null) {
    localStorage.setItem("mood","chill"); 
}

document.addEventListener('DOMContentLoaded', () => {
    loadNotesList();
    setupEventListeners();
});

function getCookie(name) {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  return match ? decodeURIComponent(match[2]) : null;
}

function base64ToBytes(b64) {
  const binary = atob(b64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return bytes;
}

function bytesToBase64(bytes) {
  let binary = "";
  for (let i = 0; i < bytes.length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

function xor(data, key) {
  const out = new Uint8Array(data.length);
  for (let i = 0; i < data.length; i++) {
    out[i] = data[i] ^ key[i % key.length];
  }
  return out;
}

function encryptParam(value) {
  const keyB64 = getCookie("client_key");
  if (!keyB64) {
    throw new Error("Missing client_key cookie");
  }

  const key = base64ToBytes(keyB64);
  const data = new TextEncoder().encode(value);

  const encrypted = xor(data, key);

  return bytesToBase64(encrypted);
}

function setupEventListeners() {
    document.getElementById('newNoteBtn').addEventListener('click', () => {
        openEditModal();
    });

    document.getElementById('moodChangeBtn').addEventListener('click', () => {
        openMoodModal();
    });

    document.getElementById('noteForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        await saveNote();
    });

    document.getElementById('shareForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        await shareNote();
    });

    document.getElementById('cancelBtn').addEventListener('click', () => {
        closeEditModal();
    });

    document.getElementById('cancelBtnShare').addEventListener('click', () => {
        closeShareModal();
    });

    document.getElementById('closeEditModal').addEventListener('click', () => {
        closeEditModal();
    });

    document.getElementById('closeShareModal').addEventListener('click', () => {
        closeShareModal();
    })

    document.getElementById('closeViewModal').addEventListener('click', () => {
        closeViewModal();
    });

    document.getElementById('closemoodChangeModal').addEventListener('click', () => {
        closemoodChangeModal();    
    })

    document.getElementById('editNoteBtn').addEventListener('click', () => {
        const noteId = currentNoteId;
        closeViewModal();
        openEditModal(noteId);
        currentNoteId = null;
    });

    document.getElementById("shareNoteBtn").addEventListener('click', () => {
        const noteId = currentNoteId;
        closeViewModal();
        openShareModal(noteId);
        currentNoteId = null;
    })

    document.getElementById('deleteNoteBtn').addEventListener('click', () => {
        deleteCurrentNote();
    });

    window.addEventListener('click', (e) => {
        if (e.target.classList.contains('modal')) {
            closeViewModal();
            closeEditModal();
        }
    });
}

function truncateTitle(title, maxLength = 20) {
    if (title.length <= maxLength) return title;
    return title.substring(0, maxLength) + '...';
}

async function loadNotesList() {
    try {
        let mood = localStorage.getItem("mood") ?? "chill";
        const response = await fetch(`/api/notes?filter=${mood}`);
        const data = await response.json();
        
        const notesGrid = document.getElementById('notesGrid');
        notesGrid.innerHTML = '';

        if (data.notes.length === 0) {
            notesGrid.innerHTML = '<div class="empty-state">No notes yet. Create your first note.</div>';
            return;
        }

        data.notes.forEach(note => {
            const card = document.createElement('div');
            card.className = 'note-card';
            card.dataset.id = note.id;
            
            const title = document.createElement('h3');
            title.textContent = truncateTitle(note.title || 'Untitled', 20);
            title.title = note.title; 
            
            card.appendChild(title);
            card.addEventListener('click', () => openViewModal(note.id));
            
            notesGrid.appendChild(card);
        });
    } catch (error) {
        console.error('Error loading notes:', error);
    }
}

async function openViewModal(id) {
    try {
        let mood = localStorage.getItem("mood") ?? "chill";
        const response = await fetch(`/api/notes/${id}?filter=${mood}`);
        const note = await response.json();

        document.getElementById('viewNoteTitle').textContent = note.title;
        
        const renderResponse = await fetch('/render/note', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                title: note.title,
                content: note.content
            })
        });

        const html = await renderResponse.text();
        
        const contentDiv = document.getElementById('viewNoteContent');
        contentDiv.innerText = note.content;

        currentNoteId = id;
        document.getElementById('viewNoteModal').classList.add('show');
    } catch (error) {
        console.error('Error loading note:', error);
    }
}

async function openMoodModal(id) {
    document.getElementById('moodChangeModal').classList.add('show');
}

function closeViewModal() {
    document.getElementById('viewNoteModal').classList.remove('show');
}

function closemoodChangeModal() {
    document.getElementById('moodChangeModal').classList.remove('show');
}

async function openEditModal(noteId = null) {
    const modal = document.getElementById('editNoteModal');
    const form = document.getElementById('noteForm');
    const modalTitle = document.getElementById('modalTitle');

    form.reset();

    if (noteId !== null) {
        modalTitle.textContent = 'Edit Note';
        document.getElementById('noteId').value = noteId;
        
        try {
            let mood = localStorage.getItem("mood") ?? "chill";
            const response = await fetch(`/api/notes/${noteId}?filter=${mood}`);
            const note = await response.json();
            
            document.getElementById('noteTitle').value = note.title;
            document.getElementById('noteContent').value = note.content;
        } catch (error) {
            console.error('Error loading note:', error);
        }
    } else {
        modalTitle.textContent = 'New Note';
        document.getElementById('noteId').value = '';
    }

    modal.classList.add('show');
}

async function openShareModal(noteId = null) {
    const modal = document.getElementById('shareNoteModal');
    const form = document.getElementById('shareForm');
    const modalTitle = document.getElementById('modalTitle');

    form.reset();

    if (noteId !== null) {
        modalTitle.textContent = 'Share Note';
        document.getElementById('noteId').value = noteId;
        
        try {
            let mood = localStorage.getItem("mood") ?? "chill";
            const response = await fetch(`/api/notes/${noteId}?filter=${mood}`);
            const note = await response.json();
            
            document.getElementById('noteTitle').value = note.title;
            document.getElementById('noteContent').value = note.content;
        } catch (error) {
            console.error('Error loading note:', error);
        }
    } else {
        modalTitle.textContent = 'New Note';
        document.getElementById('noteId').value = '';
    }

    modal.classList.add('show');
}

function closeEditModal() {
    document.getElementById('editNoteModal').classList.remove('show');
}

function closeShareModal() {
    document.getElementById('shareNoteModal').classList.remove('show');
}

async function saveNote() {
    const id = document.getElementById('noteId').value;
    const title = encryptParam(document.getElementById('noteTitle').value);
    const content = encryptParam(document.getElementById('noteContent').value);

    const data = { title, content };

    try {
        let response;
        if (id) {
            response = await fetch(`/api/notes/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
        } else {
            response = await fetch('/api/notes', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
        }

        if (response.ok) {
            closeEditModal();
            await loadNotesList();
        } else {
            const error = await response.json();
            alert(error.error || 'Error saving note');
        }
    } catch (error) {
        console.error('Error saving note:', error);
        alert('Error saving note');
    }
}

async function shareNote() {
    const note_id = document.getElementById('noteId').value;
    const allowed_ip = document.getElementById('allowedIp').value;
    const name = document.getElementById('filename').value;

    const data = { note_id, allowed_ip, name };

    try {
        response = await fetch(`/share/create`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        const resp_data = await response.json();

        if (resp_data.path) {
            alert(`Note accessible from ip ${allowed_ip} at path ${location.href}${resp_data.path.slice(1)}`);
        } else {
            alert(resp_data.error || 'Error saving note');
        }
    } catch (error) {
        console.error('Error sharing note:', error);
        alert('Error sharing note');
    }
}

async function deleteCurrentNote() {
    if (currentNoteId === null) return;

    if (!confirm('Delete this note?')) {
        return;
    }

    try {
        const response = await fetch(`/api/notes/${currentNoteId}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            closeViewModal();
            await loadNotesList();
        }
    } catch (error) {
        console.error('Error deleting note:', error);
        alert('Error deleting note');
    }
}

function setMood(mood) {
    localStorage.setItem("mood",mood);
    closemoodChangeModal();
    location.reload();
}