<script setup>
import { ref, onMounted, watch } from 'vue';
import { emitter } from '~/services/Emitter';
import Server from '~/services/Server';
import { CreateWindow } from '~/services/Windows';
import { ShowContextMenu, HideContextMenu } from '~/services/ContextMenu';

const props = defineProps({
    folders: Array,
    notes: Array,
    campaignId: String,
    level: { type: Number, default: 0 },
    parentFolderId: String,
    expandedFolderIds: { type: Array, default: () => [] }
});

const emit = defineEmits(['open-note', 'reload-notes']);

// Track which folder IDs have been requested to avoid duplicate requests
const loadingFolders = new Set();
const dragHoveredFolderId = ref(null);

// Cache of loaded folder contents — persists across reloads until cleared
// Each entry: { [folderId]: { notes: [], subfolders: [] } }
const folderContentCache = ref({});

function toggleExpanded(folderId) {
    emit('toggle-expanded-folder', folderId);
}

watch(
    () => props.expandedFolderIds,
    () => {
        if (props.level === 0) {
            loadExpandedFolders();
        }
    },
    { deep: true }
);

onMounted(() => {
    loadExpandedFolders();
});

function loadFolderContents(folderId) {
    if (loadingFolders.has(folderId)) return;
    loadingFolders.add(folderId);

    Server().get('/note/subfolder/list', { params: { campaign: props.campaignId, folder: folderId } })
        .then(res => {
            if (res.data.status !== 'ok') return;
            folderContentCache.value[folderId] = {
                notes: res.data.notes.map(n => ({ key: n._id, title: n.title, text: n.content || '' })),
                subfolders: res.data.subfolders || []
            };
        }).catch(() => {}).finally(() => {
            loadingFolders.delete(folderId);
        });
}

function getFolderNotes(folderId) {
    return folderContentCache.value[folderId]?.notes || [];
}

function getFolderSubfolders(folderId) {
    return folderContentCache.value[folderId]?.subfolders || [];
}

// Load contents for all currently-expanded folders
function loadExpandedFolders() {
    const idsToLoad = props.level === 0
        ? props.expandedFolderIds
        : (props.parentFolderId && props.expandedFolderIds.includes(props.parentFolderId) ? [props.parentFolderId] : []);

    for (const id of idsToLoad) {
        if (folderContentCache.value[id]) continue;
        loadFolderContents(id);
    }
}

async function handleDropNoteOnFolder(folderId, event) {
    const noteKey = event.dataTransfer.getData('text/plain');
    if (!noteKey || !folderId) return;

    dragHoveredFolderId.value = null;

    try {
        await Server().post('/note/update', { id: noteKey, folder: folderId });
        emit('reload-notes');
    } catch (e) {}
}

async function handleDropNoteOnRoot(event) {
    const noteKey = event.dataTransfer.getData('text/plain');
    if (!noteKey) return;

    dragHoveredFolderId.value = null;

    try {
        await Server().post('/note/update', { id: noteKey, folder: null });
        emit('reload-notes');
    } catch (e) {}
}

// Called on reload — clears cache so expanded folders refetch fresh content
function clearCacheAndReloadExpanded() {
    const folderIdsToReLoad = [];
    if (props.level === 0) {
        for (const id of props.expandedFolderIds) {
            if (folderContentCache.value[id]) folderIdsToReLoad.push(id);
            delete folderContentCache.value[id];
        }
    } else if (props.parentFolderId && folderContentCache.value[props.parentFolderId]) {
        folderIdsToReLoad.push(props.parentFolderId);
        delete folderContentCache.value[props.parentFolderId];
    }

    // Force reactivity by creating a new object
    folderContentCache.value = {};

    for (const id of folderIdsToReLoad) {
        loadFolderContents(id);
    }
}

// Exposed to parent components
defineExpose({ clearCacheAndReloadExpanded });

function startDragNote(event, note) {
    event.dataTransfer.setData('text/plain', note.key);
    event.dataTransfer.effectAllowed = 'move';
}

function setDragHover(id) {
    dragHoveredFolderId.value = id;
}

function clearDragHover() {
    dragHoveredFolderId.value = null;
}

function buildNoteContextMenu(note) {
    return [
        { name: 'Open', icon: '/icons/iconoir/regular/book.svg', action: () => emit('open-note', note) },
        { name: 'Rename', icon: '/icons/iconoir/regular/edit-pencil.svg', action: () => renameNote(note) },
        {
            name: 'Move to Folder...', icon: '/icons/iconoir/regular/folder.svg',
            context: buildMoveToMenu(note)
        },
        { divider: true },
        { name: 'Delete', icon: '/icons/iconoir/regular/trash.svg', action: () => deleteNote(note) }
    ];
}

function buildFolderContextMenu(folder) {
    if (!folder || !folder._id) return [];
    return [
        { name: 'New Note Here', icon: '/icons/iconoir/regular/plus.svg', action: () => createNoteInFolder(folder._id) },
        { name: 'Rename', icon: '/icons/iconoir/regular/edit-pencil.svg', action: () => renameFolder(folder._id, folder.name) },
        { name: 'Delete Folder', icon: '/icons/iconoir/regular/trash.svg', action: () => deleteFolder(folder._id) }
    ];
}

let selectedNoteForMove = {};

function buildMoveToMenu(note) {
    selectedNoteForMove = note;
    const moveItems = (props.folders || []).map(folder => ({
        name: folder.name, icon: '/icons/iconoir/regular/folder.svg', action: () => moveNoteToFolder(note, folder._id)
    }));

    if (moveItems.length > 0) moveItems.push({ divider: true });

    moveItems.push({ name: '(Root)', icon: '/icons/iconoir/regular/book.svg', action: () => moveNoteToFolder(note, null) });
    return moveItems;
}

function renameNote(note) { CreateWindow('rename_note', { title: note.title, key: note.key }); }

async function deleteNote(note) {
    try {
        const response = await Server().post('/note/delete', { id: note.key });
        if (response.data.status === 'ok') { emit('reload-notes'); emitter.emit('delete-note', note.key); }
    } catch (error) {} finally {
        HideContextMenu();
    }
}

function renameFolder(folderId, name) { CreateWindow('new_folder', { folderId, campaign: props.campaignId, name }); }

async function deleteFolder(folderId) {
    const response = await Server().post('/folder/delete', { id: folderId });
    if (response.data.status === 'ok') emit('reload-notes');
    HideContextMenu();
}

async function moveNoteToFolder(note, folderId) {
    try {
        const response = await Server().post('/note/update', { id: note.key, folder: folderId || null });
        if (response.data.status !== 'ok') return;
        emit('reload-notes');
    } catch (e) {}
    HideContextMenu();
}

async function createNoteInFolder(folderId) {
    try {
        const response = await Server().post('/note/create', { title: 'New note', content: '', campaign: props.campaignId, folder: folderId });
        if (response.data.status === 'ok') emit('reload-notes');
    } catch (e) {}
}
</script>

<template>
    <div class="nested-list" :class="'level-' + level">
        <!-- Folders at this level -->
      <template v-for="folder in folders" :key="folder._id">
            <div class="folder-item" :class="{ 'drag-over': dragHoveredFolderId === folder._id }"
                  @dragover.prevent="setDragHover(folder._id)"
                  @dragleave.self="clearDragHover"
                  @drop.stop="handleDropNoteOnFolder(folder._id, $event)">
                <button type="button" class="folder-toggle" @click="toggleExpanded(folder._id)" @contextmenu.prevent="ShowContextMenu(buildFolderContextMenu(folder))">
                    <img
                        class="folder-arrow"
                        :src="expandedFolderIds.includes(folder._id) ? '/icons/iconoir/regular/nav-arrow-down.svg' : '/icons/iconoir/regular/nav-arrow-right.svg'"
                        alt="" aria-hidden="true"
                    >
                    <img class="folder-icon" src="/icons/iconoir/regular/folder.svg" alt="">
                    <span class="folder-name">{{ folder.name }}</span>
                </button>

                <div v-show="expandedFolderIds.includes(folder._id)"
                    class="folder-children" :class="{ 'drag-over': dragHoveredFolderId === folder._id }"
                    @dragover.prevent="setDragHover(folder._id)" @dragleave.self="clearDragHover"
                    @drop.stop="handleDropNoteOnFolder(folder._id, $event)">

                    <!-- Load contents now — cache will be populated on demand -->
                    <template v-if="expandedFolderIds.includes(folder._id) && !folderContentCache[folder._id]">
                        <div class="sidebar-state" style="font-size:13px;opacity:0.6;">Loading...</div>
                    </template>

                    <NestedNoteList
                        v-if="expandedFolderIds.includes(folder._id)"
                        :folders="getFolderSubfolders(folder._id)"
                        :notes="getFolderNotes(folder._id)"
                        :campaign-id="campaignId"
                        :level="level + 1"
                        :parent-folder-id="folder._id"
                        :expanded-folder-ids="expandedFolderIds"
                        @open-note="$emit('open-note', $event)"
                        @reload-notes="clearCacheAndReloadExpanded"
                        @toggle-expanded-folder="toggleExpanded"
                    />

                    <div v-if="expandedFolderIds.includes(folder._id) && folderContentCache[folder._id] !== undefined && (getFolderNotes(folder._id).length === 0 && getFolderSubfolders(folder._id).length === 0)" class="sidebar-state">
                        Empty folder
                    </div>
                </div>
            </div>
        </template>

        <!-- Notes at this level -->
        <template v-for="note in notes" :key="note.key">
            <button type="button" class="note-link" draggable="true" @dragstart="startDragNote($event, note)" @click.stop="$emit('open-note', note)" @contextmenu.prevent="ShowContextMenu(buildNoteContextMenu(note))">
                <span class="note-link-title">{{ note.title }}</span>
            </button>
        </template>

        <!-- Drop zone for root-level notes -->
        <div v-if="level === 0" class="root-drop-zone" :class="{ 'drag-over': dragHoveredFolderId === 'root' }" @drop.stop="handleDropNoteOnRoot($event)">
        </div>

        <div v-if="folders.length === 0 && (!notes || notes.length === 0) && level === 0" class="sidebar-state">Empty</div>
    </div>
</template>

<style scoped>
.nested-list { display: flex; flex-direction: column; gap: 2px; }

.folder-item { display: flex; flex-direction: column; cursor: default; border-radius: 10px; }
.folder-item.drag-over { background: var(--color-button-hover); }

.folder-toggle { width: 100%; padding: 6px 8px; margin: 0; border: none; background: transparent; display: flex; align-items: center; gap: 6px; cursor: grab; border-radius: 10px; color: var(--color-text); font-size: inherit; transition: background-color 0.15s ease; }
.folder-toggle:hover { background: var(--color-background-soft); }

.folder-arrow { width: 14px; height: 14px; filter: invert(var(--color-icon-invert)); opacity: 0.5; }
.folder-icon { width: 16px; height: 16px; filter: invert(var(--color-icon-invert)); }
.folder-name { font-weight: 500; flex: 1; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.folder-children { padding-left: 20px; margin-top: 2px; cursor: default; }
.folder-children.drag-over { background: #ffffff22; border-radius: 10px; }

.note-link { width: 100%; padding: 6px; margin: 0; box-shadow: none; border: none; display: flex; flex-direction: column; align-items: flex-start; text-align: left; cursor: grab; }
.note-link-title { font-weight: 600; word-break: break-word; }

.sidebar-state { padding: 12px; border-radius: 10px; background: var(--color-background-soft); font-size: 14px; }

.root-drop-zone { min-height: 24px; position: relative; transition: background-color 0.15s ease, border-color 0.15s ease; border-radius: 10px; }
.root-drop-zone.drag-over { background: var(--color-button-hover); }
</style>
