(() => {
  const html = document.documentElement;
  const AR_LABEL = '\u0627\u0644\u0639\u0631\u0628\u064a\u0629';
  const DARK_AR = '\u0627\u0644\u0648\u0636\u0639 \u0627\u0644\u062f\u0627\u0643\u0646';
  const LIGHT_AR = '\u0627\u0644\u0648\u0636\u0639 \u0627\u0644\u0641\u0627\u062a\u062d';
  const SEARCH_AR = '\u0627\u0643\u062a\u0628 \u0644\u0644\u0628\u062d\u062b...';

  const getCookie = (name) => {
    const match = document.cookie.match(new RegExp('(?:^|; )' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^;]*)'));
    return match ? decodeURIComponent(match[1]) : '';
  };

  const setCookie = (name, value) => {
    document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=31536000; SameSite=Lax`;
  };

  const currentLang = () => (html.lang === 'ar' ? 'ar' : 'en');
  const currentTheme = () => (html.dataset.theme === 'dark' ? 'dark' : 'light');

  const applyTheme = (theme) => {
    const next = theme === 'dark' ? 'dark' : 'light';
    html.dataset.theme = next;
    html.setAttribute('data-theme', next);
    setCookie('orion_theme', next);
    try { localStorage.setItem('orion_theme', next); } catch (error) {}
    updateUiButtons();
  };

  const updateUiButtons = () => {
    const isDark = currentTheme() === 'dark';
    const isArabic = currentLang() === 'ar';

    document.querySelectorAll('[data-ui-theme-toggle]').forEach((button) => {
      button.classList.toggle('is-active', isDark);
      const text = button.querySelector('.ui-toggle__text');
      if (text) {
        text.textContent = isArabic ? (isDark ? LIGHT_AR : DARK_AR) : (isDark ? 'Light mode' : 'Dark mode');
      }
    });

    document.querySelectorAll('[data-ui-lang-toggle]').forEach((button) => {
      const text = button.querySelector('.ui-toggle__text');
      if (text) text.textContent = isArabic ? 'English' : AR_LABEL;
    });
  };

  const switchLanguage = () => {
    const nextLang = currentLang() === 'ar' ? 'en' : 'ar';
    setCookie('orion_lang', nextLang);
    const url = new URL(window.location.href);
    url.searchParams.set('lang', nextLang);
    window.location.href = url.toString();
  };

  const clearPrintClone = () => {
    document.body.classList.remove('is-printing-selection');
    document.querySelectorAll('.print-clone-root').forEach((node) => node.remove());
  };

  const resolvePrintTarget = (selectorOrElement) => {
    if (!selectorOrElement) return null;
    if (selectorOrElement instanceof Element) return selectorOrElement;
    try {
      return document.querySelector(String(selectorOrElement));
    } catch (error) {
      return null;
    }
  };

  const textFrom = (node) => (node?.textContent || '').replace(/\s+/g, ' ').trim();

  const findPrintTitle = (target) => {
    const explicit = String(target?.dataset?.printTitle || '').trim();
    if (explicit) return explicit;
    const heading = target?.querySelector('h1, h2, h3, .table-header h3, .invoice-title-row span');
    const headingText = textFrom(heading);
    if (headingText) return headingText;
    return document.title.replace(/\s*[-|]\s*/g, ' - ').trim() || 'Report';
  };

  const findPrintLogo = (target) => {
    const explicit = String(target?.dataset?.printLogo || '').trim();
    if (explicit) return explicit;
    const image = target?.querySelector('[data-print-logo-source], .invoice-brand img, img[alt*="Logo"], img[alt*="logo"]')
      || document.querySelector('.workspace-hero img, .portal-orbit-logo img, img[alt*="Logo"], img[alt*="logo"]');
    return image?.getAttribute('src') || '';
  };

  const buildPrintHeader = (target) => {
    const header = document.createElement('header');
    header.className = 'print-report-header';

    const logoSrc = findPrintLogo(target);
    if (logoSrc) {
      const logo = document.createElement('img');
      logo.src = logoSrc;
      logo.alt = '';
      logo.className = 'print-report-header__logo';
      header.appendChild(logo);
    }

    const title = document.createElement('h1');
    title.textContent = findPrintTitle(target);
    header.appendChild(title);
    return header;
  };

  const printTarget = (selectorOrElement) => {
    const target = resolvePrintTarget(selectorOrElement);
    if (!target) {
      window.print();
      return;
    }

    clearPrintClone();
    const cloneRoot = document.createElement('main');
    cloneRoot.className = 'print-clone-root';
    cloneRoot.setAttribute('aria-hidden', 'true');

    const clone = target.cloneNode(true);
    clone.removeAttribute('id');
    clone.querySelectorAll('[id]').forEach((node) => node.removeAttribute('id'));
    if (target.hasAttribute('data-report-print')) {
      cloneRoot.appendChild(buildPrintHeader(target));
    }
    cloneRoot.appendChild(clone);
    document.body.appendChild(cloneRoot);
    document.body.classList.add('is-printing-selection');

    window.setTimeout(() => window.print(), 0);
  };

  window.orionPrintTarget = printTarget;
  window.addEventListener('afterprint', clearPrintClone);

  const enhanceSearchableSelects = () => {
    const placeholder = currentLang() === 'ar' ? SEARCH_AR : 'Type to search...';
    document.querySelectorAll('select:not([multiple]):not([data-select-search-ready])').forEach((select) => {
      if (select.closest('.select-search')) return;
      select.dataset.selectSearchReady = '1';

      const wrapper = document.createElement('div');
      wrapper.className = 'select-search';
      const input = document.createElement('input');
      input.type = 'search';
      input.className = 'select-search__input';
      input.placeholder = placeholder;
      input.autocomplete = 'off';
      input.disabled = select.disabled;
      input.required = select.required;
      input.setAttribute('aria-autocomplete', 'list');
      input.setAttribute('aria-expanded', 'false');
      select.dataset.originalRequired = select.required ? '1' : '0';
      select.required = false;

      const selectedText = select.options[select.selectedIndex]?.textContent?.trim() || '';
      input.value = selectedText;
      const menu = document.createElement('div');
      menu.className = 'select-search__menu';
      menu.setAttribute('role', 'listbox');

      select.parentNode.insertBefore(wrapper, select);
      wrapper.appendChild(input);
      wrapper.appendChild(menu);
      wrapper.appendChild(select);

      let activeIndex = -1;
      const availableOptions = () => Array.from(select.options).filter((option) => option.value !== '' && !option.disabled && !option.hidden);
      const optionText = (option) => option.textContent?.replace(/\s+/g, ' ').trim() || '';
      const optionMatches = (option, query) => {
        if (!query) return true;
        const haystack = `${optionText(option)} ${option.value}`.toLowerCase();
        return haystack.includes(query);
      };
      const closeMenu = () => {
        menu.classList.remove('is-open');
        menu.innerHTML = '';
        input.setAttribute('aria-expanded', 'false');
        activeIndex = -1;
      };
      const commitOption = (option) => {
        if (!option) return;
        select.value = option.value;
        input.value = optionText(option);
        closeMenu();
        select.dispatchEvent(new Event('change', { bubbles: true }));
      };
      const setActive = (nextIndex) => {
        const items = Array.from(menu.querySelectorAll('.select-search__option'));
        if (!items.length) {
          activeIndex = -1;
          return;
        }
        activeIndex = (nextIndex + items.length) % items.length;
        items.forEach((item, index) => item.classList.toggle('is-active', index === activeIndex));
        items[activeIndex]?.scrollIntoView({ block: 'nearest' });
      };
      const renderMenu = () => {
        const query = input.value.trim().toLowerCase();
        const matches = availableOptions().filter((option) => optionMatches(option, query)).slice(0, 30);
        menu.innerHTML = '';
        matches.forEach((option) => {
          const item = document.createElement('button');
          item.type = 'button';
          item.className = 'select-search__option';
          item.setAttribute('role', 'option');
          item.dataset.value = option.value;
          const labelNode = document.createElement('span');
          labelNode.textContent = optionText(option);
          const valueNode = document.createElement('small');
          valueNode.textContent = option.value;
          item.appendChild(labelNode);
          item.appendChild(valueNode);
          item.addEventListener('mousedown', (event) => {
            event.preventDefault();
            commitOption(option);
          });
          menu.appendChild(item);
        });
        const hasMatches = matches.length > 0;
        menu.classList.toggle('is-open', hasMatches);
        input.setAttribute('aria-expanded', hasMatches ? 'true' : 'false');
        activeIndex = hasMatches ? 0 : -1;
        setActive(activeIndex);
      };

      input.addEventListener('input', () => {
        const typed = input.value.trim();
        const selectedOption = select.options[select.selectedIndex] || null;
        if (!selectedOption || optionText(selectedOption) !== typed) {
          select.value = '';
        }
        renderMenu();
      });
      input.addEventListener('focus', () => {
        input.select();
        renderMenu();
      });
      input.addEventListener('blur', () => {
        window.setTimeout(() => {
          input.value = select.options[select.selectedIndex]?.textContent?.trim() || input.value.trim();
          closeMenu();
        }, 120);
      });
      input.addEventListener('keydown', (event) => {
        const items = Array.from(menu.querySelectorAll('.select-search__option'));
        if (event.key === 'ArrowDown') {
          event.preventDefault();
          if (!items.length) renderMenu();
          setActive(activeIndex + 1);
          return;
        }
        if (event.key === 'ArrowUp') {
          event.preventDefault();
          if (!items.length) renderMenu();
          setActive(activeIndex - 1);
          return;
        }
        if (event.key === 'Escape') {
          closeMenu();
          return;
        }
        if (event.key === 'Enter') {
          event.preventDefault();
          const activeItem = items[activeIndex] || items[0];
          const option = activeItem ? Array.from(select.options).find((candidate) => candidate.value === activeItem.dataset.value) : null;
          commitOption(option);
        }
      });

      select.addEventListener('change', () => {
        input.value = select.options[select.selectedIndex]?.textContent?.trim() || '';
        input.disabled = select.disabled;
        closeMenu();
      });
    });
  };

  const initPaymentAccountFiltering = () => {
    const methodToCategory = (method) => {
      const normalized = String(method || '').toLowerCase();
      if (normalized === 'cash') return 'cash';
      if (['bank', 'card', 'transfer'].includes(normalized)) return 'bank';
      return '';
    };

    const syncSelectInput = (select) => {
      const input = select.closest('.select-search')?.querySelector('.select-search__input');
      if (!input) return;
      input.value = select.options[select.selectedIndex]?.textContent?.trim() || '';
    };

    const refreshAccountSelect = (accountSelect) => {
      const form = accountSelect.closest('form') || document;
      const methodSelect = form.querySelector('[data-payment-method-select], #payment_method');
      const desired = methodToCategory(methodSelect?.value || '');
      const currentOption = accountSelect.options[accountSelect.selectedIndex] || null;

      Array.from(accountSelect.options).forEach((option) => {
        if (option.value === '') {
          option.disabled = false;
          option.hidden = false;
          return;
        }
        const category = option.dataset.paymentCategory || '';
        const hidden = desired !== '' && category !== '' && category !== desired;
        option.disabled = hidden;
        option.hidden = hidden;
      });

      if (currentOption && currentOption.disabled) {
        accountSelect.value = '';
      }
      syncSelectInput(accountSelect);
    };

    document.querySelectorAll('[data-payment-account-select]').forEach((accountSelect) => {
      refreshAccountSelect(accountSelect);
      const form = accountSelect.closest('form') || document;
      const methodSelect = form.querySelector('[data-payment-method-select], #payment_method');
      if (methodSelect && methodSelect.dataset.paymentFilterReady !== '1') {
        methodSelect.dataset.paymentFilterReady = '1';
        methodSelect.addEventListener('change', () => {
          form.querySelectorAll('[data-payment-account-select]').forEach(refreshAccountSelect);
        });
      }
    });
  };

  const syncSearchInput = (select) => {
    if (!select) return;
    const input = select.closest('.select-search')?.querySelector('.select-search__input');
    if (input) {
      input.value = select.options[select.selectedIndex]?.textContent?.trim() || '';
      input.disabled = select.disabled;
    }
  };

  const setSelectValue = (select, value) => {
    if (!select) return;
    const nextValue = String(value || '');
    if (select.value === nextValue) {
      syncSearchInput(select);
      return;
    }
    select.value = nextValue;
    syncSearchInput(select);
    select.dispatchEvent(new Event('change', { bubbles: true }));
  };

  const initStudentSelectors = () => {
    const stageEl = document.getElementById('stage_code');
    const gradeEl = document.getElementById('grade_code');
    const classEl = document.getElementById('class_code');
    const studentEl = document.getElementById('student_number');
    const guardianEl = document.getElementById('guardian_contact_code');
    const invoiceEl = document.getElementById('student_invoice_id');
    const revenueTypeEl = document.getElementById('revenue_type_code');
    if (!stageEl && !gradeEl && !classEl && !studentEl && !invoiceEl && !revenueTypeEl) return;

    const amountFrom = (value) => {
      const parsed = Number(String(value ?? '').replace(/,/g, '').trim());
      return Number.isFinite(parsed) ? parsed : 0;
    };
    const money = (value) => (Math.round(amountFrom(value) * 100) / 100).toFixed(2);
    const hideByPredicate = (select, predicate) => {
      if (!select) return;
      const selected = select.options[select.selectedIndex] || null;
      Array.from(select.options).forEach((option) => {
        if (!option.value) {
          option.disabled = false;
          option.hidden = false;
          return;
        }
        const shouldHide = Boolean(predicate(option));
        option.disabled = shouldHide;
        option.hidden = shouldHide;
      });
      if (selected && selected.value && (selected.disabled || selected.hidden)) {
        setSelectValue(select, '');
      } else {
        syncSearchInput(select);
      }
    };
    const refreshGradeOptions = () => {
      const stage = String(stageEl?.value || '').trim();
      hideByPredicate(gradeEl, (option) => stage !== '' && String(option.dataset.stageCode || '') !== stage);
      refreshClassOptions();
    };
    const refreshClassOptions = () => {
      const stage = String(stageEl?.value || '').trim();
      const grade = String(gradeEl?.value || '').trim();
      hideByPredicate(classEl, (option) => {
        const optionStage = String(option.dataset.stageCode || '');
        const optionGrade = String(option.dataset.gradeCode || '');
        return (stage !== '' && optionStage !== stage) || (grade !== '' && optionGrade !== grade);
      });
    };
    const applyStudent = () => {
      if (!studentEl) return;
      const option = studentEl.options[studentEl.selectedIndex] || null;
      if (!option || !studentEl.value) return;
      setSelectValue(guardianEl, option.dataset.guardianContactCode || '');
      setSelectValue(stageEl, option.dataset.stageCode || '');
      setSelectValue(gradeEl, option.dataset.gradeCode || '');
      setSelectValue(classEl, option.dataset.classCode || '');
      refreshGradeOptions();
      refreshClassOptions();
    };
    const applyStudentInvoice = () => {
      if (!invoiceEl) return;
      const option = invoiceEl.options[invoiceEl.selectedIndex] || null;
      if (!option || !invoiceEl.value) return;
      setSelectValue(studentEl, option.dataset.studentNumber || '');
      setSelectValue(guardianEl, option.dataset.guardianContactCode || '');
      const referenceEl = document.getElementById('reference');
      const amountEl = document.getElementById('amount');
      if (referenceEl && option.dataset.studentInvoiceNumber) referenceEl.value = option.dataset.studentInvoiceNumber;
      if (amountEl && option.dataset.remaining) amountEl.value = money(option.dataset.remaining);
      applyStudent();
    };
    const applyRevenueType = () => {
      if (!revenueTypeEl) return;
      const option = revenueTypeEl.options[revenueTypeEl.selectedIndex] || null;
      if (!option || !revenueTypeEl.value) return;
      const subtotalEl = document.getElementById('subtotal');
      const taxableEl = document.getElementById('is_taxable');
      const taxNameEl = document.getElementById('tax_name');
      const taxRateEl = document.getElementById('tax_rate_percent');
      const revenueAccountEl = document.getElementById('revenue_account_code');
      const costCenterEl = document.getElementById('cost_center_code');
      if (subtotalEl && option.dataset.defaultAmount && amountFrom(subtotalEl.value) <= 0) {
        subtotalEl.value = money(option.dataset.defaultAmount);
        subtotalEl.dispatchEvent(new Event('input', { bubbles: true }));
      }
      if (taxableEl && option.dataset.isTaxable !== undefined) {
        taxableEl.checked = option.dataset.isTaxable === '1';
        taxableEl.dispatchEvent(new Event('change', { bubbles: true }));
      }
      setSelectValue(taxNameEl, option.dataset.taxName || '');
      if (taxRateEl && option.dataset.taxRate) {
        taxRateEl.value = money(option.dataset.taxRate);
        taxRateEl.dispatchEvent(new Event('input', { bubbles: true }));
      }
      setSelectValue(revenueAccountEl, option.dataset.revenueAccountCode || '');
      setSelectValue(costCenterEl, option.dataset.costCenterCode || costCenterEl?.value || '');
    };

    stageEl?.addEventListener('change', refreshGradeOptions);
    gradeEl?.addEventListener('change', refreshClassOptions);
    studentEl?.addEventListener('change', applyStudent);
    invoiceEl?.addEventListener('change', applyStudentInvoice);
    revenueTypeEl?.addEventListener('change', applyRevenueType);
    refreshGradeOptions();
    refreshClassOptions();
  };

  const initZatcaQr = () => {
    document.querySelectorAll('[data-zatca-qr-code]').forEach((target) => {
      if (target.dataset.qrReady === '1') return;
      const value = target.getAttribute('data-zatca-value') || '';
      if (!value) return;
      target.dataset.qrReady = '1';
      target.textContent = '';
      if (!window.QRCode) {
        target.classList.add('is-fallback');
        target.textContent = value;
        return;
      }
      try {
        new window.QRCode(target, {
          text: value,
          width: 132,
          height: 132,
          correctLevel: window.QRCode.CorrectLevel?.M ?? 0,
        });
        window.setTimeout(() => {
          const canvas = target.querySelector('canvas');
          if (!canvas) return;
          const img = document.createElement('img');
          img.className = 'zatca-qr__img';
          img.alt = 'ZATCA QR';
          img.src = canvas.toDataURL('image/png');
          target.innerHTML = '';
          target.appendChild(img);
        }, 30);
      } catch (error) {
        target.classList.add('is-fallback');
        target.textContent = value;
      }
    });
  };

  const applySidebarState = (collapsed) => {
    const sidebarToggle = document.getElementById('sidebarToggle');
    if (!sidebarToggle) {
      document.body.classList.remove('sidebar-collapsed');
      return;
    }
    document.body.classList.toggle('sidebar-collapsed', collapsed);
    sidebarToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
    sidebarToggle.setAttribute('title', collapsed ? 'Expand sidebar' : 'Collapse sidebar');
    sidebarToggle.textContent = collapsed ? '>>' : '<<';
  };

  const initBulkSelection = () => {
    document.querySelectorAll('[data-bulk-scope]').forEach((scope) => {
      if (scope.dataset.bulkSelectionReady === '1') return;
      scope.dataset.bulkSelectionReady = '1';

      const form = scope.querySelector('[data-bulk-delete-form]');
      const checkboxes = Array.from(scope.querySelectorAll('[data-bulk-checkbox]'));
      const selectModeButton = scope.querySelector('[data-bulk-select-mode]');
      const selectAllButton = scope.querySelector('[data-bulk-select-all]');
      const clearButton = scope.querySelector('[data-bulk-clear]');
      const deleteButton = scope.querySelector('[data-bulk-delete]');
      const assignButton = scope.querySelector('[data-bulk-assign]');
      const statementGroupSelect = scope.querySelector('[data-bulk-statement-group-select]');
      const countEl = scope.querySelector('[data-bulk-count]');
      const selectedLabel = (countEl?.textContent || '').replace(/^\s*\d+\s*/, '').trim() || (currentLang() === 'ar' ? '\u0645\u062d\u062f\u062f' : 'selected');

      if (!checkboxes.length) return;

      const enabledCheckboxes = () => checkboxes.filter((checkbox) => !checkbox.disabled);
      const setSelectionMode = (active) => {
        scope.classList.toggle('is-bulk-selecting', active);
      };
      const selectedCount = () => enabledCheckboxes().filter((checkbox) => checkbox.checked).length;
      const updateState = () => {
        const selected = selectedCount();
        if (deleteButton) deleteButton.disabled = selected === 0;
        if (assignButton) assignButton.disabled = selected === 0 || !String(statementGroupSelect?.value || '').trim();
        if (countEl) countEl.textContent = `${selected} ${selectedLabel}`;
        checkboxes.forEach((checkbox) => {
          const row = checkbox.closest('tr') || checkbox.closest('.coa-tree-row');
          row?.classList.toggle('is-row-selected', checkbox.checked && !checkbox.disabled);
        });
        if (selected > 0) {
          setSelectionMode(true);
        }
      };
      const clearSelection = () => {
        enabledCheckboxes().forEach((checkbox) => { checkbox.checked = false; });
        setSelectionMode(false);
        updateState();
      };

      selectModeButton?.addEventListener('click', () => {
        if (scope.classList.contains('is-bulk-selecting')) {
          clearSelection();
        } else {
          setSelectionMode(true);
        }
      });

      selectAllButton?.addEventListener('click', () => {
        setSelectionMode(true);
        enabledCheckboxes().forEach((checkbox) => { checkbox.checked = true; });
        updateState();
      });

      clearButton?.addEventListener('click', clearSelection);
      checkboxes.forEach((checkbox) => checkbox.addEventListener('change', updateState));
      statementGroupSelect?.addEventListener('change', updateState);

      form?.addEventListener('submit', (event) => {
        const selected = selectedCount();
        if (selected === 0) {
          event.preventDefault();
          window.alert(currentLang() === 'ar' ? '\u0627\u062e\u062a\u0631 \u0633\u062c\u0644\u0627 \u0648\u0627\u062d\u062f\u0627 \u0639\u0644\u0649 \u0627\u0644\u0623\u0642\u0644.' : 'Select at least one record first.');
          return;
        }
        const action = String(event.submitter?.value || '').trim();
        if (action === 'bulk_assign_statement_group') {
          if (!String(statementGroupSelect?.value || '').trim()) {
            event.preventDefault();
            window.alert(currentLang() === 'ar' ? '\u0627\u062e\u062a\u0631 \u0628\u0646\u062f \u0627\u0644\u0642\u0648\u0627\u0626\u0645 \u0627\u0644\u0645\u0627\u0644\u064a\u0629 \u0623\u0648\u0644\u0627.' : 'Choose a financial statement group first.');
            return;
          }
          const assignMessage = form.dataset.assignConfirmMessage || (currentLang() === 'ar' ? '\u0631\u0628\u0637 \u0627\u0644\u062d\u0633\u0627\u0628\u0627\u062a \u0627\u0644\u0645\u062d\u062f\u062f\u0629 \u0628\u0628\u0646\u062f \u0627\u0644\u0642\u0648\u0627\u0626\u0645 \u0627\u0644\u0645\u0627\u0644\u064a\u0629\u061f' : 'Assign selected accounts to this financial statement group?');
          if (!window.confirm(assignMessage)) {
            event.preventDefault();
          }
          return;
        }
        const message = form.dataset.confirmMessage || (currentLang() === 'ar' ? '\u062d\u0630\u0641 \u0627\u0644\u0633\u062c\u0644\u0627\u062a \u0627\u0644\u0645\u062d\u062f\u062f\u0629\u061f' : 'Delete selected records?');
        if (!window.confirm(message)) {
          event.preventDefault();
        }
      });

      updateState();
    });
  };

  const initChartAccountTree = () => {
    document.querySelectorAll('[data-coa-tree]').forEach((tree) => {
      if (tree.dataset.coaTreeReady === '1') return;
      tree.dataset.coaTreeReady = '1';

      const modal = tree.querySelector('[data-coa-modal]');
      const modalParentCode = modal?.querySelector('[data-coa-modal-parent-code]');
      const modalParentLabel = modal?.querySelector('[data-coa-modal-parent-label]');
      const modalAccountCode = modal?.querySelector('[data-coa-modal-account-code]');
      const modalAccountName = modal?.querySelector('[data-coa-modal-account-name]');
      const modalAccountType = modal?.querySelector('[data-coa-modal-account-type]');
      const modalStatementGroup = modal?.querySelector('[data-coa-modal-statement-group]');

      const syncSelect = (select, value) => {
        if (!select) return;
        select.value = value || '';
        select.dispatchEvent(new Event('change', { bubbles: true }));
      };

      const setExpanded = (node, expanded) => {
        if (!node) return;
        node.classList.toggle('is-collapsed', !expanded);
        const button = node.querySelector(':scope > .coa-tree-row [data-coa-toggle]');
        const symbol = node.querySelector(':scope > .coa-tree-row [data-coa-toggle-symbol]');
        if (button) button.setAttribute('aria-expanded', expanded ? 'true' : 'false');
        if (symbol) symbol.textContent = expanded ? '-' : '+';
      };

      tree.querySelectorAll('[data-coa-node]').forEach((node) => {
        setExpanded(node, !node.classList.contains('is-collapsed'));
      });

      tree.addEventListener('click', (event) => {
        const toggle = event.target.closest('[data-coa-toggle]');
        if (toggle && tree.contains(toggle)) {
          event.preventDefault();
          const node = toggle.closest('[data-coa-node]');
          setExpanded(node, node?.classList.contains('is-collapsed'));
          return;
        }

        const addButton = event.target.closest('[data-coa-add-child]');
        if (addButton && tree.contains(addButton) && modal) {
          event.preventDefault();
          const parentCode = String(addButton.dataset.parentCode || '').trim();
          const parentName = String(addButton.dataset.parentName || '').trim();
          const nextCode = String(addButton.dataset.nextCode || '').trim();
          const accountType = String(addButton.dataset.accountType || '').trim();
          const statementGroup = String(addButton.dataset.statementGroup || '').trim();

          if (modalParentCode) modalParentCode.value = parentCode;
          if (modalParentLabel) modalParentLabel.value = parentName ? `${parentCode} - ${parentName}` : parentCode;
          if (modalAccountCode) modalAccountCode.value = nextCode;
          if (modalAccountName) modalAccountName.value = '';
          syncSelect(modalAccountType, accountType);
          syncSelect(modalStatementGroup, statementGroup);

          modal.hidden = false;
          document.body.classList.add('has-coa-modal-open');
          window.setTimeout(() => modalAccountName?.focus(), 20);
        }
      });

      tree.querySelector('[data-coa-expand-all]')?.addEventListener('click', () => {
        tree.querySelectorAll('[data-coa-node]').forEach((node) => setExpanded(node, true));
      });

      tree.querySelector('[data-coa-collapse-all]')?.addEventListener('click', () => {
        tree.querySelectorAll('[data-coa-node]').forEach((node) => {
          if (node.querySelector(':scope > .coa-tree-children')) {
            setExpanded(node, false);
          }
        });
      });

      const closeModal = () => {
        if (!modal) return;
        modal.hidden = true;
        document.body.classList.remove('has-coa-modal-open');
      };

      modal?.addEventListener('click', (event) => {
        if (event.target === modal || event.target.closest('[data-coa-modal-close]')) {
          event.preventDefault();
          closeModal();
        }
      });

      document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && modal && !modal.hidden) {
          closeModal();
        }
      });
    });
  };

  const initDocumentLineEditors = () => {
    document.querySelectorAll('[data-document-lines-editor]').forEach((editor) => {
      if (editor.dataset.documentLinesReady === '1') return;
      editor.dataset.documentLinesReady = '1';

      const body = editor.querySelector('[data-doc-lines-body]');
      const template = editor.querySelector('template[data-doc-line-template]');
      const form = editor.closest('form');
      if (!body || !template || !form) return;

      let taxRates = {};
      try {
        taxRates = JSON.parse(editor.getAttribute('data-tax-rates') || '{}') || {};
      } catch (error) {
        taxRates = {};
      }
      let withholdingTaxRates = {};
      try {
        withholdingTaxRates = JSON.parse(editor.getAttribute('data-withholding-tax-rates') || '{}') || {};
      } catch (error) {
        withholdingTaxRates = {};
      }
      let vendorWithholding = {};
      try {
        vendorWithholding = JSON.parse(editor.getAttribute('data-vendor-withholding') || '{}') || {};
      } catch (error) {
        vendorWithholding = {};
      }

      const parseAmount = (value) => {
        const normalized = String(value ?? '')
          .replace(/[\u0660-\u0669]/g, (digit) => String(digit.charCodeAt(0) - 0x0660))
          .replace(/[\u06f0-\u06f9]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0))
          .replace(/,/g, '')
          .trim();
        const parsed = Number(normalized);
        return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
      };
      const money = (value) => (Math.round((Number.isFinite(value) ? value : 0) * 100) / 100).toFixed(2);
      const formatMoney = (value) => new Intl.NumberFormat(currentLang() === 'ar' ? 'ar-EG' : 'en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(Number.isFinite(value) ? value : 0);
      const rows = () => Array.from(body.querySelectorAll('[data-doc-line-row]'));
      const hidden = (id) => form.querySelector(`#${CSS.escape(id)}`);
      const setHidden = (id, value) => {
        const input = hidden(id);
        if (input) input.value = value;
      };
      const selectedTaxRate = (row) => {
        const select = row.querySelector('[data-doc-line-tax-name]');
        const rateInput = row.querySelector('[data-doc-line-tax-rate]');
        if (!select || !select.value) return parseAmount(rateInput?.value);
        const option = select.options[select.selectedIndex] || null;
        const optionRate = option?.dataset?.taxRate;
        if (optionRate !== undefined && optionRate !== '') return parseAmount(optionRate);
        if (Object.prototype.hasOwnProperty.call(taxRates, select.value)) return parseAmount(taxRates[select.value]);
        const match = (option?.textContent || '').match(/([0-9]+(?:\.[0-9]+)?)\s*%|%\s*([0-9]+(?:\.[0-9]+)?)/);
        return match ? parseAmount(match[1] || match[2]) : parseAmount(rateInput?.value);
      };
      const selectedWithholdingRate = () => {
        const select = hidden('withholding_tax_name');
        const rateInput = hidden('withholding_tax_rate_percent');
        if (!select || !select.value) return 0;
        const option = select.options ? (select.options[select.selectedIndex] || null) : null;
        const optionRate = option?.dataset?.taxRate;
        if (optionRate !== undefined && optionRate !== '') return parseAmount(optionRate);
        if (Object.prototype.hasOwnProperty.call(withholdingTaxRates, select.value)) return parseAmount(withholdingTaxRates[select.value]);
        const match = (option?.textContent || '').match(/([0-9]+(?:\.[0-9]+)?)\s*%|%\s*([0-9]+(?:\.[0-9]+)?)/);
        return match ? parseAmount(match[1] || match[2]) : parseAmount(rateInput?.value);
      };
      const applyVendorWithholding = () => {
        const vendorEl = hidden('vendor_code');
        const withholdingNameEl = hidden('withholding_tax_name');
        const withholdingRateEl = hidden('withholding_tax_rate_percent');
        if (!vendorEl || !withholdingNameEl) return;
        const vendorMeta = vendorWithholding[vendorEl.value] || null;
        if (!vendorMeta || !vendorMeta.tax_name) return;
        if (!withholdingNameEl.value) withholdingNameEl.value = vendorMeta.tax_name;
        if (withholdingRateEl) withholdingRateEl.value = money(parseAmount(vendorMeta.rate));
      };
      const rowHasValues = (row) => {
        if (!row) return false;
        return Boolean(
          (row.querySelector('[name="doc_line_item_code[]"]')?.value || '').trim()
          || (row.querySelector('[name="doc_line_description[]"]')?.value || '').trim()
          || (row.querySelector('[name="doc_line_account_code[]"]')?.value || '').trim()
          || parseAmount(row.querySelector('[data-doc-line-unit]')?.value) > 0
        );
      };
      const updateLineNumbers = () => {
        rows().forEach((row, index) => {
          const number = row.querySelector('[data-doc-line-number]');
          if (number) number.textContent = String(index + 1);
        });
      };
      const updatePaymentStatus = (grandTotal, paymentBasisTotal = grandTotal) => {
        const paidEl = form.querySelector('#inline_paid_amount, #paid_amount');
        const statusEl = form.querySelector('#status');
        const paymentMethodEl = form.querySelector('#payment_method');
        const paymentAccountEl = form.querySelector('#payment_account_name');
        const offsetAccountEl = form.querySelector('#offset_account_code');
        let paid = parseAmount(paidEl?.value);
        if (paid > paymentBasisTotal && paidEl) {
          paid = paymentBasisTotal;
          paidEl.value = money(paid);
        }
        const hasPaid = paid > 0;
        if (paymentMethodEl) {
          paymentMethodEl.required = hasPaid;
          if (!hasPaid) paymentMethodEl.value = '';
        }
        if (paymentAccountEl) {
          paymentAccountEl.required = hasPaid;
          if (!hasPaid) paymentAccountEl.value = '';
        }
        if (statusEl) {
          const current = String(statusEl.value || '').toLowerCase();
          if (current !== 'draft' && current !== 'cancelled') {
            if (paid <= 0 || paymentBasisTotal <= 0) {
              statusEl.value = ['approved', 'partially_paid', 'paid'].includes(current) ? 'approved' : 'issued';
            } else if (paid >= (paymentBasisTotal - 0.01)) {
              statusEl.value = 'paid';
            } else {
              statusEl.value = 'partially_paid';
            }
          }
        }
        if (offsetAccountEl) {
          const requiresOffset = (grandTotal - paid) > 0.01;
          const field = offsetAccountEl.closest('.field');
          if (field) field.style.display = requiresOffset ? '' : 'none';
          offsetAccountEl.required = requiresOffset;
          if (!requiresOffset) offsetAccountEl.value = '';
        }
      };
      const recalc = () => {
        let subtotal = 0;
        let discount = 0;
        let taxTotal = 0;
        let grandTotal = 0;
        let firstTaxName = '';
        let firstTaxRate = 0;

        rows().forEach((row) => {
          const qty = parseAmount(row.querySelector('[data-doc-line-qty]')?.value) || 0;
          const unit = parseAmount(row.querySelector('[data-doc-line-unit]')?.value) || 0;
          const discountInput = row.querySelector('[data-doc-line-discount]');
          let rowDiscount = parseAmount(discountInput?.value);
          const taxableCheckbox = row.querySelector('[data-doc-line-taxable]');
          const taxableValue = row.querySelector('[data-doc-line-taxable-value]');
          const taxRateInput = row.querySelector('[data-doc-line-tax-rate]');
          const taxNameEl = row.querySelector('[data-doc-line-tax-name]');
          const isTaxable = Boolean(taxableCheckbox?.checked);
          if (taxableValue) taxableValue.value = isTaxable ? '1' : '0';

          const gross = Math.round(qty * unit * 100) / 100;
          if (rowDiscount > gross) {
            rowDiscount = gross;
            if (discountInput) discountInput.value = money(rowDiscount);
          }
          const base = Math.max(0, Math.round((gross - rowDiscount) * 100) / 100);
          let taxRate = isTaxable ? selectedTaxRate(row) : 0;
          if (isTaxable && taxRate <= 0) taxRate = 15;
          if (!isTaxable && taxNameEl) taxNameEl.value = '';
          if (taxRateInput) {
            taxRateInput.value = money(taxRate);
            taxRateInput.readOnly = !isTaxable;
          }
          const rowTax = isTaxable ? Math.round(base * taxRate) / 100 : 0;
          const rowTotal = Math.round((base + rowTax) * 100) / 100;

          const subtotalValue = row.querySelector('[data-doc-line-subtotal-value]');
          const taxValue = row.querySelector('[data-doc-line-tax-value]');
          const totalValue = row.querySelector('[data-doc-line-total-value]');
          const totalLabel = row.querySelector('[data-doc-line-total]');
          if (subtotalValue) subtotalValue.value = money(base);
          if (taxValue) taxValue.value = money(rowTax);
          if (totalValue) totalValue.value = money(rowTotal);
          if (totalLabel) totalLabel.textContent = formatMoney(rowTotal);

          if (rowHasValues(row)) {
            subtotal += base;
            discount += rowDiscount;
            taxTotal += rowTax;
            grandTotal += rowTotal;
            if (isTaxable && firstTaxName === '') {
              firstTaxName = taxNameEl?.value || '';
              firstTaxRate = taxRate;
            }
          }
        });

        subtotal = Math.round(subtotal * 100) / 100;
        discount = Math.round(discount * 100) / 100;
        taxTotal = Math.round(taxTotal * 100) / 100;
        grandTotal = Math.round(grandTotal * 100) / 100;

        setHidden('subtotal', money(subtotal));
        setHidden('discount_total', money(discount));
        setHidden('tax_total', money(taxTotal));
        setHidden('grand_total', money(grandTotal));
        setHidden('is_taxable', taxTotal > 0 ? '1' : '0');
        setHidden('tax_name', firstTaxName);
        setHidden('tax_rate_percent', money(firstTaxRate));
        applyVendorWithholding();
        const withholdingNameEl = hidden('withholding_tax_name');
        const withholdingRateEl = hidden('withholding_tax_rate_percent');
        const withholdingTotalEl = hidden('withholding_tax_total');
        const netPayableEl = hidden('net_payable');
        const withholdingRate = selectedWithholdingRate();
        const withholdingTotal = withholdingNameEl?.value ? Math.min(grandTotal, Math.round((subtotal * withholdingRate) * 100) / 10000) : 0;
        const netPayable = Math.max(0, Math.round((grandTotal - withholdingTotal) * 100) / 100);
        if (withholdingRateEl) {
          withholdingRateEl.value = money(withholdingRate);
          withholdingRateEl.readOnly = Boolean(withholdingNameEl?.value);
        }
        if (withholdingTotalEl) {
          withholdingTotalEl.value = money(withholdingTotal);
          withholdingTotalEl.readOnly = true;
        }
        if (netPayableEl) {
          netPayableEl.value = money(netPayable);
          netPayableEl.readOnly = true;
        }

        editor.querySelectorAll('[data-doc-lines-subtotal], [data-tax-summary-base]').forEach((node) => { node.textContent = formatMoney(subtotal); });
        editor.querySelectorAll('[data-doc-lines-discount]').forEach((node) => { node.textContent = formatMoney(discount); });
        editor.querySelectorAll('[data-doc-lines-tax], [data-tax-summary-tax]').forEach((node) => { node.textContent = formatMoney(taxTotal); });
        editor.querySelectorAll('[data-doc-lines-withholding]').forEach((node) => { node.textContent = formatMoney(withholdingTotal); });
        editor.querySelectorAll('[data-doc-lines-net-payable]').forEach((node) => { node.textContent = formatMoney(netPayable); });
        editor.querySelectorAll('[data-doc-lines-grand], [data-tax-summary-grand]').forEach((node) => { node.textContent = formatMoney(grandTotal); });
        document.querySelectorAll('[data-tax-summary-base]').forEach((node) => { node.textContent = formatMoney(subtotal); });
        document.querySelectorAll('[data-tax-summary-tax]').forEach((node) => { node.textContent = formatMoney(taxTotal); });
        document.querySelectorAll('[data-tax-summary-withholding]').forEach((node) => { node.textContent = formatMoney(withholdingTotal); });
        document.querySelectorAll('[data-tax-summary-net-payable]').forEach((node) => { node.textContent = formatMoney(netPayable); });
        document.querySelectorAll('[data-tax-summary-grand]').forEach((node) => { node.textContent = formatMoney(grandTotal); });
        updatePaymentStatus(grandTotal, netPayableEl ? netPayable : grandTotal);
        updateLineNumbers();
      };
      const addLine = (focus = true) => {
        body.appendChild(template.content.cloneNode(true));
        enhanceSearchableSelects();
        updateLineNumbers();
        recalc();
        if (focus) rows().at(-1)?.querySelector('select, input')?.focus();
      };

      editor.querySelector('[data-doc-line-add]')?.addEventListener('click', () => addLine());
      body.addEventListener('input', recalc);
      body.addEventListener('change', recalc);
      body.addEventListener('click', (event) => {
        const removeButton = event.target.closest('[data-doc-line-remove]');
        if (!removeButton) return;
        removeButton.closest('[data-doc-line-row]')?.remove();
        if (!rows().length) addLine(false);
        recalc();
      });
      form.querySelector('#inline_paid_amount, #paid_amount')?.addEventListener('input', recalc);
      form.querySelector('#inline_paid_amount, #paid_amount')?.addEventListener('change', recalc);
      ['#vendor_code', '#withholding_tax_name', '#withholding_tax_rate_percent'].forEach((selector) => {
        const element = form.querySelector(selector);
        element?.addEventListener('input', recalc);
        element?.addEventListener('change', recalc);
      });
      form.addEventListener('submit', (event) => {
        recalc();
        const filledRows = rows().filter(rowHasValues);
        if (!filledRows.length) {
          event.preventDefault();
          window.alert(currentLang() === 'ar' ? '\u0623\u0636\u0641 \u0628\u0646\u062f\u0627 \u0648\u0627\u062d\u062f\u0627 \u0639\u0644\u0649 \u0627\u0644\u0623\u0642\u0644.' : 'Add at least one line.');
        }
      });

      recalc();
    });
  };

  const initJournalEntryEditor = () => {
    const editor = document.querySelector('[data-journal-editor]');
    if (!editor || editor.dataset.journalEditorReady === '1') return;
    editor.dataset.journalEditorReady = '1';

    const body = editor.querySelector('[data-journal-lines-body]');
    const template = editor.querySelector('template[data-journal-line-template]');
    const form = editor.querySelector('form');
    const headerDescriptionEl = editor.querySelector('#description');
    if (!body || !template || !form) return;

    const parseAmount = (value) => {
      const parsed = Number(String(value || '').replace(/,/g, ''));
      return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
    };
    const formatAmount = (value) => new Intl.NumberFormat(currentLang() === 'ar' ? 'ar-EG' : 'en-US', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(Number.isFinite(value) ? value : 0);
    const rows = () => Array.from(body.querySelectorAll('[data-journal-line-row]'));
    const lineDescriptionInput = (row) => row?.querySelector('input[name="line_description[]"]');
    const rowHasAnyValue = (row) => {
      if (!row) return false;
      const account = row.querySelector('select[name="line_account_code[]"]')?.value || '';
      const costCenter = row.querySelector('select[name="line_cost_center_code[]"]')?.value || '';
      const label = lineDescriptionInput(row)?.value || '';
      const debit = parseAmount(row.querySelector('[data-journal-debit]')?.value);
      const credit = parseAmount(row.querySelector('[data-journal-credit]')?.value);
      return account.trim() !== '' || costCenter.trim() !== '' || label.trim() !== '' || debit > 0 || credit > 0;
    };
    const fillDefaultLabel = (row) => {
      const input = lineDescriptionInput(row);
      const headerDescription = (headerDescriptionEl?.value || '').trim();
      if (!input || input.value.trim() !== '' || headerDescription === '' || !rowHasAnyValue(row)) return;
      input.value = headerDescription;
    };
    const updateLineNumbers = () => {
      rows().forEach((row, index) => {
        const numberCell = row.querySelector('[data-journal-line-number]');
        if (numberCell) numberCell.textContent = String(index + 1);
      });
    };
    const updateTotals = () => {
      let totalDebit = 0;
      let totalCredit = 0;
      rows().forEach((row) => {
        totalDebit += parseAmount(row.querySelector('[data-journal-debit]')?.value);
        totalCredit += parseAmount(row.querySelector('[data-journal-credit]')?.value);
      });
      const difference = Math.round((totalDebit - totalCredit) * 100) / 100;
      editor.querySelectorAll('[data-journal-total-debit], [data-journal-total-debit-card]').forEach((node) => {
        node.textContent = formatAmount(totalDebit);
      });
      editor.querySelectorAll('[data-journal-total-credit], [data-journal-total-credit-card]').forEach((node) => {
        node.textContent = formatAmount(totalCredit);
      });
      const differenceNode = editor.querySelector('[data-journal-difference]');
      if (differenceNode) {
        const balanced = Math.abs(difference) < 0.01 && totalDebit > 0;
        differenceNode.classList.toggle('is-balanced', balanced);
        differenceNode.classList.toggle('is-unbalanced', !balanced);
        differenceNode.textContent = balanced
          ? (currentLang() === 'ar' ? '\u0645\u062a\u0648\u0627\u0632\u0646' : 'Balanced')
          : `${currentLang() === 'ar' ? '\u0627\u0644\u0641\u0631\u0642' : 'Difference'} ${formatAmount(Math.abs(difference))}`;
      }
    };
    const addLine = (focus = true) => {
      const fragment = template.content.cloneNode(true);
      body.appendChild(fragment);
      enhanceSearchableSelects();
      updateLineNumbers();
      updateTotals();
      if (focus) {
        const currentRows = rows();
        currentRows[currentRows.length - 1]?.querySelector('select, input')?.focus();
      }
    };
    const ensureTrailingBlankRow = (row) => {
      const currentRows = rows();
      if (!row || currentRows[currentRows.length - 1] !== row || !rowHasAnyValue(row)) return;
      addLine(false);
    };
    const handleRowEdited = (row) => {
      if (!row) {
        updateTotals();
        return;
      }
      fillDefaultLabel(row);
      ensureTrailingBlankRow(row);
      updateLineNumbers();
      updateTotals();
    };

    editor.querySelector('[data-journal-add-line]')?.addEventListener('click', () => addLine());
    body.addEventListener('input', (event) => {
      const debitInput = event.target.closest('[data-journal-debit]');
      const creditInput = event.target.closest('[data-journal-credit]');
      const row = event.target.closest('[data-journal-line-row]');
      if (row && debitInput && parseAmount(debitInput.value) > 0) {
        const credit = row.querySelector('[data-journal-credit]');
        if (credit) credit.value = '';
      }
      if (row && creditInput && parseAmount(creditInput.value) > 0) {
        const debit = row.querySelector('[data-journal-debit]');
        if (debit) debit.value = '';
      }
      handleRowEdited(row);
    });
    body.addEventListener('change', (event) => {
      handleRowEdited(event.target.closest('[data-journal-line-row]'));
    });
    headerDescriptionEl?.addEventListener('change', () => {
      rows().forEach((row) => fillDefaultLabel(row));
    });
    body.addEventListener('click', (event) => {
      const removeButton = event.target.closest('[data-journal-remove-line]');
      if (!removeButton) return;
      removeButton.closest('[data-journal-line-row]')?.remove();
      while (rows().length < 2) addLine(false);
      updateLineNumbers();
      updateTotals();
    });

    form.addEventListener('submit', (event) => {
      let filledRows = 0;
      let totalDebit = 0;
      let totalCredit = 0;
      rows().forEach((row) => {
        fillDefaultLabel(row);
        const account = row.querySelector('select[name="line_account_code[]"]')?.value || '';
        const debit = parseAmount(row.querySelector('[data-journal-debit]')?.value);
        const credit = parseAmount(row.querySelector('[data-journal-credit]')?.value);
        if (account !== '' || debit > 0 || credit > 0) filledRows += 1;
        totalDebit += debit;
        totalCredit += credit;
      });
      if (filledRows < 2) {
        event.preventDefault();
        window.alert(currentLang() === 'ar' ? '\u0627\u0644\u0642\u064a\u062f \u0644\u0627\u0632\u0645 \u064a\u062d\u062a\u0648\u064a \u0639\u0644\u0649 \u0633\u0637\u0631\u064a\u0646 \u0639\u0644\u0649 \u0627\u0644\u0623\u0642\u0644.' : 'Journal entry must contain at least two lines.');
        return;
      }
      if (Math.abs(totalDebit - totalCredit) >= 0.01 || totalDebit <= 0) {
        event.preventDefault();
        window.alert(currentLang() === 'ar' ? '\u0627\u0644\u0642\u064a\u062f \u0644\u0627\u0632\u0645 \u064a\u0643\u0648\u0646 \u0645\u062a\u0648\u0627\u0632\u0646 \u0642\u0628\u0644 \u0627\u0644\u062d\u0641\u0638.' : 'Journal entry must be balanced before saving.');
      }
    });

    updateLineNumbers();
    updateTotals();
  };

  const initPasswordToggles = () => {
    document.querySelectorAll('[data-toggle-password]').forEach((button) => {
      if (button.dataset.passwordToggleReady === '1') return;
      button.dataset.passwordToggleReady = '1';
      const targetId = button.getAttribute('data-target') || '';
      const input = targetId ? document.getElementById(targetId) : button.parentElement?.querySelector('input[type="password"], input[type="text"]');
      if (!input) return;

      const syncLabel = () => {
        const visible = input.type === 'text';
        button.textContent = currentLang() === 'ar'
          ? (visible ? '\u0625\u062e\u0641\u0627\u0621' : '\u0625\u0638\u0647\u0627\u0631')
          : (visible ? 'Hide' : 'Show');
      };

      button.addEventListener('click', () => {
        input.type = input.type === 'password' ? 'text' : 'password';
        syncLabel();
        input.focus();
      });
      syncLabel();
    });
  };

  const init = () => {
    const cookieTheme = getCookie('orion_theme');
    if (cookieTheme === 'dark' || cookieTheme === 'light') {
      html.dataset.theme = cookieTheme;
      html.setAttribute('data-theme', cookieTheme);
    }

    updateUiButtons();
    enhanceSearchableSelects();
    initPaymentAccountFiltering();
    initStudentSelectors();
    initZatcaQr();
    initBulkSelection();
    initChartAccountTree();
    initDocumentLineEditors();
    initJournalEntryEditor();
    initPasswordToggles();

    document.addEventListener('click', (event) => {
      const themeButton = event.target.closest('[data-ui-theme-toggle]');
      if (themeButton) {
        event.preventDefault();
        applyTheme(currentTheme() === 'dark' ? 'light' : 'dark');
        return;
      }

      const langButton = event.target.closest('[data-ui-lang-toggle]');
      if (langButton) {
        event.preventDefault();
        switchLanguage();
        return;
      }

      const sidebarButton = event.target.closest('#sidebarToggle');
      if (sidebarButton) {
        event.preventDefault();
        const nextState = !document.body.classList.contains('sidebar-collapsed');
        applySidebarState(nextState);
        try { window.localStorage.setItem('orion_sidebar_collapsed', nextState ? '1' : '0'); } catch (error) {}
        return;
      }

      const printButton = event.target.closest('[data-print-page]');
      if (printButton) {
        event.preventDefault();
        const explicitTarget = printButton.getAttribute('data-print-target');
        const scopedTarget = explicitTarget
          ? resolvePrintTarget(explicitTarget)
          : (printButton.closest('[data-print-scope]') || document.querySelector('[data-default-print-target]'));
        if (scopedTarget) {
          printTarget(scopedTarget);
        } else {
          window.print();
        }
      }
    });

    let collapsed = false;
    try { collapsed = window.localStorage.getItem('orion_sidebar_collapsed') === '1'; } catch (error) {}
    applySidebarState(collapsed);

    document.querySelectorAll('[data-tab-button]').forEach((button) => {
      button.addEventListener('click', () => {
        const target = button.getAttribute('data-tab-button');
        if (!target) return;
        document.querySelectorAll('[data-tab-button]').forEach((other) => other.classList.remove('is-active'));
        document.querySelectorAll('[data-tab-panel]').forEach((panel) => panel.classList.remove('is-active'));
        button.classList.add('is-active');
        document.querySelector(`[data-tab-panel="${target}"]`)?.classList.add('is-active');
      });
    });

    document.getElementById('floatingPrintBtn')?.addEventListener('click', () => {
      const target = document.querySelector('[data-default-print-target]');
      if (target) {
        printTarget(target);
      } else {
        window.print();
      }
    });

    document.querySelectorAll('[data-auto-submit]').forEach((input) => {
      input.addEventListener('change', () => input.closest('form')?.submit());
    });
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
