(function initPortfolioRegister(global) {
  const {
    EMAIL_REGEX
  } = global.PortfolioAppConfig;

  const REGISTER_COUNTRY_OPTIONS = [
    { value: 'AT', label: 'Austria' },
    { value: 'BE', label: 'Belgium' },
    { value: 'BG', label: 'Bulgaria' },
    { value: 'HR', label: 'Croatia' },
    { value: 'CY', label: 'Cyprus' },
    { value: 'EE', label: 'Estonia' },
    { value: 'FI', label: 'Finland' },
    { value: 'FR', label: 'France' },
    { value: 'DE', label: 'Germany' },
    { value: 'GR', label: 'Greece' },
    { value: 'IE', label: 'Ireland' },
    { value: 'IT', label: 'Italy' },
    { value: 'LV', label: 'Latvia' },
    { value: 'LT', label: 'Lithuania' },
    { value: 'LU', label: 'Luxembourg' },
    { value: 'MT', label: 'Malta' },
    { value: 'NL', label: 'The Netherlands' },
    { value: 'PT', label: 'Portugal' },
    { value: 'SK', label: 'Slovakia' },
    { value: 'SI', label: 'Slovenia' },
    { value: 'ES', label: 'Spain' }
  ];
  const REGISTER_COUNTRY_CODE_SET = new Set(REGISTER_COUNTRY_OPTIONS.map((entry) => entry.value));

  const {
    getValidationMessage
  } = global.PortfolioApp;

  const {
    hashPasswordWithArgon2
  } = global.PortfolioHashing || {};

  const sharedComponents = global.PortfolioSharedComponents || {};
  const BlockingScreenLoader = sharedComponents.BlockingScreenLoader;

  function validateRegistrationFields(values) {
    const errors = {};
    const name = (values.name || '').trim();
    const email = (values.email || '').trim();
    const password = values.password || '';
    const confirmPassword = values.confirmPassword || '';
    const country = (values.country || '').trim().toUpperCase();

    if (!name) {
      errors.name = 'Name is required.';
    } else if (name.length < 5) {
      errors.name = 'Name must be at least 5 characters long.';
    }

    if (!email) {
      errors.email = 'Email is required.';
    } else if (!EMAIL_REGEX.test(email)) {
      errors.email = 'Enter a valid email address.';
    }

    if (!password) {
      errors.password = 'Password is required.';
    }

    if (!confirmPassword) {
      errors.confirmPassword = 'Please confirm your password.';
    } else if (password && confirmPassword && password !== confirmPassword) {
      errors.confirmPassword = 'Passwords do not match.';
    }

    if (!country) {
      errors.country = 'Country is required.';
    } else if (!REGISTER_COUNTRY_CODE_SET.has(country)) {
      errors.country = 'Choose a valid country.';
    }

    return errors;
  }

  function RegisterPage({ navigate }) {
    const [formValues, setFormValues] = React.useState({ name: '', email: '', password: '', confirmPassword: '', country: '' });
    const [errors, setErrors] = React.useState({});
    const [status, setStatus] = React.useState(null);
    const [isSubmitting, setIsSubmitting] = React.useState(false);

    const handleChange = (event) => {
      const { name, value } = event.target;
      setFormValues((current) => {
        const nextValues = Object.assign({}, current);
        nextValues[name] = value;
        return nextValues;
      });

      if (errors[name]) {
        setErrors((current) => {
          const nextErrors = Object.assign({}, current);
          nextErrors[name] = undefined;
          return nextErrors;
        });
      }

      if (status) {
        setStatus(null);
      }
    };

    const handleSubmit = async (event) => {
      event.preventDefault();
      setStatus(null);

      const disableClientValidation = Boolean(window.disableClientValidation);
      const nextErrors = disableClientValidation ? {} : validateRegistrationFields(formValues);
      setErrors(nextErrors);
      if (!disableClientValidation && Object.keys(nextErrors).length > 0) {
        setStatus({ type: 'error', message: getValidationMessage('A Validation Issue occurred.') });
        return;
      }

      setIsSubmitting(true);
      try {
        const passwordHash = await hashPasswordWithArgon2(formValues.password);
        const response = await fetch('/api/register', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            name: formValues.name.trim(),
            email: formValues.email.trim(),
            passwordHash,
            country: formValues.country.trim().toUpperCase()
          })
        });

        if (response.status === 422) {
          const payload = await response.json().catch(() => ({}));
          setStatus({
            type: 'error',
            message: getValidationMessage(payload.message || 'A Validation Issue occurred.', payload.code != null ? payload.code : 1003)
          });
          return;
        }

        if (response.status === 500) {
          const payload = await response.json().catch(() => ({}));
          setStatus({
            type: 'error',
            message: getValidationMessage(payload.message || 'A Technical Error occurred.', payload.code != null ? payload.code : 1100)
          });
          return;
        }

        if (!response.ok) {
          throw new Error('Registration request failed');
        }

        const payload = await response.json();
        setStatus({ type: 'success', message: payload.message || 'You have registered successfully.' });
        setErrors({});
        setFormValues({ name: '', email: '', password: '', confirmPassword: '', country: '' });
      } catch (error) {
        setStatus({ type: 'error', message: getValidationMessage('A Technical Error occurred.', 1100) });
      } finally {
        setIsSubmitting(false);
      }
    };

    return (
      <div className="content auth-shell">
        {typeof BlockingScreenLoader === 'function' ? (
          <BlockingScreenLoader
            isActive={isSubmitting}
            title="Registration in Progress"
            message="Please wait."
          />
        ) : null}

        <section className="auth-card">
          <div className="auth-header">
            <div>
              <h2 style={{ margin: 0 }}>Register</h2>
              <p className="muted" style={{ margin: '0.3rem 0 0' }}>Create your secure account in minutes.</p>
            </div>
            <button className="secondary-btn" onClick={() => navigate('/')}>Back to Overview</button>
          </div>

          <form className="form-grid" style={{ marginTop: '1rem' }} onSubmit={handleSubmit}>
            {(!status || status.type !== 'success') && (
              <div className={`field ${errors.name ? 'invalid' : ''}`}>
                <label htmlFor="name">Name</label>
                <input id="name" name="name" type="text" value={formValues.name} onChange={handleChange} placeholder="Alex Morgan" autoComplete="name" />
                {errors.name && <span className="error-message">{errors.name}</span>}
              </div>
            )}
            {(!status || status.type !== 'success') && (
              <div className={`field ${errors.email ? 'invalid' : ''}`}>
                <label htmlFor="email">Email</label>
                <input id="email" name="email" type="email" value={formValues.email} onChange={handleChange} placeholder="you@company.com" autoComplete="email" />
                {errors.email && <span className="error-message">{errors.email}</span>}
              </div>
            )}
            {(!status || status.type !== 'success') && (
              <div className={`field ${errors.password ? 'invalid' : ''}`}>
                <label htmlFor="password">Password</label>
                <input id="password" name="password" type="password" value={formValues.password} onChange={handleChange} placeholder="Enter a strong password" autoComplete="new-password" />
                {errors.password && <span className="error-message">{errors.password}</span>}
              </div>
            )}
            {(!status || status.type !== 'success') && (
              <div className={`field ${errors.confirmPassword ? 'invalid' : ''}`}>
                <label htmlFor="confirmPassword">Confirm password</label>
                <input id="confirmPassword" name="confirmPassword" type="password" value={formValues.confirmPassword} onChange={handleChange} placeholder="Repeat password" autoComplete="new-password" />
                {errors.confirmPassword && <span className="error-message">{errors.confirmPassword}</span>}
              </div>
            )}
            {(!status || status.type !== 'success') && (
              <div className={`field ${errors.country ? 'invalid' : ''}`}>
                <label htmlFor="country">Country</label>
                <select id="country" name="country" value={formValues.country} onChange={handleChange}>
                  <option value="">Select country</option>
                  {REGISTER_COUNTRY_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>{option.label}</option>
                  ))}
                </select>
                {errors.country && <span className="error-message">{errors.country}</span>}
              </div>
            )}

            {status && (
              <div className={`status-message ${status.type}`} role="status">
                <span>{status.message}</span>
                {status.type === 'success' && (
                  <button className="secondary-btn" type="button" onClick={() => navigate('/auth/login')}>Go to login</button>
                )}
              </div>
            )}

            {(!status || status.type !== 'success') && (
              <div className="hero-actions upload-hero-actions">
                <button className="primary-btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Working...' : 'Register Account'}</button>
              </div>
            )}
          </form>
        </section>

      </div>
    );
  }

  function getRegisterFallbackMessage(view) {
    if (view !== 'register') {
      return null;
    }

    return getValidationMessage('A Validation Issue occurred.');
  }

  global.PortfolioRegister = {
    RegisterPage,
    getRegisterFallbackMessage
  };
})(window);
