import { consume } from "@lit/context";
import { LitElement, css, html } from "lit";
import { customElement } from "lit/decorators.js";
import type { ContextMixinInterface } from "./ContextMixin.js";
import { efContext } from "./efContext.js";

@customElement("ef-time-display")
export class EFTimeDisplay extends LitElement {
  static styles = css`
    :host {
      display: inline-block;
      font-family: var(--ef-font-family, system-ui);
      font-size: var(--ef-font-size-xs, 0.75rem);
      color: var(--ef-text-color, rgb(75 85 99));
      white-space: nowrap;
    }
  `;

  @consume({ context: efContext, subscribe: true })
  context?: ContextMixinInterface | null;

  private _onTimeUpdate = () => {
    this.requestUpdate();
  };

  connectedCallback(): void {
    super.connectedCallback();
    this.context?.addEventListener(
      "timeupdate",
      this._onTimeUpdate as EventListener,
    );
  }

  protected updated(changedProperties: Map<PropertyKey, unknown>): void {
    if (changedProperties.has("context")) {
      // Clean up old listener
      const oldContext = changedProperties.get(
        "context",
      ) as ContextMixinInterface | null;
      oldContext?.removeEventListener(
        "timeupdate",
        this._onTimeUpdate as EventListener,
      );

      // Add new listener
      this.context?.addEventListener(
        "timeupdate",
        this._onTimeUpdate as EventListener,
      );
    }
  }

  disconnectedCallback(): void {
    this.context?.removeEventListener("timeupdate", this._onTimeUpdate);
    super.disconnectedCallback();
  }

  private formatTime(ms: number): string {
    const totalSeconds = Math.floor(ms / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    return `${minutes}:${seconds.toString().padStart(2, "0")}`;
  }

  render() {
    const currentTime = this.context?.currentTimeMs ?? 0;
    const totalTime = this.context?.targetTimegroup?.durationMs ?? 0;

    return html`
      <span part="time">
        ${this.formatTime(currentTime)} / ${this.formatTime(totalTime)}
      </span>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "ef-time-display": EFTimeDisplay;
  }
}
