/**
 * 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 } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { styles } from './nile-grid-cell-item.css';
import NileElement from '../../internal/nile-element';
import {
  initCellResize,
  cellResizeMove,
  cellResizeDone,
} from './nile-grid-cell-item.utils';

/**
 * Nile grid-cell component.
 *
 * @tag nile-grid-cell-item
 *
 */
@customElement('nile-grid-cell-item')
export class NileGridCellItem extends NileElement {
  /**
   * The styles for nile-grid-cell-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;

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

  private onHandlePointerDown = (ev: PointerEvent) => {
    
    const el = this as HTMLElement;

    const downXRef = { value: 0 };
    const startWRef = { value: 0 };

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

    const { target, col } = result;
    const move = (e: PointerEvent) => cellResizeMove(el, col, startWRef.value, downXRef.value, e);
    const done = () => cellResizeDone(el, col, ev, target, move);

    target.addEventListener('pointermove', move);
    target.addEventListener('pointerup', done, { once: true });
    target.addEventListener('pointercancel', done, { once: true });
  };

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

  /* #endregion */
}

export default NileGridCellItem;

declare global {
  interface HTMLElementTagNameMap {
    'nile-grid-cell-item': NileGridCellItem;
  }
}
