// ====== Modal Dialog Functionality ======

import { $, $$, createElement } from '../core/helpers.js';
import { uiManager } from '../modules/ui.js';

class ModalManager {
    constructor() {
        this.modals = new Map();
        this.init();
    }

    init() {
        this.setupGlobalModalHandlers();
    }

    setupGlobalModalHandlers() {
        // Close modals on overlay click is handled in uiManager
        // Add any additional global modal handlers here
    }

    createModal(options = {}) {
        const {
            id = `modal-${Date.now()}`,
            title = '',
            content = '',
            size = 'medium', // small, medium, large, fullscreen
            showClose = true,
            closeOnOverlay = true,
            actions = []
        } = options;

        // Create modal structure
        const modal = createElement('div', {
            id: id,
            className: `modal modal--${size}`
        }, [
            createElement('div', { className: 'modal-overlay' }),
            createElement('div', { className: 'modal-content' }, [
                // Header
                createElement('div', { className: 'modal-header' }, [
                    createElement('h3', { className: 'modal-title' }, title),
                    showClose && createElement('button', {
                        className: 'modal-close',
                        onclick: () => this.closeModal(id)
                    }, '×')
                ]),
                
                // Body
                createElement('div', { className: 'modal-body' }, content),
                
                // Footer with actions
                actions.length > 0 && createElement('div', { className: 'modal-footer' }, 
                    actions.map(action => 
                        createElement('button', {
                            className: `btn ${action.primary ? 'btn-primary' : 'btn-outline'}`,
                            onclick: action.handler
                        }, action.label)
                    )
                )
            ])
        ]);

        document.body.appendChild(modal);
        this.registerModal(modal);

        return modal;
    }

    registerModal(modal) {
        const triggers = $$(`[data-modal-target="${modal.id}"]`);
        
        triggers.forEach(trigger => {
            uiManager.registerModal(trigger, modal);
        });

        this.modals.set(modal.id, modal);
    }

    openModal(modalId) {
        const modal = this.modals.get(modalId);
        if (modal) {
            uiManager.openModal(modal);
        }
    }

    closeModal(modalId) {
        const modal = this.modals.get(modalId);
        if (modal) {
            uiManager.closeModal(modal);
        }
    }

    // Predefined modal types
    async confirm(options) {
        return new Promise((resolve) => {
            const modal = this.createModal({
                title: options.title || 'Confirm Action',
                content: options.message || 'Are you sure you want to proceed?',
                actions: [
                    {
                        label: options.cancelText || 'Cancel',
                        handler: () => {
                            this.closeModal(modal.id);
                            resolve(false);
                        }
                    },
                    {
                        label: options.confirmText || 'Confirm',
                        primary: true,
                        handler: () => {
                            this.closeModal(modal.id);
                            resolve(true);
                        }
                    }
                ]
            });

            this.openModal(modal.id);
        });
    }

    alert(options) {
        const modal = this.createModal({
            title: options.title || 'Alert',
            content: options.message || '',
            actions: [
                {
                    label: options.buttonText || 'OK',
                    primary: true,
                    handler: () => this.closeModal(modal.id)
                }
            ]
        });

        this.openModal(modal.id);
    }

    prompt(options) {
        return new Promise((resolve) => {
            const input = createElement('input', {
                type: options.type || 'text',
                className: 'form-input',
                placeholder: options.placeholder || '',
                value: options.defaultValue || ''
            });

            const content = createElement('div', {}, [
                createElement('p', {}, options.message || 'Please enter a value:'),
                input
            ]);

            const modal = this.createModal({
                title: options.title || 'Enter Value',
                content: content,
                actions: [
                    {
                        label: options.cancelText || 'Cancel',
                        handler: () => {
                            this.closeModal(modal.id);
                            resolve(null);
                        }
                    },
                    {
                        label: options.confirmText || 'OK',
                        primary: true,
                        handler: () => {
                            this.closeModal(modal.id);
                            resolve(input.value);
                        }
                    }
                ]
            });

            this.openModal(modal.id);
            
            // Focus input when modal opens
            setTimeout(() => input.focus(), 100);
        });
    }

    // Loading modal
    showLoading(message = 'Loading...') {
        const modal = this.createModal({
            id: 'loading-modal',
            title: '',
            content: createElement('div', { className: 'loading-content' }, [
                createElement('div', { className: 'loading-spinner' }),
                createElement('p', {}, message)
            ]),
            showClose: false,
            closeOnOverlay: false
        });

        this.openModal(modal.id);
        return modal.id;
    }

    hideLoading(modalId = 'loading-modal') {
        this.closeModal(modalId);
    }
}

// Create singleton instance
export const modalManager = new ModalManager();