(function ($, Drupal) {
  Drupal.behaviors.grantsDashboard = {
    attach(context) {
      $(once("grantsDashboard", "html", context).forEach((element) => {
        (($) => {
          $(document).ready(() => {
            // Establishes base JS functionality for tabbing features
            const tabWrapper = $("#tab-block");
            const tabMnu = tabWrapper.find(".tab-mnu  li");
            const tabContent = tabWrapper.find(".tab-cont > .tab-pane");

            // Switches tab to 'Awards' if the 'View Awards' link is clicked
            $("tbody .views-field-field-view-awards-link a").click(() => {
              Cookies.set("grants-dashboard-tab", "awards");

              $("#nofos-tab").removeClass("active").attr("aria-selected", "false");
              $("#awards-tab").addClass("active").attr("aria-selected", "true");
              tabContent.not(":last-child").hide();
              $("#awards_content").show();
            });

            // OCWT-2643: Added click event to 'Clear Filters' button to empty Collapsiblock cookie to reset open filters
            // OCWT-3155 - Ensures that 'Clear Filters' button always hard resets all open filters and sorting settings
            // The cookie path has changed from /grants to /
            $(".facet-summary-item--clear.button a")
              .attr("href", "/grants/grants-dashboard")
              .click(() => {
                Cookies.remove("collapsiblock", { path: "/" });
                localStorage.removeItem("State");
                localStorage.removeItem("CD");
                $("#block-awardsbycongressionaldistrict select").children("option").show();
              });

            // All cases in which the Awards tab should be open on page load,
            // including searches, pagination, and field sorting
            if (
              window.location.href.includes("#awards-tab") ||
              Cookies.get("grants-dashboard-tab") === "awards"
            ) {
              $("#nofos-tab").removeClass("active").attr("aria-selected", "false");
              $("#awards-tab").addClass("active").attr("aria-selected", "true");
              tabContent.not(":last-child").hide();
              Cookies.set("grants-dashboard-tab", "awards");
            } else {
              $("#awards-tab").removeClass("active").attr("aria-selected", "false");
              $("#nofos-tab").addClass("active").attr("aria-selected", "true");
              tabContent.not(":first-child").hide();
              Cookies.set("grants-dashboard-tab", "nofos");
            }

            // Assigns HTML attributes for JS functionality
            tabMnu.each((i, el) => {
              $(el).attr("data-tab", `tab${i}`);
            });

            tabContent.each((i, el) => {
              $(el).attr("data-tab", `tab${i}`);
            });

            tabMnu.on("keypress click", (event) => {
              const tabData = $(event.currentTarget).data("tab");
              if (event.which === 13 || event.type === "click") {
                tabWrapper.find(tabContent).hide();
                tabWrapper.find(tabContent).filter(`[data-tab="${tabData}"]`).show();
              }
            });

            $(".tab-mnu > li").on("keypress click", (event) => {
              if (event.which === 13 || event.type === "click") {
                $(".tab-mnu li.active")
                  .removeClass("active")
                  .attr("aria-selected", "false");
                $(event.currentTarget).addClass("active").attr("aria-selected", "true");
              }
            });

            // Grants table sort active indicating icon
            $(() => {
              const sortDefault = $(".view-grants-dashboard table").find(
                'thead th:not(.is-active) a[title^="sort by"]'
              );
              if (sortDefault) {
                $(sortDefault).append(
                  `<span class='tablesort-default'><i class='fa-solid fa-sort'></i><span class='visually-hidden'>Click to sort</span></></span>`
                );
              }
            });

            // Grants Dashboard Search
            if (window.location.href.includes("/grants/grants-dashboard") === true && window.location.href.search(/grants_dashboard__search=[^&]/g) === -1) {
              $("#edit-reset--2").attr("disabled", "disabled");
            }

            // Grants Dashboard Facets Checkboxes and Dropdown to USWDS standard
            $(() => {
              $(".grant-facet .facets-widget-checkbox")
                .find("input.facets-checkbox")
                .addClass("usa-checkbox__input");
              $(".grant-facet .facets-widget-checkbox")
                .find("label")
                .addClass("usa-checkbox__label");
              $(".grant-facet .facets-widget-dropdown")
                .find("select")
                .addClass("usa-select");
              $(".grant-facet .usa-select").hover((event) => {
                $(event.currentTarget).css("border-color", "#565c65");
              });
            });

            // OCWT-2659 - Add title attributes to Center facet checkboxes
            $("#by-center-cmhs")
              .parent()
              .attr("title", "Center for Mental Health Services");
            $("#by-center-csap")
              .parent()
              .attr("title", "Center for Substance Abuse Prevention");
            $("#by-center-csat")
              .parent()
              .attr("title", "Center for Substance Abuse and Treatment");
            $("#by-center-fg").parent().attr("title", "Flex Grant");
            $("#by-center-obhe")
              .parent()
              .attr("title", "Office of Behavioral Health Equity");
            // OCWT-5339 - New title (why are we adding title tags this way?)
            $("#by-center-otap")
              .parent()
              .attr("title", "Office of Tribal Affairs and Policy");

            // OCWT-2959 - Add tab tracking via Cookie
            $("#nofos-tab").click(() => {
              Cookies.set("grants-dashboard-tab", "nofos");
            });
            $("#awards-tab").click(() => {
              Cookies.set("grants-dashboard-tab", "awards");
            });

            // OCWT-4548
            // OCWT-8761
            $(".usa-accordion__button.grants-accordion-button").on(
              "keydown click",
              (event) => {
                let bgColor = $(event.target).parents('tr').css('background-color');
                
                if (event.type === "click") {
                  if ($(event.currentTarget).attr("aria-expanded") === "false") {
                    $(event.currentTarget).attr("aria-label", "click to hide project period");
                  }
                  if ($(event.currentTarget).attr("aria-expanded") === "true") {
                    $(event.currentTarget).attr("aria-label", "click to show project period");
                  }
                }
                if (event.which === 13) {
                  if ($(event.currentTarget).attr("aria-expanded") === "false") {
                    $(event.currentTarget).attr({
                      "aria-label": "click to hide project period",
                      "aria-expanded": "true",
                    });
                    $(event.currentTarget)
                      .closest("tr")
                      .next()
                      .find(".usa-accordion__content.grant-accordion__content")
                      .removeAttr("hidden");
                    $(event.target)
                      .parents('tr')
                      .children('td')
                      .css('border-left', '1px solid ' + bgColor);
                  } else {
                    $(event.currentTarget).attr({
                      "aria-label": "click to show project period",
                      "aria-expanded": "false",
                    });
                    $(event.currentTarget)
                      .closest("tr")
                      .next()
                      .find(".usa-accordion__content.grant-accordion__content")
                      .attr("hidden", "hidden");
                    $(event.target)
                      .parents('tr')
                      .children('td')
                      .css('border-left', '1px solid #dddddd');
                  }
                }
              }
            );

            // OCWT-3326 - Disable 'Congressional District' facet by default
            const states = ['Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Federated States of Micronesia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Islands', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

            const abbrev = ['AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PW', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY'];

            let currentState, abbr, currentURL, count, a, b;

            $("#block-awardsbystate select").change(() => {
              const pastState = localStorage.getItem("State");
              const pastDist = localStorage.getItem("CD");
              currentState = $("#block-awardsbystate select option:selected").text().trim();
              currentURL=window.location.href;
              count = (currentURL.match(/5B/g) || []).length;
              abbr = abbrev[states.indexOf(currentState)].trim();
              localStorage.setItem("State",encodeURI(currentState));
              if (window.location.href.includes('by_state') && window.location.href.includes('by_congressional_district')) {  
                if (window.location.href.includes('by_region')) {
                  a = currentURL.replace("f%5B"+ (count - 2) +"%5D=by_congressional_district%3A" + pastDist + "&", "");
                } else {
                  a = currentURL.replace("&f%5B"+ (count - 1) +"%5D=by_congressional_district%3A" + pastDist, "");
                }
                b = a.replace(pastState,encodeURI(currentState));
                localStorage.removeItem("CD");
                window.location.assign(b);
              }
              if (window.location.href.includes('by_state') && !window.location.href.includes('by_congressional_district')) {
                b = currentURL.replace(pastState,encodeURI(currentState));
                localStorage.removeItem("CD");
                window.location.assign(b);
              }
              if (!window.location.href.includes('by_state') && window.location.href.includes('by_congressional_district')) {
                if (window.location.href.includes('by_region')) {
                  a = currentURL.replace("f%5B"+ (count - 2) +"%5D=by_congressional_district%3A" + pastDist + "&", "");
                } else {
                  a = currentURL.replace("f%5B"+ (count - 1) +"%5D=by_congressional_district%3A" + pastDist, "");
                }
                b = a + '&' + encodeURI('f['+count+']=by_state:'+currentState);
                localStorage.removeItem("CD");
                window.location.assign(b);
              }

              $("#block-awardsbycongressionaldistrict select").children("option").hide();
              $("#block-awardsbycongressionaldistrict select").children("option[value*='%3A" + abbr + "']").show();
            });
            $("#block-awardsbycongressionaldistrict select").change(() => {
              localStorage.setItem("CD",
              encodeURI($("#block-awardsbycongressionaldistrict select option:selected").text().trim()));
            });
            $("#block-awardsbynofonumber .grants-filters-info").click(false);
            $("#block-awardsbycongressionaldistrict .grants-filters-info").click(false);

            // OCWT-3326
            setTimeout(() => {
              $("a.grants-filters-info.samhsa-tooltip").removeAttr("aria-expanded");
            }, 300);

            // OCWT-5317
            if (window.location.href.indexOf("grants/grants-dashboard") > 0)
              Cookies.set("grants-dashboard-url", window.location.href);
            if ($("#back-to-grants").length > 0) {
              $("#back-to-grants").attr("href", Cookies.get("grants-dashboard-url"));
            }

            // OCWT-6495
            // Remove anchor tag from 508 tree
            $("#block-awards-active-filters .facet-summary-item--facet a").attr("tabindex", -1);
            // Add click event when focused and enter key pressed
            $("#block-awards-active-filters .facet-summary-item--facet").each(function(index, element) {
              $(element).focus(function() {
                $(element).keypress(function(e) {
                  if(e.which == 13) {
                    $(element).find("a")[0].click();
                  }
                });
              });
            });

            $(".view-display-id-grants_dashboard__nofos table.views-view-table tbody tr td.views-field-field-view-awards-link a").attr("aria-label", "View Awards for NOFO");

            // OCWT - 8635
            // Expand All / Collapse All
            $("#expand-all--nofos").on("click", () => {
              $("#nofos_content").find(".grants-accordion-button--mobile").attr('aria-expanded', true);
              $("#nofos_content").find(".mobile-content").removeAttr('hidden');
            });

            $("#collapse-all--nofos").on("click", () => {
              $("#nofos_content").find(".grants-accordion-button--mobile").attr('aria-expanded', false);
              $("#nofos_content").find(".mobile-content").attr('hidden', "");
            });

            $("#expand-all--awards").on("click", () => {
              $("#awards_content").find(".grants-accordion-button").attr('aria-expanded', true);
              $("#awards_content").find(".grants-accordion-button--mobile").attr('aria-expanded', true);
              $("#awards_content").find(".grant-accordion__content").removeAttr('hidden');
              $("#awards_content").find(".mobile-content").removeAttr('hidden');
            });

            $("#collapse-all--awards").on("click", () => {
              $("#awards_content").find(".grants-accordion-button").attr('aria-expanded', false);
              $("#awards_content").find(".grants-accordion-button--mobile").attr('aria-expanded', false);
              $("#awards_content").find(".grant-accordion__content").attr('hidden', "");
              $("#awards_content").find(".mobile-content").attr('hidden', "");
            });
            
            // OCWT-8182
            $(".grants-filters-info.samhsa-tooltip").on("click", (event) => {
              event.stopPropagation();
            });
          });

          // OCWT-3809
          $(".fiscal-year-grant-announcements").click((e) => {
            e.preventDefault();
            const trimmedUrl = $(e.target).attr("href").slice(0, -27);
            window.location.href = trimmedUrl;
          });
          // OCWT-3641
          if ($(window).width() < 500) {
            $(
              "#awards_content .view-grants-dashboard.view-id-grants_dashboard.view-display-id-grants_dashboard__awards .usa-pagination"
            )
              .attr("id", "dashboard-awards-pagination")
              .detach()
              .insertAfter(".grant-dashboard#main-content-inner");
            $(
              "#awards_content .view-grants-dashboard.view-id-grants_dashboard.view-display-id-grants_dashboard__awards .view-pagination-text"
            )
              .attr("id", "dashboard-awards-pagination-text")
              .detach()
              .insertAfter("#dashboard-awards-pagination");
            $(
              "#nofos_content .view-grants-dashboard.view-id-grants_dashboard.view-display-id-grants_dashboard__nofos .usa-pagination"
            )
              .attr("id", "dashboard-nofos-pagination")
              .detach()
              .insertAfter(".grant-dashboard#main-content-inner");
            $(
              "#nofos_content .view-grants-dashboard.view-id-grants_dashboard.view-display-id-grants_dashboard__nofos .view-pagination-text"
            )
              .attr("id", "dashboard-nofos-pagination-text")
              .detach()
              .insertAfter("#dashboard-nofos-pagination");
            setTimeout(() => {
              if ($("li#nofos-tab").hasClass("active")) {
                $(
                  "#dashboard-awards-pagination, #dashboard-awards-pagination-text"
                ).css("display", "none");
                $("#dashboard-nofos-pagination, #dashboard-nofos-pagination-text").css(
                  "display",
                  "block"
                );
              }
              if ($("li#awards-tab").hasClass("active")) {
                $("#dashboard-nofos-pagination, #dashboard-nofos-pagination-text").css(
                  "display",
                  "none"
                );
                $(
                  "#dashboard-awards-pagination, #dashboard-awards-pagination-text"
                ).css("display", "block");
              }
            }, 500);
            $("li#nofos-tab").click(() => {
              $("#dashboard-awards-pagination, #dashboard-awards-pagination-text").css(
                "display",
                "none"
              );
              $("#dashboard-nofos-pagination, #dashboard-nofos-pagination-text").css(
                "display",
                "block"
              );
            });
            $("li#awards-tab").click(() => {
              $("#dashboard-nofos-pagination, #dashboard-nofos-pagination-text").css(
                "display",
                "none"
              );
              $("#dashboard-awards-pagination, #dashboard-awards-pagination-text").css(
                "display",
                "block"
              );
            });
          }

          // OCWT-4279
          $("td[headers='view-field-webinar-link-table-column'] a").each((i, el) => {
            setTimeout(() => {
              if ($(el).is("[alt='FAQ Document']")) {
                $(el).attr("aria-label", "FAQ Document (opens in a new window)");
              }
              if ($(el).is("[alt='View Webinar']")) {
                $(el).attr("aria-label", "View PDF Webinar (opens in a new window)");
              }
              if ($(el).is("[href*='youtu']")) {
                $(el).attr("aria-label", "View Video Webinar (opens in a new window)");
              }
            }, 1000);
          });

          $(".block-facets-summary .facet-summary-item--facet a").each((i, el) => {
            if(i === 0) {
              $(el).attr("aria-label", `${$(".active-filters-count").text()} - ${$(el).parent().prev(".facet-title").text()} - Selected filter element: ${$(el).text()} - Click to unselect this filter element`);
            } else {
              $(el).attr("aria-label", `${$(el).parent().prev(".facet-title").text()} - Selected filter element: ${$(el).text()} - Click to unselect this filter element`);
            }
          });

          // export page mobile menu
          if ($('body').hasClass('path-batch')) {
              $('#top-search-glass-icon').click(function() {
                $('.search-form-wrapper-mobile').toggleClass('open');
                $('.search-form-wrapper-mobile').toggleClass('close');
              });

              $('.search-form-wrapper-mobile').addClass('close');
          }

          // Positions data export button in Tab Block above table
          $(document).ready(function() {
            let $dataExport = $('.csvButton').first(); 
            let $tabBlock = $('.csvDownloadWrapper'); 

            if (!$dataExport.closest('.csvDownloadWrapper').length) {
                $tabBlock.append($dataExport);
            }

            $('.csvButton').each(function() {
                let $tabButton = $(this);
                if (!$tabButton.closest('.csvDownloadWrapper').length) {
                    $tabButton.hide();
                }
            });
          });
        })(jQuery);
      }));
    }
  }
})(jQuery, Drupal);