'use client';
import { useState, useEffect, useCallback } from 'react';
import { dbOperations } from './db';
/**
 * Hook for managing the workspace (auto-created per API)
 */ export function useWorkspace(apiSpecUrl, apiName = 'API Notes') {
    const [workspace, setWorkspace] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    useEffect(()=>{
        if (!apiSpecUrl) {
            setWorkspace(null);
            setLoading(false);
            return;
        }
        const loadWorkspace = async ()=>{
            try {
                setLoading(true);
                const ws = await dbOperations.getOrCreateWorkspace(apiSpecUrl, `${apiName} Notes`);
                setWorkspace(ws);
                setError(null);
            } catch (err) {
                setError(err instanceof Error ? err : new Error('Failed to load workspace'));
            } finally{
                setLoading(false);
            }
        };
        loadWorkspace();
    }, [
        apiSpecUrl,
        apiName
    ]);
    const clearWorkspace = useCallback(async ()=>{
        if (!workspace) return;
        await dbOperations.clearWorkspace(workspace.id);
    }, [
        workspace
    ]);
    return {
        workspace,
        loading,
        error,
        clearWorkspace,
        workspaceId: workspace?.id || null
    };
}
/**
 * Hook for managing notes/files in the workspace
 */ export function useNotes(workspaceId) {
    const [notes, setNotes] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const loadNotes = useCallback(async ()=>{
        if (!workspaceId) {
            setNotes([]);
            setLoading(false);
            return;
        }
        try {
            setLoading(true);
            const list = await dbOperations.listNotes(workspaceId);
            setNotes(list);
            setError(null);
        } catch (err) {
            setError(err instanceof Error ? err : new Error('Failed to load notes'));
        } finally{
            setLoading(false);
        }
    }, [
        workspaceId
    ]);
    useEffect(()=>{
        loadNotes();
    }, [
        loadNotes
    ]);
    const createNote = useCallback(async (path, content = '')=>{
        if (!workspaceId) return null;
        const note = await dbOperations.createNote(workspaceId, path, content);
        setNotes((prev)=>[
                ...prev,
                note
            ]);
        return note;
    }, [
        workspaceId
    ]);
    const readNote = useCallback(async (path)=>{
        if (!workspaceId) return '';
        const note = await dbOperations.getNote(workspaceId, path);
        return note?.content || '';
    }, [
        workspaceId
    ]);
    const updateNote = useCallback(async (path, content)=>{
        if (!workspaceId) return;
        await dbOperations.updateNote(workspaceId, path, content);
        setNotes((prev)=>prev.map((n)=>n.path === path ? {
                    ...n,
                    content,
                    updatedAt: new Date()
                } : n));
    }, [
        workspaceId
    ]);
    const deleteNote = useCallback(async (path)=>{
        if (!workspaceId) return;
        await dbOperations.deleteNote(workspaceId, path);
        setNotes((prev)=>prev.filter((n)=>n.path !== path));
    }, [
        workspaceId
    ]);
    const renameNote = useCallback(async (oldPath, newPath)=>{
        if (!workspaceId) return;
        await dbOperations.renameNote(workspaceId, oldPath, newPath);
        setNotes((prev)=>prev.map((n)=>n.path === oldPath ? {
                    ...n,
                    path: newPath,
                    updatedAt: new Date()
                } : n));
    }, [
        workspaceId
    ]);
    const deleteAllNotes = useCallback(async ()=>{
        if (!workspaceId) return;
        await dbOperations.clearWorkspace(workspaceId);
        setNotes([]);
    }, [
        workspaceId
    ]);
    return {
        notes,
        loading,
        error,
        createNote,
        readNote,
        updateNote,
        deleteNote,
        deleteAllNotes,
        renameNote,
        refresh: loadNotes
    };
}
/**
 * Hook for managing editor state (tabs, active file, etc.)
 */ export function useEditorState(workspaceId) {
    const [state, setState] = useState(null);
    // Load saved state
    useEffect(()=>{
        if (!workspaceId) {
            setState(null);
            return;
        }
        const loadState = async ()=>{
            const saved = await dbOperations.getEditorState(workspaceId);
            if (saved) {
                setState(saved);
            } else {
                // Initialize new state
                setState({
                    workspaceId,
                    openTabs: [],
                    activeTab: null,
                    cursorPositions: {},
                    scrollPositions: {}
                });
            }
        };
        loadState();
    }, [
        workspaceId
    ]);
    // Save state when it changes
    useEffect(()=>{
        if (state && workspaceId) {
            dbOperations.saveEditorState(state);
        }
    }, [
        state,
        workspaceId
    ]);
    const openTab = useCallback(async (path)=>{
        setState((prev)=>{
            if (!prev) return prev;
            const newTabs = prev.openTabs.includes(path) ? prev.openTabs : [
                ...prev.openTabs,
                path
            ];
            return {
                ...prev,
                openTabs: newTabs,
                activeTab: path
            };
        });
    }, []);
    const closeTab = useCallback((path)=>{
        setState((prev)=>{
            if (!prev) return prev;
            const newTabs = prev.openTabs.filter((t)=>t !== path);
            const newActive = prev.activeTab === path ? newTabs[newTabs.length - 1] || null : prev.activeTab;
            return {
                ...prev,
                openTabs: newTabs,
                activeTab: newActive
            };
        });
    }, []);
    const setActiveTab = useCallback((path)=>{
        setState((prev)=>{
            if (!prev) return prev;
            return {
                ...prev,
                activeTab: path
            };
        });
    }, []);
    const saveCursorPosition = useCallback((path, line, column)=>{
        setState((prev)=>{
            if (!prev) return prev;
            return {
                ...prev,
                cursorPositions: {
                    ...prev.cursorPositions,
                    [path]: {
                        line,
                        column
                    }
                }
            };
        });
    }, []);
    const clearAllTabs = useCallback(()=>{
        setState((prev)=>{
            if (!prev) return prev;
            return {
                ...prev,
                openTabs: [],
                activeTab: null,
                cursorPositions: {},
                scrollPositions: {}
            };
        });
    }, []);
    return {
        state,
        openTab,
        closeTab,
        setActiveTab,
        saveCursorPosition,
        clearAllTabs
    };
}
export { getFileType, getMonacoLanguage, supportsPreview } from './types';
export { getWorkspaceId } from './db';
