<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ember (ember-changeset-validations)</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <!-- Load required libraries with template-compatible versions -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.13.13/ember.debug.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.13.13/ember-template-compiler.js"></script>
    <style>
        :root {
            --ember-color: #e04e39;
            --ember-color-light: #f5988d;
            --ember-color-dark: #b83e2b;
        }
        
        body {
            background-color: #f8f9fa;
            padding-bottom: 50px;
        }
        
        .form-container {
            max-width: 800px;
            margin: 20px auto;
            padding: 30px;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
        }
        
        .form-section {
            margin-bottom: 35px;
            padding: 25px;
            background-color: #f8f9fa;
            border-radius: 10px;
            border: 1px solid #e9ecef;
        }
        
        .form-section h3 {
            margin-top: 0;
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid #e9ecef;
            color: var(--ember-color);
            font-weight: 600;
        }
        
        .error-text {
            color: var(--ember-color);
            font-size: 0.75rem;
            margin-top: 0.25rem;
            font-weight: 500;
        }
        
        .error-field {
            border-color: var(--ember-color) !important;
            background-color: #fff8f8;
        }
        
        .label-required:after {
            content: " *";
            color: var(--ember-color);
        }
        
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        
        .modal-container {
            background-color: white;
            padding: 25px;
            border-radius: 12px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .modal-header h4 {
            margin: 0;
            color: #495057;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #6c757d;
        }
        
        .modal-footer {
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #e9ecef;
            display: flex;
            justify-content: flex-end;
        }
        
        .btn-ember {
            background-color: var(--ember-color);
            border-color: var(--ember-color);
            color: white;
        }
        
        .btn-ember:hover {
            background-color: var(--ember-color-dark);
            border-color: var(--ember-color-dark);
            color: white;
        }
        
        .ember-toggle {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }
        
        .ember-toggle input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .ember-toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }
        
        .ember-toggle-slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .ember-toggle-slider {
            background-color: var(--ember-color);
        }
        
        input:focus + .ember-toggle-slider {
            box-shadow: 0 0 1px var(--ember-color);
        }
        
        input:checked + .ember-toggle-slider:before {
            transform: translateX(26px);
        }
        
        .toggle-container {
            display: flex;
            align-items: center;
            margin-top: 15px;
        }
        
        .toggle-label {
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="mt-4 mb-3 text-center">Ember (ember-changeset-validations)</h1>
        <p class="text-center mb-4">This is a fully interactive Ember form using ember-changeset-validations for form validation.</p>
        
        <div class="alert alert-success" id="success-message" style="display: none;">
            <strong>Success!</strong> Form submitted successfully! The secret is: dumbledore
        </div>
        
        <div id="ember-app-container">
            <!-- Ember app will render here -->
        </div>
    </div>
    
    <script type="text/x-handlebars" data-template-name="application">
        <form class="form-container" id="ember-form" {{action "submitForm" on="submit"}}>
            <div class="form-section">
                <h3>Simple Form</h3>

                <div class="mb-3">
                    <label for="email" class="form-label label-required">Email Address</label>
                    {{input type="email" id="email" value=changeset.email class="form-control" required=true}}
                    {{#if changeset.error.email}}
                        <div class="error-text">
                            {{changeset.error.email.validation}}
                        </div>
                    {{/if}}
                </div>

                <div class="mb-3">
                    <label for="country" class="form-label label-required">Country</label>
                    <select id="country" {{action "updateCountry" on="change"}} class="form-select" required>
                        <option value="">Select country</option>
                        <option value="US">United States</option>
                        <option value="CA">Canada</option>
                        <option value="UK">United Kingdom</option>
                        <option value="AU">Australia</option>
                    </select>
                    {{#if changeset.error.country}}
                        <div class="error-text">
                            {{changeset.error.country.validation}}
                        </div>
                    {{/if}}
                </div>

                <div class="mb-3">
                    <label for="birthDate" class="form-label label-required">Date of Birth</label>
                    {{input type="date" id="birthDate" value=changeset.birthDate class="form-control" required=true}}
                    {{#if changeset.error.birthDate}}
                        <div class="error-text">
                            {{changeset.error.birthDate.validation}}
                        </div>
                    {{/if}}
                </div>

                <div class="mb-3">
                    <label class="form-label label-required">Preferred Contact Method</label>
                    <div class="form-check">
                        {{input type="radio" class="form-check-input" id="contactEmail" name="contactMethod" value="email" checked=isEmailChecked change="updateContactMethod" param="email"}}
                        <label class="form-check-label" for="contactEmail">Email</label>
                    </div>
                    <div class="form-check">
                        {{input type="radio" class="form-check-input" id="contactPhone" name="contactMethod" value="phone" checked=isPhoneChecked change="updateContactMethod" param="phone"}}
                        <label class="form-check-label" for="contactPhone">Phone</label>
                    </div>
                    <div class="form-check">
                        {{input type="radio" class="form-check-input" id="contactMail" name="contactMethod" value="mail" checked=isMailChecked change="updateContactMethod" param="mail"}}
                        <label class="form-check-label" for="contactMail">Mail</label>
                    </div>
                    {{#if changeset.error.contactMethod}}
                        <div class="error-text">
                            {{changeset.error.contactMethod.validation}}
                        </div>
                    {{/if}}
                </div>

                <div class="mb-3">
                    <label for="fileUpload" class="form-label label-required">File Upload</label>
                    {{input type="file" id="fileUpload" class="form-control" required=true}}
                    {{#if changeset.error.fileUpload}}
                        <div class="error-text">
                            {{changeset.error.fileUpload.validation}}
                        </div>
                    {{/if}}
                </div>
            </div>

            <button type="submit" class="btn btn-ember">Submit Form</button>
        </form>
    </script>

    <script>
        // Add basic error handling for missing dependencies
        window.addEventListener('error', function(e) {
            console.error('Global error:', e.error, e.filename, e.lineno);
        });
        
        window.addEventListener('load', function() {
            // Check if all dependencies are loaded
            if (typeof Ember === 'undefined') {
                console.error('Ember is not loaded');
                document.getElementById('ember-app-container').innerHTML = '<div class="alert alert-danger">Error: Ember.js failed to load</div>';
                return;
            }
            
            if (typeof $ === 'undefined') {
                console.error('jQuery is not loaded');
                return;
            }
            
            if (typeof Handlebars === 'undefined') {
                console.error('Handlebars is not loaded');
                return;
            }
            try {
                console.log('Initializing Ember application...');
                console.log('Ember version:', Ember.VERSION);
                console.log('jQuery version:', $.fn.jquery);
                console.log('Handlebars version:', Handlebars.VERSION);
                
                // Initialize Ember application
                var App = Ember.Application.create({
                    rootElement: '#ember-app-container'
                });
                
                console.log('Ember application created successfully');
                
                // Check if templates are being found
                setTimeout(() => {
                    const templates = Ember.TEMPLATES;
                    console.log('Available templates:', Object.keys(templates || {}));
                    console.log('Application template exists:', !!templates?.application);
                    
                    // Check if the app has rendered anything
                    const container = document.getElementById('ember-app-container');
                    console.log('Container content length:', container.innerHTML.length);
                }, 1000);
                
            } catch (error) {
                console.error('Error initializing Ember application:', error);
            }

            try {
                console.log('Creating Application Controller...');
                // Create Application Controller
                App.ApplicationController = Ember.Controller.extend({
                isEmailChecked: function() {
                    return this.get('changeset.contactMethod') === 'email';
                }.property('changeset.contactMethod'),

                isPhoneChecked: function() {
                    return this.get('changeset.contactMethod') === 'phone';
                }.property('changeset.contactMethod'),

                isMailChecked: function() {
                    return this.get('changeset.contactMethod') === 'mail';
                }.property('changeset.contactMethod'),

                init: function() {
                    this._super();
                    // Create model
                    const model = {
                        email: '',
                        country: '',
                        birthDate: '',
                        contactMethod: '',
                        fileUpload: ''
                    };

                    // Instead of using changeset, we'll directly use the model
                    this.set('model', model);
                    // For compatibility with the template, we'll alias model as changeset
                    this.set('changeset', model);
                    this.set('errors', {});
                },

                validate: function() {
                    // Get values directly from DOM as fallback
                    const emailInput = document.getElementById('email');
                    const countrySelect = document.getElementById('country');
                    const birthDateInput = document.getElementById('birthDate');
                    const contactMethodRadio = document.querySelector('input[name="contactMethod"]:checked');
                    const fileInput = document.getElementById('fileUpload');

                    const model = this.get('model');
                    const errors = {};

                    // Update model from DOM if needed
                    if (emailInput && emailInput.value) {
                        this.set('model.email', emailInput.value);
                    }
                    if (countrySelect && countrySelect.value) {
                        this.set('model.country', countrySelect.value);
                    }
                    if (birthDateInput && birthDateInput.value) {
                        this.set('model.birthDate', birthDateInput.value);
                    }
                    if (contactMethodRadio && contactMethodRadio.value) {
                        this.set('model.contactMethod', contactMethodRadio.value);
                    }

                    // Email validation
                    const email = emailInput ? emailInput.value : model.email;
                    if (!email || email.trim() === '') {
                        errors.email = { validation: 'Email is required' };
                    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                        errors.email = { validation: 'Please enter a valid email address' };
                    }

                    // Country validation
                    const country = countrySelect ? countrySelect.value : model.country;
                    if (!country || country.trim() === '') {
                        errors.country = { validation: 'Country is required' };
                    }

                    // Birth date validation
                    const birthDate = birthDateInput ? birthDateInput.value : model.birthDate;
                    if (!birthDate || birthDate.trim() === '') {
                        errors.birthDate = { validation: 'Date of Birth is required' };
                    }

                    // Contact method validation
                    const contactMethod = contactMethodRadio ? contactMethodRadio.value : model.contactMethod;
                    if (!contactMethod || contactMethod.trim() === '') {
                        errors.contactMethod = { validation: 'Preferred Contact Method is required' };
                    }

                    // File upload validation
                    if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
                        errors.fileUpload = { validation: 'File upload is required' };
                    }

                    console.log('Validation - Email:', email, 'Country:', country, 'BirthDate:', birthDate, 'Contact:', contactMethod, 'File:', fileInput?.files?.length);
                    console.log('Validation errors:', errors);

                    this.set('changeset.error', errors);
                    return Object.keys(errors).length === 0;
                },

                actions: {
                    updateCountry: function(event) {
                        const value = event.target.value;
                        this.set('model.country', value);
                        this.set('changeset.country', value);
                        // Clear error on change
                        if (this.get('changeset.error.country')) {
                            const errors = this.get('changeset.error');
                            delete errors.country;
                            this.set('changeset.error', errors);
                        }
                    },
                    updateContactMethod: function(value) {
                        this.set('model.contactMethod', value);
                        this.set('changeset.contactMethod', value);
                        // Clear error on change
                        if (this.get('changeset.error.contactMethod')) {
                            const errors = this.get('changeset.error');
                            delete errors.contactMethod;
                            this.set('changeset.error', errors);
                        }
                    },
                    submitForm: function(event) {
                        event.preventDefault();

                        // Validate all fields
                        if (this.validate()) {
                            console.log('Form submitted successfully!', this.get('model'));

                            const successMessage = document.getElementById('success-message');
                            successMessage.style.display = 'block';

                            // Hide success message after 3 seconds
                            setTimeout(function() {
                                successMessage.style.display = 'none';
                            }, 8000);
                        } else {
                            console.log('Form has errors', this.get('changeset.error'));
                        }
                    }
                }
            });

            console.log('Application Controller created successfully');
            } catch (error) {
                console.error('Error creating Application Controller:', error);
            }

            try {
                console.log('Registering Handlebars helpers...');
                // Helper for checking equality in templates - using newer syntax to avoid deprecation
                if (Ember.Helper && Ember.Helper.helper) {
                    Ember.Helper.helper('eq', function(params) {
                        return params[0] === params[1];
                    });
                } else {
                    // Fallback for older Ember versions
                    Ember.Handlebars.registerHelper('eq', function(a, b) {
                        return a === b;
                    });
                }
                console.log('Handlebars helpers registered successfully');
            } catch (error) {
                console.error('Error registering Handlebars helpers:', error);
            }
        });

    </script>
</body>
</html>
