class CreateRoomModal {
    constructor() {
        this.modalId = 'cr-modal-overlay';
        this.isRendered = false;
        this.render(); // Crear el HTML en el DOM al instanciar
    }

    render() {
        if (document.getElementById(this.modalId)) return;

        const modalHtml = `
            <div class="cr-modal-overlay" id="${this.modalId}">
                <div class="cr-modal-content">
                    <button class="cr-modal-close" id="cr-close">✕</button>
                    <h2 class="cr-modal-title">Create Watch Party</h2>
                    
                    <form id="cr-form">
                        <div class="cr-form-group">
                            <label>Room Name</label>
                            <input type="text" class="cr-input" name="name" placeholder="My Awesome Room" required maxlength="50" />
                        </div>

                        <div class="cr-form-group">
                            <label>Password (Optional)</label>
                            <input type="password" class="cr-input" name="password" placeholder="Leave empty for public" maxlength="50" />
                        </div>
                        
                        <div class="cr-form-group cr-checkbox-group">
                            <label class="cr-checkbox">
                                <input type="checkbox" name="expose" />
                                <span>Generate public link (via tunnel)</span>
                            </label>
                        </div>

                        <div class="cr-actions">
                            <button type="button" class="cr-btn-cancel" id="cr-cancel">Cancel</button>
                            <button type="submit" class="cr-btn-confirm">Create Room</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        this.bindEvents();
        this.isRendered = true;
    }

    bindEvents() {
        const modal = document.getElementById(this.modalId);
        const closeBtn = document.getElementById('cr-close');
        const cancelBtn = document.getElementById('cr-cancel');
        const form = document.getElementById('cr-form');

        const close = () => this.close();

        closeBtn.onclick = close;
        cancelBtn.onclick = close;

        // Cerrar si clicamos fuera del contenido
        modal.onclick = (e) => {
            if (e.target === modal) close();
        };

        form.onsubmit = (e) => this.handleSubmit(e);
    }

    open() {
        const token = localStorage.getItem('token');
        if (!token) {
            // Aquí puedes disparar tu modal de login o redirigir
            alert('You must be logged in to create a room');
            window.location.href = '/login'; // Opcional
            return;
        }

        const modal = document.getElementById(this.modalId);
        modal.classList.add('show');
        document.querySelector('#cr-form input[name="name"]').focus();
    }

    close() {
        const modal = document.getElementById(this.modalId);
        modal.classList.remove('show');
        document.getElementById('cr-form').reset();
    }

    async handleSubmit(e) {
        e.preventDefault();
        const btn = e.target.querySelector('button[type="submit"]');
        const originalText = btn.textContent;

        btn.disabled = true;
        btn.textContent = 'Creating...';

        const formData = new FormData(e.target);
        const expose = formData.get('expose') === 'on';
        const name = formData.get('name').trim();
        const password = formData.get('password').trim();
        const token = localStorage.getItem('token');

        try {
            const res = await fetch('/api/rooms', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    name,
                    password: password || undefined,
                    expose
                })
            });

            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Failed to create room');

            this.close();

            window.open(`/room?id=${data.room.id}`, '_blank', 'noopener,noreferrer');
        } catch (err) {
            alert(err.message);
        } finally {
            btn.disabled = false;
            btn.textContent = originalText;
        }
    }
}

window.CreateRoomModal = CreateRoomModal;
