import { state } from './state.js';
import {
    injectDependencies,
    fetchTags,
    fetchBinderList,
    fetchBinder,
    fetchSettings,
    savePlacements,
    saveViewport
} from './api.js';
import { renderBinder, updateBinderSelectors, injectOpenResourceModal } from './renderer.js';
import { initCanvas } from './canvas.js';
import {
    handleCardDrop,
    handleBinderLinkDrop,
    deleteCards,
    archiveDoneCards,
    handlePastedPaths,
    handlePastedUrls,
    handlePastedText,
    handlePastedImage,
    canUndoArrange
} from './cardActions.js';
import { openResourceModal, closeModal, toggleTag, showConfirmDialog } from './modals.js';
import { setupEventListeners, refreshImagePasteToggleButton } from './eventListeners.js';
import { initGravity, cancelGravity } from './gravity.js';

state.modals.resource = document.getElementById('resourceModal');
state.modals.binder = document.getElementById('binderModal');
state.modals.binderLink = document.getElementById('binderLinkModal');
state.modals.searchResource = document.getElementById('searchResourceModal');
state.modals.bulkTag = document.getElementById('bulkTagModal');
state.modals.bulkResize = document.getElementById('bulkResizeModal');
state.modals.binderDashboard = document.getElementById('binderDashboardModal');

injectDependencies(renderBinder, updateBinderSelectors);

injectOpenResourceModal(openResourceModal);

const BinderManager = initCanvas();

initGravity(BinderManager);


window.BinderManager = BinderManager;

window.App = {
    savePlacements,
    saveViewport,
    loadBinder: async (binderId) => {
        await fetchBinder(binderId);
        updateBinderSelectors();
    },
    handleCardDrop,
    handleBinderLinkDrop,
    deleteCards,
    archiveDoneCards,
    handlePastedPaths,
    handlePastedUrls,
    handlePastedText,
    handlePastedImage,
    canUndoArrange,
    cancelGravity,
    showCreateResourceModalWithPath: (path, x, y) => {
        openResourceModal(null);
        const fileName = path.split(/[\/\\]/).pop();
        document.getElementById('resourceTitle').value = fileName.replace(/\.[a-zA-Z0-9]{2,5}$/, '');
        document.getElementById('resourceContent').value = `Path: ${path}`;
        document.getElementById('resourceTags').value = 'Imported';
    },
    showConfirmDialog
};

window.closeModal = closeModal;
window.toggleTag = toggleTag;

document.addEventListener('DOMContentLoaded', async () => {
    setupEventListeners();
    await fetchTags();
    await fetchBinderList();
    await fetchSettings();
    refreshImagePasteToggleButton();

    if (state.binderList.length === 0) {
        try {
            const res = await fetch(`/api/binderes`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ title: 'New Workspace', description: 'Main workspace' })
            });
            const newBinder = await res.json();
            state.binderList.push(newBinder);
        } catch (e) {
            console.error('Failed to create initial binder', e);
        }
    }
    
    let lastBinderId = localStorage.getItem('lorebinder_last_binder');
    if (!lastBinderId || !state.binderList.find(c => c.id === lastBinderId)) {
        lastBinderId = state.binderList[0].id;
    }
    
    await fetchBinder(lastBinderId);
    
    updateBinderSelectors();
});
