/**
 * Copyright Aquera Inc 2025
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { html, CSSResultArray, TemplateResult, PropertyValues } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { styles } from './nile-grid-head-item.css';
import NileElement from '../../internal/nile-element';
import {
  initHeadResize,
  headResizeMove,
  headResizeDone,
  addListeners,
  removeListeners,
} from './nile-grid-head-item.utils';
import { NileGrid } from '../nile-grid';

/**
 * Nile grid-head-item component.
 *
 * @tag nile-grid-head-item
 *
 */
@customElement('nile-grid-head-item')
export class NileGridHeadItem extends NileElement {
  /**
   * The styles for nile-grid-head-item
   * @remarks If you are extending this class you can extend the base styles with super. Eg `return [super(), myCustomStyles]`
   */
  public static get styles(): CSSResultArray {
    return [styles];
  }

  @property({ type: Number, reflect: true, attribute: true }) colspan = 1;
  @property({ type: Number, reflect: true, attribute: true }) rowspan = 1;
  @property({ type: Boolean, reflect: true, attribute: true }) resizable = false;
  @property({ type: String, reflect: true, attribute: true }) width: string | null = null;
  @property({ type: String, reflect: true, attribute: true }) sticky: string | null = null;
  @property({ type: Boolean, reflect: true, attribute: true }) lockWidth: boolean = false;

  connectedCallback() {
    super.connectedCallback();
    this.setAttribute('role','row');
  }

  private onHandlePointerDown = (ev: PointerEvent) => {
    const el = this as HTMLElement;
    const nileGrid = this.closest('nile-grid') as NileGrid;
    const downXRef = { value: 0 };
    const startWRef = { value: 0 };

    const result = initHeadResize(el, ev, downXRef, startWRef);
    if (!result) return;

    const { target, col } = result;
    const move = (e: PointerEvent) => headResizeMove(el, col, startWRef.value, downXRef.value, e, nileGrid);
    const done = (e: PointerEvent) => {
      headResizeDone(el, col, e, target, move);
      removeListeners(target, move, done);
    }
    addListeners(target, move, done);
  };

  disconnectedCallback() {
    super.disconnectedCallback();
    this.removeAttribute('role');
  }

  public render(): TemplateResult {
    return html`
      <div part="grid-head-item-base" class="head-item-base">
        <slot></slot>
        ${this.resizable
          ? html`
              <div
                aria-hidden="false"
                class="resize-handle"
                part="resize-handle"
                @pointerdown=${this.onHandlePointerDown}
              ></div>
            `
          : null}
      </div>
    `;
  }

  /* #endregion */
}

export default NileGridHeadItem;

declare global {
  interface HTMLElementTagNameMap {
    'nile-grid-head-item': NileGridHeadItem;
  }
}
