// ReferenceUI: handles 'new', 'edit', 'delete', and 'switch' reference actions
class ReferenceUI {
    constructor() {
        this.$newBtn = $('#newReference');
        this.$editBtn = $('#editReference');
        this.$deleteBtns = $('.deleteReference');
        this.$switchItems = $('.refItem');
        this.$modal = $('#referenceModal');
        this.$modalTitle = $('#referenceModalLabel');
        this.$nameInput = $('#referenceName');
        this.$saveBtn = $('#saveReference');
    }

    init() {
        this.$newBtn.on('click', () => this.openForm('New'));
        this.$editBtn.on('click', () => this.openForm('Edit'));
        this.$deleteBtns.on('click', e => this.handleDelete($(e.currentTarget).data('ref-id')));
        this.$switchItems.on('click', e => this.handleSwitch($(e.currentTarget).data('ref-id')));
        this.$saveBtn.on('click', () => this.saveReference());
    }

    urlBase(mode) {
        let url = `${$('#pathPrefix').val()}index.php?action=reference`;
        if(mode) url += `&mode=${mode}`;
        return url;
    }

    openForm(type) {
        this.$modalTitle.text(`${type} Reference`);
        const current = $('#sessionReference').val();
        this.$nameInput.val(type === 'Edit' ? current : '');
        this.$modal.modal('show');
    }

    saveReference() {
        const newName = this.$nameInput.val().trim();
        const current = $('#sessionReference').val();
        const action = this.$modalTitle.text().startsWith('New') ? 'create' : 'rename';
        if (!newName) return alert('Name cannot be empty');
        if(action === 'create') {
            const prefix = $('#pathPrefix').val();
            window.location.href = `${prefix}index.php?reference=${encodeURIComponent(newName)}`;
            return;
        }
        $.post(this.urlBase('rename'), {
            reference: newName
        }, data => {
            if (data.success) location.reload();
            else alert(`Error: ${data.message}`);
        });
    }

    handleDelete(refId) {
        if (!confirm('Delete this reference?')) return;
        $.post(`${$('#pathPrefix').val()}index.php?action=delete`, { reference: refId }, data => {
            if (data.success) location.reload();
            else alert(`Error deleting: ${data.message}`);
        });
    }

    handleSwitch(refId) {
        // navigate to selected reference
        const prefix = $('#pathPrefix').val();
        window.location.href = `${prefix}index.php?reference=${encodeURIComponent(refId)}`;
    }
}