import { useCallback, useEffect, useState } from 'react' import { invoke } from '@tauri-apps/api/core' import { isTauri, mockInvoke } from '../mock-tauri' import type { VaultEntry, GitCommit, ModifiedFile } from '../types' export function useVaultLoader(vaultPath: string) { const [entries, setEntries] = useState([]) const [allContent, setAllContent] = useState>({}) const [modifiedFiles, setModifiedFiles] = useState([]) useEffect(() => { setEntries([]) setAllContent({}) setModifiedFiles([]) const loadVault = async () => { try { let result: VaultEntry[] if (isTauri()) { result = await invoke('list_vault', { path: vaultPath }) } else { console.info('[mock] Using mock Tauri data for browser testing') result = await mockInvoke('list_vault', {}) } console.log(`Vault scan complete: ${result.length} entries found`) setEntries(result) let content: Record if (isTauri()) { content = {} } else { content = await mockInvoke>('get_all_content', {}) } setAllContent(content) } catch (err) { console.warn('Vault scan failed:', err) } } loadVault() }, [vaultPath]) const loadModifiedFiles = useCallback(async () => { try { let files: ModifiedFile[] if (isTauri()) { files = await invoke('get_modified_files', { vaultPath }) } else { files = await mockInvoke('get_modified_files', {}) } setModifiedFiles(files) } catch (err) { console.warn('Failed to load modified files:', err) setModifiedFiles([]) } }, [vaultPath]) useEffect(() => { loadModifiedFiles() }, [loadModifiedFiles]) const addEntry = useCallback((entry: VaultEntry, content: string) => { setEntries((prev) => [entry, ...prev]) setAllContent((prev) => ({ ...prev, [entry.path]: content })) }, []) const updateContent = useCallback((path: string, content: string) => { setAllContent((prev) => ({ ...prev, [path]: content })) }, []) const loadGitHistory = useCallback(async (path: string): Promise => { try { if (isTauri()) { return await invoke('get_file_history', { vaultPath, path }) } else { return await mockInvoke('get_file_history', { path }) } } catch (err) { console.warn('Failed to load git history:', err) return [] } }, [vaultPath]) const loadDiff = useCallback(async (path: string): Promise => { if (isTauri()) { return invoke('get_file_diff', { vaultPath, path }) } else { return mockInvoke('get_file_diff', { path }) } }, [vaultPath]) const isFileModified = useCallback((path: string): boolean => { return modifiedFiles.some((f) => f.path === path) }, [modifiedFiles]) const commitAndPush = useCallback(async (message: string): Promise => { if (isTauri()) { await invoke('git_commit', { vaultPath, message }) try { await invoke('git_push', { vaultPath }) return 'Committed and pushed' } catch { return 'Committed (push failed)' } } else { await mockInvoke('git_commit', { message }) await mockInvoke('git_push', {}) return 'Committed and pushed' } }, [vaultPath]) return { entries, allContent, modifiedFiles, addEntry, updateContent, loadModifiedFiles, loadGitHistory, loadDiff, isFileModified, commitAndPush, } }