(() => {
  'use strict';

  const allowedPostTargets = new Set(['role_switch.php', 'my_profile.php']);

  const scriptName = (url) => {
    try {
      const parsed = new URL(url || window.location.href, window.location.href);
      const parts = parsed.pathname.split('/').filter(Boolean);
      return parts.length ? parts[parts.length - 1] : '';
    } catch (_) {
      return '';
    }
  };

  const isProtectedPostForm = (form) => {
    const method = String(form.getAttribute('method') || 'get').toLowerCase();
    if (method !== 'post') return false;
    return !allowedPostTargets.has(scriptName(form.getAttribute('action') || window.location.href));
  };

  const lockForm = (form) => {
    if (!isProtectedPostForm(form) || form.dataset.taskPreviewLocked === '1') return;
    form.dataset.taskPreviewLocked = '1';
    form.setAttribute('aria-readonly', 'true');

    form.querySelectorAll('button[type="submit"], input[type="submit"], button:not([type])').forEach((control) => {
      control.hidden = true;
      control.setAttribute('aria-hidden', 'true');
      control.tabIndex = -1;
    });

    form.querySelectorAll('input:not([type="hidden"]), select, textarea').forEach((control) => {
      control.disabled = true;
      control.setAttribute('aria-disabled', 'true');
    });

    form.addEventListener('submit', (event) => {
      event.preventDefault();
      event.stopImmediatePropagation();
    }, true);
  };

  const lockPreviewActions = (root = document) => {
    root.querySelectorAll('form').forEach(lockForm);
  };

  const style = document.createElement('style');
  style.textContent = `
    body.task-preview-mode form[data-task-preview-locked="1"] {
      opacity: .78;
    }
    body.task-preview-mode form[data-task-preview-locked="1"] input:disabled,
    body.task-preview-mode form[data-task-preview-locked="1"] select:disabled,
    body.task-preview-mode form[data-task-preview-locked="1"] textarea:disabled {
      cursor: not-allowed;
    }
  `;
  document.head.appendChild(style);

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => lockPreviewActions(), { once: true });
  } else {
    lockPreviewActions();
  }

  document.addEventListener('submit', (event) => {
    const form = event.target instanceof HTMLFormElement ? event.target : null;
    if (!form || !isProtectedPostForm(form)) return;
    event.preventDefault();
    event.stopImmediatePropagation();
  }, true);

  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      for (const node of mutation.addedNodes) {
        if (!(node instanceof Element)) continue;
        if (node.matches('form')) lockForm(node);
        lockPreviewActions(node);
      }
    }
  });
  observer.observe(document.documentElement, { childList: true, subtree: true });
})();
