/* DIAR-6B.3-R3: passive browser contract with no DOM observer and no geometry-changing classes. */
(function () {
  'use strict';
  const root = document.documentElement;
  const body = document.body;
  if (!body || !String(body.dataset.nativeSidebarPage || '').startsWith('diar-')) return;

  function audit() {
    const sidebar = document.querySelector('[data-native-sidebar]');
    const main = document.querySelector('[data-native-main]');
    if (!sidebar || !main || window.innerWidth <= 760) {
      root.dataset.diarRtlStructural = 'MOBILE';
      return;
    }
    const rtl = root.dir === 'rtl';
    const s = sidebar.getBoundingClientRect();
    const m = main.getBoundingClientRect();
    const sideOk = rtl ? Math.abs(s.right - window.innerWidth) <= 2 : Math.abs(s.left) <= 2;
    const overlap = Math.max(0, Math.min(s.right, m.right) - Math.max(s.left, m.left));
    root.dataset.diarRtlStructural = sideOk && overlap <= 1 ? 'PASS' : 'FAIL';
  }

  function activateEvidenceHash() {
    const buttons = Array.from(document.querySelectorAll('[data-evidence-tab]'));
    if (!buttons.length) return;
    const requested = String(location.hash || '').replace(/^#/, '');
    if (!requested) return;
    const target = buttons.find((button) => button.dataset.evidenceTab === requested);
    if (target) target.click();
  }

  document.addEventListener('DOMContentLoaded', function () {
    audit();
    activateEvidenceHash();
    document.querySelectorAll('[data-evidence-tab]').forEach(function (button) {
      button.addEventListener('click', function () {
        const key = button.dataset.evidenceTab || '';
        if (key && history.replaceState) history.replaceState(null, '', '#' + key);
      });
    });
  }, { once: true });
  window.addEventListener('resize', audit, { passive: true });
})();
