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

tap.test('should show context menu on WYSIWYG blocks', async () => {
  // Create WYSIWYG editor
  const wysiwygEditor = new DeesInputWysiwyg();
  wysiwygEditor.value = '<p>Test paragraph</p><h1>Test heading</h1>';
  document.body.appendChild(wysiwygEditor);
  
  // Wait for editor to be ready
  await wysiwygEditor.updateComplete;
  await new Promise(resolve => setTimeout(resolve, 100));
  
  // Get the first block element
  const firstBlockWrapper = wysiwygEditor.shadowRoot!.querySelector('.block-wrapper');
  expect(firstBlockWrapper).toBeTruthy();
  
  const blockComponent = firstBlockWrapper!.querySelector('dees-wysiwyg-block') as any;
  expect(blockComponent).toBeTruthy();
  
  // Wait for block to be ready
  await blockComponent.updateComplete;
  
  // Get the editable content inside the block's shadow DOM
  const editableBlock = blockComponent.shadowRoot!.querySelector('.block');
  expect(editableBlock).toBeTruthy();
  
  // Simulate right-click on the editable block
  const contextMenuEvent = new MouseEvent('contextmenu', {
    clientX: 200,
    clientY: 200,
    bubbles: true,
    cancelable: true,
    composed: true // Important for shadow DOM
  });
  
  editableBlock!.dispatchEvent(contextMenuEvent);
  
  // Wait for context menu to appear
  await new Promise(resolve => setTimeout(resolve, 100));
  
  // Check if context menu is created
  const contextMenu = document.querySelector('dees-contextmenu');
  expect(contextMenu).toBeInstanceOf(DeesContextmenu);
  
  // Check if menu items from WYSIWYG block are rendered
  const menuItems = contextMenu!.shadowRoot!.querySelectorAll('.menuitem');
  const menuTexts = Array.from(menuItems).map(item => 
    item.querySelector('.menuitem-text')?.textContent?.trim()
  );
  
  // Should have "Change Type" and "Delete Block" items
  expect(menuTexts).toContain('Change Type');
  expect(menuTexts).toContain('Delete Block');
  
  // Check if "Change Type" has submenu indicator
  const changeTypeItem = Array.from(menuItems).find(item => 
    item.querySelector('.menuitem-text')?.textContent?.trim() === 'Change Type'
  );
  expect(changeTypeItem?.classList.contains('has-submenu')).toEqual(true);
  
  // Clean up
  contextMenu!.remove();
  wysiwygEditor.remove();
});

export default tap.start();