import onFind from './dom/onFind'

onFind(
  '.ContentEditSites-access .ComboInput.is-multiple',
  (comboInput: HTMLElement) => {
    const context = comboInput.closest<HTMLElement>('.Widget')

    // If user does not have permissions to see a site granted access to a piece of content,
    // hides that site from access list/label yet persists that site's access across publishes
    const hiddenOptions = context?.querySelectorAll<HTMLOptionElement>(
      '.ContentEditSites-access option[data-hidden="true"]',
    )
    const hiddenCount = hiddenOptions?.length
    if (hiddenCount) {
      const selectedSites = comboInput.querySelectorAll(
        '.ComboInput-option[aria-selected="true"]',
      )
      const array = Array.prototype.slice.call(selectedSites)
      const selectedLabel = comboInput.querySelectorAll('.ComboInput-selected')

      for (let i = 0; i < hiddenCount; i++) {
        const hiddenId = hiddenOptions[i]?.value
        const hiddenSite = comboInput.querySelector(
          `.ComboInput-option[data-value="${hiddenId}"]`,
        )
        hiddenSite?.setAttribute('data-no-permission', 'true')

        const hiddenIndex = array.indexOf(hiddenSite)
        selectedLabel[hiddenIndex].remove()
      }
    }

    // Hides site owner from list of sites in access widget
    // Updates whenever owner changes
    if (context) {
      onFind(
        context,
        '.ContentEditSites-owner .ComboInput-selected',
        (siteOwner: HTMLElement) => {
          const owner = siteOwner.closest('.ContentEditSites-owner')
          const select = owner?.querySelector('select')
          const selectedId = select?.options[select.selectedIndex].value
          const comboInputId = comboInput.getAttribute('aria-owns')
          const siteList = document.querySelector(
            `.ComboInput-list#${comboInputId}`,
          )
          const previousOwner = siteList?.querySelector<HTMLElement>(
            '.ComboInput-option[data-is-owner]',
          )
          if (previousOwner) {
            previousOwner.removeAttribute('data-is-owner')

            if (
              !previousOwner.hasAttribute('data-is-hidden') &&
              previousOwner.dataset.source
            ) {
              const siteCategory = siteList?.querySelector(
                `.ComboInput-heading[data-value="${previousOwner.dataset.source}"]`,
              )
              siteCategory?.removeAttribute('data-hidden')
            }
          }
          if (selectedId) {
            const ownerOption = siteList?.querySelector<HTMLElement>(
              `.ComboInput-option[data-value="${selectedId}"]`,
            )
            ownerOption?.setAttribute('data-is-owner', 'true')

            const selectedSites = siteList?.querySelectorAll(
              '.ComboInput-option[aria-selected="true"]:not([data-no-permission])',
            )
            const sitesArray = Array.prototype.slice.call(selectedSites)
            const ownerIndex = sitesArray.indexOf(ownerOption)
            if (ownerIndex >= 0) {
              const siteLabel =
                comboInput?.querySelector('.ComboInput-label')?.children

              if (siteLabel) {
                siteLabel[ownerIndex].remove()
              }
            }
            ownerOption?.setAttribute('aria-selected', 'false')
            // Hides site category label (in access dropdown) if site owner is the only site in the category
            const siteCategoryId = ownerOption?.dataset.source
            if (siteCategoryId) {
              const visibleSites = siteList?.querySelectorAll(
                `.ComboInput-option:not([data-is-owner])[data-source="${siteCategoryId}"]`,
              )
              if (!visibleSites?.length) {
                const siteCategory = siteList?.querySelector(
                  `.ComboInput-heading[data-value="${siteCategoryId}"`,
                )
                siteCategory?.setAttribute('data-hidden', 'true')
              }
            }
          }
        },
      )
    }
  },
)
