/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * (See repository root for full license header requirements.)
 *
 * modal.js
 * Extracted from legacy monolith `canvas-editor.js` (Phase 2.7 Step 14)
 * Provides an attach function that decorates an editor instance with
 * showModal(title, content) and closeModal() helpers. Idempotent.
 */

/** Attach modal helpers onto an editor instance */
export function attachModalSystem(editor) {
    if (editor.__modalSystemAttached) return; // idempotent guard
    editor.__modalSystemAttached = true;

    editor.showModal = function showModal(title, content) {
        let modal = document.getElementById('canvas-editor-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'canvas-editor-modal';
            modal.className = 'canvas-modal';
            modal.innerHTML = `
                <div class="canvas-modal-backdrop">
                    <div class="canvas-modal-content">
                        <div class="canvas-modal-header">
                            <h3 class="canvas-modal-title"></h3>
                            <button type="button" class="canvas-modal-close">&times;</button>
                        </div>
                        <div class="canvas-modal-body"></div>
                    </div>
                </div>`;
            document.body.appendChild(modal);

            // Unified close handler (backdrop or X button)
            modal.addEventListener('click', (e) => {
                const backdrop = modal.querySelector('.canvas-modal-backdrop');
                const closeBtn = modal.querySelector('.canvas-modal-close');
                if (e.target === backdrop || e.target === closeBtn) {
                    editor.closeModal();
                }
            });
        }

        modal.querySelector('.canvas-modal-title').textContent = title;
        modal.querySelector('.canvas-modal-body').innerHTML = content;
        modal.style.display = 'block';
        document.body.classList.add('modal-open');
    };

    editor.closeModal = function closeModal() {
        const modal = document.getElementById('canvas-editor-modal');
        if (modal) {
            modal.style.display = 'none';
            document.body.classList.remove('modal-open');
        }
    };
}

export default { attachModalSystem };
