document.body.addEventListener('htmx:responseError', (event) => {
  const target = event.detail.target;
  if (target) {
    target.innerHTML = '<div class="alert alert-danger">요청 처리 중 오류가 발생했습니다.</div>';
  }
});

const READ_ONLY_POST_ALLOWLIST = new Set([
  '/login',
  '/logout',
  '/probe',
  '/vector-knowledge/search',
  '/security-sql-scripts/explanation',
  '/mcp-chatbot',
  '/mcp-client-demo',
  '/mcp-reasoning',
]);

function normalizeActionPath(value) {
  if (!value) {
    return '';
  }
  try {
    return new URL(value, window.location.origin).pathname;
  } catch (_error) {
    return value;
  }
}

function isReadOnlyMode() {
  return document.querySelector('meta[name="backoffice-read-only"]')?.content === 'true';
}

function isFormMutation(form) {
  const method = (form.getAttribute('method') || 'get').toLowerCase();
  const hxPost = form.getAttribute('hx-post');
  if (hxPost) {
    return !READ_ONLY_POST_ALLOWLIST.has(normalizeActionPath(hxPost));
  }
  if (method !== 'post') {
    return false;
  }
  return !READ_ONLY_POST_ALLOWLIST.has(normalizeActionPath(form.getAttribute('action')));
}

function disableReadOnlyMutationForms() {
  if (!isReadOnlyMode()) {
    return;
  }
  document.querySelectorAll('form').forEach((form) => {
    if (!isFormMutation(form)) {
      return;
    }
    if (!form.previousElementSibling?.matches?.('[data-readonly-mutation-notice]')) {
      const notice = document.createElement('div');
      notice.className = 'alert alert-secondary readonly-mutation-notice';
      notice.setAttribute('data-readonly-mutation-notice', 'true');
      notice.textContent = '읽기 전용 계정은 이 변경 작업을 실행할 수 없습니다.';
      form.parentNode?.insertBefore(notice, form);
    }
    form.classList.add('readonly-mutation-disabled');
    form.setAttribute('aria-disabled', 'true');
    form.querySelectorAll('input:not([type="hidden"]), select, textarea, button').forEach((control) => {
      control.disabled = true;
    });
  });
}

function resetFilterToggle(button, target) {
  if (!button || !target) {
    return;
  }
  button.setAttribute('aria-expanded', 'false');
  button.classList.remove('active');
  target.innerHTML = button.dataset.toggleDefaultText || 'Filter 이름을 클릭하면 policy/filter source가 표시됩니다.';
}

function setFilterToggleLoading(button, target) {
  if (!button || !target) {
    return;
  }
  button.setAttribute('aria-expanded', 'true');
  button.classList.add('active');
  target.innerHTML = button.dataset.toggleLoadingText || 'policy/filter source를 조회하는 중입니다.';
}

function findHtmxTarget(button) {
  const selector = button?.getAttribute('hx-target') || button?.getAttribute('data-hx-target');
  return selector ? document.querySelector(selector) : null;
}

function syncPolicyTemplate(select) {
  const form = select?.closest('form');
  if (!form) {
    return;
  }
  const option = select.options[select.selectedIndex];
  const hasTemplate = Boolean(option?.dataset.policyName);
  const policyName = form.querySelector('[data-policy-template-field="policyName"]');
  const functionKey = form.querySelector('[data-policy-template-field="functionKey"]');
  const enabled = form.querySelector('[data-policy-template-field="enabled"]');
  const updateCheck = form.querySelector('[data-policy-template-field="updateCheck"]');
  if (policyName) {
    policyName.value = option?.dataset.policyName || '';
  }
  if (functionKey) {
    functionKey.value = option?.dataset.functionKey || '';
  }
  if (enabled) {
    enabled.checked = hasTemplate ? option?.dataset.enabled === 'true' : true;
  }
  if (updateCheck) {
    updateCheck.checked = hasTemplate ? option?.dataset.updateCheck === 'true' : false;
  }
  const selectedStatements = (hasTemplate ? option?.dataset.statementTypes || '' : 'SELECT')
      .split(',')
      .map((value) => value.trim())
      .filter(Boolean);
  form.querySelectorAll('[data-policy-template-statement]').forEach((checkbox) => {
    checkbox.checked = selectedStatements.includes(checkbox.value);
  });
  const preview = (name, value) => {
    const target = form.querySelector(`[data-policy-template-preview="${name}"]`);
    if (target) {
      target.textContent = value;
    }
  };
  preview('policyName', option?.dataset.policyName || '선택 전');
  preview('functionKey', option?.dataset.functionKey || '선택 전');
  preview('statementTypes', selectedStatements.join(', ') || 'SELECT');
  preview(
      'options',
      `Enabled: ${enabled?.checked ? 'YES' : 'NO'} / Check: ${updateCheck?.checked ? 'YES' : 'NO'}`
  );
}

function initPersistentMenus() {
  const productNav = document.querySelector('[data-product-nav]');
  if (!productNav) {
    return;
  }
  const submenuBar = productNav.querySelector('[data-submenu-bar]');
  const triggers = Array.from(productNav.querySelectorAll('[data-submenu-trigger]'));
  const panels = Array.from(productNav.querySelectorAll('[data-submenu-panel]'));
  const path = window.location.pathname;

  const activate = (target) => {
    const hasTarget = panels.some((panel) => panel.dataset.submenuPanel === target);
    submenuBar.hidden = !hasTarget;
    triggers.forEach((trigger) => {
      const active = trigger.dataset.submenuTrigger === target;
      trigger.classList.toggle('active', active);
      trigger.setAttribute('aria-expanded', String(active));
    });
    panels.forEach((panel) => {
      panel.hidden = panel.dataset.submenuPanel !== target;
    });
  };

  const currentPanel = panels.find((panel) => Array.from(panel.querySelectorAll('a[href]')).some((link) => {
    const href = new URL(link.href, window.location.origin).pathname;
    return path === href || (href !== '/' && path.startsWith(`${href}/`));
  }));
  if (currentPanel) {
    activate(currentPanel.dataset.submenuPanel);
  }

  triggers.forEach((trigger) => {
    trigger.addEventListener('click', () => activate(trigger.dataset.submenuTrigger));
  });
}

function initQuestionPresets(root = document) {
  root.querySelectorAll('.question-preset[data-target]').forEach((button) => {
    if (button.dataset.presetReady === 'true') {
      return;
    }
    button.dataset.presetReady = 'true';
    button.addEventListener('click', () => {
      const target = document.getElementById(button.dataset.target || '');
      if (target) {
        target.value = button.dataset.question || '';
        target.focus();
      }
    });
  });
}

function initCopyButtons(root = document) {
  root.querySelectorAll('[data-copy-source]').forEach((button) => {
    if (button.dataset.copyReady === 'true') {
      return;
    }
    button.dataset.copyReady = 'true';
    button.addEventListener('click', async () => {
      const source = document.getElementById(button.dataset.copySource || '');
      const value = source?.textContent?.trim();
      if (!value) {
        return;
      }
      try {
        await navigator.clipboard.writeText(value);
        button.textContent = '복사했습니다';
      } catch (error) {
        button.textContent = '복사 실패 · 직접 선택하세요';
      }
    });
  });
}

function escapeHtml(value) {
  return value
      .replaceAll('&', '&amp;')
      .replaceAll('<', '&lt;')
      .replaceAll('>', '&gt;')
      .replaceAll('"', '&quot;')
      .replaceAll("'", '&#39;');
}

function renderInlineMarkdown(value) {
  return escapeHtml(value)
      .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
      .replace(/`([^`]+)`/g, '<code>$1</code>');
}

function isMarkdownTable(lines, index) {
  if (index + 1 >= lines.length) {
    return false;
  }
  return lines[index].trim().startsWith('|')
      && lines[index + 1].trim().startsWith('|')
      && /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/.test(lines[index + 1].trim());
}

function splitMarkdownTableRow(line) {
  return line.trim()
      .replace(/^\|/, '')
      .replace(/\|$/, '')
      .split('|')
      .map((cell) => cell.trim());
}

function renderMarkdownTable(lines, start) {
  const headers = splitMarkdownTableRow(lines[start]);
  let cursor = start + 2;
  const rows = [];
  while (cursor < lines.length && lines[cursor].trim().startsWith('|')) {
    rows.push(splitMarkdownTableRow(lines[cursor]));
    cursor += 1;
  }
  const headerHtml = headers.map((cell) => `<th>${renderInlineMarkdown(cell)}</th>`).join('');
  const bodyHtml = rows.map((row) => {
    const cells = headers.map((_, index) => `<td>${renderInlineMarkdown(row[index] || '')}</td>`).join('');
    return `<tr>${cells}</tr>`;
  }).join('');
  return {
    html: `<table><thead><tr>${headerHtml}</tr></thead><tbody>${bodyHtml}</tbody></table>`,
    next: cursor
  };
}

function renderMarkdownText(markdown) {
  const lines = markdown.replace(/\r\n/g, '\n').split('\n');
  const html = [];
  let listType = null;
  const closeList = () => {
    if (listType) {
      html.push(`</${listType}>`);
      listType = null;
    }
  };
  for (let i = 0; i < lines.length; i += 1) {
    const line = lines[i];
    const trimmed = line.trim();
    if (!trimmed) {
      closeList();
      continue;
    }
    if (isMarkdownTable(lines, i)) {
      closeList();
      const table = renderMarkdownTable(lines, i);
      html.push(table.html);
      i = table.next - 1;
      continue;
    }
    const heading = trimmed.match(/^(#{2,4})\s+(.+)$/);
    if (heading) {
      closeList();
      const level = Math.min(heading[1].length, 3);
      html.push(`<h${level}>${renderInlineMarkdown(heading[2])}</h${level}>`);
      continue;
    }
    const unordered = trimmed.match(/^[-*]\s+(.+)$/);
    if (unordered) {
      if (listType !== 'ul') {
        closeList();
        listType = 'ul';
        html.push('<ul>');
      }
      html.push(`<li>${renderInlineMarkdown(unordered[1])}</li>`);
      continue;
    }
    const ordered = trimmed.match(/^\d+\.\s+(.+)$/);
    if (ordered) {
      if (listType !== 'ol') {
        closeList();
        listType = 'ol';
        html.push('<ol>');
      }
      html.push(`<li>${renderInlineMarkdown(ordered[1])}</li>`);
      continue;
    }
    closeList();
    html.push(`<p>${renderInlineMarkdown(trimmed)}</p>`);
  }
  closeList();
  return html.join('');
}

function renderMarkdownViews(root = document) {
  root.querySelectorAll('[data-markdown-view]').forEach((view) => {
    if (view.dataset.rendered === 'true') {
      return;
    }
    view.innerHTML = renderMarkdownText(view.textContent || '');
    view.dataset.rendered = 'true';
  });
}

function filterUserRoleDetail() {
  const master = document.getElementById('userRoleMaster');
  const table = document.getElementById('userRoleDetail');
  if (!master || !table) {
    return;
  }
  const selected = master.value;
  let shown = 0;
  table.querySelectorAll('tbody tr[data-user-id]').forEach((row) => {
    const visible = row.dataset.userId === selected;
    row.hidden = !visible;
    shown += visible ? 1 : 0;
  });
  let empty = table.querySelector('tbody tr.empty-user-role-runtime');
  if (!empty) {
    empty = document.createElement('tr');
    empty.className = 'empty-user-role-runtime';
    empty.innerHTML = '<td colspan="3" class="text-muted">선택한 사용자에게 부여된 역할이 없습니다.</td>';
    table.querySelector('tbody').appendChild(empty);
  }
  empty.hidden = shown !== 0;
}

function filterGroupDetail(masterId) {
  const master = document.getElementById(masterId);
  const table = document.querySelector(`[data-group-detail-table="${masterId}"]`);
  if (!master || !table) {
    return;
  }
  const selected = master.value;
  let shown = 0;
  table.querySelectorAll('tbody tr[data-group-id]').forEach((row) => {
    const visible = row.dataset.groupId === selected;
    row.hidden = !visible;
    shown += visible ? 1 : 0;
  });
  let empty = table.querySelector('tbody tr.empty-group-detail-runtime');
  if (!empty) {
    empty = document.createElement('tr');
    empty.className = 'empty-group-detail-runtime';
    empty.innerHTML = `<td colspan="3" class="text-muted">${escapeHtml(table.dataset.emptyMessage || '선택한 그룹에 등록된 항목이 없습니다.')}</td>`;
    table.querySelector('tbody').appendChild(empty);
  }
  empty.hidden = shown !== 0;
}

function renderRuleColumnOptions(columns) {
  document.querySelectorAll('.rule-column-select').forEach((select) => {
    const current = select.value;
    select.innerHTML = '<option value="">기본 컬럼</option>' + columns
        .map((column) => `<option value="${column}">${column}</option>`)
        .join('');
    if (columns.includes(current)) {
      select.value = current;
    }
  });
}

function syncRuleTypeHints(root = document) {
  root.querySelectorAll('.rule-row').forEach((row) => {
    const typeSelect = row.querySelector('.rule-type-select');
    const columnSelect = row.querySelector('.rule-column-select');
    const valueInput = row.querySelector('input[name="ruleValue"]');
    if (!typeSelect || !columnSelect || !valueInput) {
      return;
    }

    const type = typeSelect.value;
    const valueRequired = ['=', '!=', 'DEPT', 'EMP_NO', 'TAG', 'STAKEHOLDER_SELF', 'STAKEHOLDER_CHANNEL', 'STATIC_SQL'].includes(type);
    const columnOptional = ['ALL', 'MY_DEPT', 'SELF', 'DEPT', 'EMP_NO', 'TAG', 'STATIC_SQL'].includes(type);
    const placeholderByType = {
      ALL: '값 불필요',
      MY_DEPT: '값 불필요',
      SELF: '값 불필요',
      DEPT: '예: HR',
      EMP_NO: '예: E2001',
      TAG: '예: SPRING_BOOT',
      STAKEHOLDER_SELF: '예: 설계사',
      STAKEHOLDER_CHANNEL: '예: 지점장',
      TOKEN_SUBJECT: '값 불필요',
      OWN_CONTRACT: '값 불필요',
      CHANNEL_CONTRACT: '값 불필요',
      OWN_CUSTOMER: '값 불필요',
      CHANNEL_CUSTOMER: '값 불필요',
      STATIC_SQL: "예: CONTRACT_STATUS = '정상'",
      '=': '비교 값',
      '!=': '비교 값'
    };

    columnSelect.required = !columnOptional;
    columnSelect.disabled = ['ALL', 'MY_DEPT', 'SELF', 'DEPT', 'EMP_NO', 'TAG', 'STATIC_SQL'].includes(type);
    valueInput.required = valueRequired;
    valueInput.disabled = [
      'ALL', 'MY_DEPT', 'SELF', 'TOKEN_SUBJECT', 'OWN_CONTRACT',
      'CHANNEL_CONTRACT', 'OWN_CUSTOMER', 'CHANNEL_CUSTOMER'
    ].includes(type);
    valueInput.placeholder = placeholderByType[type] || '비교 값';
    if (valueInput.disabled) {
      valueInput.value = '';
    }
    if (columnSelect.disabled) {
      columnSelect.value = '';
    }
  });
}

async function syncRuleColumnOptions() {
  const objectSelect = document.querySelector('select[name="objectRef"]');
  if (!objectSelect) {
    return;
  }
  const selectedOption = objectSelect.options[objectSelect.selectedIndex];
  const fallbackColumns = (selectedOption?.dataset.columns || '').split(',').filter(Boolean);
  const applyColumns = (columns) => {
    if (selectedOption) {
      selectedOption.dataset.columns = columns.join(',');
    }
    renderRuleColumnOptions(columns);
    updatePermissionWizardPreview(document);
  };
  applyColumns(fallbackColumns);
  try {
    const response = await fetch(`/permissions/object-columns?objectRef=${encodeURIComponent(objectSelect.value)}`);
    if (!response.ok) {
      return;
    }
    const columns = await response.json();
    applyColumns(Array.isArray(columns) ? columns : fallbackColumns);
  } catch (error) {
    applyColumns(fallbackColumns);
  }
}

async function syncObjectCatalogSelection() {
  const catalog = document.getElementById('objectCatalogSelect');
  if (!catalog || !catalog.value) {
    return;
  }
  const selected = catalog.options[catalog.selectedIndex];
  const ownerInput = document.querySelector('input[name="owner"]');
  const objectInput = document.querySelector('input[name="objectName"]');
  const ordsPathInput = document.querySelector('input[name="ordsPath"]');
  if (ownerInput) {
    ownerInput.value = selected.dataset.owner || '';
  }
  if (objectInput) {
    objectInput.value = selected.dataset.objectName || '';
  }
  if (ordsPathInput) {
    const owner = (selected.dataset.owner || '').toLowerCase();
    const objectName = (selected.dataset.objectName || '').toLowerCase();
    ordsPathInput.value = owner && objectName ? `cb-ords/cb-object-query/${owner}/${objectName}` : '';
    ordsPathInput.readOnly = true;
  }
  const ordsPathEdit = document.querySelector('[data-ords-path-edit]');
  if (ordsPathEdit) {
    ordsPathEdit.checked = false;
  }
}

function initOrdsPathEditToggle() {
  const toggle = document.querySelector('[data-ords-path-edit]');
  const input = document.querySelector('[data-ords-path-input]');
  if (!toggle || !input) {
    return;
  }
  toggle.addEventListener('change', () => {
    input.readOnly = !toggle.checked;
    if (toggle.checked) {
      input.focus();
    }
  });
}

function initProbeObjectDescription() {
  const select = document.querySelector('select[name="objectId"]');
  const target = document.querySelector('[data-probe-object-description]');
  if (!select || !target) {
    return;
  }
  const update = () => {
    const option = selectedOption(select);
    target.textContent = option?.dataset.description
        || '선택한 대상의 설명이 등록되지 않았습니다. ORDS 조회 대상에서 설명을 추가하세요.';
  };
  select.addEventListener('change', update);
  update();
}

function initProbeVectorInput() {
  const select = document.querySelector('select[name="objectId"]');
  const blocks = document.querySelectorAll('[data-vector-probe-input]');
  const input = document.querySelector('[data-vector-probe-input] textarea[name="requestBody"]');
  const controls = document.querySelectorAll('[data-vector-probe-input] textarea, [data-vector-probe-input] select, [data-vector-probe-input] input');
  if (!select || !blocks.length || !input) {
    return;
  }
  const update = () => {
    const option = selectedOption(select);
    const isVectorSearch = option?.dataset.vectorSearch === 'true';
    blocks.forEach(block => {
      block.hidden = !isVectorSearch;
    });
    controls.forEach(control => {
      control.disabled = !isVectorSearch;
    });
    input.required = isVectorSearch;
    if (!isVectorSearch) {
      input.value = '';
    }
  };
  select.addEventListener('change', update);
  update();
}

function selectedText(select) {
  if (!select || select.selectedIndex < 0) {
    return '-';
  }
  return select.options[select.selectedIndex].textContent.trim();
}

function selectedOption(select) {
  if (!select || select.selectedIndex < 0) {
    return null;
  }
  return select.options[select.selectedIndex];
}

function splitList(value, separator = '|') {
  return (value || '')
      .split(separator)
      .map((item) => item.trim())
      .filter(Boolean);
}

function formatList(values, emptyText) {
  if (!values.length) {
    return emptyText;
  }
  const shown = values.slice(0, 4).join(', ');
  return values.length > 4 ? `${shown} 외 ${values.length - 4}` : shown;
}

function setWizardPreview(wizard, name, value) {
  wizard.querySelectorAll(`[data-preview="${name}"]`).forEach((target) => {
    target.textContent = value;
  });
}

function setTokenPreview(preview, name, value) {
  preview.querySelectorAll(`[data-token-preview="${name}"]`).forEach((target) => {
    target.textContent = value;
  });
}

function updateTokenContextPreview(select) {
  const form = select.closest('form');
  const preview = form?.querySelector('[data-token-context-preview]');
  if (!preview) {
    return;
  }
  const option = selectedOption(select);
  if (!option || !option.value) {
    setTokenPreview(preview, 'status', '미선택');
    setTokenPreview(preview, 'username', '원문 직접 입력');
    setTokenPreview(preview, 'prefix', '-');
    setTokenPreview(preview, 'expiresAt', '-');
    setTokenPreview(preview, 'directRoles', '-');
    setTokenPreview(preview, 'groups', '-');
    setTokenPreview(preview, 'inheritedRoles', '-');
    setTokenPreview(preview, 'description', '토큰을 선택하면 등록된 사용자/역할 컨텍스트를 먼저 확인할 수 있습니다.');
    return;
  }

  const directRoles = splitList(option.dataset.directRoles || '');
  const groups = splitList(option.dataset.groups || '');
  const inheritedRoles = splitList(option.dataset.inheritedRoles || '');
  setTokenPreview(preview, 'status', option.dataset.status || '-');
  setTokenPreview(preview, 'username', option.dataset.username || '-');
  setTokenPreview(preview, 'prefix', option.dataset.prefix || '****');
  setTokenPreview(preview, 'expiresAt', option.dataset.expiresAt || '-');
  setTokenPreview(preview, 'directRoles', formatList(directRoles, '직접 역할 없음'));
  setTokenPreview(preview, 'groups', formatList(groups, '소속 그룹 없음'));
  setTokenPreview(preview, 'inheritedRoles', formatList(inheritedRoles, '그룹 상속 역할 없음'));
  setTokenPreview(preview, 'description', option.dataset.description || '설명 없음');
}

function initTokenContextPreviews() {
  document.querySelectorAll('[data-token-context-select]').forEach((select) => {
    select.addEventListener('change', () => updateTokenContextPreview(select));
    updateTokenContextPreview(select);
  });
}

function filterEffectiveMatrixTable(select) {
  const table = document.getElementById(select.dataset.effectiveFilter || '');
  if (!table) {
    return;
  }
  const value = select.value || '';
  table.querySelectorAll('.effective-empty-row').forEach((row) => row.remove());
  let visibleRows = 0;
  table.querySelectorAll('tbody tr[data-effective-id]').forEach((row) => {
    const visible = !value || row.dataset.effectiveId === value;
    row.hidden = !visible;
    if (visible) {
      visibleRows += 1;
    }
  });
  if (value && visibleRows === 0) {
    const body = table.querySelector('tbody');
    const columnCount = table.querySelectorAll('thead th').length || 1;
    const row = document.createElement('tr');
    row.className = 'effective-empty-row';
    row.innerHTML = `<td colspan="${columnCount}" class="text-muted">${table.dataset.emptyMessage || '선택한 항목이 없습니다.'}</td>`;
    body?.appendChild(row);
  }
  if (select.matches('[data-effective-user-select]')) {
    updateEffectiveUserFocus(table, value);
  }
}

function updateEffectiveUserFocus(table, userId) {
  const focus = document.querySelector('[data-effective-user-focus]');
  if (!focus || !table) {
    return;
  }
  const row = Array.from(table.querySelectorAll('tbody tr[data-effective-id]'))
      .find((item) => item.dataset.effectiveId === (userId || ''));
  const values = {
    username: row?.dataset.username || '사용자 선택',
    profile: row?.dataset.profile || '사번 / 부서',
    directRoles: row?.dataset.directRoles || '-',
    inheritance: row?.dataset.inheritance || '-',
    effectiveRoles: row?.dataset.effectiveRoles || '-',
    objects: row?.dataset.objects || '-',
    permissionCount: row?.dataset.permissionCount || '0'
  };
  Object.entries(values).forEach(([field, value]) => {
    const target = focus.querySelector(`[data-effective-user-field="${field}"]`);
    if (target) {
      target.textContent = value;
    }
  });
}

function initEffectiveMatrixTabs() {
  const tabs = document.querySelectorAll('[data-effective-tab]');
  const panes = document.querySelectorAll('[data-effective-pane]');
  if (!tabs.length || !panes.length) {
    return;
  }
  tabs.forEach((tab) => {
    tab.addEventListener('click', () => {
      const target = tab.dataset.effectiveTab;
      tabs.forEach((item) => {
        const active = item === tab;
        item.classList.toggle('is-active', active);
        item.setAttribute('aria-selected', String(active));
      });
      panes.forEach((pane) => {
        pane.hidden = pane.dataset.effectivePane !== target;
      });
    });
  });
}

function initEffectiveMatrixFilters() {
  document.querySelectorAll('[data-effective-filter]').forEach((select) => {
    select.addEventListener('change', () => filterEffectiveMatrixTable(select));
    filterEffectiveMatrixTable(select);
  });
}

function sqlLiteral(value) {
  return `'${String(value || '').replaceAll("'", "''")}'`;
}

function permissionRuleBusinessLabel(type, column, value) {
  const displayColumn = column || {
    MY_DEPT: 'DEPT_CODE',
    SELF: 'OWNER_EMP_NO',
    DEPT: 'DEPT_CODE',
    EMP_NO: 'OWNER_EMP_NO',
    TAG: 'TECH_TAG',
    TOKEN_SUBJECT: 'USER_ID',
    OWN_CONTRACT: 'FC_ID',
    CHANNEL_CONTRACT: 'FC_CHANNEL',
    OWN_CUSTOMER: 'CUST_ID/CONTRACT_NO',
    CHANNEL_CUSTOMER: 'CUST_ID/CONTRACT_NO',
    STATIC_SQL: '',
    ALL: ''
  }[type] || '선택 컬럼';
  if (type === 'ALL') {
    return '전체 행';
  }
  if (type === 'TOKEN_SUBJECT') {
    return `토큰 이해관계자 본인 행 (${displayColumn})`;
  }
  if (type === 'OWN_CONTRACT') {
    return `담당 게임 서비스 범위 (${displayColumn})`;
  }
  if (type === 'CHANNEL_CONTRACT') {
    return `토큰 채널 게임 서비스 범위 (${displayColumn})`;
  }
  if (type === 'OWN_CUSTOMER') {
    return `담당 게임 사용자·거래 데이터 범위 (${displayColumn})`;
  }
  if (type === 'CHANNEL_CUSTOMER') {
    return `토큰 채널 게임 사용자·거래 데이터 범위 (${displayColumn})`;
  }
  if (type === 'STATIC_SQL') {
    return `정적 SQL 조건: ${value || '조건식 미입력'}`;
  }
  if (type === 'MY_DEPT') {
    return `내 부서 행 (${displayColumn})`;
  }
  if (type === 'SELF') {
    return `내 사번/소유자 행 (${displayColumn})`;
  }
  if (type === 'TAG') {
    return `태그 조건 ${displayColumn} contains ${value || '-'}`;
  }
  return [displayColumn, type, value].filter(Boolean).join(' ');
}

function collectWizardRules(root) {
  return Array.from(root.querySelectorAll('.rule-row')).map((row) => {
    const column = row.querySelector('[name="ruleColumn"]')?.value || '';
    const type = row.querySelector('[name="ruleType"]')?.value || '';
    const value = row.querySelector('[name="ruleValue"]')?.value || '';
    const displayColumn = column || {
      MY_DEPT: 'DEPT_CODE',
      SELF: 'OWNER_EMP_NO',
      DEPT: 'DEPT_CODE',
      EMP_NO: 'OWNER_EMP_NO',
      TAG: 'TECH_TAG',
      STAKEHOLDER_SELF: '선택 컬럼',
      STAKEHOLDER_CHANNEL: '선택 컬럼',
      TOKEN_SUBJECT: '선택 컬럼',
      OWN_CONTRACT: '선택 컬럼',
      CHANNEL_CONTRACT: '선택 컬럼',
      OWN_CUSTOMER: '선택 컬럼',
      CHANNEL_CUSTOMER: '선택 컬럼',
      STATIC_SQL: '',
      ALL: ''
    }[type] || '';
    return permissionRuleBusinessLabel(type, displayColumn, value);
  }).filter(Boolean);
}

function collectWizardPredicates(root) {
  return Array.from(root.querySelectorAll('.rule-row')).map((row) => {
    const column = row.querySelector('[name="ruleColumn"]')?.value || '';
    const type = row.querySelector('[name="ruleType"]')?.value || '';
    const value = row.querySelector('[name="ruleValue"]')?.value || '';
    const displayColumn = column || {
      MY_DEPT: 'DEPT_CODE',
      SELF: 'OWNER_EMP_NO',
      DEPT: 'DEPT_CODE',
      EMP_NO: 'OWNER_EMP_NO',
      TAG: 'TECH_TAG',
      STAKEHOLDER_SELF: '선택 컬럼',
      STAKEHOLDER_CHANNEL: '선택 컬럼',
      TOKEN_SUBJECT: '선택 컬럼',
      OWN_CONTRACT: '선택 컬럼',
      CHANNEL_CONTRACT: '선택 컬럼',
      OWN_CUSTOMER: '선택 컬럼',
      CHANNEL_CUSTOMER: '선택 컬럼',
      STATIC_SQL: '',
      ALL: ''
    }[type] || '';
    if (type === 'ALL') {
      return '1 = 1';
    }
    if (type === 'STATIC_SQL') {
      return value;
    }
    if (type === 'MY_DEPT') {
      return `${displayColumn} = SYS_CONTEXT('CB_AGENT_CTX', 'DEPT_CODE')`;
    }
    if (type === 'SELF') {
      return `${displayColumn} = SYS_CONTEXT('CB_AGENT_CTX', 'EMP_NO')`;
    }
    if (type === 'STAKEHOLDER_SELF') {
      return '조건 코드 STAKEHOLDER_SELF: DB 행 접근 함수가 토큰 컨텍스트와 등록된 업무 관계를 기준으로 조건을 생성';
    }
    if (type === 'STAKEHOLDER_CHANNEL') {
      return '조건 코드 STAKEHOLDER_CHANNEL: DB 행 접근 함수가 토큰 채널과 등록된 업무 관계를 기준으로 조건을 생성';
    }
    if (type === 'TOKEN_SUBJECT') {
      return `${displayColumn} = SYS_CONTEXT('CB_AGENT_CTX', 'STAKEHOLDER_USER_ID')`;
    }
    if (type === 'OWN_CONTRACT') {
      return `${displayColumn} = SYS_CONTEXT('CB_AGENT_CTX', 'STAKEHOLDER_USER_ID')`;
    }
    if (type === 'CHANNEL_CONTRACT') {
      return `${displayColumn} = SYS_CONTEXT('CB_AGENT_CTX', 'STAKEHOLDER_CHANNEL')`;
    }
    if (type === 'OWN_CUSTOMER') {
      return '조건 코드 OWN_CUSTOMER: DB 행 접근 함수가 담당 사용자와 게임 데이터 관계를 기준으로 조건을 생성';
    }
    if (type === 'CHANNEL_CUSTOMER') {
      return '조건 코드 CHANNEL_CUSTOMER: DB 행 접근 함수가 토큰 채널과 게임 데이터 관계를 기준으로 조건을 생성';
    }
    if (type === 'DEPT' || type === 'EMP_NO') {
      return `${displayColumn} = ${sqlLiteral(value)}`;
    }
    if (type === 'TAG') {
      return `REGEXP_LIKE(UPPER(${displayColumn}), ${sqlLiteral(`(^|,)${value.toUpperCase()}(,|$)`)})`;
    }
    if (type === '=') {
      return `TO_CHAR(${displayColumn}) = ${sqlLiteral(value)}`;
    }
    if (type === '!=') {
      return `TO_CHAR(${displayColumn}) <> ${sqlLiteral(value)}`;
    }
    return '';
  }).filter(Boolean);
}

function updatePermissionWizardPreview(root = document) {
  const wizard = root.querySelector('[data-permission-wizard]');
  if (!wizard) {
    return;
  }
  const roleSelect = wizard.querySelector('[name="roleId"]');
  const objectSelect = wizard.querySelector('[name="objectRef"]');
  const effectSelect = wizard.querySelector('[name="permissionEffect"]');
  const roleOption = selectedOption(roleSelect);
  const objectOption = selectedOption(objectSelect);
  const effect = effectSelect?.value || 'ALLOW';
  const rules = collectWizardRules(wizard);
  const predicates = collectWizardPredicates(wizard);
  const ruleText = rules.length ? rules.join(', ') : '행 규칙 없음';
  const hasRole = Boolean(roleSelect?.value);
  const hasObject = Boolean(objectSelect?.value);
  const hasAllRule = rules.includes('ALL');
  const hasAllRuleConflict = hasAllRule && rules.length > 1;
  const directUsers = splitList(roleOption?.dataset.directUsers || '');
  const groups = splitList(roleOption?.dataset.groups || '');
  const groupUsers = splitList(roleOption?.dataset.groupUsers || '');
  const objectColumns = splitList(objectOption?.dataset.columns || '', ',');
  const maskableColumns = splitList(objectOption?.dataset.maskableColumns || '', ',');
  const rowPolicy = effect === 'DENY'
      ? `거부 규칙: ${ruleText}`
      : `허용 규칙: ${ruleText}`;
  const predicateText = effect === 'DENY'
      ? (rules.includes('ALL') ? 'DENY ALL: 1 = 0' : `DENY 후보: NOT (${predicates.join(' AND ') || '조건 없음'})`)
      : `ALLOW 후보: ${predicates.join(' AND ') || '조건 없음'}`;
  const columnPolicy = maskableColumns.length
      ? `ASO 마스킹 후보: ${maskableColumns.join(', ')}. 실제 원문/마스킹은 컬럼 마스킹 화면에서 설정합니다.`
      : '이 행 접근 규칙은 행만 제어합니다. 컬럼 원문/마스킹은 컬럼 마스킹에서 관리합니다.';
  const affectedPrincipals = `직접 사용자 ${directUsers.length}명 / 그룹 ${groups.length}개 / 그룹 상속 사용자 ${groupUsers.length}명`;
  const readiness = !hasRole
      ? '역할을 선택하세요'
      : !hasObject
          ? '보호 객체를 선택하세요'
          : hasAllRuleConflict
              ? 'ALL 규칙을 단독으로 정리하세요'
              : '저장 전 검토 가능';
  const saveGuard = hasAllRule
      ? `${effect === 'DENY' ? '전체 행 거부' : '전체 행 허용'}입니다. ${affectedPrincipals}에게 영향을 줄 수 있습니다.`
      : `${effect === 'DENY' ? '선택 조건의 행을 거부' : '선택 조건의 행만 허용'}합니다. 저장 후 결과 확인에서 실제 VPD predicate를 검증하세요.`;

  wizard.querySelector('[data-wizard-summary="role"]').textContent = selectedText(roleSelect);
  wizard.querySelector('[data-wizard-summary="object"]').textContent = selectedText(objectSelect);
  wizard.querySelector('[data-wizard-summary="effect"]').textContent = effect;
  wizard.querySelector('[data-wizard-summary="rules"]').textContent = ruleText;
  wizard.querySelector('[data-wizard-summary="affected"]').textContent = hasRole ? affectedPrincipals : '역할 선택 후 확인';
  wizard.querySelector('[data-wizard-summary="readiness"]').textContent = readiness;

  setWizardPreview(wizard, 'role', selectedText(roleSelect));
  setWizardPreview(wizard, 'sensitivity', roleOption?.dataset.maxSensitivity || 'PUBLIC');
  setWizardPreview(wizard, 'object', objectOption?.dataset.objectDisplay || selectedText(objectSelect));
  setWizardPreview(wizard, 'directUsers', formatList(directUsers, '직접 부여 사용자 없음'));
  setWizardPreview(wizard, 'roleGroups', formatList(groups, '역할이 부여된 그룹 없음'));
  setWizardPreview(wizard, 'groupUsers', formatList(groupUsers, '그룹 상속 사용자 없음'));
  setWizardPreview(wizard, 'affectedPrincipals', affectedPrincipals);
  setWizardPreview(wizard, 'objectColumns', formatList(objectColumns, '컬럼 조회 전'));
  setWizardPreview(wizard, 'objectColumnsFinal', formatList(objectColumns, '컬럼 조회 전'));
  setWizardPreview(wizard, 'maskableColumns', formatList(maskableColumns, '마스킹 대상 컬럼 없음'));
  setWizardPreview(wizard, 'rowPolicy', rowPolicy);
  setWizardPreview(wizard, 'predicatePreview', predicateText);
  setWizardPreview(wizard, 'columnPolicy', columnPolicy);
  setWizardPreview(wizard, 'saveGuard', hasRole && hasObject ? saveGuard : '역할과 보호 객체를 선택하면 저장 영향을 계산합니다.');
}

function permissionWizardIndicators(wizard) {
  return wizard.closest('.content-band')?.querySelectorAll('[data-wizard-target]') || [];
}

function showPermissionWizardValidation(wizard, message) {
  const validation = wizard.querySelector('[data-wizard-validation]');
  if (!validation) {
    return;
  }
  validation.textContent = message;
  validation.hidden = false;
}

function clearPermissionWizardValidation(wizard) {
  const validation = wizard.querySelector('[data-wizard-validation]');
  if (validation) {
    validation.hidden = true;
    validation.textContent = '';
  }
}

function permissionWizardRuleValidationMessage(wizard) {
  const rows = Array.from(wizard.querySelectorAll('.rule-row'));
  if (!rows.length) {
    return '행 규칙을 하나 이상 추가하세요.';
  }
  const values = rows.map((row) => ({
    column: row.querySelector('[name="ruleColumn"]')?.value || '',
    type: row.querySelector('[name="ruleType"]')?.value || '',
    value: row.querySelector('[name="ruleValue"]')?.value.trim() || ''
  }));
  if (values.some((rule) => rule.type === 'ALL') && values.length > 1) {
    return 'ALL 규칙은 다른 조건 규칙과 함께 저장할 수 없습니다. ALL만 남기거나 ALL을 삭제하세요.';
  }
  const valueRequired = ['=', '!=', 'DEPT', 'EMP_NO', 'TAG', 'STAKEHOLDER_SELF', 'STAKEHOLDER_CHANNEL', 'STATIC_SQL'];
  const seen = new Set();
  for (const [index, rule] of values.entries()) {
    const position = index + 1;
    if (!rule.type) {
      return `${position}번째 행 규칙 유형을 선택하세요.`;
    }
    if ([
      '=', '!=', 'STAKEHOLDER_SELF', 'STAKEHOLDER_CHANNEL', 'TOKEN_SUBJECT',
      'OWN_CONTRACT', 'CHANNEL_CONTRACT', 'OWN_CUSTOMER', 'CHANNEL_CUSTOMER'
    ].includes(rule.type) && !rule.column) {
      return `${position}번째 ${rule.type} 규칙에는 비교할 컬럼이 필요합니다.`;
    }
    if (valueRequired.includes(rule.type) && !rule.value) {
      return `${position}번째 ${rule.type} 규칙의 값을 입력하세요.`;
    }
    if (rule.type === 'STATIC_SQL' && rule.column) {
      return `${position}번째 정적 SQL 조건은 컬럼을 따로 선택하지 마세요.`;
    }
    if (rule.type === 'TAG' && rule.value && !/^[A-Za-z0-9_-]+$/.test(rule.value)) {
      return `${position}번째 TAG 값은 영문·숫자, '_' 또는 '-'만 사용할 수 있습니다.`;
    }
    const signature = `${rule.column}:${rule.type}:${rule.value.toUpperCase()}`;
    if (seen.has(signature)) {
      return `${position}번째 행 규칙이 앞의 규칙과 중복됩니다.`;
    }
    seen.add(signature);
  }
  return '';
}

function validatePermissionWizardStep(wizard, step) {
  if (step === 1 && !wizard.querySelector('[name="roleId"]')?.value) {
    return '권한을 적용할 역할을 선택하세요.';
  }
  if (step === 2 && !wizard.querySelector('[name="objectRef"]')?.value) {
    return '권한을 적용할 보호 객체를 선택하세요.';
  }
  if (step === 3) {
    return permissionWizardRuleValidationMessage(wizard);
  }
  return '';
}

function focusPermissionWizardStep(wizard, step) {
  const panel = wizard.querySelector(`[data-wizard-step="${step}"]`);
  panel?.querySelector('select, input, button')?.focus();
}

function activatePermissionWizardStep(wizard, step) {
  const panels = Array.from(wizard.querySelectorAll('[data-wizard-step]'));
  const maxStep = panels.length;
  const nextStep = Math.max(1, Math.min(step, maxStep));
  panels.forEach((panel) => {
    panel.classList.toggle('active', Number(panel.dataset.wizardStep) === nextStep);
  });
  permissionWizardIndicators(wizard).forEach((button) => {
    const active = Number(button.dataset.wizardTarget) === nextStep;
    button.classList.toggle('active', active);
    button.setAttribute('aria-current', active ? 'step' : 'false');
  });
  wizard.dataset.currentStep = String(nextStep);
  const prev = wizard.querySelector('[data-wizard-prev]');
  const next = wizard.querySelector('[data-wizard-next]');
  const submit = wizard.querySelector('[data-wizard-submit]');
  if (prev) {
    prev.disabled = nextStep === 1;
  }
  if (next) {
    next.hidden = nextStep === maxStep;
  }
  if (submit) {
    submit.hidden = nextStep !== maxStep;
  }
  updatePermissionWizardPreview(document);
}

function movePermissionWizard(wizard, targetStep) {
  const currentStep = Number(wizard.dataset.currentStep || '1');
  if (targetStep <= currentStep) {
    clearPermissionWizardValidation(wizard);
    activatePermissionWizardStep(wizard, targetStep);
    return true;
  }
  for (let step = 1; step < targetStep; step += 1) {
    const message = validatePermissionWizardStep(wizard, step);
    if (message) {
      activatePermissionWizardStep(wizard, step);
      showPermissionWizardValidation(wizard, message);
      focusPermissionWizardStep(wizard, step);
      return false;
    }
  }
  clearPermissionWizardValidation(wizard);
  activatePermissionWizardStep(wizard, targetStep);
  return true;
}

function initPermissionWizard() {
  const wizard = document.querySelector('[data-permission-wizard]');
  if (!wizard) {
    return;
  }
  wizard.dataset.currentStep = wizard.dataset.currentStep || '1';
  wizard.querySelector('[data-wizard-prev]')?.addEventListener('click', () => {
    movePermissionWizard(wizard, Number(wizard.dataset.currentStep || '1') - 1);
  });
  wizard.querySelector('[data-wizard-next]')?.addEventListener('click', () => {
    movePermissionWizard(wizard, Number(wizard.dataset.currentStep || '1') + 1);
  });
  permissionWizardIndicators(wizard).forEach((button) => {
    button.addEventListener('click', () => movePermissionWizard(wizard, Number(button.dataset.wizardTarget)));
  });
  wizard.addEventListener('input', () => {
    clearPermissionWizardValidation(wizard);
    updatePermissionWizardPreview(document);
  });
  wizard.addEventListener('change', () => {
    clearPermissionWizardValidation(wizard);
    updatePermissionWizardPreview(document);
  });
  wizard.addEventListener('submit', (event) => {
    for (let step = 1; step <= 3; step += 1) {
      const message = validatePermissionWizardStep(wizard, step);
      if (message) {
        event.preventDefault();
        activatePermissionWizardStep(wizard, step);
        showPermissionWizardValidation(wizard, message);
        focusPermissionWizardStep(wizard, step);
        return;
      }
    }
  });
  activatePermissionWizardStep(wizard, Number(wizard.dataset.currentStep || '1'));
}

const backofficeSupportObjectPatterns = [
  /^CB_APP_/,
  /^CB_PERMISSION(_|$)/,
  /^CB_PROTECTED_/,
  /^CB_USER_/,
  /^CB_GROUP_/,
  /^CB_ORDS_/,
  /^CB_AGENT_BEARER_/,
  /^CB_BACKOFFICE_/,
  /^APP_(GROUP|ROLE|USER)$/,
  /^DB_SOURCE$/,
  /^PERMISSION$/,
  /^USER_GROUP$/
];

function isBackofficeSupportObject(objectName) {
  const normalized = (objectName || '').trim().toUpperCase();
  return backofficeSupportObjectPatterns.some((pattern) => pattern.test(normalized));
}

function initVpdTargetFilters() {
  const controls = document.querySelector('[data-vpd-target-controls]');
  const body = document.querySelector('[data-vpd-target-body]');
  if (!controls || !body) {
    return;
  }
  const rows = Array.from(body.querySelectorAll('[data-vpd-target-row]')).map((row) => ({
    row,
    detail: row.nextElementSibling?.matches('[data-vpd-target-detail]') ? row.nextElementSibling : null,
    object: (row.dataset.object || '').toUpperCase(),
    objectName: (row.dataset.objectName || '').toUpperCase(),
    objectType: (row.dataset.objectType || '').toUpperCase(),
    vpdApplied: row.dataset.vpdApplied || 'false',
    protectedObject: row.dataset.protectedObject || 'false'
  }));
  const search = controls.querySelector('[data-vpd-target-search]');
  const type = controls.querySelector('[data-vpd-target-type]');
  const vpd = controls.querySelector('[data-vpd-target-vpd]');
  const protectedObject = controls.querySelector('[data-vpd-target-protected]');
  const includeSupport = controls.querySelector('[data-vpd-target-include-support]');
  const pageSize = controls.querySelector('[data-vpd-target-page-size]');
  const visibleCount = controls.querySelector('[data-vpd-target-visible]');
  const matchedCount = controls.querySelector('[data-vpd-target-matched]');
  const totalCount = controls.querySelector('[data-vpd-target-total]');
  const reset = controls.querySelector('[data-vpd-target-reset]');
  const empty = document.createElement('tr');
  empty.className = 'vpd-target-empty-runtime';
  empty.innerHTML = '<td colspan="7" class="text-muted">필터 조건에 맞는 TABLE/VIEW가 없습니다.</td>';
  body.appendChild(empty);

  const matchesFilters = (entry) => {
    const query = (search?.value || '').trim().toUpperCase();
    if (query && !entry.object.includes(query)) {
      return false;
    }
    if (type?.value && entry.objectType !== type.value) {
      return false;
    }
    if (vpd?.value && entry.vpdApplied !== vpd.value) {
      return false;
    }
    if (protectedObject?.value && entry.protectedObject !== protectedObject.value) {
      return false;
    }
    if (!includeSupport?.checked && isBackofficeSupportObject(entry.objectName)) {
      return false;
    }
    return true;
  };

  const applyFilters = () => {
    const maxRows = pageSize?.value === 'ALL' ? Number.POSITIVE_INFINITY : Number(pageSize?.value || 50);
    let matched = 0;
    let visible = 0;
    rows.forEach((entry) => {
      const matchedRow = matchesFilters(entry);
      if (matchedRow) {
        matched += 1;
      }
      const show = matchedRow && visible < maxRows;
      if (show) {
        visible += 1;
      }
      entry.row.hidden = !show;
      if (entry.detail) {
        entry.detail.hidden = !show;
      }
    });
    empty.hidden = matched !== 0;
    if (visibleCount) {
      visibleCount.textContent = String(visible);
    }
    if (matchedCount) {
      matchedCount.textContent = String(matched);
    }
    if (totalCount) {
      totalCount.textContent = String(rows.length);
    }
  };

  [search, type, vpd, protectedObject, includeSupport, pageSize].forEach((control) => {
    control?.addEventListener(control === search ? 'input' : 'change', applyFilters);
  });
  reset?.addEventListener('click', () => {
    if (search) {
      search.value = '';
    }
    if (type) {
      type.value = '';
    }
    if (vpd) {
      vpd.value = '';
    }
    if (protectedObject) {
      protectedObject.value = '';
    }
    if (includeSupport) {
      includeSupport.checked = false;
    }
    if (pageSize) {
      pageSize.value = '50';
    }
    applyFilters();
    search?.focus();
  });
  applyFilters();
}

function initMaskingExceptionPreview() {
  const preview = document.querySelector('[data-masking-exception-preview]');
  const columnSelect = document.querySelector('select[name="columnId"]');
  const userSelect = document.querySelector('select[name="userId"]');
  if (!preview || !columnSelect) {
    return;
  }

  const empty = preview.querySelector('[data-masking-preview-empty]');
  const details = preview.querySelector('[data-masking-preview-details]');
  const target = preview.querySelector('[data-masking-preview-target]');
  const masked = preview.querySelector('[data-masking-preview-masked]');
  const unmasked = preview.querySelector('[data-masking-preview-unmasked]');
  const context = preview.querySelector('[data-masking-preview-context]');

  const update = () => {
    const option = columnSelect.options[columnSelect.selectedIndex];
    if (!option?.value) {
      if (empty) {
        empty.hidden = false;
      }
      if (details) {
        details.hidden = true;
      }
      return;
    }
    const selectedUser = userSelect?.options[userSelect.selectedIndex];
    const userLabel = selectedUser?.dataset.userLabel || '선택한 사용자';
    const columnTarget = option.dataset.target || option.textContent?.trim() || '선택한 컬럼';
    const template = option.dataset.template || '컬럼 마스킹 규칙';
    const result = option.dataset.result || '마스킹된 값';
    const asoFunction = option.dataset.asoFunction || 'DBMS_REDACT';
    const contextName = option.dataset.context || 'MR_<column_id>';

    if (empty) {
      empty.hidden = true;
    }
    if (details) {
      details.hidden = false;
    }
    if (target) {
      target.textContent = `${columnTarget} · ${template} (${asoFunction})`;
    }
    if (masked) {
      masked.textContent = `${columnTarget} 값은 ${result}로 반환됩니다.`;
    }
    if (unmasked) {
      unmasked.textContent = `${userLabel}은(는) 행 접근 정책이 허용한 행에서 원래 ${columnTarget} 값을 봅니다.`;
    }
    if (context) {
      context.textContent = `CB_AGENT_CTX.${contextName} = Y이면 원문, 기본값 또는 N이면 ${asoFunction}으로 마스킹합니다.`;
    }
  };

  columnSelect.addEventListener('change', update);
  userSelect?.addEventListener('change', update);
  update();
}

document.addEventListener('DOMContentLoaded', () => {
  initPersistentMenus();
  initQuestionPresets();
  initCopyButtons();
  renderMarkdownViews();
  initVpdTargetFilters();
  initMaskingExceptionPreview();
  const master = document.getElementById('userRoleMaster');
  if (master) {
    master.addEventListener('change', filterUserRoleDetail);
    filterUserRoleDetail();
  }
  document.querySelectorAll('.group-master-select').forEach((select) => {
    select.addEventListener('change', () => filterGroupDetail(select.id));
    filterGroupDetail(select.id);
  });
  initTokenContextPreviews();
  initEffectiveMatrixFilters();
  initEffectiveMatrixTabs();
  const objectSelect = document.querySelector('select[name="objectRef"]');
  if (objectSelect) {
    objectSelect.addEventListener('change', () => {
      syncRuleColumnOptions();
      updatePermissionWizardPreview(document);
    });
    syncRuleColumnOptions();
  }
  initPermissionWizard();
  document.querySelectorAll('.rule-type-select').forEach((select) => {
    select.addEventListener('change', () => {
      syncRuleTypeHints();
      updatePermissionWizardPreview(document);
    });
  });
  syncRuleTypeHints();
  const catalog = document.getElementById('objectCatalogSelect');
  if (catalog) {
    catalog.addEventListener('change', syncObjectCatalogSelection);
    syncObjectCatalogSelection();
  }
  initOrdsPathEditToggle();
  initProbeObjectDescription();
  initProbeVectorInput();
  document.querySelectorAll('[data-policy-template-select]').forEach((select) => {
    select.addEventListener('change', () => syncPolicyTemplate(select));
    syncPolicyTemplate(select);
  });
  document.querySelectorAll('[data-rule-add]').forEach((button) => {
    button.addEventListener('click', () => {
      const row = button.closest('.rule-row');
      const list = document.getElementById('rowRuleList');
      if (!row || !list) {
        return;
      }
      const clone = row.cloneNode(true);
      clone.querySelectorAll('input').forEach((input) => input.value = '');
      const cloneButton = clone.querySelector('[data-rule-add]');
      cloneButton.textContent = '삭제';
      cloneButton.addEventListener('click', () => {
        clone.remove();
        updatePermissionWizardPreview(document);
      });
      clone.querySelectorAll('.rule-type-select').forEach((select) => {
        select.addEventListener('change', () => {
          syncRuleTypeHints();
          updatePermissionWizardPreview(document);
        });
      });
      list.appendChild(clone);
      syncRuleColumnOptions();
      syncRuleTypeHints(clone);
      updatePermissionWizardPreview(document);
    });
  });
  updatePermissionWizardPreview(document);
  disableReadOnlyMutationForms();
});

document.body.addEventListener('htmx:beforeRequest', (event) => {
  const button = event.detail.elt;
  if (!button?.matches?.('[data-filter-toggle]')) {
    return;
  }
  const target = findHtmxTarget(button);
  if (button.getAttribute('aria-expanded') === 'true') {
    event.preventDefault();
    resetFilterToggle(button, target);
    return;
  }
  setFilterToggleLoading(button, target);
});

document.body.addEventListener('htmx:afterSwap', (event) => {
  const button = event.detail.elt;
  if (button?.matches?.('[data-filter-toggle]')) {
    button.setAttribute('aria-expanded', 'true');
    button.classList.add('active');
  }
  renderMarkdownViews(event.detail.target || document);
  disableReadOnlyMutationForms();
});
