import { provide } from "@lit/context";
import { css, html, LitElement } from "lit";
import { customElement } from "lit/decorators.js";
import { ContextMixin } from "./ContextMixin.js";
import { focusedElementContext } from "./focusedElementContext.js";
import { TWMixin } from "./TWMixin.js";

@customElement("ef-preview")
export class EFPreview extends ContextMixin(TWMixin(LitElement)) {
  static styles = [
    css`
      :host {
        position: relative;
        display: block;
        cursor: crosshair;
      }
    `,
  ];

  @provide({ context: focusedElementContext })
  focusedElement?: HTMLElement;

  constructor() {
    super();
    this.addEventListener("mouseover", (e) => {
      const target = e.target as HTMLElement;
      const timegroup = target.closest("ef-timegroup");
      if (target !== this && timegroup) {
        this.focusedElement = target;
      }
    });
    this.addEventListener("mouseout", (e) => {
      const relatedTarget = e.relatedTarget as HTMLElement;
      const targetingTimegroup = relatedTarget?.closest("ef-timegroup");
      // Clear focus if:
      // 1. Moving outside the preview entirely, or
      // 2. Moving to the preview itself, or
      // 3. Moving to an element that's not within a timegroup
      if (
        !this.contains(relatedTarget) ||
        relatedTarget === this ||
        !targetingTimegroup
      ) {
        this.focusedElement = undefined;
      }
    });
  }

  render() {
    return html`<slot></slot>`;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "ef-preview": EFPreview;
  }
}
