const store = Vue.reactive({
    cwd: '',
    files: [],
    selectedItems: [],
    searchQuery: '',
    sortBy: 'name',
    sortDesc: false,
    clipboard: { items: [], mode: null },
    recentFiles: JSON.parse(localStorage.getItem('extplorer_recent_files') || '[]'),
    showHidden: localStorage.getItem('extplorer_show_hidden') === 'true',
    viewMode: localStorage.getItem('extplorer_view_mode') || 'grid',
    isMobile: window.innerWidth < 992,
    isLoading: false,
    isDraggingOver: false,
    treeVersion: 0,
    uploadProgress: 0,
    uploadCurrent: 0,
    uploadTotal: 0,
    uploadFileName: '',
    error: null,
    
    // Trash State
    isTrashMode: false,
    trashItems: [],

    refreshTree() {
        this.treeVersion++;
    },

    async reload() {
        await this.loadPath(this.cwd);
        this.refreshTree();
    },

    pagination: {
        page: 1,
        pageSize: Number(localStorage.getItem('extplorer_page_size')) || 100,
        total: 0
    },

    toggleViewMode(mode) {
        if (!mode) {
            this.viewMode = this.viewMode === 'grid' ? 'list' : 'grid';
        } else {
            this.viewMode = mode;
        }
        localStorage.setItem('extplorer_view_mode', this.viewMode);
    },

    toggleHidden() {
        this.showHidden = !this.showHidden;
        localStorage.setItem('extplorer_show_hidden', this.showHidden);
        this.loadPath(this.cwd);
    },

    setPageSize(size) {
        const next = Number(size) || this.pagination.pageSize;
        if (next === this.pagination.pageSize) return;
        this.pagination.pageSize = next;
        localStorage.setItem('extplorer_page_size', String(next));
        this.loadPath(this.cwd, 1);
    },
    
    // Trash Actions
    async loadTrash() {
        this.isLoading = true;
        this.error = null;
        this.isTrashMode = true;
        this.selectedItems = [];
        try {
            const res = await Api.get('trash/list');
            this.trashItems = res.items.map(i => ({...i, mtime: i.deletedAt})); // Map deletedAt to mtime for sorting
            this.pagination.total = this.trashItems.length;
        } catch (e) {
            this.error = e.message;
        } finally {
            this.isLoading = false;
        }
    },

    exitTrash() {
        this.isTrashMode = false;
        this.loadPath(this.cwd || '');
    },

    addToRecent(file) {
        if (file.type === 'dir') return;
        // Remove if already exists to move to top
        this.recentFiles = this.recentFiles.filter(f => f.path !== file.path);
        this.recentFiles.unshift(file);
        // Keep only last 10
        if (this.recentFiles.length > 10) this.recentFiles.pop();
        localStorage.setItem('extplorer_recent_files', JSON.stringify(this.recentFiles));
    },

    clearRecent() {
        this.recentFiles = [];
        localStorage.removeItem('extplorer_recent_files');
    },

    async loadPath(path, page = 1) {
        this.isLoading = true;
        this.isTrashMode = false; // Always exit trash mode when navigating
        this.error = null;
        this.selectedItems = []; // Clear selection on navigate
        this.searchQuery = ''; // Clear search query when navigating
        
        try {
            const offset = (page - 1) * this.pagination.pageSize;
            const res = await Api.get('ls', { 
                path, 
                showHidden: this.showHidden,
                limit: this.pagination.pageSize,
                offset: offset,
                sortBy: this.sortBy,
                sortDesc: this.sortDesc
            });
            
            const items = res.items;
            this.pagination.total = res.total;
            this.pagination.page = page;
            this.files = items;
            this.cwd = path;
            
            // Persist Last Path
            localStorage.setItem('extplorer_last_path', path);
        } catch (e) {
            this.error = e.message;
            console.error(e);
        } finally {
            this.isLoading = false;
        }
    },

    async performSearch(query) {
        if (!query) {
            return this.loadPath(this.cwd);
        }
        this.isLoading = true;
        this.error = null;
        this.selectedItems = [];
        try {
            const res = await Api.get('search', { q: query });
            this.files = res.items;
            this.pagination.total = res.total;
            this.pagination.page = 1;
        } catch (e) {
            this.error = e.message;
        } finally {
            this.isLoading = false;
        }
    },

    toggleSelection(file) {
        const index = this.selectedItems.findIndex(f => f.name === file.name);
        if (index === -1) {
            this.selectedItems.push(file);
        } else {
            this.selectedItems.splice(index, 1);
        }
    },

    isSelected(file) {
        return this.selectedItems.some(f => f.name === file.name);
    },

    clearSelection() {
        this.selectedItems = [];
    }
});

// Global resize listener
window.addEventListener('resize', () => {
    store.isMobile = window.innerWidth < 992;
});
