/**
 * Insertr - The Tailwind of CMS
 * Main library entry point
 */

import { InsertrCore } from './core/insertr.js';
import { InsertrEditor } from './core/editor.js';
import { InsertrAuth } from './core/auth.js';
import { ApiClient } from './core/api-client.js';

// Create global Insertr instance
window.Insertr = {
    // Core functionality
    core: null,
    editor: null,
    auth: null,
    apiClient: null,

    // Initialize the library
    init(options = {}) {
        console.log('🔧 Insertr v1.0.0 initializing... (Hot Reload Ready)');

        this.core = new InsertrCore(options);
        this.auth = new InsertrAuth(options);
        this.apiClient = new ApiClient(options);
        this.editor = new InsertrEditor(this.core, this.auth, this.apiClient, options);

        // Auto-initialize if DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.start());
        } else {
            this.start();
        }

        return this;
    },

    // Start the system - only creates the minimal trigger
    start() {
        if (this.auth) {
            this.auth.init(); // Creates footer trigger only
        }
        // Note: Editor is NOT started here, only when trigger is clicked
    },

    // Start the full editor system (called when trigger is activated)
    startEditor() {
        if (this.editor && !this.editor.isActive) {
            this.editor.start();
        }
    },

    // Public API methods
    login() {
        return this.auth ? this.auth.toggleAuthentication() : null;
    },

    logout() {
        if (this.auth && this.auth.isAuthenticated()) {
            this.auth.toggleAuthentication();
        }
    },

    toggleEditMode() {
        return this.auth ? this.auth.toggleEditMode() : null;
    },

    isAuthenticated() {
        return this.auth ? this.auth.isAuthenticated() : false;
    },

    isEditMode() {
        return this.auth ? this.auth.isEditMode() : false;
    },

    // TODO: Version info based on package.json?
};

// Auto-initialize in development mode with proper DOM ready handling
function autoInitialize() {
    if (document.querySelector('.insertr')) {
        window.Insertr.init();
    }
}

// Run auto-initialization when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', autoInitialize);
} else {
    // DOM is already ready
    autoInitialize();
}

export default window.Insertr;
