/**
 * 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';
import { InsertrControlPanel } from './ui/control-panel.js';

// Create global Insertr instance
window.Insertr = {
    // Core functionality (business logic)
    core: null,
    editor: null,
    auth: null,
    apiClient: null,
    
    // UI layer (presentation)
    controlPanel: null,

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

        // Load CSS first
        this.loadStyles(options);

        // Initialize core business logic modules
        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);
        
        // Initialize UI layer
        this.controlPanel = new InsertrControlPanel(this.auth, this.editor, this.apiClient, options);

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

        return this;
    },

    // Load Insertr CSS styles
    loadStyles(options = {}) {
        // Check if styles are already loaded
        if (document.querySelector('link[href*="insertr.css"]') || document.getElementById('insertr-styles')) {
            return;
        }

        // Determine CSS path
        let cssPath = options.cssPath;
        if (!cssPath) {
            // Auto-detect based on script location
            const insertrScript = document.querySelector('script[data-insertr-injected]');
            if (insertrScript && insertrScript.src) {
                // Replace insertr.min.js with insertr.css
                cssPath = insertrScript.src.replace(/insertr(\.min)?\.js$/, 'insertr.css');
            } else {
                // Fallback to relative path
                cssPath = 'lib/dist/insertr.css';
            }
        }

        // Create and load CSS link
        const link = document.createElement('link');
        link.id = 'insertr-styles';
        link.rel = 'stylesheet';
        link.href = cssPath;
        link.onload = () => console.log('✅ Insertr CSS loaded');
        link.onerror = () => console.warn('⚠️ Failed to load Insertr CSS from:', cssPath);
        
        document.head.appendChild(link);
    },

    // Start the system - initializes auth gates and UI
    start() {
        if (this.auth) {
            this.auth.init(); // Sets up editor gates
        }
        
        if (this.controlPanel) {
            this.controlPanel.init(); // Creates unified control panel UI
        }
        
        // Note: Editor is NOT started here, only when authentication succeeds
    },

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

    // 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')) {
        // Check for configuration from script data attributes
        const insertrScript = document.querySelector('script[data-insertr-injected]');
        const config = {};
        
        if (insertrScript) {
            config.siteId = insertrScript.getAttribute('data-site-id'); // No fallback - let ApiClient handle missing values
            config.apiEndpoint = insertrScript.getAttribute('data-api-endpoint') || '/api/content';
            config.mockAuth = insertrScript.getAttribute('data-mock-auth') === 'true';
            config.debug = insertrScript.getAttribute('data-debug') === 'true';
        }
        
        window.Insertr.init(config);
    }
}

// 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;
