/**
 * Fusion Authorizer Portal - Assessment Form
 */

odoo.define('fusion_authorizer_portal.assessment_form', function (require) {
    'use strict';
    
    var publicWidget = require('web.public.widget');
    
    publicWidget.registry.AssessmentForm = publicWidget.Widget.extend({
        selector: '#assessment-form',
        events: {
            'change input, change select, change textarea': '_onFieldChange',
            'submit': '_onSubmit',
        },
        
        init: function () {
            this._super.apply(this, arguments);
            this.hasUnsavedChanges = false;
        },
        
        start: function () {
            this._super.apply(this, arguments);
            this._initializeForm();
            return Promise.resolve();
        },
        
        _initializeForm: function () {
            var self = this;
            
            // Warn before leaving with unsaved changes
            window.addEventListener('beforeunload', function (e) {
                if (self.hasUnsavedChanges) {
                    e.preventDefault();
                    e.returnValue = '';
                    return '';
                }
            });
            
            // Auto-fill full name from first + last name
            var firstNameInput = this.el.querySelector('[name="client_first_name"]');
            var lastNameInput = this.el.querySelector('[name="client_last_name"]');
            var fullNameInput = this.el.querySelector('[name="client_name"]');
            
            if (firstNameInput && lastNameInput && fullNameInput) {
                var updateFullName = function () {
                    var first = firstNameInput.value.trim();
                    var last = lastNameInput.value.trim();
                    if (first || last) {
                        fullNameInput.value = (first + ' ' + last).trim();
                    }
                };
                
                firstNameInput.addEventListener('blur', updateFullName);
                lastNameInput.addEventListener('blur', updateFullName);
            }
            
            // Number input validation
            var numberInputs = this.el.querySelectorAll('input[type="number"]');
            numberInputs.forEach(function (input) {
                input.addEventListener('input', function () {
                    var value = parseFloat(this.value);
                    var min = parseFloat(this.min) || 0;
                    var max = parseFloat(this.max) || 9999;
                    
                    if (value < min) this.value = min;
                    if (value > max) this.value = max;
                });
            });
        },
        
        _onFieldChange: function (ev) {
            this.hasUnsavedChanges = true;
            
            // Visual feedback that form has changes
            var saveBtn = this.el.querySelector('button[value="save"]');
            if (saveBtn) {
                saveBtn.classList.add('btn-warning');
                saveBtn.classList.remove('btn-primary');
            }
        },
        
        _onSubmit: function (ev) {
            // Validate required fields
            var requiredFields = this.el.querySelectorAll('[required]');
            var isValid = true;
            
            requiredFields.forEach(function (field) {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                ev.preventDefault();
                alert('Please fill in all required fields.');
                return false;
            }
            
            this.hasUnsavedChanges = false;
            return true;
        }
    });
    
    return publicWidget.registry.AssessmentForm;
});
