/**
 * Security settings page — toggles the auth-mode sections and runs the
 * BC connection test.
 */
import { resolveHost } from '/js/core/app-dom.js';
import { getJson } from '/js/core/app-http.js';

const SELECTOR = '[data-app-component="security-settings"]';
const EMPTY_API = Object.freeze({ destroy: () => {} });

const resolveRoot = (root) => {
  const host = resolveHost(root);
  if (host instanceof HTMLElement && host.matches(SELECTOR)) {
    return host;
  }
  return host.querySelector(SELECTOR);
};

export function initSecuritySettings(root = document) {
  const form = resolveRoot(root);
  if (!form) {
    return EMPTY_API;
  }

  const section = form.closest('section') || document;
  const listenerController = new AbortController();
  const modeSelect = form.querySelector('[data-security-auth-mode]');
  const authSections = Array.from(form.querySelectorAll('[data-security-auth-section]'));

  const applyMode = () => {
    const mode = modeSelect ? modeSelect.value : 'basic';
    authSections.forEach((el) => {
      el.toggleAttribute('hidden', el.dataset.securityAuthSection !== mode);
    });
  };

  if (modeSelect) {
    modeSelect.addEventListener('change', applyMode, { signal: listenerController.signal });
    applyMode();
  }

  const testButton = section.querySelector('[data-security-test-connection]');
  const result = section.querySelector('[data-security-test-result]');
  if (testButton) {
    testButton.addEventListener('click', async () => {
      const url = testButton.dataset.url || '';
      if (url === '') {
        return;
      }
      testButton.setAttribute('aria-busy', 'true');
      testButton.disabled = true;
      if (result) {
        result.textContent = testButton.dataset.textTesting || 'Testing...';
        result.dataset.variant = '';
      }
      try {
        const data = await getJson(url);
        if (result) {
          const ok = data && data.ok === true;
          result.textContent = ok
            ? (testButton.dataset.textOk || 'Connection successful')
            : `${testButton.dataset.textFail || 'Connection failed'}: ${(data && data.error) || ''}`;
          result.dataset.variant = ok ? 'success' : 'error';
        }
      } catch {
        if (result) {
          result.textContent = testButton.dataset.textFail || 'Connection failed';
          result.dataset.variant = 'error';
        }
      } finally {
        testButton.removeAttribute('aria-busy');
        testButton.disabled = false;
      }
    }, { signal: listenerController.signal });
  }

  return {
    destroy: () => listenerController.abort(),
  };
}
