(function () {
  'use strict';

  const config = window.CUSTAUSU_ADMIN_AUTH_PAGES_CONSISTENCY || {};
  const issues = Array.isArray(config.issues) ? config.issues : [];
  const noteText = String(config.noteText || '');
  const noteTexts =
    config.noteTexts && typeof config.noteTexts === 'object'
      ? config.noteTexts
      : {};

  function normalizePath(value) {
    value = String(value || '').trim();

    if (!value) {
      return '';
    }

    try {
      const url = new URL(value, window.location.origin);
      value = url.pathname || value;
    } catch (error) {}

    value = '/' + value.replace(/^\/+|\/+$/g, '');
    return value === '/' ? '/' : value + '/';
  }

  function findRouteInput(issue) {
    const lang = String(issue.lang || '');
    const route = String(issue.route || '');
    const stored = normalizePath(issue.stored || '');
    const candidates = Array.from(document.querySelectorAll(
      'input[type="text"], input[type="url"], input:not([type]), textarea'
    ));

    let found = candidates.find(function (element) {
      const name = String(element.getAttribute('name') || '');

      return name.indexOf('routes_paths') !== -1
        && name.indexOf('[' + lang + ']') !== -1
        && name.indexOf('[' + route + ']') !== -1;
    });

    if (found) {
      return found;
    }

    if (stored) {
      found = candidates.find(function (element) {
        return normalizePath(element.value || '') === stored;
      });
    }

    return found || null;
  }

  issues.forEach(function (issue) {
    const input = findRouteInput(issue);

    if (!input) {
      return;
    }

    const box =
      input.closest('.custausu-field-alert')
      || input.closest('.custausu-route-block')
      || input.closest('td')
      || input.parentElement;

    if (!box) {
      return;
    }

    box.classList.add(
      'custausu-field-alert',
      'custausu-field-alert--error',
      'custausu-route-consistency-error'
    );

    input.classList.add('custausu-route-consistency-error__input');
    input.setAttribute('aria-invalid', 'true');

    if (!box.querySelector('.custausu-route-consistency-error__note')) {
      const note = document.createElement('div');
      const stored = issue.stored ? String(issue.stored) : '';
      const current = issue.current ? String(issue.current) : '';

      note.className =
        'custausu-field-alert__note custausu-field-alert__note--error '
        + 'custausu-route-consistency-error__note';

      const reason = String(issue.reason || '');
      const issueNote = String(noteTexts[reason] || noteText);

      note.textContent =
        issueNote
        + (stored || current ? ' (' + stored + ' → ' + current + ')' : '');

      box.appendChild(note);
    }
  });
}());
