<%
    // TODO: code cleanup + putting this behind a toggle/attribute
    const previousNote = (() => {
        // If we are at the subRoot, there is no previous
        if (note.noteId === subRoot.note.noteId) return null;

        const parent = note.getParentNotes()[0];
        const children = parent.getVisibleChildNotes();
        const index = children.findIndex(n => n.noteId === note.noteId);

        // If we are the first child, previous goes up a level
        // this is already protected by the first if statement
        if (index === 0) return parent;

        // We are not the first child at this level so previous
        // should go to the end of the previous tree
        let candidate = children[index - 1];
        while (candidate.hasVisibleChildren()) {
            const children = candidate.getVisibleChildNotes();
            const lastChild = children[children.length - 1];
            candidate = lastChild;
        }

        return candidate;
    })();

    const nextNote = (() => {
        // If this currently active note has children, next
        // should be the first child
        if (note.hasVisibleChildren()) return note.getVisibleChildNotes()[0];

        let parent = note.getParentNotes()[0];
        let children = parent.getVisibleChildNotes();
        let index = children.findIndex(n => n.noteId === note.noteId);

        // If we are not the last of the current level, just go
        // to the next sibling note
        if (index !== children.length - 1) return children[index + 1];

        // We are the last sibling, we need to find the next ancestral note
        while (index === children.length - 1) {
            // If we are already at subRoot level, no reason trying to go higher
            if (parent.noteId === subRoot.note.noteId) return null;

            const originalParent = parent;
            parent = parent.getParentNotes()[0];
            children = parent.getVisibleChildNotes();
            index = children.findIndex(n => n.noteId === originalParent.noteId);
        }

        return children[index + 1];
    })();
%>

<div class="navigation">
    <% if (previousNote) { %><a class="previous" href="./<%- previousNote.shareId %>"><%- previousNote.title %></a><% } %>
    <% if (nextNote) { %><a class="next" href="./<%- nextNote.shareId %>"><%- nextNote.title %></a><% } %>
</div>