export default class UserSelectModal {

    constructor({ eventBus, api, currentUser, tabId }) {

        this.eventBus = eventBus;
        this.api = api;
        this.currentUser = currentUser;

        this.el = null;
        this.users = [];
        this.tabId = tabId;  // 👈 اضافه شد

    }

    async open() {

        await this.loadUsers();

        this.el = document.createElement('div');
        this.el.className = 'modal-overlay';
        this.el.innerHTML = this._template();

        document.body.appendChild(this.el);

        this._bindEvents();
    }

    close() {
        if (this.el) {
            this.el.remove();
            this.el = null;
        }
    }

    /* ----------------------------------------------
       Load users (from API or static)
    ---------------------------------------------- */

    async loadUsers() {
        try {
            this.users = await this.api.get('/users');
        } catch (err) {
            console.error('UserSelectModal.loadUsers error', err);
            this.users = [];
        }
    }

    /* ----------------------------------------------
       TEMPLATE
    ---------------------------------------------- */

    _template() {

        const userList = this.users.map(u => `
            <div class="user-row" data-user-id="${u.id}">
                <span>${u.fullname}</span>
            </div>
        `).join('');

        return `
        <div class="modal-window">
            <div class="modal-header">
                <h3>Select User</h3>
                <button class="modal-close-btn" data-ref="closeBtn">✖</button>
            </div>

            <div class="modal-body">
                ${userList}
            </div>
        </div>
        `;
    }

    /* ----------------------------------------------
       EVENTS
    ---------------------------------------------- */

    _bindEvents() {

        // Close button
        this.el.querySelector('[data-ref="closeBtn"]').addEventListener('click', () => {
            this.close();
        });

        // User selection
        this.el.querySelectorAll('.user-row').forEach(row => {
            row.addEventListener('click', () => {
                const userId = row.dataset.userId;

                const selectedUser = this.users.find(u => u.id == userId);
                if (!selectedUser) return;

                // Fire event
                this.eventBus.emit("modal:userSelected", {
                    tabId: this.tabId,
                    userId: selectedUser.id,
                    user: selectedUser
                });


                this.close();
            });
        });
    }

}
