(() => {
  const form = document.querySelector('[data-dental-finding-form]');
  let refreshSurfaceOptions = () => {};
  let suppressInitialToothScroll = false;
  const noticeStorageKey = 'dentalChartPendingNotice';
  const toothClickTimes = new WeakMap();
  let findingFormDirty = false;
  let findingFormSubmitting = false;

  const toothAnchorId = (tooth) => tooth ? `tooth-${String(tooth).replace(/[^a-zA-Z0-9_-]/g, '')}` : '';
  const elementMostlyVisible = (element) => {
    if (!element) return false;
    const rect = element.getBoundingClientRect();
    const topGuard = 72;
    const bottomGuard = Math.max(topGuard + 80, window.innerHeight - 48);
    return rect.top >= topGuard && rect.bottom <= bottomGuard && rect.left >= 0 && rect.right <= window.innerWidth;
  };
  const preserveWindowScroll = (x, y) => {
    try { window.scrollTo({ left: x, top: y, behavior: 'auto' }); }
    catch (_) { window.scrollTo(x, y); }
  };

  const toothUrl = (href, tooth, openFinding = false, includeHash = true) => {
    try {
      const url = new URL(href || window.location.href, window.location.href);
      if (openFinding) url.searchParams.set('open_finding', '1');
      else url.searchParams.delete('open_finding');
      if (tooth) url.searchParams.set('tooth', tooth);
      const anchor = toothAnchorId(tooth);
      if (includeHash && anchor) url.hash = anchor;
      else url.hash = '';
      return url.toString();
    } catch (_) {
      return href || window.location.href;
    }
  };

  const rememberToothScroll = (tooth) => {
    try {
      sessionStorage.setItem('dentalChartSelectedTooth', tooth || '');
      sessionStorage.setItem('dentalChartScrollY', String(window.scrollY || window.pageYOffset || 0));
    } catch (_) {
      // Browser storage can be disabled; charting still works without it.
    }
  };

  const rememberChartNotice = (message) => {
    try { sessionStorage.setItem(noticeStorageKey, message || ''); } catch (_) {}
  };

  const consumeChartNotice = () => {
    try {
      const message = sessionStorage.getItem(noticeStorageKey) || '';
      sessionStorage.removeItem(noticeStorageKey);
      return message;
    } catch (_) { return ''; }
  };

  const selectedToothTrigger = (tooth) => {
    if (!tooth) return null;
    const safe = String(tooth).replace(/\"/g, '\\"');
    return document.querySelector(`[data-chart-tooth="${safe}"]`);
  };

  const scrollToTooth = (tooth, behavior = 'auto') => {
    const trigger = selectedToothTrigger(tooth);
    if (!trigger) return;
    window.setTimeout(() => {
      if (!elementMostlyVisible(trigger)) {
        trigger.scrollIntoView({ behavior, block: 'center', inline: 'center' });
      }
    }, 35);
  };

  const toothLabel = (tooth) => {
    const source = [...document.querySelectorAll('[data-chart-tooth]')]
      .find((item) => item.dataset.chartTooth === tooth && item.dataset.toothLabel);
    return source?.dataset.toothLabel || `FDI ${tooth}`;
  };

  const setSelectedTooth = (tooth) => {
    if (!tooth) return;
    const input = form?.querySelector('[data-tooth-input]');
    if (input) input.value = tooth;
    document.querySelectorAll('[data-xray-tooth-input]').forEach((input) => {
      input.value = tooth;
    });
    document.querySelectorAll('[data-chart-tooth][data-tooth-editable]').forEach((item) => {
      item.classList.toggle('selected', item.dataset.chartTooth === tooth);
    });
    document.querySelectorAll('[data-tooth-label], [data-chart-selected-label]').forEach((label) => {
      if (label.hasAttribute('data-chart-tooth')) return;
      label.textContent = toothLabel(tooth);
    });
    refreshSurfaceOptions();
  };

  const showChartNotice = (message) => {
    const existing = document.querySelector('[data-chart-access-notice]');
    if (existing) {
      existing.hidden = false;
      existing.textContent = message;
      return;
    }
    const notice = document.createElement('div');
    notice.className = 'flash warning chart-access-notice';
    notice.dataset.chartAccessNotice = '1';
    notice.setAttribute('role', 'alert');
    notice.textContent = message;
    const host = document.querySelector('.dental-chart-card') || document.querySelector('main.main') || document.querySelector('main') || document.body;
    host.prepend(notice);
  };

  const openFindingDialog = (trigger, tooth) => {
    const dialogId = trigger.dataset.findingDialog || 'finding-form';
    const dialog = document.getElementById(dialogId);
    if (!form || !dialog || typeof dialog.showModal !== 'function') return false;
    const keepX = window.scrollX || window.pageXOffset || 0;
    const keepY = window.scrollY || window.pageYOffset || 0;
    setSelectedTooth(tooth);
    dialog.showModal();
    document.body.classList.add('dialog-open');
    window.setTimeout(() => {
      preserveWindowScroll(keepX, keepY);
      try { form.querySelector('[data-condition-select]')?.focus({ preventScroll: true }); }
      catch (_) { form.querySelector('[data-condition-select]')?.focus(); }
    }, 50);
    return true;
  };

  const findingUrl = (href, tooth = '') => toothUrl(href, tooth, true, true);


  document.querySelectorAll('[data-chart-dentition-link]').forEach((link) => {
    link.addEventListener('click', () => {
      try { window.dentalStoreScrollForNextLoad?.('odontogram-dentition-switch', '#dental-chart-workspace'); } catch (_) {}
    }, { capture: true });
  });

  const toothTriggers = [...document.querySelectorAll('[data-chart-tooth]')];
  toothTriggers.forEach((trigger) => {
    trigger.addEventListener('click', (event) => {
      const now = Date.now();
      const previousClick = Number(toothClickTimes.get(trigger) || 0);
      if (now - previousClick < 250) {
        event.preventDefault();
        return;
      }
      toothClickTimes.set(trigger, now);
      const tooth = trigger.dataset.chartTooth || '';
      const isChartAnchor = trigger.hasAttribute('data-tooth-editable');
      if (isChartAnchor) event.preventDefault();
      const keepX = window.scrollX || window.pageXOffset || 0;
      const keepY = window.scrollY || window.pageYOffset || 0;
      setSelectedTooth(tooth);
      rememberToothScroll(tooth);

      // Existing Add Finding/X-ray buttons only need to synchronize the tooth field.
      if (!isChartAnchor) return;

      const href = trigger.getAttribute('href') || trigger.href || window.location.href;
      const editable = trigger.dataset.toothEditable === '1';
      if (!editable) {
        showChartNotice(trigger.dataset.readOnlyMessage || 'This tooth chart is read-only. You may inspect the selected tooth, but recording a finding requires the assigned dentist and an open treatment encounter.');
        try {
          const url = new URL(toothUrl(href, tooth, false, false), window.location.href);
          window.history.replaceState({}, '', url.pathname + url.search);
        } catch (_) {
          // Read-only selection still works even if the URL cannot be synchronized.
        }
        window.setTimeout(() => preserveWindowScroll(keepX, keepY), 0);
        return;
      }

      if (openFindingDialog(trigger, tooth)) {
        try {
          const url = new URL(toothUrl(href, tooth, true, false), window.location.href);
          window.history.replaceState({}, '', url.pathname + url.search);
        } catch (_) {
          // The dialog is already open; URL synchronization is non-critical.
        }
        window.setTimeout(() => preserveWindowScroll(keepX, keepY), 0);
        return;
      }

      // Embedded treatment charts do not duplicate the full finding form.
      // Continue to the full odontogram and request that it open the form.
      if (href) window.location.assign(findingUrl(href, tooth));
    });
  });

  const focusTooth = (trigger) => {
    if (!trigger) return;
    try { trigger.focus({ preventScroll: true }); }
    catch (_) { trigger.focus(); }
    const tooth = trigger.dataset.chartTooth || '';
    setSelectedTooth(tooth);
    rememberToothScroll(tooth);
    if (!elementMostlyVisible(trigger)) {
      trigger.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    }
  };

  toothTriggers.forEach((trigger) => {
    trigger.addEventListener('keydown', (event) => {
      const row = trigger.closest('.tooth-model-row');
      const rows = [...document.querySelectorAll('.tooth-model-row')];
      const rowItems = row ? [...row.querySelectorAll('[data-chart-tooth]')] : toothTriggers;
      const index = rowItems.indexOf(trigger);
      let next = null;
      if (event.key === 'ArrowRight') next = rowItems[Math.min(rowItems.length - 1, index + 1)];
      else if (event.key === 'ArrowLeft') next = rowItems[Math.max(0, index - 1)];
      else if (event.key === 'Home') next = rowItems[0];
      else if (event.key === 'End') next = rowItems[rowItems.length - 1];
      else if ((event.key === 'ArrowUp' || event.key === 'ArrowDown') && row) {
        const rowIndex = rows.indexOf(row);
        const targetRow = rows[rowIndex + (event.key === 'ArrowUp' ? -1 : 1)];
        const targetItems = targetRow ? [...targetRow.querySelectorAll('[data-chart-tooth]')] : [];
        if (targetItems.length) {
          const ratio = rowItems.length > 1 ? index / (rowItems.length - 1) : 0;
          next = targetItems[Math.round(ratio * (targetItems.length - 1))];
        }
      } else if (event.key === ' ' || event.key === 'Enter') {
        event.preventDefault();
        trigger.click();
        return;
      } else if (event.key.toLowerCase() === 'x') {
        event.preventDefault();
        const tooth = trigger.dataset.chartTooth || '';
        setSelectedTooth(tooth);
        const dialog = document.getElementById('xray-form') || document.getElementById('chairside-xray-form');
        if (dialog && typeof dialog.showModal === 'function') {
          dialog.showModal();
          window.setTimeout(() => {
            const first = dialog.querySelector('select, input, textarea, button');
            try { first?.focus({ preventScroll: true }); }
            catch (_) { first?.focus(); }
          }, 40);
        } else {
          showChartNotice('Open the full treatment encounter to attach an X-ray to this tooth.');
        }
        return;
      }
      if (next) {
        event.preventDefault();
        focusTooth(next);
      }
    });
  });

  document.querySelectorAll('[data-xray-tooth], [data-xray-for-selected]').forEach((trigger) => {
    trigger.addEventListener('click', () => {
      const tooth = trigger.dataset.xrayTooth || form?.querySelector('[data-tooth-input]')?.value || new URLSearchParams(window.location.search).get('tooth') || '';
      if (tooth) setSelectedTooth(tooth);
    });
  });

  if (form) {
    form.addEventListener('input', () => { findingFormDirty = true; });
    form.addEventListener('change', () => { findingFormDirty = true; });
    form.addEventListener('submit', () => { findingFormSubmitting = true; findingFormDirty = false; });
    form.closest('dialog')?.addEventListener('close', () => { findingFormDirty = false; });
    window.addEventListener('beforeunload', (event) => {
      if (!findingFormDirty || findingFormSubmitting) return;
      event.preventDefault();
      event.returnValue = '';
    });
    const condition = form.querySelector('[data-condition-select]');
    const severity = form.querySelector('[data-severity-select]');
    const help = form.querySelector('[data-condition-help]');
    const diagnosisToggle = form.querySelector('[data-diagnosis-toggle]');
    const diagnosisFields = form.querySelector('[data-diagnosis-fields]');
    const toothInput = form.querySelector('[data-tooth-input]');
    const surfacePicker = form.querySelector('[data-surface-picker]');
    const surfaceTitle = form.querySelector('[data-surface-title]');
    const surfaceHelp = form.querySelector('[data-surface-help]');
    const surfaceError = form.querySelector('[data-surface-error]');
    const surfaceCheckboxes = [...form.querySelectorAll('input[name="surfaces[]"]')];

    const isAnteriorTooth = (tooth) => /^[1-8][1-8]$/.test(tooth || '') && Number(String(tooth).slice(-1)) <= 3;
    const selectedConditionCategory = () => (condition?.selectedOptions?.[0]?.dataset.category || '').toLowerCase();
    const isCariesFinding = () => selectedConditionCategory() === 'caries';
    const visibleSurfaceCheckboxes = () => surfaceCheckboxes.filter((item) => !item.disabled && !item.closest('[data-surface-option]')?.hidden);

    refreshSurfaceOptions = () => {
      if (!surfacePicker) return;
      const tooth = toothInput?.value || '';
      const toothKnown = /^[1-8][1-8]$/.test(tooth || '');
      const anterior = isAnteriorTooth(tooth);
      const caries = isCariesFinding();
      const allowedCaries = !toothKnown ? [] : (anterior ? ['M', 'D', 'F', 'L'] : ['M', 'D', 'L', 'B']);
      surfacePicker.classList.toggle('caries-surface-picker', caries);
      surfacePicker.dataset.toothClass = anterior ? 'anterior' : 'posterior';

      surfaceCheckboxes.forEach((checkbox) => {
        const option = checkbox.closest('[data-surface-option]');
        const scope = option?.dataset.surfaceScope || 'all';
        let visible = true;
        if (caries) visible = allowedCaries.includes(checkbox.value);
        else if (scope === 'anterior') visible = !toothKnown || anterior;
        else if (scope === 'posterior') visible = !toothKnown || !anterior;

        if (option) option.hidden = !visible;
        checkbox.disabled = !visible;
        if (!visible) checkbox.checked = false;
      });

      if (caries) {
        if (!toothKnown) {
          if (surfaceTitle) surfaceTitle.textContent = 'Caries surfaces';
          if (surfaceHelp) surfaceHelp.textContent = 'Choose an FDI tooth first. The valid anterior or posterior surfaces will then appear.';
        } else {
          if (surfaceTitle) surfaceTitle.textContent = `Caries surfaces — ${anterior ? 'Anterior' : 'Posterior'} tooth`;
          if (surfaceHelp) {
            surfaceHelp.textContent = anterior
              ? 'Choose one or more: Mesial, Distal, Facial, or Lingual.'
              : 'Choose one or more: Mesial, Distal, Lingual, or Buccal.';
          }
        }
      } else {
        if (surfaceTitle) surfaceTitle.textContent = 'Tooth surface(s)';
        if (surfaceHelp) surfaceHelp.textContent = 'Choose the affected surface. Facial is used for anterior teeth; Buccal is used for posterior teeth.';
        const visible = visibleSurfaceCheckboxes();
        if (!visible.some((item) => item.checked)) {
          const whole = visible.find((item) => item.value === 'Whole');
          if (whole) whole.checked = true;
        }
      }
      if (surfaceError) surfaceError.hidden = true;
    };

    const updateCondition = () => {
      const option = condition?.selectedOptions?.[0];
      if (option?.value && severity && option.dataset.severity) severity.value = option.dataset.severity;
      if (help) {
        const pieces = option?.value
          ? [option.dataset.description, option.dataset.procedure ? `Common next step: ${option.dataset.procedure}.` : ''].filter(Boolean)
          : ['Select a standardized condition to show its clinical description.'];
        help.textContent = pieces.join(' ');
      }
      refreshSurfaceOptions();
    };

    condition?.addEventListener('change', updateCondition);
    toothInput?.addEventListener('change', refreshSurfaceOptions);
    diagnosisToggle?.addEventListener('change', () => {
      if (diagnosisFields) diagnosisFields.hidden = !diagnosisToggle.checked;
    });

    surfaceCheckboxes.forEach((checkbox) => {
      checkbox.addEventListener('change', () => {
        const visible = visibleSurfaceCheckboxes();
        const whole = visible.find((item) => item.value === 'Whole');
        if (checkbox.value === 'Whole' && checkbox.checked) visible.filter((item) => item !== checkbox).forEach((item) => { item.checked = false; });
        if (checkbox.value !== 'Whole' && checkbox.checked && whole) whole.checked = false;
        if (!isCariesFinding() && !visible.some((item) => item.checked) && whole) whole.checked = true;
        if (surfaceError) surfaceError.hidden = true;
      });
    });

    form.addEventListener('submit', (event) => {
      if (!isCariesFinding()) return;
      const selected = visibleSurfaceCheckboxes().filter((item) => item.checked);
      if (selected.length) return;
      event.preventDefault();
      if (surfaceError) surfaceError.hidden = false;
      surfacePicker?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      visibleSurfaceCheckboxes()[0]?.focus();
    });

    const surfaceShortcuts = {m:'M',d:'D',f:'F',b:'B',l:'L',p:'P',o:'O',i:'I',c:'Cervical',r:'Root',w:'Whole'};
    form.addEventListener('keydown', (event) => {
      if (!event.altKey || event.ctrlKey || event.metaKey) return;
      const surface = surfaceShortcuts[event.key.toLowerCase()];
      if (!surface) return;
      const checkbox = form.querySelector(`input[name="surfaces[]"][value="${surface}"]`);
      if (!checkbox || checkbox.disabled || checkbox.closest('[data-surface-option]')?.hidden) return;
      event.preventDefault();
      checkbox.click();
      checkbox.focus();
    });

    updateCondition();
    const params = new URLSearchParams(window.location.search);
    const requestedTooth = params.get('tooth') || '';
    if (requestedTooth) setSelectedTooth(requestedTooth);
    else refreshSurfaceOptions();
    if (params.get('open_finding') === '1' && requestedTooth) {
      const trigger = [...document.querySelectorAll('[data-chart-tooth][data-tooth-editable="1"]')]
        .find((item) => item.dataset.chartTooth === requestedTooth);
      if (trigger) {
        suppressInitialToothScroll = true;
        openFindingDialog(trigger, requestedTooth);
      }
    }
  }

  const params = new URLSearchParams(window.location.search);
  const selectedFromQuery = params.get('tooth') || '';
  const selectedFromHash = (window.location.hash || '').replace(/^#tooth-/, '');
  let selectedFromMemory = '';
  try { selectedFromMemory = sessionStorage.getItem('dentalChartSelectedTooth') || ''; } catch (_) {}
  const initialTooth = selectedFromQuery || selectedFromHash || selectedFromMemory;
  const pendingNotice = consumeChartNotice();
  if (pendingNotice) showChartNotice(pendingNotice);
  if (initialTooth) {
    setSelectedTooth(initialTooth);
    if (!suppressInitialToothScroll && (selectedFromQuery || selectedFromHash)) {
      scrollToTooth(initialTooth, 'auto');
    }
  }
})();
