export function initAccessTokenSettings() {
  for (const table of document.querySelectorAll<HTMLTableElement>('.js-access-token-scope-table')) {
    const selectAllInputs = Array.from(table.querySelectorAll<HTMLInputElement>('.js-access-token-scope-select-all'));
    const categoryRows = Array.from(table.querySelectorAll<HTMLTableRowElement>('tr')).filter((row) => !row.classList.contains('js-access-token-scope-select-all-row'));

    const getRowSelector = (scopeValue: string, category: string) => scopeValue ?
      `input[type="radio"][value="${CSS.escape(`${scopeValue}:${category}`)}"]` :
      'input[type="radio"][value=""]';

    const updateSelectAllState = () => {
      let matchedValue: string | null = null;
      for (const input of selectAllInputs) {
        const scopeValue = input.value;
        const everyRowMatches = categoryRows.every((row) => {
          const category = row.cells[0]?.textContent?.trim();
          if (!category) return false;
          return row.querySelector<HTMLInputElement>(getRowSelector(scopeValue, category))?.checked === true;
        });
        if (everyRowMatches) {
          matchedValue = scopeValue;
          break;
        }
      }
      for (const input of selectAllInputs) {
        input.checked = matchedValue !== null && input.value === matchedValue;
      }
    };

    for (const input of selectAllInputs) {
      input.addEventListener('change', () => {
        if (!input.checked) return;
        const scopeValue = input.value;
        for (const row of categoryRows) {
          const category = row.cells[0]?.textContent?.trim();
          if (!category) continue;
          row.querySelector<HTMLInputElement>(getRowSelector(scopeValue, category))!.checked = true;
        }
        updateSelectAllState();
      });
    }

    for (const row of categoryRows) {
      for (const input of row.querySelectorAll<HTMLInputElement>('input[type="radio"]')) {
        input.addEventListener('change', updateSelectAllState);
      }
    }

    updateSelectAllState();
  }
}
