(() => {
  const tabs = Array.from(document.querySelectorAll('[data-inventory-tab]'));
  const panels = Array.from(document.querySelectorAll('[data-inventory-panel]'));
  tabs.forEach((tab) => tab.addEventListener('click', () => {
    const target = tab.dataset.inventoryTab;
    tabs.forEach((item) => item.classList.toggle('active', item === tab));
    panels.forEach((panel) => panel.classList.toggle('active', panel.dataset.inventoryPanel === target));
  }));

  const filter = document.getElementById('software-inventory-filter');
  const table = document.getElementById('software-inventory-table');
  if (filter && table) {
    filter.addEventListener('input', () => {
      const matches = window.AssetManagerSearchTextMatches ||
        ((value, term) => String(value || '').toLocaleLowerCase().includes(String(term || '').toLocaleLowerCase()));
      const needle = filter.value.trim();
      table.querySelectorAll('tbody tr').forEach((row) => {
        row.hidden = Boolean(needle) && !matches(row.textContent, needle);
      });
    });
  }
})();

(() => {
  const tree = document.querySelector('.inventory-tree');
  if (!tree) return;
  const state = window.AssetBrowserState;
  const assetId = location.pathname.match(/\/assets\/(\d+)/)?.[1] || 'unknown';
  const storageKey = `inventory-tree:${assetId}`;
  let openPaths = new Set();
  if (state) {
    try { openPaths = new Set(JSON.parse(state.get(storageKey) || '[]')); } catch (_) {}
  }
  tree.querySelectorAll('details[data-inventory-tree-path]').forEach((node) => {
    const path = node.dataset.inventoryTreePath;
    node.open = openPaths.has(path);
    node.addEventListener('toggle', () => {
      if (!state) return;
      if (node.open) openPaths.add(path); else openPaths.delete(path);
      state.set(storageKey, JSON.stringify([...openPaths]));
    });
  });
})();
