(function ($) {
  'use strict';

  const searchPlaceholder = Drupal.t('Search FEMA.gov', {}, {context: 'Javascript'});
  const searchAlt = Drupal.t('Search icon', {}, {context: 'Javascript'});
  const searchLabel = Drupal.t('Enter Search Term(s):', {}, {context: 'Javascript'});

  Drupal.behaviors.usaSearchResizeBehavior = {
    attach: function (context) {

      var currentScript = $('[src="//search.usa.gov/javascripts/remote.loader.js"]');
      if (!currentScript.length) {
        var usasearch_config = { siteHandle:"fema" };
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "//search.usa.gov/javascripts/remote.loader.js";
        document.getElementsByTagName("head")[0].appendChild(script);
      }

      var mobileBreakpoint = 1023;
      // Resize timeout event ID.
      var resizeTimeoutId;
      // Resize timeout duration in milliseconds.
      var resizeTimeoutDuration = 100;

      const produceSearch = (searchForm,affiliate,query) => {
        return '<div class="usasearch-search-block-form usa-form contextual-region block block-usasearch block-usasearch-search-form-block" role="search">' +
          `<form id="${searchForm}" action="https://search.usa.gov/search" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓"/>` +
            `<input type="hidden" name="affiliate" id="${affiliate}" value="fema"/>` +
            `<label for="${query}" class="visually-hidden">${searchLabel}</label>` +
            `<input class="usa-input" type="search" placeholder="${searchPlaceholder}" name="query" id="${query}" autocomplete="off" class="usagov-search-autocomplete"/>` +
            '<div>'+
           `<input class="usa-button" type="submit" name="commit" value="${searchPlaceholder}" data-disable-with="Search">` +
           `<img src="/profiles/femad8_gov/themes/fema_uswds/images/icon_search.svg" alt="${searchAlt}">` +
           '</div>' +
          '</form>' +
        '</div>';
      };

      var resizeDebounce = function () {
        clearTimeout(resizeTimeoutId);
        resizeTimeoutId = setTimeout(doneResizing, resizeTimeoutDuration);
      };

      var doneResizing = function () {
        var width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
       var mobileSearches = $('.mobile-usa-search');
       var desktopSearches = $('.desktop-usa-search');
       mobileSearches.each(function(i){
         if (width <= mobileBreakpoint) {
           if ($(this).children().length === 0) {
             var query = 'mobile_query_' + i;
             var searchForm = 'mobile_search_form_' + i;
             var affiliate = 'mobile_affiliate_' + i;
             var search = produceSearch(searchForm,affiliate,query);
             $(this).append(search)
           }
         }else{
           $(this).empty();
         }
       })
       desktopSearches.each(function(i){
         if (width > mobileBreakpoint) {
           if ($(this).children().length === 0) {
             var query = 'desktop_query_' + i;
             var searchForm = 'desktop_search_form_' + i;
             var affiliate = 'desktop_affiliate_' + i;
             var search = produceSearch(searchForm,affiliate,query);
             $(this).append(search)
           }
         }else{
           $(this).empty();
         }
       })
      };
      doneResizing();
      $(window).resize(resizeDebounce);

    }
  };
})(jQuery);