import { html, TemplateResult } from 'lit'
import { DemoPage } from '../../../src/demo/DemoPage.js'
import { ContextualMenu } from '../../../src/elements/contextual-menu/internals/ContextualMenu.js'
import { ContextMenuCommand, CommandExecuteOptions } from '../../../src/elements/contextual-menu/internals/types.js'

class ComponentPage extends DemoPage {
  override accessor componentName = 'Custom data'

  override firstRender(): void {
    super.firstRender()
    this.initContextMenu()
  }

  initContextMenu(): void {
    const container = document.body.querySelector('#workspace') as HTMLElement
    const instance = new ContextualMenu(container)
    const commands: ContextMenuCommand[] = [
      {
        target: 'custom',
        label: 'Custom action',
        title: 'Custom action title',
        execute: (args: CommandExecuteOptions): void => {
          console.log(args)
        },
      },
    ]
    instance.registerCommands(commands)
    instance.connect()
  }

  customTriggerHandler(e: Event): void {
    e.preventDefault()
    const container = document.body.querySelector('#workspace') as HTMLElement
    container.dispatchEvent(
      new CustomEvent('custommenu', {
        detail: {
          name: 'custom',
          x: container.offsetLeft + 100,
          y: container.offsetTop + 100,
          customData: { test: true },
        },
      })
    )
  }

  contentTemplate(): TemplateResult {
    return html`
      <a href="./">Back</a>
      <section class="demo-section">
        <h2 class="title-large">Contextual menu with custom data</h2>
        <div id="workspace">
          <div class="target" data-id="test-value"></div>
        </div>
        <button id="customTrigger" @click="${this.customTriggerHandler}">Trigger custom</button>
        <p>The menu is only triggered via the custom event.</p>
      </section>
    `
  }
}

const instance = new ComponentPage()
instance.render()
