import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DeesContextmenu } from '../ts_web/elements/dees-contextmenu/dees-contextmenu.js';

tap.test('should close all parent menus when clicking action in nested submenu', async () => {
  let actionCalled = false;
  
  // Create a test element
  const testDiv = document.createElement('div');
  testDiv.style.width = '300px';
  testDiv.style.height = '300px';
  testDiv.style.background = '#f0f0f0';
  testDiv.innerHTML = 'Right-click for nested menu test';
  document.body.appendChild(testDiv);
  
  // Simulate right-click to open context menu
  const contextMenuEvent = new MouseEvent('contextmenu', {
    clientX: 150,
    clientY: 150,
    bubbles: true,
    cancelable: true
  });
  
  // Open context menu with nested structure
  DeesContextmenu.openContextMenuWithOptions(contextMenuEvent, [
    {
      name: 'Parent Item',
      iconName: 'folder',
      action: async () => {}, // Parent items with submenus need an action
      submenu: [
        {
          name: 'Child Item',
          iconName: 'file',
          action: async () => {
            actionCalled = true;
            console.log('Child action called');
          }
        },
        {
          name: 'Another Child',
          iconName: 'fileText',
          action: async () => console.log('Another child')
        }
      ]
    },
    {
      name: 'Regular Item',
      iconName: 'box',
      action: async () => console.log('Regular item')
    }
  ]);
  
  // Wait for main menu to appear
  await new Promise(resolve => setTimeout(resolve, 150));
  
  // Check main menu exists
  const mainMenu = document.querySelector('dees-contextmenu');
  expect(mainMenu).toBeInstanceOf(DeesContextmenu);
  
  // Hover over "Parent Item" to trigger submenu
  const parentItem = mainMenu!.shadowRoot!.querySelector('.menuitem');
  expect(parentItem).toBeTruthy();
  parentItem!.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
  
  // Wait for submenu to appear
  await new Promise(resolve => setTimeout(resolve, 300));
  
  // Check submenu exists
  const allMenus = document.querySelectorAll('dees-contextmenu');
  expect(allMenus.length).toEqual(2); // Main menu and submenu
  
  const submenu = allMenus[1];
  expect(submenu).toBeTruthy();
  
  // Click on "Child Item" in submenu
  const childItem = submenu.shadowRoot!.querySelector('.menuitem');
  expect(childItem).toBeTruthy();
  childItem!.click();
  
  // Wait for menus to close (windowLayer destruction takes 300ms + context menu 100ms)
  await new Promise(resolve => setTimeout(resolve, 600));
  
  // Verify action was called
  expect(actionCalled).toEqual(true);
  
  // Verify all menus are closed
  const remainingMenus = document.querySelectorAll('dees-contextmenu');
  expect(remainingMenus.length).toEqual(0);
  
  // Clean up
  testDiv.remove();
});

export default tap.start();